[8147] Some fixes and cleanups in mind control and charmed code. Mind control stil...
[getmangos.git] / src / game / Player.cpp
blobf81ef2e17a32ac875022095e97a37fe00e2f72d4
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.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 "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 m_DelayedOperations = 0;
342 m_bCanDelayTeleport = false;
343 m_bHasDelayedTeleport = false;
344 m_teleport_options = 0;
346 pTrader = 0;
347 ClearTrade();
349 m_cinematic = 0;
351 PlayerTalkClass = new PlayerMenu( GetSession() );
352 m_currentBuybackSlot = BUYBACK_SLOT_START;
354 m_DailyQuestChanged = false;
355 m_lastDailyQuestTime = 0;
357 for (int i=0; i<MAX_TIMERS; ++i)
358 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
360 m_MirrorTimerFlags = UNDERWATER_NONE;
361 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
362 m_isInWater = false;
363 m_drunkTimer = 0;
364 m_drunk = 0;
365 m_restTime = 0;
366 m_deathTimer = 0;
367 m_deathExpireTime = 0;
369 m_swingErrorMsg = 0;
371 m_DetectInvTimer = 1*IN_MILISECONDS;
373 m_bgBattleGroundID = 0;
374 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
375 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
377 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
378 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
380 m_bgTeam = 0;
382 m_logintime = time(NULL);
383 m_Last_tick = m_logintime;
384 m_WeaponProficiency = 0;
385 m_ArmorProficiency = 0;
386 m_canParry = false;
387 m_canBlock = false;
388 m_canDualWield = false;
389 m_canTitanGrip = false;
390 m_ammoDPS = 0.0f;
392 m_temporaryUnsummonedPetNumber = 0;
393 //cache for UNIT_CREATED_BY_SPELL to allow
394 //returning reagents for temporarily removed pets
395 //when dying/logging out
396 m_oldpetspell = 0;
398 ////////////////////Rest System/////////////////////
399 time_inn_enter=0;
400 inn_pos_mapid=0;
401 inn_pos_x=0;
402 inn_pos_y=0;
403 inn_pos_z=0;
404 m_rest_bonus=0;
405 rest_type=REST_TYPE_NO;
406 ////////////////////Rest System/////////////////////
408 m_mailsLoaded = false;
409 m_mailsUpdated = false;
410 unReadMails = 0;
411 m_nextMailDelivereTime = 0;
413 m_resetTalentsCost = 0;
414 m_resetTalentsTime = 0;
415 m_itemUpdateQueueBlocked = false;
417 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
418 m_forced_speed_changes[i] = 0;
420 m_stableSlots = 0;
422 /////////////////// Instance System /////////////////////
424 m_HomebindTimer = 0;
425 m_InstanceValid = true;
426 m_dungeonDifficulty = DIFFICULTY_NORMAL;
428 m_lastPotionId = 0;
430 m_activeSpec = 0;
431 m_specsCount = 1;
433 for (int i = 0; i < BASEMOD_END; ++i)
435 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
436 m_auraBaseMod[i][PCT_MOD] = 1.0f;
439 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
440 m_baseRatingValue[i] = 0;
442 m_baseSpellDamage = 0;
443 m_baseSpellHealing = 0;
444 m_baseFeralAP = 0;
445 m_baseManaRegen = 0;
447 // Honor System
448 m_lastHonorUpdateTime = time(NULL);
450 // Player summoning
451 m_summon_expire = 0;
452 m_summon_mapid = 0;
453 m_summon_x = 0.0f;
454 m_summon_y = 0.0f;
455 m_summon_z = 0.0f;
457 m_mover = this;
459 m_miniPet = 0;
460 m_bgAfkReportedTimer = 0;
461 m_contestedPvPTimer = 0;
463 m_declinedname = NULL;
464 m_runes = NULL;
466 m_lastFallTime = 0;
467 m_lastFallZ = 0;
470 Player::~Player ()
472 CleanupsBeforeDelete();
474 // it must be unloaded already in PlayerLogout and accessed only for loggined player
475 //m_social = NULL;
477 // Note: buy back item already deleted from DB when player was saved
478 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
480 if(m_items[i])
481 delete m_items[i];
483 CleanupChannels();
485 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
486 delete itr->second;
488 //all mailed items should be deleted, also all mail should be deallocated
489 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
490 delete *itr;
492 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
493 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
495 delete PlayerTalkClass;
497 if (m_transport)
499 m_transport->RemovePassenger(this);
502 for(size_t x = 0; x < ItemSetEff.size(); x++)
503 if(ItemSetEff[x])
504 delete ItemSetEff[x];
506 // clean up player-instance binds, may unload some instance saves
507 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
508 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
509 itr->second.save->RemovePlayer(this);
511 delete m_declinedname;
512 delete m_runes;
515 void Player::CleanupsBeforeDelete()
517 if(m_uint32Values) // only for fully created Object
519 TradeCancel(false);
520 DuelComplete(DUEL_INTERUPTED);
522 Unit::CleanupsBeforeDelete();
525 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 )
527 //FIXME: outfitId not used in player creating
529 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
531 m_name = name;
533 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
534 if(!info)
536 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
537 return false;
540 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
541 m_items[i] = NULL;
543 SetMapId(info->mapId);
544 Relocate(info->positionX,info->positionY,info->positionZ);
546 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
547 if(!cEntry)
549 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
550 return false;
553 uint8 powertype = cEntry->powerType;
555 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
556 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
558 setFactionForRace(race);
560 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
562 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
563 InitDisplayIds();
564 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
565 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
566 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
567 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
568 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
570 // -1 is default value
571 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
573 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
574 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
575 SetByteValue(PLAYER_BYTES_3, 0, gender);
577 SetUInt32Value( PLAYER_GUILDID, 0 );
578 SetUInt32Value( PLAYER_GUILDRANK, 0 );
579 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
581 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
582 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
583 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
584 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
585 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
586 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
587 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
588 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
590 // set starting level
591 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
592 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
593 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
595 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
597 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
598 if(gm_level > start_level)
599 start_level = gm_level;
602 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
604 InitRunes();
606 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
607 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
608 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
610 // Played time
611 m_Last_tick = time(NULL);
612 m_Played_time[0] = 0;
613 m_Played_time[1] = 0;
615 // base stats and related field values
616 InitStatsForLevel();
617 InitTaxiNodesForLevel();
618 InitGlyphsForLevel();
619 InitTalentForLevel();
620 InitPrimaryProfessions(); // to max set before any spell added
622 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
623 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
624 SetHealth(GetMaxHealth());
625 if (getPowerType()==POWER_MANA)
627 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
628 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
631 if(getPowerType() == POWER_RUNIC_POWER)
633 SetPower(POWER_RUNE, 8);
634 SetMaxPower(POWER_RUNE, 8);
635 SetPower(POWER_RUNIC_POWER, 0);
636 SetMaxPower(POWER_RUNIC_POWER, 1000);
639 // original spells
640 learnDefaultSpells();
642 // original action bar
643 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
644 addActionButton(action_itr->button,action_itr->action,action_itr->type);
646 // original items
647 CharStartOutfitEntry const* oEntry = NULL;
648 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
650 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
652 if(entry->RaceClassGender == RaceClassGender)
654 oEntry = entry;
655 break;
660 if(oEntry)
662 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
664 if(oEntry->ItemId[j] <= 0)
665 continue;
667 uint32 item_id = oEntry->ItemId[j];
670 // Hack for not existed item id in dbc 3.0.3
671 if(item_id==40582)
672 continue;
674 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
675 if(!iProto)
677 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
678 continue;
681 // max stack by default (mostly 1), 1 for infinity stackable
682 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
684 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
686 switch(iProto->Spells[0].SpellCategory)
688 case 11: // food
689 if(iProto->Stackable > 4)
690 count = 4;
691 break;
692 case 59: // drink
693 if(iProto->Stackable > 2)
694 count = 2;
695 break;
699 StoreNewItemInBestSlots(item_id, count);
703 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
704 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
706 // bags and main-hand weapon must equipped at this moment
707 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
708 // or ammo not equipped in special bag
709 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
711 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
713 uint16 eDest;
714 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
715 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
716 if( msg == EQUIP_ERR_OK )
718 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
719 EquipItem( eDest, pItem, true);
721 // move other items to more appropriate slots (ammo not equipped in special bag)
722 else
724 ItemPosCountVec sDest;
725 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
726 if( msg == EQUIP_ERR_OK )
728 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
729 pItem = StoreItem( sDest, pItem, true);
732 // if this is ammo then use it
733 msg = CanUseAmmo( pItem->GetEntry() );
734 if( msg == EQUIP_ERR_OK )
735 SetAmmo( pItem->GetEntry() );
739 // all item positions resolved
741 return true;
744 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
746 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
748 // attempt equip by one
749 while(titem_amount > 0)
751 uint16 eDest;
752 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
753 if( msg != EQUIP_ERR_OK )
754 break;
756 EquipNewItem( eDest, titem_id, true);
757 AutoUnequipOffhandIfNeed();
758 --titem_amount;
761 if(titem_amount == 0)
762 return true; // equipped
764 // attempt store
765 ItemPosCountVec sDest;
766 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
767 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
768 if( msg == EQUIP_ERR_OK )
770 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
771 return true; // stored
774 // item can't be added
775 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
776 return false;
779 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
781 if (MaxValue == DISABLED_MIRROR_TIMER)
783 if (CurrentValue!=DISABLED_MIRROR_TIMER)
784 StopMirrorTimer(Type);
785 return;
787 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
788 data << (uint32)Type;
789 data << CurrentValue;
790 data << MaxValue;
791 data << Regen;
792 data << (uint8)0;
793 data << (uint32)0; // spell id
794 GetSession()->SendPacket( &data );
797 void Player::StopMirrorTimer(MirrorTimerType Type)
799 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
800 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
801 data << (uint32)Type;
802 GetSession()->SendPacket( &data );
805 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
807 if(!isAlive() || isGameMaster())
808 return;
810 // Absorb, resist some environmental damage type
811 uint32 absorb = 0;
812 uint32 resist = 0;
813 if (type == DAMAGE_LAVA)
814 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
815 else if (type == DAMAGE_SLIME)
816 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
818 damage-=absorb+resist;
820 DealDamageMods(this,damage,&absorb);
822 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
823 data << uint64(GetGUID());
824 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
825 data << uint32(damage);
826 data << uint32(absorb);
827 data << uint32(resist);
828 SendMessageToSet(&data, true);
830 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
832 if(!isAlive())
834 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
836 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
837 DurabilityLossAll(0.10f,false);
838 // durability lost message
839 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
840 GetSession()->SendPacket(&data2);
843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
847 int32 Player::getMaxTimer(MirrorTimerType timer)
849 switch (timer)
851 case FATIGUE_TIMER:
852 return MINUTE*IN_MILISECONDS;
853 case BREATH_TIMER:
855 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
856 return DISABLED_MIRROR_TIMER;
857 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
858 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
859 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
860 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
861 return UnderWaterTime;
863 case FIRE_TIMER:
865 if (!isAlive())
866 return DISABLED_MIRROR_TIMER;
867 return 1*IN_MILISECONDS;
869 default:
870 return 0;
872 return 0;
875 void Player::UpdateMirrorTimers()
877 // Desync flags for update on next HandleDrowning
878 if (m_MirrorTimerFlags)
879 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
882 void Player::HandleDrowning(uint32 time_diff)
884 if (!m_MirrorTimerFlags)
885 return;
887 // In water
888 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
890 // Breath timer not activated - activate it
891 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
893 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
894 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
896 else // If activated - do tick
898 m_MirrorTimer[BREATH_TIMER]-=time_diff;
899 // Timer limit - need deal damage
900 if (m_MirrorTimer[BREATH_TIMER] < 0)
902 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
903 // Calculate and deal damage
904 // TODO: Check this formula
905 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
906 EnvironmentalDamage(DAMAGE_DROWNING, damage);
908 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
909 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
912 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
914 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
915 // Need breath regen
916 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
917 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
918 StopMirrorTimer(BREATH_TIMER);
919 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
920 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
923 // In dark water
924 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
926 // Fatigue timer not activated - activate it
927 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
929 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
930 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
932 else
934 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
935 // Timer limit - need deal damage or teleport ghost to graveyard
936 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
938 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
939 if (isAlive()) // Calculate and deal damage
941 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
942 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
944 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
945 RepopAtGraveyard();
947 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
948 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
951 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
953 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
954 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
955 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
956 StopMirrorTimer(FATIGUE_TIMER);
957 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
958 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
961 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
963 // Breath timer not activated - activate it
964 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
965 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
966 else
968 m_MirrorTimer[FIRE_TIMER]-=time_diff;
969 if (m_MirrorTimer[FIRE_TIMER] < 0)
971 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
972 // Calculate and deal damage
973 // TODO: Check this formula
974 uint32 damage = urand(600, 700);
975 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
976 EnvironmentalDamage(DAMAGE_LAVA, damage);
977 else
978 EnvironmentalDamage(DAMAGE_SLIME, damage);
982 else
983 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
985 // Recheck timers flag
986 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
987 for (int i = 0; i< MAX_TIMERS; ++i)
988 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
990 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
991 break;
993 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
996 ///The player sobers by 256 every 10 seconds
997 void Player::HandleSobering()
999 m_drunkTimer = 0;
1001 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1002 SetDrunkValue(drunk);
1005 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1007 if(value >= 23000)
1008 return DRUNKEN_SMASHED;
1009 if(value >= 12800)
1010 return DRUNKEN_DRUNK;
1011 if(value & 0xFFFE)
1012 return DRUNKEN_TIPSY;
1013 return DRUNKEN_SOBER;
1016 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1018 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1020 m_drunk = newDrunkenValue;
1021 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1023 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1025 // special drunk invisibility detection
1026 if(newDrunkenState >= DRUNKEN_DRUNK)
1027 m_detectInvisibilityMask |= (1<<6);
1028 else
1029 m_detectInvisibilityMask &= ~(1<<6);
1031 if(newDrunkenState == oldDrunkenState)
1032 return;
1034 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1035 data << uint64(GetGUID());
1036 data << uint32(newDrunkenState);
1037 data << uint32(itemId);
1039 SendMessageToSet(&data, true);
1042 void Player::Update( uint32 p_time )
1044 if(!IsInWorld())
1045 return;
1047 // undelivered mail
1048 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1050 SendNewMail();
1051 ++unReadMails;
1053 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1054 m_nextMailDelivereTime = 0;
1057 //used to implement delayed far teleports
1058 SetCanDelayTeleport(true);
1059 Unit::Update( p_time );
1060 SetCanDelayTeleport(false);
1062 // update player only attacks
1063 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1065 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1068 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1070 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1073 time_t now = time (NULL);
1075 UpdatePvPFlag(now);
1077 UpdateContestedPvP(p_time);
1079 UpdateDuelFlag(now);
1081 CheckDuelDistance(now);
1083 UpdateAfkReport(now);
1085 // Update items that have just a limited lifetime
1086 if (now>m_Last_tick)
1087 UpdateItemDuration(uint32(now- m_Last_tick));
1089 if (!m_timedquests.empty())
1091 std::set<uint32>::iterator iter = m_timedquests.begin();
1092 while (iter != m_timedquests.end())
1094 QuestStatusData& q_status = mQuestStatus[*iter];
1095 if( q_status.m_timer <= p_time )
1097 uint32 quest_id = *iter;
1098 ++iter; // current iter will be removed in FailTimedQuest
1099 FailTimedQuest( quest_id );
1101 else
1103 q_status.m_timer -= p_time;
1104 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1105 ++iter;
1110 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1112 Unit *pVictim = getVictim();
1113 if (pVictim && !IsNonMeleeSpellCasted(false))
1115 // default combat reach 10
1116 // TODO add weapon,skill check
1118 float pldistance = ATTACK_DISTANCE;
1120 if (isAttackReady(BASE_ATTACK))
1122 if(!IsWithinDistInMap(pVictim, pldistance))
1124 setAttackTimer(BASE_ATTACK,100);
1125 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1127 SendAttackSwingNotInRange();
1128 m_swingErrorMsg = 1;
1131 //120 degrees of radiant range
1132 else if( !HasInArc( 2*M_PI/3, pVictim ))
1134 setAttackTimer(BASE_ATTACK,100);
1135 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1137 SendAttackSwingBadFacingAttack();
1138 m_swingErrorMsg = 2;
1141 else
1143 m_swingErrorMsg = 0; // reset swing error state
1145 // prevent base and off attack in same time, delay attack at 0.2 sec
1146 if(haveOffhandWeapon())
1148 uint32 off_att = getAttackTimer(OFF_ATTACK);
1149 if(off_att < ATTACK_DISPLAY_DELAY)
1150 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1152 AttackerStateUpdate(pVictim, BASE_ATTACK);
1153 resetAttackTimer(BASE_ATTACK);
1157 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1159 if(!IsWithinDistInMap(pVictim, pldistance))
1161 setAttackTimer(OFF_ATTACK,100);
1163 else if( !HasInArc( 2*M_PI/3, pVictim ))
1165 setAttackTimer(OFF_ATTACK,100);
1167 else
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 uint32 base_att = getAttackTimer(BASE_ATTACK);
1171 if(base_att < ATTACK_DISPLAY_DELAY)
1172 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1173 // do attack
1174 AttackerStateUpdate(pVictim, OFF_ATTACK);
1175 resetAttackTimer(OFF_ATTACK);
1179 Unit *owner = pVictim->GetOwner();
1180 Unit *u = owner ? owner : pVictim;
1181 if(u->IsPvP() && (!duel || duel->opponent != u))
1183 UpdatePvP(true);
1184 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1189 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1191 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1193 int time_inn = time(NULL)-GetTimeInnEnter();
1194 if (time_inn >= 10) //freeze update
1196 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1197 //speed collect rest bonus (section/in hour)
1198 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1199 UpdateInnerTime(time(NULL));
1204 if(m_regenTimer > 0)
1206 if(p_time >= m_regenTimer)
1207 m_regenTimer = 0;
1208 else
1209 m_regenTimer -= p_time;
1212 if (m_weaponChangeTimer > 0)
1214 if(p_time >= m_weaponChangeTimer)
1215 m_weaponChangeTimer = 0;
1216 else
1217 m_weaponChangeTimer -= p_time;
1220 if (m_zoneUpdateTimer > 0)
1222 if(p_time >= m_zoneUpdateTimer)
1224 uint32 newzone, newarea;
1225 GetZoneAndAreaId(newzone,newarea);
1227 if( m_zoneUpdateId != newzone )
1228 UpdateZone(newzone,newarea); // also update area
1229 else
1231 // use area updates as well
1232 // needed for free far all arenas for example
1233 if( m_areaUpdateId != newarea )
1234 UpdateArea(newarea);
1236 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1239 else
1240 m_zoneUpdateTimer -= p_time;
1243 if (isAlive())
1245 RegenerateAll();
1248 if (m_deathState == JUST_DIED)
1250 KillPlayer();
1253 if(m_nextSave > 0)
1255 if(p_time >= m_nextSave)
1257 // m_nextSave reseted in SaveToDB call
1258 SaveToDB();
1259 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1261 else
1263 m_nextSave -= p_time;
1267 //Handle Water/drowning
1268 HandleDrowning(p_time);
1270 //Handle detect stealth players
1271 if (m_DetectInvTimer > 0)
1273 if (p_time >= m_DetectInvTimer)
1275 m_DetectInvTimer = 3000;
1276 HandleStealthedUnitsDetection();
1278 else
1279 m_DetectInvTimer -= p_time;
1282 // Played time
1283 if (now > m_Last_tick)
1285 uint32 elapsed = uint32(now - m_Last_tick);
1286 m_Played_time[0] += elapsed; // Total played time
1287 m_Played_time[1] += elapsed; // Level played time
1288 m_Last_tick = now;
1291 if (m_drunk)
1293 m_drunkTimer += p_time;
1295 if (m_drunkTimer > 10*IN_MILISECONDS)
1296 HandleSobering();
1299 // not auto-free ghost from body in instances
1300 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1302 if(p_time >= m_deathTimer)
1304 m_deathTimer = 0;
1305 BuildPlayerRepop();
1306 RepopAtGraveyard();
1308 else
1309 m_deathTimer -= p_time;
1312 UpdateEnchantTime(p_time);
1313 UpdateHomebindTime(p_time);
1315 // group update
1316 SendUpdateToOutOfRangeGroupMembers();
1318 Pet* pet = GetPet();
1319 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1321 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1324 //we should execute delayed teleports only for alive(!) players
1325 //because we don't want player's ghost teleported from graveyard
1326 if(IsHasDelayedTeleport() && isAlive())
1327 TeleportTo(m_teleport_dest, m_teleport_options);
1330 void Player::setDeathState(DeathState s)
1332 uint32 ressSpellId = 0;
1334 bool cur = isAlive();
1336 if(s == JUST_DIED && cur)
1338 // drunken state is cleared on death
1339 SetDrunkValue(0);
1340 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1341 ClearComboPoints();
1343 clearResurrectRequestData();
1345 // remove form before other mods to prevent incorrect stats calculation
1346 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1348 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1349 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1351 // remove uncontrolled pets
1352 RemoveMiniPet();
1354 // save value before aura remove in Unit::setDeathState
1355 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1357 // passive spell
1358 if(!ressSpellId)
1359 ressSpellId = GetResurrectionSpellId();
1360 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1361 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1362 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1364 Unit::setDeathState(s);
1366 // restore resurrection spell id for player after aura remove
1367 if(s == JUST_DIED && cur && ressSpellId)
1368 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1370 if(isAlive() && !cur)
1372 //clear aura case after resurrection by another way (spells will be applied before next death)
1373 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1375 // restore default warrior stance
1376 if(getClass()== CLASS_WARRIOR)
1377 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1381 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1383 // 0 1 2 3 4 5 6 7
1384 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1385 // 8 9 10 11 12 13 14
1386 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1387 // 15 16 17 18 19 20
1388 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1390 Field *fields = result->Fetch();
1392 uint32 guid = fields[0].GetUInt32();
1393 uint8 pRace = fields[2].GetUInt8();
1394 uint8 pClass = fields[3].GetUInt8();
1396 PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
1397 if(!info)
1399 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1400 return false;
1403 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1404 *p_data << fields[1].GetString(); // name
1405 *p_data << uint8(pRace); // race
1406 *p_data << uint8(pClass); // class
1407 *p_data << uint8(fields[4].GetUInt8()); // gender
1409 uint32 playerBytes = fields[5].GetUInt32();
1410 *p_data << uint8(playerBytes); // skin
1411 *p_data << uint8(playerBytes >> 8); // face
1412 *p_data << uint8(playerBytes >> 16); // hair style
1413 *p_data << uint8(playerBytes >> 24); // hair color
1415 uint32 playerBytes2 = fields[6].GetUInt32();
1416 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1418 *p_data << uint8(fields[7].GetUInt8()); // level
1419 *p_data << uint32(fields[8].GetUInt32()); // zone
1420 *p_data << uint32(fields[9].GetUInt32()); // map
1422 *p_data << fields[10].GetFloat(); // x
1423 *p_data << fields[11].GetFloat(); // y
1424 *p_data << fields[12].GetFloat(); // z
1426 *p_data << uint32(fields[13].GetUInt32()); // guild id
1428 uint32 char_flags = 0;
1429 uint32 playerFlags = fields[14].GetUInt32();
1430 uint32 atLoginFlags = fields[15].GetUInt32();
1431 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1432 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1433 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1434 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1435 if(playerFlags & PLAYER_FLAGS_GHOST)
1436 char_flags |= CHARACTER_FLAG_GHOST;
1437 if(atLoginFlags & AT_LOGIN_RENAME)
1438 char_flags |= CHARACTER_FLAG_RENAME;
1439 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1441 if(!fields[20].GetCppString().empty())
1442 char_flags |= CHARACTER_FLAG_DECLINED;
1444 else
1445 char_flags |= CHARACTER_FLAG_DECLINED;
1447 *p_data << uint32(char_flags); // character flags
1448 // character customize (flags?)
1449 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? 1 : 0);
1450 *p_data << uint8(1); // unknown
1452 // Pets info
1454 uint32 petDisplayId = 0;
1455 uint32 petLevel = 0;
1456 uint32 petFamily = 0;
1458 // show pet at selection character in character list only for non-ghost character
1459 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1461 uint32 entry = fields[16].GetUInt32();
1462 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1463 if(cInfo)
1465 petDisplayId = fields[17].GetUInt32();
1466 petLevel = fields[18].GetUInt32();
1467 petFamily = cInfo->family;
1471 *p_data << uint32(petDisplayId);
1472 *p_data << uint32(petLevel);
1473 *p_data << uint32(petFamily);
1476 // TODO: do not access data field here
1477 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1479 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1481 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1482 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1483 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1484 if(!proto)
1486 *p_data << uint32(0);
1487 *p_data << uint8(0);
1488 *p_data << uint32(0);
1489 continue;
1492 SpellItemEnchantmentEntry const *enchant = NULL;
1494 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1495 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1497 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantSlot >> enchantSlot*16))
1498 break;
1501 *p_data << uint32(proto->DisplayInfoID);
1502 *p_data << uint8(proto->InventoryType);
1503 *p_data << uint32(enchant ? enchant->aura_id : 0);
1505 *p_data << uint32(0); // first bag display id
1506 *p_data << uint8(0); // first bag inventory type
1507 *p_data << uint32(0); // enchant?
1509 return true;
1512 bool Player::ToggleAFK()
1514 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1516 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1518 // afk player not allowed in battleground
1519 if(state && InBattleGround())
1520 LeaveBattleground();
1522 return state;
1525 bool Player::ToggleDND()
1527 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1529 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1532 uint8 Player::chatTag() const
1534 // it's bitmask
1535 // 0x8 - ??
1536 // 0x4 - gm
1537 // 0x2 - dnd
1538 // 0x1 - afk
1539 if(isGMChat())
1540 return 4;
1541 else if(isDND())
1542 return 3;
1543 if(isAFK())
1544 return 1;
1545 else
1546 return 0;
1549 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1551 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1553 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1554 return false;
1557 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1558 Pet* pet = GetPet();
1560 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1562 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1563 // don't let gm level > 1 either
1564 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1565 return false;
1567 // client without expansion support
1568 if(GetSession()->Expansion() < mEntry->Expansion())
1570 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1572 if(GetTransport())
1573 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1575 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1577 return false; // normal client can't teleport to this map...
1579 else
1581 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1584 // if we were on a transport, leave
1585 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1587 m_transport->RemovePassenger(this);
1588 m_transport = NULL;
1589 m_movementInfo.t_x = 0.0f;
1590 m_movementInfo.t_y = 0.0f;
1591 m_movementInfo.t_z = 0.0f;
1592 m_movementInfo.t_o = 0.0f;
1593 m_movementInfo.t_time = 0;
1596 // The player was ported to another map and looses the duel immediately.
1597 // We have to perform this check before the teleport, otherwise the
1598 // ObjectAccessor won't find the flag.
1599 if (duel && GetMapId()!=mapid)
1601 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1602 if (obj)
1603 DuelComplete(DUEL_FLED);
1606 // reset movement flags at teleport, because player will continue move with these flags after teleport
1607 m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
1609 if ((GetMapId() == mapid) && (!m_transport))
1611 //lets reset far teleport flag if it wasn't reset during chained teleports
1612 SetSemaphoreTeleportFar(false);
1613 //setup delayed teleport flag
1614 SetDelayedTeleportFlag(IsCanDelayTeleport());
1615 //if teleport spell is casted in Unit::Update() func
1616 //then we need to delay it until update process will be finished
1617 if(IsHasDelayedTeleport())
1619 SetSemaphoreTeleportNear(true);
1620 //lets save teleport destination for player
1621 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1622 m_teleport_options = options;
1623 return true;
1626 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1628 //same map, only remove pet if out of range for new position
1629 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1630 UnsummonPetTemporaryIfAny();
1633 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1634 CombatStop();
1636 // this will be used instead of the current location in SaveToDB
1637 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1638 SetFallInformation(0, z);
1640 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1641 // at client packet MSG_MOVE_TELEPORT_ACK
1642 SetSemaphoreTeleportNear(true);
1643 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1644 if(!GetSession()->PlayerLogout())
1646 WorldPacket data;
1647 BuildTeleportAckMsg(&data, x, y, z, orientation);
1648 GetSession()->SendPacket(&data);
1651 else
1653 // far teleport to another map
1654 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1655 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1657 // Check enter rights before map getting to avoid creating instance copy for player
1658 // this check not dependent from map instance copy and same for all instance copies of selected map
1659 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1660 return false;
1662 // If the map is not created, assume it is possible to enter it.
1663 // It will be created in the WorldPortAck.
1664 Map *map = MapManager::Instance().FindMap(mapid);
1665 if (!map || map->CanEnter(this))
1667 //lets reset near teleport flag if it wasn't reset during chained teleports
1668 SetSemaphoreTeleportNear(false);
1669 //setup delayed teleport flag
1670 SetDelayedTeleportFlag(IsCanDelayTeleport());
1671 //if teleport spell is casted in Unit::Update() func
1672 //then we need to delay it until update process will be finished
1673 if(IsHasDelayedTeleport())
1675 SetSemaphoreTeleportFar(true);
1676 //lets save teleport destination for player
1677 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1678 m_teleport_options = options;
1679 return true;
1682 SetSelection(0);
1684 CombatStop();
1686 ResetContestedPvP();
1688 // remove player from battleground on far teleport (when changing maps)
1689 if(BattleGround const* bg = GetBattleGround())
1691 // Note: at battleground join battleground id set before teleport
1692 // and we already will found "current" battleground
1693 // just need check that this is targeted map or leave
1694 if(bg->GetMapId() != mapid)
1695 LeaveBattleground(false); // don't teleport to entry point
1698 // remove pet on map change
1699 if (pet)
1700 UnsummonPetTemporaryIfAny();
1702 // remove all dyn objects
1703 RemoveAllDynObjects();
1705 // stop spellcasting
1706 // not attempt interrupt teleportation spell at caster teleport
1707 if(!(options & TELE_TO_SPELL))
1708 if(IsNonMeleeSpellCasted(true))
1709 InterruptNonMeleeSpells(true);
1711 //remove auras before removing from map...
1712 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1714 if(!GetSession()->PlayerLogout())
1716 // send transfer packets
1717 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1718 data << uint32(mapid);
1719 if (m_transport)
1721 data << m_transport->GetEntry() << GetMapId();
1723 GetSession()->SendPacket(&data);
1725 data.Initialize(SMSG_NEW_WORLD, (20));
1726 if (m_transport)
1728 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1730 else
1732 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1734 GetSession()->SendPacket( &data );
1735 SendSavedInstances();
1737 // remove from old map now
1738 if(oldmap) oldmap->Remove(this, false);
1741 // new final coordinates
1742 float final_x = x;
1743 float final_y = y;
1744 float final_z = z;
1745 float final_o = orientation;
1747 if(m_transport)
1749 final_x += m_movementInfo.t_x;
1750 final_y += m_movementInfo.t_y;
1751 final_z += m_movementInfo.t_z;
1752 final_o += m_movementInfo.t_o;
1755 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1756 SetFallInformation(0, final_z);
1757 // if the player is saved before worldportack (at logout for example)
1758 // this will be used instead of the current location in SaveToDB
1760 // move packet sent by client always after far teleport
1761 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1762 SetSemaphoreTeleportFar(true);
1764 else
1765 return false;
1767 return true;
1770 void Player::ProcessDelayedOperations()
1772 if(m_DelayedOperations == 0)
1773 return;
1775 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1777 ResurrectPlayer(0.0f, false);
1779 if(GetMaxHealth() > m_resurrectHealth)
1780 SetHealth( m_resurrectHealth );
1781 else
1782 SetHealth( GetMaxHealth() );
1784 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1785 SetPower(POWER_MANA, m_resurrectMana );
1786 else
1787 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1789 SetPower(POWER_RAGE, 0 );
1790 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1792 SpawnCorpseBones();
1795 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1797 SaveToDB();
1800 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1802 CastSpell(this, 26013, true); // Deserter
1805 //we have executed ALL delayed ops, so clear the flag
1806 m_DelayedOperations = 0;
1809 void Player::ScheduleDelayedOperation(uint32 operation)
1811 if(operation >= DELAYED_END)
1812 return;
1814 m_DelayedOperations |= operation;
1817 void Player::AddToWorld()
1819 ///- Do not add/remove the player from the object storage
1820 ///- It will crash when updating the ObjectAccessor
1821 ///- The player should only be added when logging in
1822 Unit::AddToWorld();
1824 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1826 if(m_items[i])
1827 m_items[i]->AddToWorld();
1831 void Player::RemoveFromWorld()
1833 // cleanup
1834 if(IsInWorld())
1836 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1837 Uncharm();
1838 UnsummonAllTotems();
1839 RemoveMiniPet();
1842 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1844 if(m_items[i])
1845 m_items[i]->RemoveFromWorld();
1848 ///- Do not add/remove the player from the object storage
1849 ///- It will crash when updating the ObjectAccessor
1850 ///- The player should only be removed when logging out
1851 Unit::RemoveFromWorld();
1854 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1856 float addRage;
1858 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1860 if(attacker)
1862 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1864 // talent who gave more rage on attack
1865 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1867 else
1869 addRage = damage/rageconversion*2.5;
1871 // Berserker Rage effect
1872 if(HasAura(18499,0))
1873 addRage *= 1.3;
1876 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1878 ModifyPower(POWER_RAGE, uint32(addRage*10));
1881 void Player::RegenerateAll()
1883 if (m_regenTimer != 0)
1884 return;
1885 uint32 regenDelay = 2000;
1887 // Not in combat or they have regeneration
1888 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1889 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1891 RegenerateHealth();
1892 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1894 Regenerate(POWER_RAGE);
1895 if(getClass() == CLASS_DEATH_KNIGHT)
1896 Regenerate(POWER_RUNIC_POWER);
1900 Regenerate( POWER_ENERGY );
1902 Regenerate( POWER_MANA );
1904 if(getClass() == CLASS_DEATH_KNIGHT)
1905 Regenerate( POWER_RUNE );
1907 m_regenTimer = regenDelay;
1910 void Player::Regenerate(Powers power)
1912 uint32 curValue = GetPower(power);
1913 uint32 maxValue = GetMaxPower(power);
1915 float addvalue = 0.0f;
1917 switch (power)
1919 case POWER_MANA:
1921 bool recentCast = IsUnderLastManaUseEffect();
1922 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1923 if (recentCast)
1925 // Mangos Updates Mana in intervals of 2s, which is correct
1926 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1928 else
1930 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1932 } break;
1933 case POWER_RAGE: // Regenerate rage
1935 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1936 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1937 } break;
1938 case POWER_ENERGY: // Regenerate energy (rogue)
1939 addvalue = 20;
1940 break;
1941 case POWER_RUNIC_POWER:
1943 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1944 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1945 } break;
1946 case POWER_RUNE:
1948 for(uint32 i = 0; i < MAX_RUNES; ++i)
1949 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1950 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1951 } break;
1952 case POWER_FOCUS:
1953 case POWER_HAPPINESS:
1954 case POWER_HEALTH:
1955 break;
1958 // Mana regen calculated in Player::UpdateManaRegen()
1959 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1960 if(power != POWER_MANA)
1962 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1963 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1964 if ((*i)->GetModifier()->m_miscvalue == power)
1965 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1968 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1970 curValue += uint32(addvalue);
1971 if (curValue > maxValue)
1972 curValue = maxValue;
1974 else
1976 if(curValue <= uint32(addvalue))
1977 curValue = 0;
1978 else
1979 curValue -= uint32(addvalue);
1981 SetPower(power, curValue);
1984 void Player::RegenerateHealth()
1986 uint32 curValue = GetHealth();
1987 uint32 maxValue = GetMaxHealth();
1989 if (curValue >= maxValue) return;
1991 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1993 float addvalue = 0.0f;
1995 // polymorphed case
1996 if ( IsPolymorphed() )
1997 addvalue = GetMaxHealth()/3;
1998 // normal regen case (maybe partly in combat case)
1999 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2001 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2002 if (!isInCombat())
2004 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2005 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2006 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2008 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2009 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2011 if(!IsStandState())
2012 addvalue *= 1.5;
2015 // always regeneration bonus (including combat)
2016 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2018 if(addvalue < 0)
2019 addvalue = 0;
2021 ModifyHealth(int32(addvalue));
2024 bool Player::CanInteractWithNPCs(bool alive) const
2026 if(alive && !isAlive())
2027 return false;
2028 if(isInFlight())
2029 return false;
2031 return true;
2034 Creature*
2035 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2037 // unit checks
2038 if (!guid)
2039 return NULL;
2041 if(!IsInWorld())
2042 return NULL;
2044 // exist (we need look pets also for some interaction (quest/etc)
2045 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
2046 if (!unit)
2047 return NULL;
2049 // player check
2050 if(!CanInteractWithNPCs(!unit->isSpiritService()))
2051 return NULL;
2053 // appropriate npc type
2054 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2055 return NULL;
2057 // alive or spirit healer
2058 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
2059 return NULL;
2061 // not allow interaction under control, but allow with own pets
2062 if(unit->GetCharmerGUID())
2063 return NULL;
2065 // not enemy
2066 if( unit->IsHostileTo(this))
2067 return NULL;
2069 // not unfriendly
2070 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2071 if(factionTemplate->faction)
2072 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2073 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2074 return NULL;
2076 // not too far
2077 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2078 return NULL;
2080 return unit;
2083 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2085 if(GameObject *go = GetMap()->GetGameObject(guid))
2087 if(go->GetGoType() == type)
2089 float maxdist;
2090 switch(type)
2092 // TODO: find out how the client calculates the maximal usage distance to spellless working
2093 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2094 case GAMEOBJECT_TYPE_GUILD_BANK:
2095 case GAMEOBJECT_TYPE_MAILBOX:
2096 maxdist = 10.0f;
2097 break;
2098 case GAMEOBJECT_TYPE_FISHINGHOLE:
2099 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2100 break;
2101 default:
2102 maxdist = INTERACTION_DISTANCE;
2103 break;
2106 if (go->IsWithinDistInMap(this, maxdist))
2107 return go;
2109 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2110 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2113 return NULL;
2116 bool Player::IsUnderWater() const
2118 return IsInWater() &&
2119 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2122 void Player::SetInWater(bool apply)
2124 if(m_isInWater==apply)
2125 return;
2127 //define player in water by opcodes
2128 //move player's guid into HateOfflineList of those mobs
2129 //which can't swim and move guid back into ThreatList when
2130 //on surface.
2131 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2132 m_isInWater = apply;
2134 // remove auras that need water/land
2135 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2137 getHostilRefManager().updateThreatTables();
2140 void Player::SetGameMaster(bool on)
2142 if(on)
2144 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2145 setFaction(35);
2146 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2148 if (Pet* pet = GetPet())
2150 pet->setFaction(35);
2151 pet->getHostilRefManager().setOnlineOfflineState(false);
2154 for (int8 i = 0; i < MAX_TOTEM; ++i)
2155 if(m_TotemSlot[i])
2156 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2157 totem->setFaction(35);
2159 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2160 ResetContestedPvP();
2162 getHostilRefManager().setOnlineOfflineState(false);
2163 CombatStopWithPets();
2165 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2167 else
2169 // restore phase
2170 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2171 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2173 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2174 setFactionForRace(getRace());
2175 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2177 if (Pet* pet = GetPet())
2179 pet->setFaction(getFaction());
2180 pet->getHostilRefManager().setOnlineOfflineState(true);
2183 for (int8 i = 0; i < MAX_TOTEM; ++i)
2184 if(m_TotemSlot[i])
2185 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2186 totem->setFaction(getFaction());
2188 // restore FFA PvP Server state
2189 if(sWorld.IsFFAPvPRealm())
2190 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2192 // restore FFA PvP area state, remove not allowed for GM mounts
2193 UpdateArea(m_areaUpdateId);
2195 getHostilRefManager().setOnlineOfflineState(true);
2198 ObjectAccessor::UpdateVisibilityForPlayer(this);
2201 void Player::SetGMVisible(bool on)
2203 if(on)
2205 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2207 // Reapply stealth/invisibility if active or show if not any
2208 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2209 SetVisibility(VISIBILITY_GROUP_STEALTH);
2210 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2211 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2212 else
2213 SetVisibility(VISIBILITY_ON);
2215 else
2217 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2219 SetAcceptWhispers(false);
2220 SetGameMaster(true);
2222 SetVisibility(VISIBILITY_OFF);
2226 bool Player::IsGroupVisibleFor(Player* p) const
2228 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2230 default: return IsInSameGroupWith(p);
2231 case 1: return IsInSameRaidWith(p);
2232 case 2: return GetTeam()==p->GetTeam();
2236 bool Player::IsInSameGroupWith(Player const* p) const
2238 return p==this || GetGroup() != NULL &&
2239 GetGroup() == p->GetGroup() &&
2240 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2243 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2244 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2245 void Player::UninviteFromGroup()
2247 Group* group = GetGroupInvite();
2248 if(!group)
2249 return;
2251 group->RemoveInvite(this);
2253 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2255 if(group->IsCreated())
2257 group->Disband(true);
2258 objmgr.RemoveGroup(group);
2260 else
2261 group->RemoveAllInvites();
2263 delete group;
2267 void Player::RemoveFromGroup(Group* group, uint64 guid)
2269 if(group)
2271 if (group->RemoveMember(guid, 0) <= 1)
2273 // group->Disband(); already disbanded in RemoveMember
2274 objmgr.RemoveGroup(group);
2275 delete group;
2276 // removemember sets the player's group pointer to NULL
2281 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2283 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2284 data << uint64(victim ? victim->GetGUID() : 0); // guid
2285 data << uint32(GivenXP+RestXP); // given experience
2286 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2287 if(victim)
2289 data << uint32(GivenXP); // experience without rested bonus
2290 data << float(1); // 1 - none 0 - 100% group bonus output
2292 data << uint8(0); // new 2.4.0
2293 GetSession()->SendPacket(&data);
2296 void Player::GiveXP(uint32 xp, Unit* victim)
2298 if ( xp < 1 )
2299 return;
2301 if(!isAlive())
2302 return;
2304 uint32 level = getLevel();
2306 // XP to money conversion processed in Player::RewardQuest
2307 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2308 return;
2310 // handle SPELL_AURA_MOD_XP_PCT auras
2311 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2312 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2313 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2315 // XP resting bonus for kill
2316 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2318 SendLogXPGain(xp,victim,rested_bonus_xp);
2320 uint32 curXP = GetUInt32Value(PLAYER_XP);
2321 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2322 uint32 newXP = curXP + xp + rested_bonus_xp;
2324 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2326 newXP -= nextLvlXP;
2328 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2329 GiveLevel(level + 1);
2331 level = getLevel();
2332 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2335 SetUInt32Value(PLAYER_XP, newXP);
2338 // Update player to next level
2339 // Current player experience not update (must be update by caller)
2340 void Player::GiveLevel(uint32 level)
2342 if ( level == getLevel() )
2343 return;
2345 PlayerLevelInfo info;
2346 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2348 PlayerClassLevelInfo classInfo;
2349 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2351 // send levelup info to client
2352 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2353 data << uint32(level);
2354 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2355 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2356 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2357 data << uint32(0);
2358 data << uint32(0);
2359 data << uint32(0);
2360 data << uint32(0);
2361 data << uint32(0);
2362 data << uint32(0);
2363 // end for
2364 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2365 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2367 GetSession()->SendPacket(&data);
2369 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2371 //update level, max level of skills
2372 if(getLevel()!= level)
2373 m_Played_time[1] = 0; // Level Played Time reset
2374 SetLevel(level);
2375 UpdateSkillsForLevel ();
2377 // save base values (bonuses already included in stored stats
2378 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2379 SetCreateStat(Stats(i), info.stats[i]);
2381 SetCreateHealth(classInfo.basehealth);
2382 SetCreateMana(classInfo.basemana);
2384 InitTalentForLevel();
2385 InitTaxiNodesForLevel();
2386 InitGlyphsForLevel();
2388 UpdateAllStats();
2390 // set current level health and mana/energy to maximum after applying all mods.
2391 SetHealth(GetMaxHealth());
2392 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2393 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2394 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2395 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2396 SetPower(POWER_FOCUS, 0);
2397 SetPower(POWER_HAPPINESS, 0);
2399 // update level to hunter/summon pet
2400 if (Pet* pet = GetPet())
2401 pet->SynchronizeLevelWithOwner();
2403 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2406 void Player::InitTalentForLevel()
2408 uint32 level = getLevel();
2409 // talents base at level diff ( talents = level - 9 but some can be used already)
2410 if(level < 10)
2412 // Remove all talent points
2413 if(m_usedTalentCount > 0) // Free any used talents
2415 resetTalents(true);
2416 SetFreeTalentPoints(0);
2419 else
2421 uint32 talentPointsForLevel = CalculateTalentsPoints();
2423 // if used more that have then reset
2424 if(m_usedTalentCount > talentPointsForLevel)
2426 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2427 resetTalents(true);
2428 else
2429 SetFreeTalentPoints(0);
2431 // else update amount of free points
2432 else
2433 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2436 if(!GetSession()->PlayerLoading())
2437 SendTalentsInfoData(false); // update at client
2440 void Player::InitStatsForLevel(bool reapplyMods)
2442 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2443 _RemoveAllStatBonuses();
2445 PlayerClassLevelInfo classInfo;
2446 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2448 PlayerLevelInfo info;
2449 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2451 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2452 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2454 UpdateSkillsForLevel ();
2456 // set default cast time multiplier
2457 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2459 // reset size before reapply auras
2460 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2462 // save base values (bonuses already included in stored stats
2463 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2464 SetCreateStat(Stats(i), info.stats[i]);
2466 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2467 SetStat(Stats(i), info.stats[i]);
2469 SetCreateHealth(classInfo.basehealth);
2471 //set create powers
2472 SetCreateMana(classInfo.basemana);
2474 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2476 InitStatBuffMods();
2478 //reset rating fields values
2479 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2480 SetUInt32Value(index, 0);
2482 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2483 for (int i = 0; i < 7; ++i)
2485 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2486 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2487 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2490 //reset attack power, damage and attack speed fields
2491 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2492 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2493 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2495 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2496 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2497 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2498 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2499 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2500 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2502 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2503 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2504 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2505 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2506 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2507 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2509 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2510 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2511 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2512 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2514 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2515 for (uint8 i = 0; i < 7; ++i)
2516 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2518 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2519 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2520 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2522 // Dodge percentage
2523 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2525 // set armor (resistance 0) to original value (create_agility*2)
2526 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2527 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2528 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2529 // set other resistance to original value (0)
2530 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2532 SetResistance(SpellSchools(i), 0);
2533 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2534 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2537 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2538 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2539 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2541 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2542 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2544 // Reset no reagent cost field
2545 for(int i = 0; i < 3; ++i)
2546 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2547 // Init data for form but skip reapply item mods for form
2548 InitDataForForm(reapplyMods);
2550 // save new stats
2551 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2552 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2554 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2556 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2557 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2559 // cleanup unit flags (will be re-applied if need at aura load).
2560 RemoveFlag( UNIT_FIELD_FLAGS,
2561 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2562 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2563 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2564 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2565 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2566 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2568 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2570 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2571 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2573 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2574 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2576 // restore if need some important flags
2577 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2579 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2580 _ApplyAllStatBonuses();
2582 // set current level health and mana/energy to maximum after applying all mods.
2583 SetHealth(GetMaxHealth());
2584 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2585 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2586 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2587 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2588 SetPower(POWER_FOCUS, 0);
2589 SetPower(POWER_HAPPINESS, 0);
2590 SetPower(POWER_RUNIC_POWER, 0);
2592 // update level to hunter/summon pet
2593 if (Pet* pet = GetPet())
2594 pet->SynchronizeLevelWithOwner();
2597 void Player::SendInitialSpells()
2599 time_t curTime = time(NULL);
2600 time_t infTime = curTime + infinityCooldownDelayCheck;
2602 uint16 spellCount = 0;
2604 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2605 data << uint8(0);
2607 size_t countPos = data.wpos();
2608 data << uint16(spellCount); // spell count placeholder
2610 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2612 if(itr->second->state == PLAYERSPELL_REMOVED)
2613 continue;
2615 if(!itr->second->active || itr->second->disabled)
2616 continue;
2618 data << uint32(itr->first);
2619 data << uint16(0); // it's not slot id
2621 spellCount +=1;
2624 data.put<uint16>(countPos,spellCount); // write real count value
2626 uint16 spellCooldowns = m_spellCooldowns.size();
2627 data << uint16(spellCooldowns);
2628 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2630 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2631 if(!sEntry)
2632 continue;
2634 data << uint32(itr->first);
2636 data << uint16(itr->second.itemid); // cast item id
2637 data << uint16(sEntry->Category); // spell category
2639 // send infinity cooldown in special format
2640 if(itr->second.end >= infTime)
2642 data << uint32(1); // cooldown
2643 data << uint32(0x80000000); // category cooldown
2644 continue;
2647 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2649 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2651 data << uint32(0); // cooldown
2652 data << uint32(cooldown); // category cooldown
2654 else
2656 data << uint32(cooldown); // cooldown
2657 data << uint32(0); // category cooldown
2661 GetSession()->SendPacket(&data);
2663 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2666 void Player::RemoveMail(uint32 id)
2668 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2670 if ((*itr)->messageID == id)
2672 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2673 m_mail.erase(itr);
2674 return;
2679 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2681 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2682 data << (uint32) mailId;
2683 data << (uint32) mailAction;
2684 data << (uint32) mailError;
2685 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2686 data << (uint32) equipError;
2687 else if( mailAction == MAIL_ITEM_TAKEN )
2689 data << (uint32) item_guid; // item guid low?
2690 data << (uint32) item_count; // item count?
2692 GetSession()->SendPacket(&data);
2695 void Player::SendNewMail()
2697 // deliver undelivered mail
2698 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2699 data << (uint32) 0;
2700 GetSession()->SendPacket(&data);
2703 void Player::UpdateNextMailTimeAndUnreads()
2705 // calculate next delivery time (min. from non-delivered mails
2706 // and recalculate unReadMail
2707 time_t cTime = time(NULL);
2708 m_nextMailDelivereTime = 0;
2709 unReadMails = 0;
2710 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2712 if((*itr)->deliver_time > cTime)
2714 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2715 m_nextMailDelivereTime = (*itr)->deliver_time;
2717 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2718 ++unReadMails;
2722 void Player::AddNewMailDeliverTime(time_t deliver_time)
2724 if(deliver_time <= time(NULL)) // ready now
2726 ++unReadMails;
2727 SendNewMail();
2729 else // not ready and no have ready mails
2731 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2732 m_nextMailDelivereTime = deliver_time;
2736 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2738 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2739 if (!spellInfo)
2741 // do character spell book cleanup (all characters)
2742 if(!IsInWorld() && !learning) // spell load case
2744 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2745 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2747 else
2748 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2750 return false;
2753 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2755 // do character spell book cleanup (all characters)
2756 if(!IsInWorld() && !learning) // spell load case
2758 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2759 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2761 else
2762 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2764 return false;
2767 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2769 bool dependent_set = false;
2770 bool disabled_case = false;
2771 bool superceded_old = false;
2773 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2774 if (itr != m_spells.end())
2776 uint32 next_active_spell_id = 0;
2777 // fix activate state for non-stackable low rank (and find next spell for !active case)
2778 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2780 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2781 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2783 if(HasSpell(next_itr->second))
2785 // high rank already known so this must !active
2786 active = false;
2787 next_active_spell_id = next_itr->second;
2788 break;
2793 // not do anything if already known in expected state
2794 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2795 itr->second->dependent == dependent && itr->second->disabled == disabled)
2797 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2798 itr->second->state = PLAYERSPELL_UNCHANGED;
2800 return false;
2803 // dependent spell known as not dependent, overwrite state
2804 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2806 itr->second->dependent = dependent;
2807 if (itr->second->state != PLAYERSPELL_NEW)
2808 itr->second->state = PLAYERSPELL_CHANGED;
2809 dependent_set = true;
2812 // update active state for known spell
2813 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2815 itr->second->active = active;
2817 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2818 itr->second->state = PLAYERSPELL_UNCHANGED;
2819 else if(itr->second->state != PLAYERSPELL_NEW)
2820 itr->second->state = PLAYERSPELL_CHANGED;
2822 if(active)
2824 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2825 CastSpell (this,spell_id,true);
2827 else if(IsInWorld())
2829 if(next_active_spell_id)
2831 // update spell ranks in spellbook and action bar
2832 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2833 data << uint32(spell_id);
2834 data << uint32(next_active_spell_id);
2835 GetSession()->SendPacket( &data );
2837 else
2839 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2840 data << uint32(spell_id);
2841 GetSession()->SendPacket(&data);
2845 return active; // learn (show in spell book if active now)
2848 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2850 if(itr->second->state != PLAYERSPELL_NEW)
2851 itr->second->state = PLAYERSPELL_CHANGED;
2852 itr->second->disabled = disabled;
2854 if(disabled)
2855 return false;
2857 disabled_case = true;
2859 else switch(itr->second->state)
2861 case PLAYERSPELL_UNCHANGED: // known saved spell
2862 return false;
2863 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2865 delete itr->second;
2866 m_spells.erase(itr);
2867 state = PLAYERSPELL_CHANGED;
2868 break; // need re-add
2870 default: // known not saved yet spell (new or modified)
2872 // can be in case spell loading but learned at some previous spell loading
2873 if(!IsInWorld() && !learning && !dependent_set)
2874 itr->second->state = PLAYERSPELL_UNCHANGED;
2876 return false;
2881 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2883 // talent: unlearn all other talent ranks (high and low)
2884 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2886 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2888 for(int i=0; i < MAX_TALENT_RANK; ++i)
2890 // skip learning spell and no rank spell case
2891 uint32 rankSpellId = talentInfo->RankID[i];
2892 if(!rankSpellId || rankSpellId==spell_id)
2893 continue;
2895 removeSpell(rankSpellId,false,false);
2899 // non talent spell: learn low ranks (recursive call)
2900 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2902 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2903 addSpell(prev_spell,active,true,true,disabled);
2904 else // at normal learning
2905 learnSpell(prev_spell,true);
2908 PlayerSpell *newspell = new PlayerSpell;
2909 newspell->state = state;
2910 newspell->active = active;
2911 newspell->dependent = dependent;
2912 newspell->disabled = disabled;
2914 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2915 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2917 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2919 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2920 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2921 if(!i_spellInfo) continue;
2923 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2925 if(itr2->second->active)
2927 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2929 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2931 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2932 data << uint32(itr2->first);
2933 data << uint32(spell_id);
2934 GetSession()->SendPacket( &data );
2937 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2938 itr2->second->active = false;
2939 if(itr2->second->state != PLAYERSPELL_NEW)
2940 itr2->second->state = PLAYERSPELL_CHANGED;
2941 superceded_old = true; // new spell replace old in action bars and spell book.
2943 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2945 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2947 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2948 data << uint32(spell_id);
2949 data << uint32(itr2->first);
2950 GetSession()->SendPacket( &data );
2953 // mark new spell as disable (not learned yet for client and will not learned)
2954 newspell->active = false;
2955 if(newspell->state != PLAYERSPELL_NEW)
2956 newspell->state = PLAYERSPELL_CHANGED;
2963 m_spells[spell_id] = newspell;
2965 // return false if spell disabled
2966 if (newspell->disabled)
2967 return false;
2970 uint32 talentCost = GetTalentSpellCost(spell_id);
2972 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2973 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2974 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2976 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2977 CastSpell(this, spell_id, true);
2979 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2980 else if (IsPassiveSpell(spell_id))
2982 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2983 CastSpell(this, spell_id, true);
2985 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2987 CastSpell(this, spell_id, true);
2988 return false;
2991 // update used talent points count
2992 m_usedTalentCount += talentCost;
2994 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2995 if(uint32 freeProfs = GetFreePrimaryProfessionPoints())
2997 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2998 SetFreePrimaryProfessions(freeProfs-1);
3001 // add dependent skills
3002 uint16 maxskill = GetMaxSkillValueForLevel();
3004 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3006 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3007 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3009 if(spellLearnSkill)
3011 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3012 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3014 if(skill_value < spellLearnSkill->value)
3015 skill_value = spellLearnSkill->value;
3017 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3019 if(skill_max_value < new_skill_max_value)
3020 skill_max_value = new_skill_max_value;
3022 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3024 else
3026 // not ranked skills
3027 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3029 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3030 if(!pSkill)
3031 continue;
3033 if(HasSkill(pSkill->id))
3034 continue;
3036 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3037 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3038 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3040 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3042 case SKILL_RANGE_LANGUAGE:
3043 SetSkill(pSkill->id, 300, 300 );
3044 break;
3045 case SKILL_RANGE_LEVEL:
3046 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3047 break;
3048 case SKILL_RANGE_MONO:
3049 SetSkill(pSkill->id, 1, 1 );
3050 break;
3051 default:
3052 break;
3058 // learn dependent spells
3059 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3060 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3062 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3064 if(!itr2->second.autoLearned)
3066 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3067 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3068 else // at normal learning
3069 learnSpell(itr2->second.spell,true);
3073 if(!GetSession()->PlayerLoading())
3075 // not ranked skills
3076 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3078 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3079 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3082 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3085 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3086 return active && !disabled && !superceded_old;
3089 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3091 bool need_cast = false;
3093 switch(spellInfo->Id)
3095 // some spells not have stance data expected cast at form change or present
3096 case 5420: need_cast = (m_form == FORM_TREE); break;
3097 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
3098 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
3099 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
3100 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
3101 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
3102 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
3103 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
3104 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3105 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3106 // another spells have proper stance data
3107 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
3110 //Check CasterAuraStates
3111 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3114 void Player::learnSpell(uint32 spell_id, bool dependent)
3116 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3118 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3119 bool active = disabled ? itr->second->active : true;
3121 bool learning = addSpell(spell_id,active,true,dependent,false);
3123 // learn all disabled higher ranks (recursive)
3124 if(disabled)
3126 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3127 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3129 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3130 if (iter != m_spells.end() && iter->second->disabled)
3131 learnSpell(i->second,false);
3135 // prevent duplicated entires in spell book, also not send if not in world (loading)
3136 if(!learning || !IsInWorld ())
3137 return;
3139 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3140 data << uint32(spell_id);
3141 GetSession()->SendPacket(&data);
3144 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
3146 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3147 if (itr == m_spells.end())
3148 return;
3150 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3151 return;
3153 // unlearn non talent higher ranks (recursive)
3154 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3155 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3156 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3157 removeSpell(itr2->second,disabled,false);
3159 // re-search, it can be corrupted in prev loop
3160 itr = m_spells.find(spell_id);
3161 if (itr == m_spells.end())
3162 return; // already unleared
3164 bool cur_active = itr->second->active;
3165 bool cur_dependent = itr->second->dependent;
3167 if (disabled)
3169 itr->second->disabled = disabled;
3170 if(itr->second->state != PLAYERSPELL_NEW)
3171 itr->second->state = PLAYERSPELL_CHANGED;
3173 else
3175 if(itr->second->state == PLAYERSPELL_NEW)
3177 delete itr->second;
3178 m_spells.erase(itr);
3180 else
3181 itr->second->state = PLAYERSPELL_REMOVED;
3184 RemoveAurasDueToSpell(spell_id);
3186 // remove pet auras
3187 for(int i = 0; i < 3; ++i)
3188 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id, i))
3189 RemovePetAura(petSpell);
3191 // free talent points
3192 uint32 talentCosts = GetTalentSpellCost(spell_id);
3193 if(talentCosts > 0)
3195 if(talentCosts < m_usedTalentCount)
3196 m_usedTalentCount -= talentCosts;
3197 else
3198 m_usedTalentCount = 0;
3201 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3202 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3204 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3205 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3206 SetFreePrimaryProfessions(freeProfs);
3209 // remove dependent skill
3210 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3211 if(spellLearnSkill)
3213 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3214 if(!prev_spell) // first rank, remove skill
3215 SetSkill(spellLearnSkill->skill,0,0);
3216 else
3218 // search prev. skill setting by spell ranks chain
3219 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3220 while(!prevSkill && prev_spell)
3222 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3223 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3226 if(!prevSkill) // not found prev skill setting, remove skill
3227 SetSkill(spellLearnSkill->skill,0,0);
3228 else // set to prev. skill setting values
3230 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3231 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3233 if(skill_value > prevSkill->value)
3234 skill_value = prevSkill->value;
3236 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3238 if(skill_max_value > new_skill_max_value)
3239 skill_max_value = new_skill_max_value;
3241 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3246 else
3248 // not ranked skills
3249 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3250 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3252 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3254 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3255 if(!pSkill)
3256 continue;
3258 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3259 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3260 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3262 // not reset skills for professions and racial abilities
3263 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3264 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3265 continue;
3267 SetSkill(pSkill->id, 0, 0 );
3272 // remove dependent spells
3273 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3274 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3276 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3277 removeSpell(itr2->second.spell, disabled);
3279 // activate lesser rank in spellbook/action bar, and cast it if need
3280 bool prev_activate = false;
3282 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3284 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3286 // if talent then lesser rank also talent and need learn
3287 if(talentCosts)
3289 if(learn_low_rank)
3290 learnSpell (prev_id,false);
3292 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3293 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3295 // need manually update dependence state (learn spell ignore like attempts)
3296 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3297 if (prev_itr != m_spells.end())
3299 if(prev_itr->second->dependent != cur_dependent)
3301 prev_itr->second->dependent = cur_dependent;
3302 if(prev_itr->second->state != PLAYERSPELL_NEW)
3303 prev_itr->second->state = PLAYERSPELL_CHANGED;
3306 // now re-learn if need re-activate
3307 if(cur_active && !prev_itr->second->active && learn_low_rank)
3309 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3311 // downgrade spell ranks in spellbook and action bar
3312 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3313 data << uint32(spell_id);
3314 data << uint32(prev_id);
3315 GetSession()->SendPacket( &data );
3316 prev_activate = true;
3323 // remove from spell book if not replaced by lesser rank
3324 if(!prev_activate)
3326 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3327 data << uint32(spell_id);
3328 GetSession()->SendPacket(&data);
3332 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3334 m_spellCooldowns.erase(spell_id);
3336 if(update)
3337 SendClearCooldown(spell_id, this);
3340 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3342 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3343 if (ct == sSpellCategoryStore.end())
3344 return;
3346 const SpellCategorySet& ct_set = ct->second;
3347 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3349 if (ct_set.find(i->first) != ct_set.end())
3350 RemoveSpellCooldown((i++)->first, update);
3351 else
3352 ++i;
3356 void Player::RemoveArenaSpellCooldowns()
3358 // remove cooldowns on spells that has < 15 min CD
3359 SpellCooldowns::iterator itr, next;
3360 // iterate spell cooldowns
3361 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3363 next = itr;
3364 ++next;
3365 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3366 // check if spellentry is present and if the cooldown is less than 15 mins
3367 if( entry &&
3368 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3369 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3371 // remove & notify
3372 RemoveSpellCooldown(itr->first, true);
3377 void Player::RemoveAllSpellCooldown()
3379 if(!m_spellCooldowns.empty())
3381 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3382 SendClearCooldown(itr->first, this);
3384 m_spellCooldowns.clear();
3388 void Player::_LoadSpellCooldowns(QueryResult *result)
3390 // some cooldowns can be already set at aura loading...
3392 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3394 if(result)
3396 time_t curTime = time(NULL);
3400 Field *fields = result->Fetch();
3402 uint32 spell_id = fields[0].GetUInt32();
3403 uint32 item_id = fields[1].GetUInt32();
3404 time_t db_time = (time_t)fields[2].GetUInt64();
3406 if(!sSpellStore.LookupEntry(spell_id))
3408 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3409 continue;
3412 // skip outdated cooldown
3413 if(db_time <= curTime)
3414 continue;
3416 AddSpellCooldown(spell_id, item_id, db_time);
3418 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3420 while( result->NextRow() );
3422 delete result;
3426 void Player::_SaveSpellCooldowns()
3428 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3430 time_t curTime = time(NULL);
3431 time_t infTime = curTime + infinityCooldownDelayCheck;
3433 // remove outdated and save active
3434 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3436 if(itr->second.end <= curTime)
3437 m_spellCooldowns.erase(itr++);
3438 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3440 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" UI64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3441 ++itr;
3443 else
3444 ++itr;
3448 uint32 Player::resetTalentsCost() const
3450 // The first time reset costs 1 gold
3451 if(m_resetTalentsCost < 1*GOLD)
3452 return 1*GOLD;
3453 // then 5 gold
3454 else if(m_resetTalentsCost < 5*GOLD)
3455 return 5*GOLD;
3456 // After that it increases in increments of 5 gold
3457 else if(m_resetTalentsCost < 10*GOLD)
3458 return 10*GOLD;
3459 else
3461 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3462 if(months > 0)
3464 // This cost will be reduced by a rate of 5 gold per month
3465 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3466 // to a minimum of 10 gold.
3467 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3469 else
3471 // After that it increases in increments of 5 gold
3472 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3473 // until it hits a cap of 50 gold.
3474 if(new_cost > 50*GOLD)
3475 new_cost = 50*GOLD;
3476 return new_cost;
3481 bool Player::resetTalents(bool no_cost)
3483 // not need after this call
3484 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3485 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3487 uint32 talentPointsForLevel = CalculateTalentsPoints();
3489 if (m_usedTalentCount == 0)
3491 SetFreeTalentPoints(talentPointsForLevel);
3492 return false;
3495 uint32 cost = 0;
3497 if(!no_cost)
3499 cost = resetTalentsCost();
3501 if (GetMoney() < cost)
3503 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3504 return false;
3508 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3510 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3512 if (!talentInfo) continue;
3514 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3516 if(!talentTabInfo)
3517 continue;
3519 // unlearn only talents for character class
3520 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3521 // to prevent unexpected lost normal learned spell skip another class talents
3522 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3523 continue;
3525 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3527 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3529 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3531 ++itr;
3532 continue;
3535 // remove learned spells (all ranks)
3536 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3538 // unlearn if first rank is talent or learned by talent
3539 if (itrFirstId == talentInfo->RankID[j])
3541 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3542 itr = GetSpellMap().begin();
3543 continue;
3545 else if (spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3547 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3548 itr = GetSpellMap().begin();
3549 continue;
3551 else
3552 ++itr;
3557 SetFreeTalentPoints(talentPointsForLevel);
3559 if(!no_cost)
3561 ModifyMoney(-(int32)cost);
3562 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3563 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3565 m_resetTalentsCost = cost;
3566 m_resetTalentsTime = time(NULL);
3569 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3570 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3571 /* when prev line will dropped use next line
3572 if(Pet* pet = GetPet())
3574 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3575 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3580 if(m_canTitanGrip)
3582 m_canTitanGrip = false;
3583 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3584 AutoUnequipOffhandIfNeed();
3587 return true;
3590 Mail* Player::GetMail(uint32 id)
3592 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3594 if ((*itr)->messageID == id)
3596 return (*itr);
3599 return NULL;
3602 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3604 if(target == this)
3606 Object::_SetCreateBits(updateMask, target);
3608 else
3610 for(uint16 index = 0; index < m_valuesCount; index++)
3612 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3613 updateMask->SetBit(index);
3618 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3620 if(target == this)
3622 Object::_SetUpdateBits(updateMask, target);
3624 else
3626 Object::_SetUpdateBits(updateMask, target);
3627 *updateMask &= updateVisualBits;
3631 void Player::InitVisibleBits()
3633 updateVisualBits.SetCount(PLAYER_END);
3635 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3636 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3637 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3638 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3639 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3640 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3641 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3642 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3643 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3644 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3645 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3646 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3647 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3648 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3649 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3650 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3651 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3652 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3653 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3654 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3655 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3656 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3657 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3658 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3659 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3660 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3661 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3662 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3663 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3664 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3665 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3666 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3667 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3668 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3669 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3670 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3671 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3672 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3673 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3674 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3675 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3676 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3677 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3678 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3679 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3680 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3681 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3682 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3683 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3684 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3685 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3686 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3687 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3688 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3689 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3691 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3692 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3693 updateVisualBits.SetBit(PLAYER_FLAGS);
3694 updateVisualBits.SetBit(PLAYER_GUILDID);
3695 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3696 updateVisualBits.SetBit(PLAYER_BYTES);
3697 updateVisualBits.SetBit(PLAYER_BYTES_2);
3698 updateVisualBits.SetBit(PLAYER_BYTES_3);
3699 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3700 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3702 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3703 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3704 updateVisualBits.SetBit(i);
3706 // Players visible items are not inventory stuff
3707 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3709 uint32 offset = i * 2;
3711 // item entry
3712 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3713 // enchant
3714 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3717 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3720 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3722 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3724 if(m_items[i] == NULL)
3725 continue;
3727 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3730 if(target == this)
3732 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3734 if(m_items[i] == NULL)
3735 continue;
3737 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3739 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3741 if(m_items[i] == NULL)
3742 continue;
3744 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3748 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3751 void Player::DestroyForPlayer( Player *target ) const
3753 Unit::DestroyForPlayer( target );
3755 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3757 if(m_items[i] == NULL)
3758 continue;
3760 m_items[i]->DestroyForPlayer( target );
3763 if(target == this)
3765 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3767 if(m_items[i] == NULL)
3768 continue;
3770 m_items[i]->DestroyForPlayer( target );
3772 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3774 if(m_items[i] == NULL)
3775 continue;
3777 m_items[i]->DestroyForPlayer( target );
3782 bool Player::HasSpell(uint32 spell) const
3784 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3785 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3786 !itr->second->disabled);
3789 bool Player::HasActiveSpell(uint32 spell) const
3791 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3792 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3793 itr->second->active && !itr->second->disabled);
3796 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3798 if (!trainer_spell)
3799 return TRAINER_SPELL_RED;
3801 if (!trainer_spell->learnedSpell)
3802 return TRAINER_SPELL_RED;
3804 // known spell
3805 if(HasSpell(trainer_spell->learnedSpell))
3806 return TRAINER_SPELL_GRAY;
3808 // check race/class requirement
3809 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3810 return TRAINER_SPELL_RED;
3812 // check level requirement
3813 if(getLevel() < trainer_spell->reqLevel)
3814 return TRAINER_SPELL_RED;
3816 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3818 // check prev.rank requirement
3819 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3820 return TRAINER_SPELL_RED;
3822 // check additional spell requirement
3823 if(spell_chain->req && !HasSpell(spell_chain->req))
3824 return TRAINER_SPELL_RED;
3827 // check skill requirement
3828 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3829 return TRAINER_SPELL_RED;
3831 // exist, already checked at loading
3832 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3834 // secondary prof. or not prof. spell
3835 uint32 skill = spell->EffectMiscValue[1];
3837 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3838 return TRAINER_SPELL_GREEN;
3840 // check primary prof. limit
3841 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3842 return TRAINER_SPELL_GREEN_DISABLED;
3844 return TRAINER_SPELL_GREEN;
3847 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3849 uint32 guid = GUID_LOPART(playerguid);
3851 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3852 // bones will be deleted by corpse/bones deleting thread shortly
3853 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3855 // remove from guild
3856 uint32 guildId = GetGuildIdFromDB(playerguid);
3857 if(guildId != 0)
3859 Guild* guild = objmgr.GetGuildById(guildId);
3860 if(guild)
3861 guild->DelMember(guid);
3864 // remove from arena teams
3865 LeaveAllArenaTeams(playerguid);
3867 // the player was uninvited already on logout so just remove from group
3868 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3869 if(resultGroup)
3871 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3872 delete resultGroup;
3873 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3874 if(group)
3876 RemoveFromGroup(group, playerguid);
3880 // remove signs from petitions (also remove petitions if owner);
3881 RemovePetitionsAndSigns(playerguid, 10);
3883 // return back all mails with COD and Item 0 1 2 3 4 5 6
3884 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);
3885 if(resultMail)
3889 Field *fields = resultMail->Fetch();
3891 uint32 mail_id = fields[0].GetUInt32();
3892 uint16 mailTemplateId= fields[1].GetUInt16();
3893 uint32 sender = fields[2].GetUInt32();
3894 std::string subject = fields[3].GetCppString();
3895 uint32 itemTextId = fields[4].GetUInt32();
3896 uint32 money = fields[5].GetUInt32();
3897 bool has_items = fields[6].GetBool();
3899 //we can return mail now
3900 //so firstly delete the old one
3901 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3903 MailItemsInfo mi;
3904 if(has_items)
3906 // data needs to be at first place for Item::LoadFromDB
3907 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
3908 if(resultItems)
3912 Field *fields2 = resultItems->Fetch();
3914 uint32 item_guidlow = fields2[1].GetUInt32();
3915 uint32 item_template = fields2[2].GetUInt32();
3917 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3918 if(!itemProto)
3920 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3921 continue;
3924 Item *pItem = NewItemOrBag(itemProto);
3925 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3927 pItem->FSetState(ITEM_REMOVED);
3928 pItem->SaveToDB(); // it also deletes item object !
3929 continue;
3932 mi.AddItem(item_guidlow, item_template, pItem);
3934 while (resultItems->NextRow());
3936 delete resultItems;
3940 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3942 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3944 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3946 while (resultMail->NextRow());
3948 delete resultMail;
3951 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3952 // Get guids of character's pets, will deleted in transaction
3953 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3955 // NOW we can finally clear other DB data related to character
3956 CharacterDatabase.BeginTransaction();
3957 if (resultPets)
3961 Field *fields3 = resultPets->Fetch();
3962 uint32 petguidlow = fields3[0].GetUInt32();
3963 Pet::DeleteFromDB(petguidlow);
3964 } while (resultPets->NextRow());
3965 delete resultPets;
3968 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3969 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3970 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3971 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3972 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3973 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3974 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3975 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3976 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3977 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3978 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3979 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3980 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3981 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3982 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3983 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3984 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3985 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3986 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3987 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3988 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3989 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3990 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3991 CharacterDatabase.CommitTransaction();
3993 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3994 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3997 void Player::SetMovement(PlayerMovementType pType)
3999 WorldPacket data;
4000 switch(pType)
4002 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4003 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4004 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4005 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4006 default:
4007 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4008 return;
4010 data.append(GetPackGUID());
4011 data << uint32(0);
4012 GetSession()->SendPacket( &data );
4015 /* Preconditions:
4016 - a resurrectable corpse must not be loaded for the player (only bones)
4017 - the player must be in world
4019 void Player::BuildPlayerRepop()
4021 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4022 data.append(GetPackGUID());
4023 GetSession()->SendPacket(&data);
4025 if(getRace() == RACE_NIGHTELF)
4026 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)
4027 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4029 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4030 // there must be SMSG.STOP_MIRROR_TIMER
4031 // there we must send 888 opcode
4033 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4034 if(GetCorpse())
4036 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4037 assert(false);
4040 // create a corpse and place it at the player's location
4041 CreateCorpse();
4042 Corpse *corpse = GetCorpse();
4043 if(!corpse)
4045 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4046 return;
4048 GetMap()->Add(corpse);
4050 // convert player body to ghost
4051 SetHealth( 1 );
4053 SetMovement(MOVE_WATER_WALK);
4054 if(!GetSession()->isLogingOut())
4055 SetMovement(MOVE_UNROOT);
4057 // BG - remove insignia related
4058 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4060 SendCorpseReclaimDelay();
4062 // to prevent cheating
4063 corpse->ResetGhostTime();
4065 StopMirrorTimers(); //disable timers(bars)
4067 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4069 // set and clear other
4070 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4073 void Player::SendDelayResponse(const uint32 ml_seconds)
4075 //FIXME: is this delay time arg really need? 50msec by default in code
4076 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
4077 data << (uint32)time(NULL);
4078 data << (uint32)0;
4079 GetSession()->SendPacket( &data );
4082 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4084 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4085 data << uint32(-1);
4086 data << float(0);
4087 data << float(0);
4088 data << float(0);
4089 GetSession()->SendPacket(&data);
4091 // speed change, land walk
4093 // remove death flag + set aura
4094 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4095 if(getRace() == RACE_NIGHTELF)
4096 RemoveAurasDueToSpell(20584); // speed bonuses
4097 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4099 setDeathState(ALIVE);
4101 SetMovement(MOVE_LAND_WALK);
4102 SetMovement(MOVE_UNROOT);
4104 m_deathTimer = 0;
4106 // set health/powers (0- will be set in caller)
4107 if(restore_percent>0.0f)
4109 SetHealth(uint32(GetMaxHealth()*restore_percent));
4110 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4111 SetPower(POWER_RAGE, 0);
4112 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4115 // trigger update zone for alive state zone updates
4116 uint32 newzone, newarea;
4117 GetZoneAndAreaId(newzone,newarea);
4118 UpdateZone(newzone,newarea);
4120 // update visibility
4121 ObjectAccessor::UpdateVisibilityForPlayer(this);
4123 if(!applySickness)
4124 return;
4126 //Characters from level 1-10 are not affected by resurrection sickness.
4127 //Characters from level 11-19 will suffer from one minute of sickness
4128 //for each level they are above 10.
4129 //Characters level 20 and up suffer from ten minutes of sickness.
4130 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4132 if(int32(getLevel()) >= startLevel)
4134 // set resurrection sickness
4135 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4137 // not full duration
4138 if(int32(getLevel()) < startLevel+9)
4140 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4142 for(int i =0; i < 3; ++i)
4144 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4146 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4147 Aur->SendAuraUpdate(false);
4154 void Player::KillPlayer()
4156 SetMovement(MOVE_ROOT);
4158 StopMirrorTimers(); //disable timers(bars)
4160 setDeathState(CORPSE);
4161 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4163 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4164 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4166 // 6 minutes until repop at graveyard
4167 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4169 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4171 // don't create corpse at this moment, player might be falling
4173 // update visibility
4174 ObjectAccessor::UpdateObjectVisibility(this);
4177 void Player::CreateCorpse()
4179 // prevent existence 2 corpse for player
4180 SpawnCorpseBones();
4182 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4184 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4185 SetPvPDeath(false);
4187 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4189 delete corpse;
4190 return;
4193 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4194 _pb = GetUInt32Value(PLAYER_BYTES);
4195 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4197 uint8 race = (uint8)(_uf);
4198 uint8 skin = (uint8)(_pb);
4199 uint8 face = (uint8)(_pb >> 8);
4200 uint8 hairstyle = (uint8)(_pb >> 16);
4201 uint8 haircolor = (uint8)(_pb >> 24);
4202 uint8 facialhair = (uint8)(_pb2);
4204 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4205 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4207 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4208 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4210 uint32 flags = CORPSE_FLAG_UNK2;
4211 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4212 flags |= CORPSE_FLAG_HIDE_HELM;
4213 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4214 flags |= CORPSE_FLAG_HIDE_CLOAK;
4215 if(InBattleGround() && !InArena())
4216 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4217 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4219 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4221 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4223 uint32 iDisplayID;
4224 uint16 iIventoryType;
4225 uint32 _cfi;
4226 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4228 if(m_items[i])
4230 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4231 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4233 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4234 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4238 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4239 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4240 assert(entry);
4241 if(entry->map_type != MAP_BATTLEGROUND)
4242 corpse->SaveToDB();
4244 // register for player, but not show
4245 ObjectAccessor::Instance().AddCorpse(corpse);
4248 void Player::SpawnCorpseBones()
4250 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4251 SaveToDB(); // prevent loading as ghost without corpse
4254 Corpse* Player::GetCorpse() const
4256 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4259 void Player::DurabilityLossAll(double percent, bool inventory)
4261 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4262 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4263 DurabilityLoss(pItem,percent);
4265 if(inventory)
4267 // bags not have durability
4268 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4270 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4271 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4272 DurabilityLoss(pItem,percent);
4274 // keys not have durability
4275 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4277 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4278 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4279 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4280 if(Item* pItem = GetItemByPos( i, j ))
4281 DurabilityLoss(pItem,percent);
4285 void Player::DurabilityLoss(Item* item, double percent)
4287 if(!item )
4288 return;
4290 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4292 if(!pMaxDurability)
4293 return;
4295 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4297 if(pDurabilityLoss < 1 )
4298 pDurabilityLoss = 1;
4300 DurabilityPointsLoss(item,pDurabilityLoss);
4303 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4305 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4306 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4307 DurabilityPointsLoss(pItem,points);
4309 if(inventory)
4311 // bags not have durability
4312 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4314 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4315 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4316 DurabilityPointsLoss(pItem,points);
4318 // keys not have durability
4319 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4321 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4322 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4323 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4324 if(Item* pItem = GetItemByPos( i, j ))
4325 DurabilityPointsLoss(pItem,points);
4329 void Player::DurabilityPointsLoss(Item* item, int32 points)
4331 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4332 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4333 int32 pNewDurability = pOldDurability - points;
4335 if (pNewDurability < 0)
4336 pNewDurability = 0;
4337 else if (pNewDurability > pMaxDurability)
4338 pNewDurability = pMaxDurability;
4340 if (pOldDurability != pNewDurability)
4342 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4343 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4344 _ApplyItemMods(item,item->GetSlot(), false);
4346 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4348 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4349 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4350 _ApplyItemMods(item,item->GetSlot(), true);
4352 item->SetState(ITEM_CHANGED, this);
4356 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4358 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4359 DurabilityPointsLoss(pItem,1);
4362 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4364 uint32 TotalCost = 0;
4365 // equipped, backpack, bags itself
4366 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4367 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4369 // bank, buyback and keys not repaired
4371 // items in inventory bags
4372 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4373 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4374 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4375 return TotalCost;
4378 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4380 Item* item = GetItemByPos(pos);
4382 uint32 TotalCost = 0;
4383 if(!item)
4384 return TotalCost;
4386 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4387 if(!maxDurability)
4388 return TotalCost;
4390 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4392 if(cost)
4394 uint32 LostDurability = maxDurability - curDurability;
4395 if(LostDurability>0)
4397 ItemPrototype const *ditemProto = item->GetProto();
4399 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4400 if(!dcost)
4402 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4403 return TotalCost;
4406 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4407 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4408 if(!dQualitymodEntry)
4410 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4411 return TotalCost;
4414 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4415 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4417 costs = uint32(costs * discountMod);
4419 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4420 costs = 1;
4422 if (guildBank)
4424 if (GetGuildId()==0)
4426 DEBUG_LOG("You are not member of a guild");
4427 return TotalCost;
4430 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4431 if (!pGuild)
4432 return TotalCost;
4434 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4436 DEBUG_LOG("You do not have rights to withdraw for repairs");
4437 return TotalCost;
4440 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4442 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4443 return TotalCost;
4446 if (pGuild->GetGuildBankMoney() < costs)
4448 DEBUG_LOG("There is not enough money in bank");
4449 return TotalCost;
4452 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4453 TotalCost = costs;
4455 else if (GetMoney() < costs)
4457 DEBUG_LOG("You do not have enough money");
4458 return TotalCost;
4460 else
4461 ModifyMoney( -int32(costs) );
4465 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4466 item->SetState(ITEM_CHANGED, this);
4468 // reapply mods for total broken and repaired item if equipped
4469 if(IsEquipmentPos(pos) && !curDurability)
4470 _ApplyItemMods(item,pos & 255, true);
4471 return TotalCost;
4474 void Player::RepopAtGraveyard()
4476 // note: this can be called also when the player is alive
4477 // for example from WorldSession::HandleMovementOpcodes
4479 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4481 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4482 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4484 ResurrectPlayer(0.5f);
4485 SpawnCorpseBones();
4488 WorldSafeLocsEntry const *ClosestGrave = NULL;
4490 // Special handle for battleground maps
4491 if( BattleGround *bg = GetBattleGround() )
4492 ClosestGrave = bg->GetClosestGraveYard(this);
4493 else
4494 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4496 // stop countdown until repop
4497 m_deathTimer = 0;
4499 // if no grave found, stay at the current location
4500 // and don't show spirit healer location
4501 if(ClosestGrave)
4503 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4504 if(isDead()) // not send if alive, because it used in TeleportTo()
4506 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4507 data << ClosestGrave->map_id;
4508 data << ClosestGrave->x;
4509 data << ClosestGrave->y;
4510 data << ClosestGrave->z;
4511 GetSession()->SendPacket(&data);
4516 void Player::JoinedChannel(Channel *c)
4518 m_channels.push_back(c);
4521 void Player::LeftChannel(Channel *c)
4523 m_channels.remove(c);
4526 void Player::CleanupChannels()
4528 while(!m_channels.empty())
4530 Channel* ch = *m_channels.begin();
4531 m_channels.erase(m_channels.begin()); // remove from player's channel list
4532 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4533 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4534 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4537 sLog.outDebug("Player: channels cleaned up!");
4540 void Player::UpdateLocalChannels(uint32 newZone )
4542 if(m_channels.empty())
4543 return;
4545 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4546 if(!current_zone)
4547 return;
4549 ChannelMgr* cMgr = channelMgr(GetTeam());
4550 if(!cMgr)
4551 return;
4553 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4555 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4557 next = i; ++next;
4559 // skip non built-in channels
4560 if(!(*i)->IsConstant())
4561 continue;
4563 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4564 if(!ch)
4565 continue;
4567 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4568 continue;
4570 // new channel
4571 char new_channel_name_buf[100];
4572 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4573 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4575 if((*i)!=new_channel)
4577 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4579 // leave old channel
4580 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4581 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4582 LeftChannel(*i); // remove from player's channel list
4583 cMgr->LeftChannel(name); // delete if empty
4586 sLog.outDebug("Player: channels cleaned up!");
4589 void Player::LeaveLFGChannel()
4591 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4593 if((*i)->IsLFG())
4595 (*i)->Leave(GetGUID());
4596 break;
4601 void Player::UpdateDefense()
4603 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4605 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4607 // update dependent from defense skill part
4608 UpdateDefenseBonusesMod();
4612 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4614 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4616 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4617 return;
4620 float val = 1.0f;
4622 switch(modType)
4624 case FLAT_MOD:
4625 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4626 break;
4627 case PCT_MOD:
4628 if(amount <= -100.0f)
4629 amount = -200.0f;
4631 val = (100.0f + amount) / 100.0f;
4632 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4633 break;
4636 if(!CanModifyStats())
4637 return;
4639 switch(modGroup)
4641 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4642 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4643 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4644 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4645 default: break;
4649 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4651 if(modGroup >= BASEMOD_END || modType > MOD_END)
4653 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4654 return 0.0f;
4657 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4658 return 0.0f;
4660 return m_auraBaseMod[modGroup][modType];
4663 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4665 if(modGroup >= BASEMOD_END)
4667 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4668 return 0.0f;
4671 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4672 return 0.0f;
4674 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4677 uint32 Player::GetShieldBlockValue() const
4679 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4681 value = (value < 0) ? 0 : value;
4683 return uint32(value);
4686 float Player::GetMeleeCritFromAgility()
4688 uint32 level = getLevel();
4689 uint32 pclass = getClass();
4691 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4693 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4694 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4695 if (critBase==NULL || critRatio==NULL)
4696 return 0.0f;
4698 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4699 return crit*100.0f;
4702 float Player::GetDodgeFromAgility()
4704 // Table for base dodge values
4705 float dodge_base[MAX_CLASSES] = {
4706 0.0075f, // Warrior
4707 0.00652f, // Paladin
4708 -0.0545f, // Hunter
4709 -0.0059f, // Rogue
4710 0.03183f, // Priest
4711 0.0114f, // DK
4712 0.0167f, // Shaman
4713 0.034575f, // Mage
4714 0.02011f, // Warlock
4715 0.0f, // ??
4716 -0.0187f // Druid
4718 // Crit/agility to dodge/agility coefficient multipliers
4719 float crit_to_dodge[MAX_CLASSES] = {
4720 1.1f, // Warrior
4721 1.0f, // Paladin
4722 1.6f, // Hunter
4723 2.0f, // Rogue
4724 1.0f, // Priest
4725 1.0f, // DK?
4726 1.0f, // Shaman
4727 1.0f, // Mage
4728 1.0f, // Warlock
4729 0.0f, // ??
4730 1.7f // Druid
4733 uint32 level = getLevel();
4734 uint32 pclass = getClass();
4736 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4738 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4739 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4740 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4741 return 0.0f;
4743 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4744 return dodge*100.0f;
4747 float Player::GetSpellCritFromIntellect()
4749 uint32 level = getLevel();
4750 uint32 pclass = getClass();
4752 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4754 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4755 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4756 if (critBase==NULL || critRatio==NULL)
4757 return 0.0f;
4759 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4760 return crit*100.0f;
4763 float Player::GetRatingCoefficient(CombatRating cr) const
4765 uint32 level = getLevel();
4767 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4769 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4770 if (Rating == NULL)
4771 return 1.0f; // By default use minimum coefficient (not must be called)
4773 return Rating->ratio;
4776 float Player::GetRatingBonusValue(CombatRating cr) const
4778 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4781 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4783 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4784 if (melee>33.0f) melee = 33.0f;
4785 return uint32 (melee * damage /100.0f);
4788 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4790 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4791 if (ranged>33.0f) ranged=33.0f;
4792 return uint32 (ranged * damage /100.0f);
4795 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4797 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4798 // In wow script resilience limited to 33%
4799 if (spell>33.0f)
4800 spell = 33.0f;
4801 return uint32 (spell * damage / 100.0f);
4804 uint32 Player::GetDotDamageReduction(uint32 damage) const
4806 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4807 // Dot resilience not limited (limit it by 100%)
4808 if (spellDot > 100.0f)
4809 spellDot = 100.0f;
4810 return uint32 (spellDot * damage / 100.0f);
4813 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4815 switch (attType)
4817 case BASE_ATTACK:
4818 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4819 case OFF_ATTACK:
4820 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4821 default:
4822 break;
4824 return 0.0f;
4827 float Player::OCTRegenHPPerSpirit()
4829 uint32 level = getLevel();
4830 uint32 pclass = getClass();
4832 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4834 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4835 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4836 if (baseRatio==NULL || moreRatio==NULL)
4837 return 0.0f;
4839 // Formula from PaperDollFrame script
4840 float spirit = GetStat(STAT_SPIRIT);
4841 float baseSpirit = spirit;
4842 if (baseSpirit>50) baseSpirit = 50;
4843 float moreSpirit = spirit - baseSpirit;
4844 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4845 return regen;
4848 float Player::OCTRegenMPPerSpirit()
4850 uint32 level = getLevel();
4851 uint32 pclass = getClass();
4853 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4855 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4856 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4857 if (moreRatio==NULL)
4858 return 0.0f;
4860 // Formula get from PaperDollFrame script
4861 float spirit = GetStat(STAT_SPIRIT);
4862 float regen = spirit * moreRatio->ratio;
4863 return regen;
4866 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4868 m_baseRatingValue[cr]+=(apply ? value : -value);
4870 int32 amount = uint32(m_baseRatingValue[cr]);
4871 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4872 // stat used stored in miscValueB for this aura
4873 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4874 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4875 if ((*i)->GetMiscValue() & (1<<cr))
4876 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4877 if (amount < 0)
4878 amount = 0;
4879 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4881 float RatingCoeffecient = GetRatingCoefficient(cr);
4882 float RatingChange = 0.0f;
4884 bool affectStats = CanModifyStats();
4886 switch (cr)
4888 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4889 case CR_DEFENSE_SKILL:
4890 UpdateDefenseBonusesMod();
4891 break;
4892 case CR_DODGE:
4893 UpdateDodgePercentage();
4894 break;
4895 case CR_PARRY:
4896 UpdateParryPercentage();
4897 break;
4898 case CR_BLOCK:
4899 UpdateBlockPercentage();
4900 break;
4901 case CR_HIT_MELEE:
4902 UpdateMeleeHitChances();
4903 break;
4904 case CR_HIT_RANGED:
4905 UpdateRangedHitChances();
4906 break;
4907 case CR_HIT_SPELL:
4908 UpdateSpellHitChances();
4909 break;
4910 case CR_CRIT_MELEE:
4911 if(affectStats)
4913 UpdateCritPercentage(BASE_ATTACK);
4914 UpdateCritPercentage(OFF_ATTACK);
4916 break;
4917 case CR_CRIT_RANGED:
4918 if(affectStats)
4919 UpdateCritPercentage(RANGED_ATTACK);
4920 break;
4921 case CR_CRIT_SPELL:
4922 if(affectStats)
4923 UpdateAllSpellCritChances();
4924 break;
4925 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4926 case CR_HIT_TAKEN_RANGED:
4927 break;
4928 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4929 break;
4930 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4931 case CR_CRIT_TAKEN_RANGED:
4932 break;
4933 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4934 break;
4935 case CR_HASTE_MELEE:
4936 RatingChange = value / RatingCoeffecient;
4937 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4938 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4939 break;
4940 case CR_HASTE_RANGED:
4941 RatingChange = value / RatingCoeffecient;
4942 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4943 break;
4944 case CR_HASTE_SPELL:
4945 RatingChange = value / RatingCoeffecient;
4946 ApplyCastTimePercentMod(RatingChange,apply);
4947 break;
4948 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4949 case CR_WEAPON_SKILL_OFFHAND:
4950 case CR_WEAPON_SKILL_RANGED:
4951 break;
4952 case CR_EXPERTISE:
4953 if(affectStats)
4955 UpdateExpertise(BASE_ATTACK);
4956 UpdateExpertise(OFF_ATTACK);
4958 break;
4959 case CR_ARMOR_PENETRATION:
4960 break;
4964 void Player::SetRegularAttackTime()
4966 for(int i = 0; i < MAX_ATTACK; ++i)
4968 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4969 if(tmpitem && !tmpitem->IsBroken())
4971 ItemPrototype const *proto = tmpitem->GetProto();
4972 if(proto->Delay)
4973 SetAttackTime(WeaponAttackType(i), proto->Delay);
4974 else
4975 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4980 //skill+step, checking for max value
4981 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4983 if(!skill_id)
4984 return false;
4986 uint16 i=0;
4987 for (; i < PLAYER_MAX_SKILLS; ++i)
4988 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4989 break;
4991 if(i>=PLAYER_MAX_SKILLS)
4992 return false;
4994 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4995 uint32 value = SKILL_VALUE(data);
4996 uint32 max = SKILL_MAX(data);
4998 if ((!max) || (!value) || (value >= max))
4999 return false;
5001 if (value*512 < max*urand(0,512))
5003 uint32 new_value = value+step;
5004 if(new_value > max)
5005 new_value = max;
5007 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
5008 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5009 return true;
5012 return false;
5015 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5017 if ( SkillValue >= GrayLevel )
5018 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5019 if ( SkillValue >= GreenLevel )
5020 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5021 if ( SkillValue >= YellowLevel )
5022 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5023 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5026 bool Player::UpdateCraftSkill(uint32 spellid)
5028 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5030 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
5031 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
5033 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
5035 if(_spell_idx->second->skillId)
5037 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5039 // Alchemy Discoveries here
5040 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5041 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5043 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5044 learnSpell(discoveredSpell,false);
5047 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5049 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5050 _spell_idx->second->max_value,
5051 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5052 _spell_idx->second->min_value),
5053 craft_skill_gain);
5056 return false;
5059 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5061 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5063 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5065 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5066 switch (SkillId)
5068 case SKILL_HERBALISM:
5069 case SKILL_LOCKPICKING:
5070 case SKILL_JEWELCRAFTING:
5071 case SKILL_INSCRIPTION:
5072 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5073 case SKILL_SKINNING:
5074 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5075 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5076 else
5077 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5078 case SKILL_MINING:
5079 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5080 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5081 else
5082 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5084 return false;
5087 bool Player::UpdateFishingSkill()
5089 sLog.outDebug("UpdateFishingSkill");
5091 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5093 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5095 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5097 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5100 // levels sync. with spell requirement for skill levels to learn
5101 // bonus abilities in sSkillLineAbilityStore
5102 // Used only to avoid scan DBC at each skill grow
5103 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5105 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5107 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5108 if ( !SkillId )
5109 return false;
5111 if(Chance <= 0) // speedup in 0 chance case
5113 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5114 return false;
5117 uint16 i=0;
5118 for (; i < PLAYER_MAX_SKILLS; ++i)
5119 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5120 if ( i >= PLAYER_MAX_SKILLS )
5121 return false;
5123 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5124 uint16 SkillValue = SKILL_VALUE(data);
5125 uint16 MaxValue = SKILL_MAX(data);
5127 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5128 return false;
5130 int32 Roll = irand(1,1000);
5132 if ( Roll <= Chance )
5134 uint32 new_value = SkillValue+step;
5135 if(new_value > MaxValue)
5136 new_value = MaxValue;
5138 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5139 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5141 if((SkillValue < *bsl && new_value >= *bsl))
5143 learnSkillRewardedSpells( SkillId, new_value);
5144 break;
5147 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5148 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5149 return true;
5152 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5153 return false;
5156 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5158 // no skill gain in pvp
5159 Unit *pVictim = getVictim();
5160 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5161 return;
5163 if(IsInFeralForm())
5164 return; // always maximized SKILL_FERAL_COMBAT in fact
5166 if(m_form == FORM_TREE)
5167 return; // use weapon but not skill up
5169 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5171 switch(attType)
5173 case BASE_ATTACK:
5175 Item *tmpitem = GetWeaponForAttack(attType,true);
5177 if (!tmpitem)
5178 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5179 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5180 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5181 break;
5183 case OFF_ATTACK:
5184 case RANGED_ATTACK:
5186 Item *tmpitem = GetWeaponForAttack(attType,true);
5187 if (tmpitem)
5188 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5189 break;
5192 UpdateAllCritPercentages();
5195 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5197 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5198 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5199 uint32 moblevel = pVictim->getLevelForTarget(this);
5200 if(moblevel < greylevel)
5201 return;
5203 if (moblevel > plevel + 5)
5204 moblevel = plevel + 5;
5206 uint32 lvldif = moblevel - greylevel;
5207 if(lvldif < 3)
5208 lvldif = 3;
5210 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5211 if(skilldif <= 0)
5212 return;
5214 float chance = float(3 * lvldif * skilldif) / plevel;
5215 if(!defence)
5217 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5218 chance *= 0.1f * GetStat(STAT_INTELLECT);
5221 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5223 if(roll_chance_f(chance))
5225 if(defence)
5226 UpdateDefense();
5227 else
5228 UpdateWeaponSkill(attType);
5230 else
5231 return;
5234 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5236 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5237 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5239 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5240 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5241 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5243 if(talent) // permanent bonus stored in high part
5244 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5245 else // temporary/item bonus stored in low part
5246 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5247 return;
5251 void Player::UpdateSkillsForLevel()
5253 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5254 uint32 maxSkill = GetMaxSkillValueForLevel();
5256 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5258 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5259 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5261 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5263 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5264 if(!pSkill)
5265 continue;
5267 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5268 continue;
5270 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5271 uint32 max = SKILL_MAX(data);
5272 uint32 val = SKILL_VALUE(data);
5274 /// update only level dependent max skill values
5275 if(max!=1)
5277 /// miximize skill always
5278 if(alwaysMaxSkill)
5279 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5280 /// update max skill value if current max skill not maximized
5281 else if(max != maxconfskill)
5282 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5287 void Player::UpdateSkillsToMaxSkillsForLevel()
5289 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5290 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5292 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5293 if( IsProfessionOrRidingSkill(pskill))
5294 continue;
5295 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5297 uint32 max = SKILL_MAX(data);
5299 if(max > 1)
5300 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5302 if(pskill == SKILL_DEFENSE)
5303 UpdateDefenseBonusesMod();
5307 // This functions sets a skill line value (and adds if doesn't exist yet)
5308 // To "remove" a skill line, set it's values to zero
5309 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5311 if(!id)
5312 return;
5314 uint16 i=0;
5315 for (; i < PLAYER_MAX_SKILLS; ++i)
5316 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5318 if(i<PLAYER_MAX_SKILLS) //has skill
5320 if(currVal)
5322 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5323 learnSkillRewardedSpells(id, currVal);
5324 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5325 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5327 else //remove
5329 // clear skill fields
5330 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5331 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5332 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5334 // remove all spells that related to this skill
5335 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5336 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5337 if (pAbility->skillId==id)
5338 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5341 else if(currVal) //add
5343 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5344 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5346 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5347 if(!pSkill)
5349 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5350 return;
5352 // enable unlearn button for primary professions only
5353 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5354 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5355 else
5356 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5357 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5358 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5359 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5361 // apply skill bonuses
5362 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5364 // temporary bonuses
5365 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5366 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5367 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5368 (*j)->ApplyModifier(true);
5370 // permanent bonuses
5371 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5372 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5373 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5374 (*j)->ApplyModifier(true);
5376 // Learn all spells for skill
5377 learnSkillRewardedSpells(id, currVal);
5378 return;
5383 bool Player::HasSkill(uint32 skill) const
5385 if(!skill)return false;
5386 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5388 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5390 return true;
5393 return false;
5396 uint16 Player::GetSkillValue(uint32 skill) const
5398 if(!skill)
5399 return 0;
5401 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5403 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5405 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5407 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5408 result += SKILL_TEMP_BONUS(bonus);
5409 result += SKILL_PERM_BONUS(bonus);
5410 return result < 0 ? 0 : result;
5413 return 0;
5416 uint16 Player::GetMaxSkillValue(uint32 skill) const
5418 if(!skill)return 0;
5419 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5421 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5423 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5425 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5426 result += SKILL_TEMP_BONUS(bonus);
5427 result += SKILL_PERM_BONUS(bonus);
5428 return result < 0 ? 0 : result;
5431 return 0;
5434 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5436 if(!skill)return 0;
5437 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5439 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5441 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5444 return 0;
5447 uint16 Player::GetBaseSkillValue(uint32 skill) const
5449 if(!skill)return 0;
5450 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5452 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5454 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5455 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5456 return result < 0 ? 0 : result;
5459 return 0;
5462 uint16 Player::GetPureSkillValue(uint32 skill) const
5464 if(!skill)return 0;
5465 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5467 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5469 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5472 return 0;
5475 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5477 if(!skill)
5478 return 0;
5480 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5482 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5484 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5488 return 0;
5491 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5493 if(!skill)
5494 return 0;
5496 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5498 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5500 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5504 return 0;
5507 void Player::SendInitialActionButtons() const
5509 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5511 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5512 data << uint8(0); // can be 0, 1, 2 (talent spec)
5513 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5515 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5516 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5517 data << uint32(itr->second.packedData);
5518 else
5519 data << uint32(0);
5522 GetSession()->SendPacket( &data );
5523 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5526 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5528 if(button >= MAX_ACTION_BUTTONS)
5530 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5531 return NULL;
5534 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5536 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5537 return NULL;
5540 switch(type)
5542 case ACTION_BUTTON_SPELL:
5543 if(!sSpellStore.LookupEntry(action))
5545 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5546 return NULL;
5549 if(!HasSpell(action))
5551 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5552 return NULL;
5554 break;
5555 case ACTION_BUTTON_ITEM:
5556 if(!objmgr.GetItemPrototype(action))
5558 sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
5559 return NULL;
5561 break;
5562 default:
5563 break; // pther cases not checked at this moment
5567 // it create new button (NEW state) if need or return existed
5568 ActionButton& ab = m_actionButtons[button];
5570 // set data and update to CHANGED if not NEW
5571 ab.SetActionAndType(action,ActionButtonType(type));
5573 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5574 return &ab;
5577 void Player::removeActionButton(uint8 button)
5579 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5580 if (buttonItr==m_actionButtons.end())
5581 return;
5583 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5584 m_actionButtons.erase(buttonItr); // new and not saved
5585 else
5586 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5588 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5591 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5593 // prevent crash when a bad coord is sent by the client
5594 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5596 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5597 return false;
5600 Map *m = GetMap();
5602 const float old_x = GetPositionX();
5603 const float old_y = GetPositionY();
5604 const float old_z = GetPositionZ();
5605 const float old_r = GetOrientation();
5607 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5609 if (teleport || old_x != x || old_y != y || old_z != z)
5610 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5611 else
5612 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5614 // move and update visible state if need
5615 m->PlayerRelocation(this, x, y, z, orientation);
5617 // reread after Map::Relocation
5618 m = GetMap();
5619 x = GetPositionX();
5620 y = GetPositionY();
5621 z = GetPositionZ();
5623 // group update
5624 if(GetGroup() && (old_x != x || old_y != y))
5625 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5628 // code block for underwater state update
5629 UpdateUnderwaterState(m, x, y, z);
5631 CheckExploreSystem();
5633 return true;
5636 void Player::SaveRecallPosition()
5638 m_recallMap = GetMapId();
5639 m_recallX = GetPositionX();
5640 m_recallY = GetPositionY();
5641 m_recallZ = GetPositionZ();
5642 m_recallO = GetOrientation();
5645 void Player::SendMessageToSet(WorldPacket *data, bool self)
5647 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5648 if(_map)
5650 _map->MessageBroadcast(this, data, self);
5651 return;
5654 //if player is not in world and map in not created/already destroyed
5655 //no need to create one, just send packet for itself!
5656 if(self)
5657 GetSession()->SendPacket(data);
5660 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5662 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5663 if(_map)
5665 _map->MessageDistBroadcast(this, data, dist, self);
5666 return;
5669 if(self)
5670 GetSession()->SendPacket(data);
5673 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5675 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5676 if(_map)
5678 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5679 return;
5682 if(self)
5683 GetSession()->SendPacket(data);
5686 void Player::SendDirectMessage(WorldPacket *data)
5688 GetSession()->SendPacket(data);
5691 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5693 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5694 data << uint32(CinematicSequenceId);
5695 SendDirectMessage(&data);
5698 void Player::SendMovieStart(uint32 MovieId)
5700 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5701 data << uint32(MovieId);
5702 SendDirectMessage(&data);
5705 void Player::CheckExploreSystem()
5707 if (!isAlive())
5708 return;
5710 if (isInFlight())
5711 return;
5713 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5714 if(areaFlag==0xffff)
5715 return;
5716 int offset = areaFlag / 32;
5718 if(offset >= 128)
5720 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5721 return;
5724 uint32 val = (uint32)(1 << (areaFlag % 32));
5725 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5727 if( !(currFields & val) )
5729 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5731 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5733 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5734 if(!p)
5736 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5738 else if(p->area_level > 0)
5740 uint32 area = p->ID;
5741 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5743 SendExplorationExperience(area,0);
5745 else
5747 int32 diff = int32(getLevel()) - p->area_level;
5748 uint32 XP = 0;
5749 if (diff < -5)
5751 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5753 else if (diff > 5)
5755 int32 exploration_percent = (100-((diff-5)*5));
5756 if (exploration_percent > 100)
5757 exploration_percent = 100;
5758 else if (exploration_percent < 0)
5759 exploration_percent = 0;
5761 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5763 else
5765 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5768 GiveXP( XP, NULL );
5769 SendExplorationExperience(area,XP);
5771 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5776 uint32 Player::TeamForRace(uint8 race)
5778 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5779 if(!rEntry)
5781 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5782 return ALLIANCE;
5785 switch(rEntry->TeamID)
5787 case 7: return ALLIANCE;
5788 case 1: return HORDE;
5791 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5792 return ALLIANCE;
5795 uint32 Player::getFactionForRace(uint8 race)
5797 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5798 if(!rEntry)
5800 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5801 return 0;
5804 return rEntry->FactionID;
5807 void Player::setFactionForRace(uint8 race)
5809 m_team = TeamForRace(race);
5810 setFaction( getFactionForRace(race) );
5813 ReputationRank Player::GetReputationRank(uint32 faction) const
5815 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5816 return GetReputationMgr().GetRank(factionEntry);
5819 //Calculate total reputation percent player gain with quest/creature level
5820 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5822 float percent = 100.0f;
5824 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5826 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5827 percent *= rate;
5829 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5831 if (!for_quest)
5832 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5834 percent += rep > 0 ? repMod : -repMod;
5836 if (percent <= 0.0f)
5837 return 0;
5839 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5842 //Calculates how many reputation points player gains in victim's enemy factions
5843 void Player::RewardReputation(Unit *pVictim, float rate)
5845 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5846 return;
5848 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5850 if(!Rep)
5851 return;
5853 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5855 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5856 donerep1 = int32(donerep1*rate);
5857 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5858 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5859 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5860 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5862 // Wiki: Team factions value divided by 2
5863 if (factionEntry1 && Rep->is_teamaward1)
5865 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5866 if(team1_factionEntry)
5867 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5871 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5873 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5874 donerep2 = int32(donerep2*rate);
5875 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5876 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5877 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5878 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5880 // Wiki: Team factions value divided by 2
5881 if (factionEntry2 && Rep->is_teamaward2)
5883 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5884 if(team2_factionEntry)
5885 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5890 //Calculate how many reputation points player gain with the quest
5891 void Player::RewardReputation(Quest const *pQuest)
5893 // quest reputation reward/loss
5894 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5896 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5898 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5899 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5900 if(factionEntry)
5901 GetReputationMgr().ModifyReputation(factionEntry, rep);
5905 // TODO: implement reputation spillover
5908 void Player::UpdateArenaFields(void)
5910 /* arena calcs go here */
5913 void Player::UpdateHonorFields()
5915 /// called when rewarding honor and at each save
5916 uint64 now = time(NULL);
5917 uint64 today = uint64(time(NULL) / DAY) * DAY;
5919 if(m_lastHonorUpdateTime < today)
5921 uint64 yesterday = today - DAY;
5923 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5925 // update yesterday's contribution
5926 if(m_lastHonorUpdateTime >= yesterday )
5928 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5930 // this is the first update today, reset today's contribution
5931 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5932 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5934 else
5936 // no honor/kills yesterday or today, reset
5937 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5938 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5942 m_lastHonorUpdateTime = now;
5945 ///Calculate the amount of honor gained based on the victim
5946 ///and the size of the group for which the honor is divided
5947 ///An exact honor value can also be given (overriding the calcs)
5948 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5950 // do not reward honor in arenas, but enable onkill spellproc
5951 if(InArena())
5953 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5954 return false;
5956 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5957 return false;
5959 return true;
5962 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5963 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5964 return false;
5966 uint64 victim_guid = 0;
5967 uint32 victim_rank = 0;
5969 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5970 UpdateHonorFields();
5972 if(honor <= 0)
5974 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5975 return false;
5977 victim_guid = uVictim->GetGUID();
5979 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5981 Player *pVictim = (Player *)uVictim;
5983 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5984 return false;
5986 float f = 1; //need for total kills (?? need more info)
5987 uint32 k_grey = 0;
5988 uint32 k_level = getLevel();
5989 uint32 v_level = pVictim->getLevel();
5992 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5993 // [0] Just name
5994 // [1..14] Alliance honor titles and player name
5995 // [15..28] Horde honor titles and player name
5996 // [29..38] Other title and player name
5997 // [39+] Nothing
5998 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5999 // Get Killer titles, CharTitlesEntry::bit_index
6000 // Ranks:
6001 // title[1..14] -> rank[5..18]
6002 // title[15..28] -> rank[5..18]
6003 // title[other] -> 0
6004 if (victim_title == 0)
6005 victim_guid = 0; // Don't show HK: <rank> message, only log.
6006 else if (victim_title < 15)
6007 victim_rank = victim_title + 4;
6008 else if (victim_title < 29)
6009 victim_rank = victim_title - 14 + 4;
6010 else
6011 victim_guid = 0; // Don't show HK: <rank> message, only log.
6014 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6016 if(v_level<=k_grey)
6017 return false;
6019 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6021 int32 v_rank =1; //need more info
6023 honor = ((f * diff_level * (190 + v_rank*10))/6);
6024 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6026 // count the number of playerkills in one day
6027 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6028 // and those in a lifetime
6029 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6030 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6031 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6032 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6034 else
6036 Creature *cVictim = (Creature *)uVictim;
6038 if (!cVictim->isRacialLeader())
6039 return false;
6041 honor = 100; // ??? need more info
6042 victim_rank = 19; // HK: Leader
6046 if (uVictim != NULL)
6048 honor *= sWorld.getRate(RATE_HONOR);
6050 if(groupsize > 1)
6051 honor /= groupsize;
6053 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6056 // honor - for show honor points in log
6057 // victim_guid - for show victim name in log
6058 // victim_rank [1..4] HK: <dishonored rank>
6059 // victim_rank [5..19] HK: <alliance\horde rank>
6060 // victim_rank [0,20+] HK: <>
6061 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6062 data << (uint32) honor;
6063 data << (uint64) victim_guid;
6064 data << (uint32) victim_rank;
6066 GetSession()->SendPacket(&data);
6068 // add honor points
6069 ModifyHonorPoints(int32(honor));
6071 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6072 return true;
6075 void Player::ModifyHonorPoints( int32 value )
6077 if(value < 0)
6079 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6080 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6081 else
6082 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6084 else
6085 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6088 void Player::ModifyArenaPoints( int32 value )
6090 if(value < 0)
6092 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6093 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6094 else
6095 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6097 else
6098 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6101 uint32 Player::GetGuildIdFromDB(uint64 guid)
6103 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6104 if(!result)
6105 return 0;
6107 uint32 id = result->Fetch()[0].GetUInt32();
6108 delete result;
6109 return id;
6112 uint32 Player::GetRankFromDB(uint64 guid)
6114 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6115 if( result )
6117 uint32 v = result->Fetch()[0].GetUInt32();
6118 delete result;
6119 return v;
6121 else
6122 return 0;
6125 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6127 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);
6128 if(!result)
6129 return 0;
6131 uint32 id = (*result)[0].GetUInt32();
6132 delete result;
6133 return id;
6136 uint32 Player::GetZoneIdFromDB(uint64 guid)
6138 uint32 guidLow = GUID_LOPART(guid);
6139 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6140 if (!result)
6141 return 0;
6142 Field* fields = result->Fetch();
6143 uint32 zone = fields[0].GetUInt32();
6144 delete result;
6146 if (!zone)
6148 // stored zone is zero, use generic and slow zone detection
6149 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6150 if( !result )
6151 return 0;
6152 fields = result->Fetch();
6153 uint32 map = fields[0].GetUInt32();
6154 float posx = fields[1].GetFloat();
6155 float posy = fields[2].GetFloat();
6156 float posz = fields[3].GetFloat();
6157 delete result;
6159 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6161 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6164 return zone;
6167 uint32 Player::GetLevelFromDB(uint64 guid)
6169 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6170 if (!result)
6171 return 0;
6173 Field* fields = result->Fetch();
6174 uint32 level = fields[0].GetUInt32();
6175 delete result;
6177 return level;
6180 void Player::UpdateArea(uint32 newArea)
6182 // FFA_PVP flags are area and not zone id dependent
6183 // so apply them accordingly
6184 m_areaUpdateId = newArea;
6186 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6188 if(area && (area->flags & AREA_FLAG_ARENA))
6190 if(!isGameMaster())
6191 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6193 else
6195 // remove ffa flag only if not ffapvp realm
6196 // removal in sanctuaries and capitals is handled in zone update
6197 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6198 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6201 UpdateAreaDependentAuras(newArea);
6204 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6206 if(m_zoneUpdateId != newZone)
6207 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6209 m_zoneUpdateId = newZone;
6210 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6212 // zone changed, so area changed as well, update it
6213 UpdateArea(newArea);
6215 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6216 if(!zone)
6217 return;
6219 if (sWorld.getConfig(CONFIG_WEATHER))
6221 Weather *wth = sWorld.FindWeather(zone->ID);
6222 if(wth)
6224 wth->SendWeatherUpdateToPlayer(this);
6226 else
6228 if(!sWorld.AddWeather(zone->ID))
6230 // send fine weather packet to remove old zone's weather
6231 Weather::SendFineWeatherUpdateToPlayer(this);
6236 // in PvP, any not controlled zone (except zone->team == 6, default case)
6237 // in PvE, only opposition team capital
6238 switch(zone->team)
6240 case AREATEAM_ALLY:
6241 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6242 break;
6243 case AREATEAM_HORDE:
6244 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6245 break;
6246 case AREATEAM_NONE:
6247 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6248 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6249 break;
6250 default: // 6 in fact
6251 pvpInfo.inHostileArea = false;
6252 break;
6255 if(pvpInfo.inHostileArea) // in hostile area
6257 if(!IsPvP() || pvpInfo.endTimer != 0)
6258 UpdatePvP(true, true);
6260 else // in friendly area
6262 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6263 pvpInfo.endTimer = time(0); // start toggle-off
6266 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6268 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6269 if(sWorld.IsFFAPvPRealm())
6270 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6272 else
6274 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6277 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6279 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6280 SetRestType(REST_TYPE_IN_CITY);
6281 InnEnter(time(0),GetMapId(),0,0,0);
6283 if(sWorld.IsFFAPvPRealm())
6284 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6286 else // anywhere else
6288 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6290 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6292 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6294 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6295 SetRestType(REST_TYPE_NO);
6297 if(sWorld.IsFFAPvPRealm())
6298 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6301 else // not in tavern (leave city then)
6303 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6304 SetRestType(REST_TYPE_NO);
6306 // Set player to FFA PVP when not in rested environment.
6307 if(sWorld.IsFFAPvPRealm())
6308 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6313 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6314 // if player resurrected at teleport this will be applied in resurrect code
6315 if(isAlive())
6316 DestroyZoneLimitedItem( true, newZone );
6318 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6319 AutoUnequipOffhandIfNeed();
6321 // recent client version not send leave/join channel packets for built-in local channels
6322 UpdateLocalChannels( newZone );
6324 // group update
6325 if(GetGroup())
6326 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6328 UpdateZoneDependentAuras(newZone);
6331 //If players are too far way of duel flag... then player loose the duel
6332 void Player::CheckDuelDistance(time_t currTime)
6334 if(!duel)
6335 return;
6337 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6338 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6339 if(!obj)
6340 return;
6342 if(duel->outOfBound == 0)
6344 if(!IsWithinDistInMap(obj, 50))
6346 duel->outOfBound = currTime;
6348 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6349 GetSession()->SendPacket(&data);
6352 else
6354 if(IsWithinDistInMap(obj, 40))
6356 duel->outOfBound = 0;
6358 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6359 GetSession()->SendPacket(&data);
6361 else if(currTime >= (duel->outOfBound+10))
6363 DuelComplete(DUEL_FLED);
6368 void Player::DuelComplete(DuelCompleteType type)
6370 // duel not requested
6371 if(!duel)
6372 return;
6374 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6375 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6376 GetSession()->SendPacket(&data);
6377 duel->opponent->GetSession()->SendPacket(&data);
6379 if(type != DUEL_INTERUPTED)
6381 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6382 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6383 data << duel->opponent->GetName();
6384 data << GetName();
6385 SendMessageToSet(&data,true);
6388 if (type == DUEL_WON)
6390 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6391 if (duel->opponent)
6392 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6395 //Remove Duel Flag object
6396 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6397 if(obj)
6398 duel->initiator->RemoveGameObject(obj,true);
6400 /* remove auras */
6401 std::vector<uint32> auras2remove;
6402 AuraMap const& vAuras = duel->opponent->GetAuras();
6403 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6405 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6406 auras2remove.push_back(i->second->GetId());
6409 for(size_t i=0; i<auras2remove.size(); ++i)
6410 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6412 auras2remove.clear();
6413 AuraMap const& auras = GetAuras();
6414 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6416 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6417 auras2remove.push_back(i->second->GetId());
6419 for(size_t i=0; i<auras2remove.size(); ++i)
6420 RemoveAurasDueToSpell(auras2remove[i]);
6422 // cleanup combo points
6423 if(GetComboTarget()==duel->opponent->GetGUID())
6424 ClearComboPoints();
6425 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6426 ClearComboPoints();
6428 if(duel->opponent->GetComboTarget()==GetGUID())
6429 duel->opponent->ClearComboPoints();
6430 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6431 duel->opponent->ClearComboPoints();
6433 //cleanups
6434 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6435 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6436 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6437 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6439 delete duel->opponent->duel;
6440 duel->opponent->duel = NULL;
6441 delete duel;
6442 duel = NULL;
6445 //---------------------------------------------------------//
6447 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6449 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6450 return;
6452 // not apply/remove mods for broken item
6453 if(item->IsBroken())
6454 return;
6456 ItemPrototype const *proto = item->GetProto();
6458 if(!proto)
6459 return;
6461 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6463 uint32 attacktype = Player::GetAttackBySlot(slot);
6464 if(attacktype < MAX_ATTACK)
6465 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6467 _ApplyItemBonuses(proto,slot,apply);
6469 if( slot==EQUIPMENT_SLOT_RANGED )
6470 _ApplyAmmoBonuses();
6472 ApplyItemEquipSpell(item,apply);
6473 ApplyEnchantment(item, apply);
6475 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6476 CorrectMetaGemEnchants(slot, apply);
6478 sLog.outDebug("_ApplyItemMods complete.");
6481 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6483 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6484 return;
6486 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : 0;
6487 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(getLevel()) : 0;
6489 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6491 uint32 statType = 0;
6492 int32 val = 0;
6493 // If set ScalingStatDistribution need get stats and values from it
6494 if (ssd && ssv)
6496 if (ssd->StatMod[i] < 0)
6497 continue;
6498 statType = ssd->StatMod[i];
6499 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6501 else
6503 if (i >= proto->StatsCount)
6504 continue;
6505 statType = proto->ItemStat[i].ItemStatType;
6506 val = proto->ItemStat[i].ItemStatValue;
6509 if(val == 0)
6510 continue;
6512 switch (statType)
6514 case ITEM_MOD_MANA:
6515 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6516 break;
6517 case ITEM_MOD_HEALTH: // modify HP
6518 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6519 break;
6520 case ITEM_MOD_AGILITY: // modify agility
6521 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6522 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6523 break;
6524 case ITEM_MOD_STRENGTH: //modify strength
6525 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6526 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6527 break;
6528 case ITEM_MOD_INTELLECT: //modify intellect
6529 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6530 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6531 break;
6532 case ITEM_MOD_SPIRIT: //modify spirit
6533 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6534 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6535 break;
6536 case ITEM_MOD_STAMINA: //modify stamina
6537 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6538 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6539 break;
6540 case ITEM_MOD_DEFENSE_SKILL_RATING:
6541 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6542 break;
6543 case ITEM_MOD_DODGE_RATING:
6544 ApplyRatingMod(CR_DODGE, int32(val), apply);
6545 break;
6546 case ITEM_MOD_PARRY_RATING:
6547 ApplyRatingMod(CR_PARRY, int32(val), apply);
6548 break;
6549 case ITEM_MOD_BLOCK_RATING:
6550 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6551 break;
6552 case ITEM_MOD_HIT_MELEE_RATING:
6553 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6554 break;
6555 case ITEM_MOD_HIT_RANGED_RATING:
6556 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6557 break;
6558 case ITEM_MOD_HIT_SPELL_RATING:
6559 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6560 break;
6561 case ITEM_MOD_CRIT_MELEE_RATING:
6562 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6563 break;
6564 case ITEM_MOD_CRIT_RANGED_RATING:
6565 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6566 break;
6567 case ITEM_MOD_CRIT_SPELL_RATING:
6568 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6569 break;
6570 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6571 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6572 break;
6573 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6574 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6575 break;
6576 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6577 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6578 break;
6579 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6580 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6581 break;
6582 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6583 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6584 break;
6585 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6586 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6587 break;
6588 case ITEM_MOD_HASTE_MELEE_RATING:
6589 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6590 break;
6591 case ITEM_MOD_HASTE_RANGED_RATING:
6592 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6593 break;
6594 case ITEM_MOD_HASTE_SPELL_RATING:
6595 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6596 break;
6597 case ITEM_MOD_HIT_RATING:
6598 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6599 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6600 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6601 break;
6602 case ITEM_MOD_CRIT_RATING:
6603 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6604 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6605 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6606 break;
6607 case ITEM_MOD_HIT_TAKEN_RATING:
6608 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6609 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6610 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6611 break;
6612 case ITEM_MOD_CRIT_TAKEN_RATING:
6613 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6614 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6615 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6616 break;
6617 case ITEM_MOD_RESILIENCE_RATING:
6618 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6619 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6620 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6621 break;
6622 case ITEM_MOD_HASTE_RATING:
6623 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6624 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6625 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6626 break;
6627 case ITEM_MOD_EXPERTISE_RATING:
6628 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6629 break;
6630 case ITEM_MOD_ATTACK_POWER:
6631 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6632 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6633 break;
6634 case ITEM_MOD_RANGED_ATTACK_POWER:
6635 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6636 break;
6637 case ITEM_MOD_FERAL_ATTACK_POWER:
6638 ApplyFeralAPBonus(int32(val), apply);
6639 break;
6640 case ITEM_MOD_SPELL_HEALING_DONE:
6641 ApplySpellHealingBonus(int32(val), apply);
6642 break;
6643 case ITEM_MOD_SPELL_DAMAGE_DONE:
6644 ApplySpellDamageBonus(int32(val), apply);
6645 break;
6646 case ITEM_MOD_MANA_REGENERATION:
6647 ApplyManaRegenBonus(int32(val), apply);
6648 break;
6649 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6650 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6651 break;
6652 case ITEM_MOD_SPELL_POWER:
6653 ApplySpellHealingBonus(int32(val), apply);
6654 ApplySpellDamageBonus(int32(val), apply);
6655 break;
6659 // If set ScalingStatValue armor get it or use item armor
6660 uint32 armor = proto->Armor;
6661 if (ssv)
6663 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6664 armor = ssvarmor;
6666 // Add armor bonus from ArmorDamageModifier if > 0
6667 if (proto->ArmorDamageModifier > 0)
6668 armor+=proto->ArmorDamageModifier;
6669 if (armor)
6670 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6672 if (proto->Block)
6673 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6675 if (proto->HolyRes)
6676 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6678 if (proto->FireRes)
6679 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6681 if (proto->NatureRes)
6682 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6684 if (proto->FrostRes)
6685 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6687 if (proto->ShadowRes)
6688 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6690 if (proto->ArcaneRes)
6691 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6693 WeaponAttackType attType = BASE_ATTACK;
6694 float damage = 0.0f;
6696 if( slot == EQUIPMENT_SLOT_RANGED && (
6697 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6698 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6700 attType = RANGED_ATTACK;
6702 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6704 attType = OFF_ATTACK;
6707 float minDamage = proto->Damage[0].DamageMin;
6708 float maxDamage = proto->Damage[0].DamageMax;
6709 int32 extraDPS = 0;
6710 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6711 if (ssv)
6713 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6715 float average = extraDPS * proto->Delay / 1000.0f;
6716 minDamage = 0.7f * average;
6717 maxDamage = 1.3f * average;
6720 if (minDamage > 0 )
6722 damage = apply ? minDamage : BASE_MINDAMAGE;
6723 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6724 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6727 if (maxDamage > 0 )
6729 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6730 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6733 // Apply feral bonus from ScalingStatValue if set
6734 if (ssv)
6736 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6737 ApplyFeralAPBonus(feral_bonus, apply);
6739 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6740 if(getClass() == CLASS_DRUID)
6742 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6743 if (feral_bonus > 0)
6744 ApplyFeralAPBonus(feral_bonus, apply);
6747 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6748 return;
6750 if (proto->Delay)
6752 if(slot == EQUIPMENT_SLOT_RANGED)
6753 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6754 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6755 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6756 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6757 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6760 if(CanModifyStats() && (damage || proto->Delay))
6761 UpdateDamagePhysical(attType);
6764 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6766 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6767 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6768 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6770 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6771 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6772 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6774 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6775 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6776 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6779 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6781 // generic not weapon specific case processes in aura code
6782 if(aura->GetSpellProto()->EquippedItemClass == -1)
6783 return;
6785 BaseModGroup mod = BASEMOD_END;
6786 switch(attackType)
6788 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6789 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6790 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6791 default: return;
6794 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6796 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6800 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6802 // ignore spell mods for not wands
6803 Modifier const* modifier = aura->GetModifier();
6804 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6805 return;
6807 // generic not weapon specific case processes in aura code
6808 if(aura->GetSpellProto()->EquippedItemClass == -1)
6809 return;
6811 UnitMods unitMod = UNIT_MOD_END;
6812 switch(attackType)
6814 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6815 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6816 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6817 default: return;
6820 UnitModifierType unitModType = TOTAL_VALUE;
6821 switch(modifier->m_auraname)
6823 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6824 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6825 default: return;
6828 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6830 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6834 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6836 if(!item)
6837 return;
6839 ItemPrototype const *proto = item->GetProto();
6840 if(!proto)
6841 return;
6843 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6845 _Spell const& spellData = proto->Spells[i];
6847 // no spell
6848 if(!spellData.SpellId )
6849 continue;
6851 // wrong triggering type
6852 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6853 continue;
6855 // check if it is valid spell
6856 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6857 if(!spellproto)
6858 continue;
6860 ApplyEquipSpell(spellproto,item,apply,form_change);
6864 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6866 if(apply)
6868 // Cannot be used in this stance/form
6869 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6870 return;
6872 if(form_change) // check aura active state from other form
6874 bool found = false;
6875 for (int k=0; k < 3; ++k)
6877 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6878 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6880 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6882 found = true;
6883 break;
6886 if(found)
6887 break;
6890 if(found) // and skip re-cast already active aura at form change
6891 return;
6894 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6896 CastSpell(this,spellInfo,true,item);
6898 else
6900 if(form_change) // check aura compatibility
6902 // Cannot be used in this stance/form
6903 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6904 return; // and remove only not compatible at form change
6907 if(item)
6908 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6909 else
6910 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6914 void Player::UpdateEquipSpellsAtFormChange()
6916 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6918 if(m_items[i] && !m_items[i]->IsBroken())
6920 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6921 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6925 // item set bonuses not dependent from item broken state
6926 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6928 ItemSetEffect* eff = ItemSetEff[setindex];
6929 if(!eff)
6930 continue;
6932 for(uint32 y=0;y<8; ++y)
6934 SpellEntry const* spellInfo = eff->spells[y];
6935 if(!spellInfo)
6936 continue;
6938 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6939 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6944 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6946 Item *item = GetWeaponForAttack(attType, true);
6947 if(!item || item->IsBroken())
6948 return;
6950 ItemPrototype const *proto = item->GetProto();
6951 if(!proto)
6952 return;
6954 if (!Target || Target == this )
6955 return;
6957 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6959 _Spell const& spellData = proto->Spells[i];
6961 // no spell
6962 if(!spellData.SpellId )
6963 continue;
6965 // wrong triggering type
6966 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6967 continue;
6969 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6970 if(!spellInfo)
6972 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6973 continue;
6976 // not allow proc extra attack spell at extra attack
6977 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6978 return;
6980 float chance = spellInfo->procChance;
6982 if(spellData.SpellPPMRate)
6984 uint32 WeaponSpeed = GetAttackTime(attType);
6985 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6987 else if(chance > 100.0f)
6989 chance = GetWeaponProcChance();
6992 if (roll_chance_f(chance))
6993 CastSpell(Target, spellInfo->Id, true, item);
6996 // item combat enchantments
6997 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6999 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7000 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7001 if(!pEnchant) continue;
7002 for (int s=0;s<3;s++)
7004 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7005 continue;
7007 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7008 if (!spellInfo)
7010 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7011 continue;
7014 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7015 if (roll_chance_f(chance))
7017 if(IsPositiveSpell(pEnchant->spellid[s]))
7018 CastSpell(this, pEnchant->spellid[s], true, item);
7019 else
7020 CastSpell(Target, pEnchant->spellid[s], true, item);
7026 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7028 ItemPrototype const* proto = item->GetProto();
7029 // special learning case
7030 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7032 uint32 learn_spell_id = proto->Spells[0].SpellId;
7033 uint32 learning_spell_id = proto->Spells[1].SpellId;
7035 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7036 if(!spellInfo)
7038 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7039 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7040 return;
7043 Spell *spell = new Spell(this, spellInfo, false);
7044 spell->m_CastItem = item;
7045 spell->m_cast_count = cast_count; //set count of casts
7046 spell->m_currentBasePoints[0] = learning_spell_id;
7047 spell->prepare(&targets);
7048 return;
7051 // use triggered flag only for items with many spell casts and for not first cast
7052 int count = 0;
7054 // item spells casted at use
7055 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7057 _Spell const& spellData = proto->Spells[i];
7059 // no spell
7060 if(!spellData.SpellId)
7061 continue;
7063 // wrong triggering type
7064 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7065 continue;
7067 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7068 if(!spellInfo)
7070 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7071 continue;
7074 Spell *spell = new Spell(this, spellInfo, (count > 0));
7075 spell->m_CastItem = item;
7076 spell->m_cast_count = cast_count; // set count of casts
7077 spell->m_glyphIndex = glyphIndex; // glyph index
7078 spell->prepare(&targets);
7080 ++count;
7083 // Item enchantments spells casted at use
7084 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7086 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7087 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7088 if(!pEnchant) continue;
7089 for (int s=0;s<3;s++)
7091 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7092 continue;
7094 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7095 if (!spellInfo)
7097 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7098 continue;
7101 Spell *spell = new Spell(this, spellInfo, (count > 0));
7102 spell->m_CastItem = item;
7103 spell->m_cast_count = cast_count; // set count of casts
7104 spell->m_glyphIndex = glyphIndex; // glyph index
7105 spell->prepare(&targets);
7107 ++count;
7112 void Player::_RemoveAllItemMods()
7114 sLog.outDebug("_RemoveAllItemMods start.");
7116 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7118 if(m_items[i])
7120 ItemPrototype const *proto = m_items[i]->GetProto();
7121 if(!proto)
7122 continue;
7124 // item set bonuses not dependent from item broken state
7125 if(proto->ItemSet)
7126 RemoveItemsSetItem(this,proto);
7128 if(m_items[i]->IsBroken())
7129 continue;
7131 ApplyItemEquipSpell(m_items[i],false);
7132 ApplyEnchantment(m_items[i], false);
7136 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7138 if(m_items[i])
7140 if(m_items[i]->IsBroken())
7141 continue;
7142 ItemPrototype const *proto = m_items[i]->GetProto();
7143 if(!proto)
7144 continue;
7146 uint32 attacktype = Player::GetAttackBySlot(i);
7147 if(attacktype < MAX_ATTACK)
7148 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7150 _ApplyItemBonuses(proto,i, false);
7152 if( i == EQUIPMENT_SLOT_RANGED )
7153 _ApplyAmmoBonuses();
7157 sLog.outDebug("_RemoveAllItemMods complete.");
7160 void Player::_ApplyAllItemMods()
7162 sLog.outDebug("_ApplyAllItemMods start.");
7164 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7166 if(m_items[i])
7168 if(m_items[i]->IsBroken())
7169 continue;
7171 ItemPrototype const *proto = m_items[i]->GetProto();
7172 if(!proto)
7173 continue;
7175 uint32 attacktype = Player::GetAttackBySlot(i);
7176 if(attacktype < MAX_ATTACK)
7177 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7179 _ApplyItemBonuses(proto,i, true);
7181 if( i == EQUIPMENT_SLOT_RANGED )
7182 _ApplyAmmoBonuses();
7186 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7188 if(m_items[i])
7190 ItemPrototype const *proto = m_items[i]->GetProto();
7191 if(!proto)
7192 continue;
7194 // item set bonuses not dependent from item broken state
7195 if(proto->ItemSet)
7196 AddItemsSetItem(this,m_items[i]);
7198 if(m_items[i]->IsBroken())
7199 continue;
7201 ApplyItemEquipSpell(m_items[i],true);
7202 ApplyEnchantment(m_items[i], true);
7206 sLog.outDebug("_ApplyAllItemMods complete.");
7209 void Player::_ApplyAmmoBonuses()
7211 // check ammo
7212 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7213 if(!ammo_id)
7214 return;
7216 float currentAmmoDPS;
7218 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7219 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7220 currentAmmoDPS = 0.0f;
7221 else
7222 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7224 if(currentAmmoDPS == GetAmmoDPS())
7225 return;
7227 m_ammoDPS = currentAmmoDPS;
7229 if(CanModifyStats())
7230 UpdateDamagePhysical(RANGED_ATTACK);
7233 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7235 if(!ammo_proto)
7236 return false;
7238 // check ranged weapon
7239 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7240 if(!weapon || weapon->IsBroken() )
7241 return false;
7243 ItemPrototype const* weapon_proto = weapon->GetProto();
7244 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7245 return false;
7247 // check ammo ws. weapon compatibility
7248 switch(weapon_proto->SubClass)
7250 case ITEM_SUBCLASS_WEAPON_BOW:
7251 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7252 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7253 return false;
7254 break;
7255 case ITEM_SUBCLASS_WEAPON_GUN:
7256 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7257 return false;
7258 break;
7259 default:
7260 return false;
7263 return true;
7266 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7267 Called by remove insignia spell effect */
7268 void Player::RemovedInsignia(Player* looterPlr)
7270 if (!GetBattleGroundId())
7271 return;
7273 // If not released spirit, do it !
7274 if(m_deathTimer > 0)
7276 m_deathTimer = 0;
7277 BuildPlayerRepop();
7278 RepopAtGraveyard();
7281 Corpse *corpse = GetCorpse();
7282 if (!corpse)
7283 return;
7285 // We have to convert player corpse to bones, not to be able to resurrect there
7286 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7287 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7288 if (!bones)
7289 return;
7291 // Now we must make bones lootable, and send player loot
7292 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7294 // We store the level of our player in the gold field
7295 // We retrieve this information at Player::SendLoot()
7296 bones->loot.gold = getLevel();
7297 bones->lootRecipient = looterPlr;
7298 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7301 void Player::SendLootRelease( uint64 guid )
7303 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7304 data << uint64(guid) << uint8(1);
7305 SendDirectMessage( &data );
7308 void Player::SendLoot(uint64 guid, LootType loot_type)
7310 if (uint64 lguid = GetLootGUID())
7311 m_session->DoLootRelease(lguid);
7313 Loot *loot = 0;
7314 PermissionTypes permission = ALL_PERMISSION;
7316 sLog.outDebug("Player::SendLoot");
7317 if (IS_GAMEOBJECT_GUID(guid))
7319 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7320 GameObject *go = GetMap()->GetGameObject(guid);
7322 // not check distance for GO in case owned GO (fishing bobber case, for example)
7323 // And permit out of range GO with no owner in case fishing hole
7324 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7326 SendLootRelease(guid);
7327 return;
7330 loot = &go->loot;
7332 if (go->getLootState() == GO_READY)
7334 uint32 lootid = go->GetLootId();
7336 if (lootid)
7338 sLog.outDebug(" if(lootid)");
7339 loot->clear();
7340 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7343 if (loot_type == LOOT_FISHING)
7344 go->getFishLoot(loot,this);
7346 go->SetLootState(GO_ACTIVATED);
7349 else if (IS_ITEM_GUID(guid))
7351 Item *item = GetItemByGuid( guid );
7353 if (!item)
7355 SendLootRelease(guid);
7356 return;
7359 loot = &item->loot;
7361 if (!item->m_lootGenerated)
7363 item->m_lootGenerated = true;
7364 loot->clear();
7366 switch(loot_type)
7368 case LOOT_DISENCHANTING:
7369 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7370 break;
7371 case LOOT_PROSPECTING:
7372 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7373 break;
7374 case LOOT_MILLING:
7375 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7376 break;
7377 default:
7378 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7379 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7380 break;
7384 else if (IS_CORPSE_GUID(guid)) // remove insignia
7386 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7388 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7390 SendLootRelease(guid);
7391 return;
7394 loot = &bones->loot;
7396 if (!bones->lootForBody)
7398 bones->lootForBody = true;
7399 uint32 pLevel = bones->loot.gold;
7400 bones->loot.clear();
7401 // It may need a better formula
7402 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7403 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7406 if (bones->lootRecipient != this)
7407 permission = NONE_PERMISSION;
7409 else
7411 Creature *creature = GetMap()->GetCreature(guid);
7413 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7414 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7416 SendLootRelease(guid);
7417 return;
7420 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7422 SendLootRelease(guid);
7423 return;
7426 loot = &creature->loot;
7428 if (loot_type == LOOT_PICKPOCKETING)
7430 if (!creature->lootForPickPocketed)
7432 creature->lootForPickPocketed = true;
7433 loot->clear();
7435 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7436 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7438 // Generate extra money for pick pocket loot
7439 const uint32 a = urand(0, creature->getLevel()/2);
7440 const uint32 b = urand(0, getLevel()/2);
7441 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7444 else
7446 // the player whose group may loot the corpse
7447 Player *recipient = creature->GetLootRecipient();
7448 if (!recipient)
7450 creature->SetLootRecipient(this);
7451 recipient = this;
7454 if (creature->lootForPickPocketed)
7456 creature->lootForPickPocketed = false;
7457 loot->clear();
7460 if (!creature->lootForBody)
7462 creature->lootForBody = true;
7463 loot->clear();
7465 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7466 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7468 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7470 if (Group* group = recipient->GetGroup())
7472 group->UpdateLooterGuid(creature,true);
7474 switch (group->GetLootMethod())
7476 case GROUP_LOOT:
7477 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7478 group->GroupLoot(recipient->GetGUID(), loot, creature);
7479 break;
7480 case NEED_BEFORE_GREED:
7481 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7482 break;
7483 case MASTER_LOOT:
7484 group->MasterLoot(recipient->GetGUID(), loot, creature);
7485 break;
7486 default:
7487 break;
7492 // possible only if creature->lootForBody && loot->empty() at spell cast check
7493 if (loot_type == LOOT_SKINNING)
7495 loot->clear();
7496 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7498 // set group rights only for loot_type != LOOT_SKINNING
7499 else
7501 if(Group* group = GetGroup())
7503 if (group == recipient->GetGroup())
7505 if (group->GetLootMethod() == FREE_FOR_ALL)
7506 permission = ALL_PERMISSION;
7507 else if (group->GetLooterGuid() == GetGUID())
7509 if (group->GetLootMethod() == MASTER_LOOT)
7510 permission = MASTER_PERMISSION;
7511 else
7512 permission = ALL_PERMISSION;
7514 else
7515 permission = GROUP_PERMISSION;
7517 else
7518 permission = NONE_PERMISSION;
7520 else if (recipient == this)
7521 permission = ALL_PERMISSION;
7522 else
7523 permission = NONE_PERMISSION;
7528 SetLootGUID(guid);
7530 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7531 switch(loot_type)
7533 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7534 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7535 default: break;
7538 // need know merged fishing/corpse loot type for achievements
7539 loot->loot_type = loot_type;
7541 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7543 data << uint64(guid);
7544 data << uint8(loot_type);
7545 data << LootView(*loot, this, permission);
7547 SendDirectMessage(&data);
7549 // add 'this' player as one of the players that are looting 'loot'
7550 if (permission != NONE_PERMISSION)
7551 loot->AddLooter(GetGUID());
7553 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7554 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7557 void Player::SendNotifyLootMoneyRemoved()
7559 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7560 GetSession()->SendPacket( &data );
7563 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7565 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7566 data << uint8(lootSlot);
7567 GetSession()->SendPacket( &data );
7570 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7572 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7573 data << Field;
7574 data << Value;
7575 GetSession()->SendPacket(&data);
7578 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7580 // data depends on zoneid/mapid...
7581 BattleGround* bg = GetBattleGround();
7582 uint16 NumberOfFields = 0;
7583 uint32 mapid = GetMapId();
7585 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7587 // may be exist better way to do this...
7588 switch(zoneid)
7590 case 0:
7591 case 1:
7592 case 4:
7593 case 8:
7594 case 10:
7595 case 11:
7596 case 12:
7597 case 36:
7598 case 38:
7599 case 40:
7600 case 41:
7601 case 51:
7602 case 267:
7603 case 1519:
7604 case 1537:
7605 case 2257:
7606 case 2918:
7607 NumberOfFields = 8;
7608 break;
7609 case 139:
7610 NumberOfFields = 41;
7611 break;
7612 case 1377:
7613 NumberOfFields = 15;
7614 break;
7615 case 2597:
7616 NumberOfFields = 83;
7617 break;
7618 case 3277:
7619 NumberOfFields = 16;
7620 break;
7621 case 3358:
7622 case 3820:
7623 NumberOfFields = 40;
7624 break;
7625 case 3483:
7626 NumberOfFields = 27;
7627 break;
7628 case 3518:
7629 NumberOfFields = 39;
7630 break;
7631 case 3519:
7632 NumberOfFields = 38;
7633 break;
7634 case 3521:
7635 NumberOfFields = 37;
7636 break;
7637 case 3698:
7638 case 3702:
7639 case 3968:
7640 NumberOfFields = 11;
7641 break;
7642 case 3703:
7643 NumberOfFields = 11;
7644 break;
7645 default:
7646 NumberOfFields = 12;
7647 break;
7650 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7651 data << uint32(mapid); // mapid
7652 data << uint32(zoneid); // zone id
7653 data << uint32(areaid); // area id, new 2.1.0
7654 data << uint16(NumberOfFields); // count of uint64 blocks
7655 data << uint32(0x8d8) << uint32(0x0); // 1
7656 data << uint32(0x8d7) << uint32(0x0); // 2
7657 data << uint32(0x8d6) << uint32(0x0); // 3
7658 data << uint32(0x8d5) << uint32(0x0); // 4
7659 data << uint32(0x8d4) << uint32(0x0); // 5
7660 data << uint32(0x8d3) << uint32(0x0); // 6
7661 // 7 1 - Arena season in progress, 0 - end of season
7662 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7663 // 8 Arena season id
7664 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7665 if(mapid == 530) // Outland
7667 data << uint32(0x9bf) << uint32(0x0); // 7
7668 data << uint32(0x9bd) << uint32(0xF); // 8
7669 data << uint32(0x9bb) << uint32(0xF); // 9
7671 switch(zoneid)
7673 case 1:
7674 case 11:
7675 case 12:
7676 case 38:
7677 case 40:
7678 case 51:
7679 case 1519:
7680 case 1537:
7681 case 2257:
7682 break;
7683 case 2597: // AV
7684 data << uint32(0x7ae) << uint32(0x1); // 7
7685 data << uint32(0x532) << uint32(0x1); // 8
7686 data << uint32(0x531) << uint32(0x0); // 9
7687 data << uint32(0x52e) << uint32(0x0); // 10
7688 data << uint32(0x571) << uint32(0x0); // 11
7689 data << uint32(0x570) << uint32(0x0); // 12
7690 data << uint32(0x567) << uint32(0x1); // 13
7691 data << uint32(0x566) << uint32(0x1); // 14
7692 data << uint32(0x550) << uint32(0x1); // 15
7693 data << uint32(0x544) << uint32(0x0); // 16
7694 data << uint32(0x536) << uint32(0x0); // 17
7695 data << uint32(0x535) << uint32(0x1); // 18
7696 data << uint32(0x518) << uint32(0x0); // 19
7697 data << uint32(0x517) << uint32(0x0); // 20
7698 data << uint32(0x574) << uint32(0x0); // 21
7699 data << uint32(0x573) << uint32(0x0); // 22
7700 data << uint32(0x572) << uint32(0x0); // 23
7701 data << uint32(0x56f) << uint32(0x0); // 24
7702 data << uint32(0x56e) << uint32(0x0); // 25
7703 data << uint32(0x56d) << uint32(0x0); // 26
7704 data << uint32(0x56c) << uint32(0x0); // 27
7705 data << uint32(0x56b) << uint32(0x0); // 28
7706 data << uint32(0x56a) << uint32(0x1); // 29
7707 data << uint32(0x569) << uint32(0x1); // 30
7708 data << uint32(0x568) << uint32(0x1); // 13
7709 data << uint32(0x565) << uint32(0x0); // 32
7710 data << uint32(0x564) << uint32(0x0); // 33
7711 data << uint32(0x563) << uint32(0x0); // 34
7712 data << uint32(0x562) << uint32(0x0); // 35
7713 data << uint32(0x561) << uint32(0x0); // 36
7714 data << uint32(0x560) << uint32(0x0); // 37
7715 data << uint32(0x55f) << uint32(0x0); // 38
7716 data << uint32(0x55e) << uint32(0x0); // 39
7717 data << uint32(0x55d) << uint32(0x0); // 40
7718 data << uint32(0x3c6) << uint32(0x4); // 41
7719 data << uint32(0x3c4) << uint32(0x6); // 42
7720 data << uint32(0x3c2) << uint32(0x4); // 43
7721 data << uint32(0x516) << uint32(0x1); // 44
7722 data << uint32(0x515) << uint32(0x0); // 45
7723 data << uint32(0x3b6) << uint32(0x6); // 46
7724 data << uint32(0x55c) << uint32(0x0); // 47
7725 data << uint32(0x55b) << uint32(0x0); // 48
7726 data << uint32(0x55a) << uint32(0x0); // 49
7727 data << uint32(0x559) << uint32(0x0); // 50
7728 data << uint32(0x558) << uint32(0x0); // 51
7729 data << uint32(0x557) << uint32(0x0); // 52
7730 data << uint32(0x556) << uint32(0x0); // 53
7731 data << uint32(0x555) << uint32(0x0); // 54
7732 data << uint32(0x554) << uint32(0x1); // 55
7733 data << uint32(0x553) << uint32(0x1); // 56
7734 data << uint32(0x552) << uint32(0x1); // 57
7735 data << uint32(0x551) << uint32(0x1); // 58
7736 data << uint32(0x54f) << uint32(0x0); // 59
7737 data << uint32(0x54e) << uint32(0x0); // 60
7738 data << uint32(0x54d) << uint32(0x1); // 61
7739 data << uint32(0x54c) << uint32(0x0); // 62
7740 data << uint32(0x54b) << uint32(0x0); // 63
7741 data << uint32(0x545) << uint32(0x0); // 64
7742 data << uint32(0x543) << uint32(0x1); // 65
7743 data << uint32(0x542) << uint32(0x0); // 66
7744 data << uint32(0x540) << uint32(0x0); // 67
7745 data << uint32(0x53f) << uint32(0x0); // 68
7746 data << uint32(0x53e) << uint32(0x0); // 69
7747 data << uint32(0x53d) << uint32(0x0); // 70
7748 data << uint32(0x53c) << uint32(0x0); // 71
7749 data << uint32(0x53b) << uint32(0x0); // 72
7750 data << uint32(0x53a) << uint32(0x1); // 73
7751 data << uint32(0x539) << uint32(0x0); // 74
7752 data << uint32(0x538) << uint32(0x0); // 75
7753 data << uint32(0x537) << uint32(0x0); // 76
7754 data << uint32(0x534) << uint32(0x0); // 77
7755 data << uint32(0x533) << uint32(0x0); // 78
7756 data << uint32(0x530) << uint32(0x0); // 79
7757 data << uint32(0x52f) << uint32(0x0); // 80
7758 data << uint32(0x52d) << uint32(0x1); // 81
7759 break;
7760 case 3277: // WS
7761 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7762 bg->FillInitialWorldStates(data);
7763 else
7765 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7766 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7767 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7768 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7769 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7770 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7771 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7772 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7774 break;
7775 case 3358: // AB
7776 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7777 bg->FillInitialWorldStates(data);
7778 else
7780 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7781 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7782 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7783 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7784 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7785 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7786 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7787 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7788 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7789 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7790 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7791 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7792 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7793 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7794 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7795 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7796 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7797 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7798 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7799 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7800 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7801 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7802 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7803 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7804 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7805 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7806 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7807 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7808 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7809 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7810 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7811 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7813 break;
7814 case 3820: // EY
7815 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7816 bg->FillInitialWorldStates(data);
7817 else
7819 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7820 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7821 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7822 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7823 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7824 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7825 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7826 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7827 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7828 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7829 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7830 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7831 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7832 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7833 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7834 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7835 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7836 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7837 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7838 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7839 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7840 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7841 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7842 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7843 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7844 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7845 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7846 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7847 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7848 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7849 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7850 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7851 // and some more ... unknown
7853 break;
7854 case 3483: // Hellfire Peninsula
7855 data << uint32(0x9ba) << uint32(0x1); // 10
7856 data << uint32(0x9b9) << uint32(0x1); // 11
7857 data << uint32(0x9b5) << uint32(0x0); // 12
7858 data << uint32(0x9b4) << uint32(0x1); // 13
7859 data << uint32(0x9b3) << uint32(0x0); // 14
7860 data << uint32(0x9b2) << uint32(0x0); // 15
7861 data << uint32(0x9b1) << uint32(0x1); // 16
7862 data << uint32(0x9b0) << uint32(0x0); // 17
7863 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7864 data << uint32(0x9ac) << uint32(0x0); // 19
7865 data << uint32(0x9a8) << uint32(0x0); // 20
7866 data << uint32(0x9a7) << uint32(0x0); // 21
7867 data << uint32(0x9a6) << uint32(0x1); // 22
7868 break;
7869 case 3519: // Terokkar Forest
7870 data << uint32(0xa41) << uint32(0x0); // 10
7871 data << uint32(0xa40) << uint32(0x14); // 11
7872 data << uint32(0xa3f) << uint32(0x0); // 12
7873 data << uint32(0xa3e) << uint32(0x0); // 13
7874 data << uint32(0xa3d) << uint32(0x5); // 14
7875 data << uint32(0xa3c) << uint32(0x0); // 15
7876 data << uint32(0xa87) << uint32(0x0); // 16
7877 data << uint32(0xa86) << uint32(0x0); // 17
7878 data << uint32(0xa85) << uint32(0x0); // 18
7879 data << uint32(0xa84) << uint32(0x0); // 19
7880 data << uint32(0xa83) << uint32(0x0); // 20
7881 data << uint32(0xa82) << uint32(0x0); // 21
7882 data << uint32(0xa81) << uint32(0x0); // 22
7883 data << uint32(0xa80) << uint32(0x0); // 23
7884 data << uint32(0xa7e) << uint32(0x0); // 24
7885 data << uint32(0xa7d) << uint32(0x0); // 25
7886 data << uint32(0xa7c) << uint32(0x0); // 26
7887 data << uint32(0xa7b) << uint32(0x0); // 27
7888 data << uint32(0xa7a) << uint32(0x0); // 28
7889 data << uint32(0xa79) << uint32(0x0); // 29
7890 data << uint32(0x9d0) << uint32(0x5); // 30
7891 data << uint32(0x9ce) << uint32(0x0); // 31
7892 data << uint32(0x9cd) << uint32(0x0); // 32
7893 data << uint32(0x9cc) << uint32(0x0); // 33
7894 data << uint32(0xa88) << uint32(0x0); // 34
7895 data << uint32(0xad0) << uint32(0x0); // 35
7896 data << uint32(0xacf) << uint32(0x1); // 36
7897 break;
7898 case 3521: // Zangarmarsh
7899 data << uint32(0x9e1) << uint32(0x0); // 10
7900 data << uint32(0x9e0) << uint32(0x0); // 11
7901 data << uint32(0x9df) << uint32(0x0); // 12
7902 data << uint32(0xa5d) << uint32(0x1); // 13
7903 data << uint32(0xa5c) << uint32(0x0); // 14
7904 data << uint32(0xa5b) << uint32(0x1); // 15
7905 data << uint32(0xa5a) << uint32(0x0); // 16
7906 data << uint32(0xa59) << uint32(0x1); // 17
7907 data << uint32(0xa58) << uint32(0x0); // 18
7908 data << uint32(0xa57) << uint32(0x0); // 19
7909 data << uint32(0xa56) << uint32(0x0); // 20
7910 data << uint32(0xa55) << uint32(0x1); // 21
7911 data << uint32(0xa54) << uint32(0x0); // 22
7912 data << uint32(0x9e7) << uint32(0x0); // 23
7913 data << uint32(0x9e6) << uint32(0x0); // 24
7914 data << uint32(0x9e5) << uint32(0x0); // 25
7915 data << uint32(0xa00) << uint32(0x0); // 26
7916 data << uint32(0x9ff) << uint32(0x1); // 27
7917 data << uint32(0x9fe) << uint32(0x0); // 28
7918 data << uint32(0x9fd) << uint32(0x0); // 29
7919 data << uint32(0x9fc) << uint32(0x1); // 30
7920 data << uint32(0x9fb) << uint32(0x0); // 31
7921 data << uint32(0xa62) << uint32(0x0); // 32
7922 data << uint32(0xa61) << uint32(0x1); // 33
7923 data << uint32(0xa60) << uint32(0x1); // 34
7924 data << uint32(0xa5f) << uint32(0x0); // 35
7925 break;
7926 case 3698: // Nagrand Arena
7927 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7928 bg->FillInitialWorldStates(data);
7929 else
7931 data << uint32(0xa0f) << uint32(0x0); // 7
7932 data << uint32(0xa10) << uint32(0x0); // 8
7933 data << uint32(0xa11) << uint32(0x0); // 9 show
7935 break;
7936 case 3702: // Blade's Edge Arena
7937 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7938 bg->FillInitialWorldStates(data);
7939 else
7941 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7942 data << uint32(0x9f1) << uint32(0x0); // 8 green
7943 data << uint32(0x9f3) << uint32(0x0); // 9 show
7945 break;
7946 case 3968: // Ruins of Lordaeron
7947 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7948 bg->FillInitialWorldStates(data);
7949 else
7951 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7952 data << uint32(0xbb9) << uint32(0x0); // 8 green
7953 data << uint32(0xbba) << uint32(0x0); // 9 show
7955 break;
7956 case 3703: // Shattrath City
7957 break;
7958 default:
7959 data << uint32(0x914) << uint32(0x0); // 7
7960 data << uint32(0x913) << uint32(0x0); // 8
7961 data << uint32(0x912) << uint32(0x0); // 9
7962 data << uint32(0x915) << uint32(0x0); // 10
7963 break;
7965 GetSession()->SendPacket(&data);
7968 uint32 Player::GetXPRestBonus(uint32 xp)
7970 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7972 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7973 rested_bonus = xp;
7975 SetRestBonus( GetRestBonus() - rested_bonus);
7977 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7978 return rested_bonus;
7981 void Player::SetBindPoint(uint64 guid)
7983 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7984 data << uint64(guid);
7985 GetSession()->SendPacket( &data );
7988 void Player::SendTalentWipeConfirm(uint64 guid)
7990 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7991 data << uint64(guid);
7992 data << uint32(resetTalentsCost());
7993 GetSession()->SendPacket( &data );
7996 void Player::SendPetSkillWipeConfirm()
7998 Pet* pet = GetPet();
7999 if(!pet)
8000 return;
8001 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8002 data << pet->GetGUID();
8003 data << uint32(pet->resetTalentsCost());
8004 GetSession()->SendPacket( &data );
8007 /*********************************************************/
8008 /*** STORAGE SYSTEM ***/
8009 /*********************************************************/
8011 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8013 assert(i < 3);
8014 if(i < 2 && item)
8016 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8017 return;
8018 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8019 if(charges == 0)
8020 return;
8021 if(charges > 1)
8022 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8023 else if(charges <= 1)
8025 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8026 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8031 void Player::SetSheath( SheathState sheathed )
8033 switch (sheathed)
8035 case SHEATH_STATE_UNARMED: // no prepared weapon
8036 SetVirtualItemSlot(0,NULL);
8037 SetVirtualItemSlot(1,NULL);
8038 SetVirtualItemSlot(2,NULL);
8039 break;
8040 case SHEATH_STATE_MELEE: // prepared melee weapon
8042 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8043 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8044 SetVirtualItemSlot(2,NULL);
8045 }; break;
8046 case SHEATH_STATE_RANGED: // prepared ranged weapon
8047 SetVirtualItemSlot(0,NULL);
8048 SetVirtualItemSlot(1,NULL);
8049 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8050 break;
8051 default:
8052 SetVirtualItemSlot(0,NULL);
8053 SetVirtualItemSlot(1,NULL);
8054 SetVirtualItemSlot(2,NULL);
8055 break;
8057 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8060 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8062 uint8 pClass = getClass();
8064 uint8 slots[4];
8065 slots[0] = NULL_SLOT;
8066 slots[1] = NULL_SLOT;
8067 slots[2] = NULL_SLOT;
8068 slots[3] = NULL_SLOT;
8069 switch( proto->InventoryType )
8071 case INVTYPE_HEAD:
8072 slots[0] = EQUIPMENT_SLOT_HEAD;
8073 break;
8074 case INVTYPE_NECK:
8075 slots[0] = EQUIPMENT_SLOT_NECK;
8076 break;
8077 case INVTYPE_SHOULDERS:
8078 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8079 break;
8080 case INVTYPE_BODY:
8081 slots[0] = EQUIPMENT_SLOT_BODY;
8082 break;
8083 case INVTYPE_CHEST:
8084 slots[0] = EQUIPMENT_SLOT_CHEST;
8085 break;
8086 case INVTYPE_ROBE:
8087 slots[0] = EQUIPMENT_SLOT_CHEST;
8088 break;
8089 case INVTYPE_WAIST:
8090 slots[0] = EQUIPMENT_SLOT_WAIST;
8091 break;
8092 case INVTYPE_LEGS:
8093 slots[0] = EQUIPMENT_SLOT_LEGS;
8094 break;
8095 case INVTYPE_FEET:
8096 slots[0] = EQUIPMENT_SLOT_FEET;
8097 break;
8098 case INVTYPE_WRISTS:
8099 slots[0] = EQUIPMENT_SLOT_WRISTS;
8100 break;
8101 case INVTYPE_HANDS:
8102 slots[0] = EQUIPMENT_SLOT_HANDS;
8103 break;
8104 case INVTYPE_FINGER:
8105 slots[0] = EQUIPMENT_SLOT_FINGER1;
8106 slots[1] = EQUIPMENT_SLOT_FINGER2;
8107 break;
8108 case INVTYPE_TRINKET:
8109 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8110 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8111 break;
8112 case INVTYPE_CLOAK:
8113 slots[0] = EQUIPMENT_SLOT_BACK;
8114 break;
8115 case INVTYPE_WEAPON:
8117 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8119 // suggest offhand slot only if know dual wielding
8120 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8121 if(CanDualWield())
8122 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8123 break;
8125 case INVTYPE_SHIELD:
8126 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8127 break;
8128 case INVTYPE_RANGED:
8129 slots[0] = EQUIPMENT_SLOT_RANGED;
8130 break;
8131 case INVTYPE_2HWEAPON:
8132 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8133 if (CanDualWield() && CanTitanGrip())
8134 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8135 break;
8136 case INVTYPE_TABARD:
8137 slots[0] = EQUIPMENT_SLOT_TABARD;
8138 break;
8139 case INVTYPE_WEAPONMAINHAND:
8140 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8141 break;
8142 case INVTYPE_WEAPONOFFHAND:
8143 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8144 break;
8145 case INVTYPE_HOLDABLE:
8146 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8147 break;
8148 case INVTYPE_THROWN:
8149 slots[0] = EQUIPMENT_SLOT_RANGED;
8150 break;
8151 case INVTYPE_RANGEDRIGHT:
8152 slots[0] = EQUIPMENT_SLOT_RANGED;
8153 break;
8154 case INVTYPE_BAG:
8155 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8156 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8157 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8158 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8159 break;
8160 case INVTYPE_RELIC:
8162 switch(proto->SubClass)
8164 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8165 if (pClass == CLASS_PALADIN)
8166 slots[0] = EQUIPMENT_SLOT_RANGED;
8167 break;
8168 case ITEM_SUBCLASS_ARMOR_IDOL:
8169 if (pClass == CLASS_DRUID)
8170 slots[0] = EQUIPMENT_SLOT_RANGED;
8171 break;
8172 case ITEM_SUBCLASS_ARMOR_TOTEM:
8173 if (pClass == CLASS_SHAMAN)
8174 slots[0] = EQUIPMENT_SLOT_RANGED;
8175 break;
8176 case ITEM_SUBCLASS_ARMOR_MISC:
8177 if (pClass == CLASS_WARLOCK)
8178 slots[0] = EQUIPMENT_SLOT_RANGED;
8179 break;
8180 case ITEM_SUBCLASS_ARMOR_SIGIL:
8181 if (pClass == CLASS_DEATH_KNIGHT)
8182 slots[0] = EQUIPMENT_SLOT_RANGED;
8183 break;
8185 break;
8187 default :
8188 return NULL_SLOT;
8191 if( slot != NULL_SLOT )
8193 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8195 for (int i = 0; i < 4; ++i)
8197 if ( slots[i] == slot )
8198 return slot;
8202 else
8204 // search free slot at first
8205 for (int i = 0; i < 4; ++i)
8207 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8209 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8210 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8211 return slots[i];
8215 // if not found free and can swap return first appropriate from used
8216 for (int i = 0; i < 4; ++i)
8218 if ( slots[i] != NULL_SLOT && swap )
8219 return slots[i];
8223 // no free position
8224 return NULL_SLOT;
8227 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8229 Item *pItem;
8230 uint32 tempcount = 0;
8232 uint8 res = EQUIP_ERR_OK;
8234 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8236 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8237 if( pItem && pItem->GetEntry() == item )
8239 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8240 if(ires==EQUIP_ERR_OK)
8242 tempcount += pItem->GetCount();
8243 if( tempcount >= count )
8244 return EQUIP_ERR_OK;
8246 else
8247 res = ires;
8250 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8252 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8253 if( pItem && pItem->GetEntry() == item )
8255 tempcount += pItem->GetCount();
8256 if( tempcount >= count )
8257 return EQUIP_ERR_OK;
8260 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8262 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8263 if( pItem && pItem->GetEntry() == item )
8265 tempcount += pItem->GetCount();
8266 if( tempcount >= count )
8267 return EQUIP_ERR_OK;
8270 Bag *pBag;
8271 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8273 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8274 if( pBag )
8276 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8278 pItem = GetItemByPos( i, j );
8279 if( pItem && pItem->GetEntry() == item )
8281 tempcount += pItem->GetCount();
8282 if( tempcount >= count )
8283 return EQUIP_ERR_OK;
8289 // not found req. item count and have unequippable items
8290 return res;
8293 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8295 uint32 count = 0;
8296 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8298 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8299 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8300 count += pItem->GetCount();
8302 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8304 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8305 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8306 count += pItem->GetCount();
8308 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8310 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8311 if( pBag )
8312 count += pBag->GetItemCount(item,skipItem);
8315 if(skipItem && skipItem->GetProto()->GemProperties)
8317 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8319 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8320 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8321 count += pItem->GetGemCountWithID(item);
8325 if(inBankAlso)
8327 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8329 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8330 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8331 count += pItem->GetCount();
8333 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8335 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8336 if( pBag )
8337 count += pBag->GetItemCount(item,skipItem);
8340 if(skipItem && skipItem->GetProto()->GemProperties)
8342 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8344 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8345 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8346 count += pItem->GetGemCountWithID(item);
8351 return count;
8354 Item* Player::GetItemByGuid( uint64 guid ) const
8356 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8358 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8359 if( pItem && pItem->GetGUID() == guid )
8360 return pItem;
8362 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8364 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8365 if( pItem && pItem->GetGUID() == guid )
8366 return pItem;
8369 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8371 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8372 if( pBag )
8374 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8376 Item* pItem = pBag->GetItemByPos( j );
8377 if( pItem && pItem->GetGUID() == guid )
8378 return pItem;
8382 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8384 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8385 if( pBag )
8387 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8389 Item* pItem = pBag->GetItemByPos( j );
8390 if( pItem && pItem->GetGUID() == guid )
8391 return pItem;
8396 return NULL;
8399 Item* Player::GetItemByPos( uint16 pos ) const
8401 uint8 bag = pos >> 8;
8402 uint8 slot = pos & 255;
8403 return GetItemByPos( bag, slot );
8406 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8408 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8409 return m_items[slot];
8410 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8411 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8413 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8414 if ( pBag )
8415 return pBag->GetItemByPos(slot);
8417 return NULL;
8420 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8422 uint16 slot;
8423 switch (attackType)
8425 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8426 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8427 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8428 default: return NULL;
8431 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8432 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8433 return NULL;
8435 if(!useable)
8436 return item;
8438 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8439 return NULL;
8441 return item;
8444 Item* Player::GetShield(bool useable) const
8446 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8447 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8448 return NULL;
8450 if(!useable)
8451 return item;
8453 if( item->IsBroken())
8454 return NULL;
8456 return item;
8459 uint32 Player::GetAttackBySlot( uint8 slot )
8461 switch(slot)
8463 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8464 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8465 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8466 default: return MAX_ATTACK;
8470 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8472 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8473 return true;
8474 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8475 return true;
8476 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8477 return true;
8478 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8479 return true;
8480 return false;
8483 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8485 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8486 return true;
8487 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8488 return true;
8489 return false;
8492 bool Player::IsBankPos( uint8 bag, uint8 slot )
8494 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8495 return true;
8496 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8497 return true;
8498 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8499 return true;
8500 return false;
8503 bool Player::IsBagPos( uint16 pos )
8505 uint8 bag = pos >> 8;
8506 uint8 slot = pos & 255;
8507 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8508 return true;
8509 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8510 return true;
8511 return false;
8514 bool Player::IsValidPos( uint8 bag, uint8 slot )
8516 // post selected
8517 if(bag == NULL_BAG)
8518 return true;
8520 if (bag == INVENTORY_SLOT_BAG_0)
8522 // any post selected
8523 if (slot == NULL_SLOT)
8524 return true;
8526 // equipment
8527 if (slot < EQUIPMENT_SLOT_END)
8528 return true;
8530 // bag equip slots
8531 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8532 return true;
8534 // backpack slots
8535 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8536 return true;
8538 // keyring slots
8539 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8540 return true;
8542 // bank main slots
8543 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8544 return true;
8546 // bank bag slots
8547 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8548 return true;
8550 return false;
8553 // bag content slots
8554 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8556 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8557 if(!pBag)
8558 return false;
8560 // any post selected
8561 if (slot == NULL_SLOT)
8562 return true;
8564 return slot < pBag->GetBagSize();
8567 // bank bag content slots
8568 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8570 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8571 if(!pBag)
8572 return false;
8574 // any post selected
8575 if (slot == NULL_SLOT)
8576 return true;
8578 return slot < pBag->GetBagSize();
8581 // where this?
8582 return false;
8586 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8588 uint32 tempcount = 0;
8589 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8591 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8592 if( pItem && pItem->GetEntry() == item )
8594 tempcount += pItem->GetCount();
8595 if( tempcount >= count )
8596 return true;
8599 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8601 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8602 if( pItem && pItem->GetEntry() == item )
8604 tempcount += pItem->GetCount();
8605 if( tempcount >= count )
8606 return true;
8609 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8611 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8613 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8615 Item* pItem = GetItemByPos( i, j );
8616 if( pItem && pItem->GetEntry() == item )
8618 tempcount += pItem->GetCount();
8619 if( tempcount >= count )
8620 return true;
8626 if(inBankAlso)
8628 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8630 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8631 if( pItem && pItem->GetEntry() == item )
8633 tempcount += pItem->GetCount();
8634 if( tempcount >= count )
8635 return true;
8638 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8640 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8642 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8644 Item* pItem = GetItemByPos( i, j );
8645 if( pItem && pItem->GetEntry() == item )
8647 tempcount += pItem->GetCount();
8648 if( tempcount >= count )
8649 return true;
8656 return false;
8659 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8661 uint32 tempcount = 0;
8662 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8664 if(i==int(except_slot))
8665 continue;
8667 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8668 if( pItem && pItem->GetEntry() == item)
8670 tempcount += pItem->GetCount();
8671 if( tempcount >= count )
8672 return true;
8676 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8677 if (pProto && pProto->GemProperties)
8679 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8681 if(i==int(except_slot))
8682 continue;
8684 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8685 if( pItem && pItem->GetProto()->Socket[0].Color)
8687 tempcount += pItem->GetGemCountWithID(item);
8688 if( tempcount >= count )
8689 return true;
8694 return false;
8697 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8699 uint32 tempcount = 0;
8700 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8702 if(i==int(except_slot))
8703 continue;
8705 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8706 if (!pItem)
8707 continue;
8709 ItemPrototype const *pProto = pItem->GetProto();
8710 if (!pProto)
8711 continue;
8713 if (pProto->ItemLimitCategory == limitCategory)
8715 tempcount += pItem->GetCount();
8716 if( tempcount >= count )
8717 return true;
8720 if( pProto->Socket[0].Color)
8722 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8723 if( tempcount >= count )
8724 return true;
8728 return false;
8731 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8733 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8734 if( !pProto )
8736 if(no_space_count)
8737 *no_space_count = count;
8738 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8741 // no maximum
8742 if(pProto->MaxCount <= 0)
8743 return EQUIP_ERR_OK;
8745 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8747 if (curcount + count > uint32(pProto->MaxCount))
8749 if(no_space_count)
8750 *no_space_count = count +curcount - pProto->MaxCount;
8751 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8754 return EQUIP_ERR_OK;
8757 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8759 Item *pItem;
8760 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8762 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8763 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8764 return true;
8766 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8768 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8769 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8770 return true;
8772 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8774 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8776 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8778 pItem = GetItemByPos( i, j );
8779 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8780 return true;
8784 return false;
8787 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8789 Item* pItem2 = GetItemByPos( bag, slot );
8791 // ignore move item (this slot will be empty at move)
8792 if (pItem2==pSrcItem)
8793 pItem2 = NULL;
8795 uint32 need_space;
8797 // empty specific slot - check item fit to slot
8798 if (!pItem2 || swap)
8800 if (bag == INVENTORY_SLOT_BAG_0)
8802 // keyring case
8803 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8804 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8806 // currencytoken case
8807 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8808 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8810 // prevent cheating
8811 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8812 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8814 else
8816 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8817 if (!pBag)
8818 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8820 ItemPrototype const* pBagProto = pBag->GetProto();
8821 if (!pBagProto)
8822 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8824 if (slot >= pBagProto->ContainerSlots)
8825 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8827 if (!ItemCanGoIntoBag(pProto,pBagProto))
8828 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8831 // non empty stack with space
8832 need_space = pProto->GetMaxStackSize();
8834 // non empty slot, check item type
8835 else
8837 // check item type
8838 if (pItem2->GetEntry() != pProto->ItemId)
8839 return EQUIP_ERR_ITEM_CANT_STACK;
8841 // check free space
8842 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
8843 return EQUIP_ERR_ITEM_CANT_STACK;
8845 // free stack space or infinity
8846 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8849 if (need_space > count)
8850 need_space = count;
8852 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8853 if (!newPosition.isContainedIn(dest))
8855 dest.push_back(newPosition);
8856 count -= need_space;
8858 return EQUIP_ERR_OK;
8861 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
8863 // skip specific bag already processed in first called _CanStoreItem_InBag
8864 if (bag==skip_bag)
8865 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8867 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8868 if (!pBag)
8869 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8871 ItemPrototype const* pBagProto = pBag->GetProto();
8872 if (!pBagProto)
8873 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8875 // specialized bag mode or non-specilized
8876 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
8877 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8879 if (!ItemCanGoIntoBag(pProto,pBagProto))
8880 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8882 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8884 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8885 if (j==skip_slot)
8886 continue;
8888 Item* pItem2 = GetItemByPos( bag, j );
8890 // ignore move item (this slot will be empty at move)
8891 if (pItem2==pSrcItem)
8892 pItem2 = NULL;
8894 // if merge skip empty, if !merge skip non-empty
8895 if ((pItem2!=NULL)!=merge)
8896 continue;
8898 if (pItem2)
8900 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8902 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8903 if(need_space > count)
8904 need_space = count;
8906 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8907 if (!newPosition.isContainedIn(dest))
8909 dest.push_back(newPosition);
8910 count -= need_space;
8912 if (count==0)
8913 return EQUIP_ERR_OK;
8917 else
8919 uint32 need_space = pProto->GetMaxStackSize();
8920 if (need_space > count)
8921 need_space = count;
8923 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8924 if (!newPosition.isContainedIn(dest))
8926 dest.push_back(newPosition);
8927 count -= need_space;
8929 if (count==0)
8930 return EQUIP_ERR_OK;
8934 return EQUIP_ERR_OK;
8937 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
8939 for(uint32 j = slot_begin; j < slot_end; ++j)
8941 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8942 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8943 continue;
8945 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8947 // ignore move item (this slot will be empty at move)
8948 if (pItem2==pSrcItem)
8949 pItem2 = NULL;
8951 // if merge skip empty, if !merge skip non-empty
8952 if ((pItem2!=NULL)!=merge)
8953 continue;
8955 if (pItem2)
8957 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8959 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8960 if (need_space > count)
8961 need_space = count;
8962 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8963 if (!newPosition.isContainedIn(dest))
8965 dest.push_back(newPosition);
8966 count -= need_space;
8968 if (count==0)
8969 return EQUIP_ERR_OK;
8973 else
8975 uint32 need_space = pProto->GetMaxStackSize();
8976 if (need_space > count)
8977 need_space = count;
8979 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8980 if (!newPosition.isContainedIn(dest))
8982 dest.push_back(newPosition);
8983 count -= need_space;
8985 if (count==0)
8986 return EQUIP_ERR_OK;
8990 return EQUIP_ERR_OK;
8993 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8995 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8997 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8998 if (!pProto)
9000 if (no_space_count)
9001 *no_space_count = count;
9002 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9005 if (pItem && pItem->IsBindedNotWith(this))
9007 if (no_space_count)
9008 *no_space_count = count;
9009 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9012 // check count of items (skip for auto move for same player from bank)
9013 uint32 no_similar_count = 0; // can't store this amount similar items
9014 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9015 if (res!=EQUIP_ERR_OK)
9017 if (count==no_similar_count)
9019 if (no_space_count)
9020 *no_space_count = no_similar_count;
9021 return res;
9023 count -= no_similar_count;
9026 // in specific slot
9027 if (bag != NULL_BAG && slot != NULL_SLOT)
9029 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9030 if (res!=EQUIP_ERR_OK)
9032 if (no_space_count)
9033 *no_space_count = count + no_similar_count;
9034 return res;
9037 if (count==0)
9039 if (no_similar_count==0)
9040 return EQUIP_ERR_OK;
9042 if (no_space_count)
9043 *no_space_count = count + no_similar_count;
9044 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9048 // not specific slot or have space for partly store only in specific slot
9050 // in specific bag
9051 if (bag != NULL_BAG)
9053 // search stack in bag for merge to
9054 if (pProto->Stackable != 1)
9056 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9058 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9059 if (res!=EQUIP_ERR_OK)
9061 if (no_space_count)
9062 *no_space_count = count + no_similar_count;
9063 return res;
9066 if (count==0)
9068 if (no_similar_count==0)
9069 return EQUIP_ERR_OK;
9071 if (no_space_count)
9072 *no_space_count = count + no_similar_count;
9073 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9076 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9077 if (res!=EQUIP_ERR_OK)
9079 if (no_space_count)
9080 *no_space_count = count + no_similar_count;
9081 return res;
9084 if (count==0)
9086 if (no_similar_count==0)
9087 return EQUIP_ERR_OK;
9089 if (no_space_count)
9090 *no_space_count = count + no_similar_count;
9091 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9094 else // equipped bag
9096 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9097 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9098 if (res!=EQUIP_ERR_OK)
9099 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9101 if (res!=EQUIP_ERR_OK)
9103 if (no_space_count)
9104 *no_space_count = count + no_similar_count;
9105 return res;
9108 if (count==0)
9110 if (no_similar_count==0)
9111 return EQUIP_ERR_OK;
9113 if (no_space_count)
9114 *no_space_count = count + no_similar_count;
9115 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9120 // search free slot in bag for place to
9121 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9123 // search free slot - keyring case
9124 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9126 uint32 keyringSize = GetMaxKeyringSize();
9127 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9128 if (res!=EQUIP_ERR_OK)
9130 if (no_space_count)
9131 *no_space_count = count + no_similar_count;
9132 return res;
9135 if (count==0)
9137 if (no_similar_count==0)
9138 return EQUIP_ERR_OK;
9140 if (no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9145 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9146 if (res!=EQUIP_ERR_OK)
9148 if (no_space_count)
9149 *no_space_count = count + no_similar_count;
9150 return res;
9153 if (count==0)
9155 if (no_similar_count==0)
9156 return EQUIP_ERR_OK;
9158 if (no_space_count)
9159 *no_space_count = count + no_similar_count;
9160 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9163 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9165 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9166 if (res!=EQUIP_ERR_OK)
9168 if (no_space_count)
9169 *no_space_count = count + no_similar_count;
9170 return res;
9173 if (count==0)
9175 if (no_similar_count==0)
9176 return EQUIP_ERR_OK;
9178 if (no_space_count)
9179 *no_space_count = count + no_similar_count;
9180 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9184 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9185 if (res!=EQUIP_ERR_OK)
9187 if (no_space_count)
9188 *no_space_count = count + no_similar_count;
9189 return res;
9192 if (count==0)
9194 if (no_similar_count==0)
9195 return EQUIP_ERR_OK;
9197 if (no_space_count)
9198 *no_space_count = count + no_similar_count;
9199 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9202 else // equipped bag
9204 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9205 if (res!=EQUIP_ERR_OK)
9206 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9208 if (res!=EQUIP_ERR_OK)
9210 if (no_space_count)
9211 *no_space_count = count + no_similar_count;
9212 return res;
9215 if (count==0)
9217 if (no_similar_count==0)
9218 return EQUIP_ERR_OK;
9220 if (no_space_count)
9221 *no_space_count = count + no_similar_count;
9222 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9227 // not specific bag or have space for partly store only in specific bag
9229 // search stack for merge to
9230 if (pProto->Stackable != 1)
9232 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9233 if (res!=EQUIP_ERR_OK)
9235 if (no_space_count)
9236 *no_space_count = count + no_similar_count;
9237 return res;
9240 if (count==0)
9242 if (no_similar_count==0)
9243 return EQUIP_ERR_OK;
9245 if (no_space_count)
9246 *no_space_count = count + no_similar_count;
9247 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9250 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9251 if (res!=EQUIP_ERR_OK)
9253 if (no_space_count)
9254 *no_space_count = count + no_similar_count;
9255 return res;
9258 if (count==0)
9260 if (no_similar_count==0)
9261 return EQUIP_ERR_OK;
9263 if (no_space_count)
9264 *no_space_count = count + no_similar_count;
9265 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9268 if (pProto->BagFamily)
9270 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9272 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9273 if (res!=EQUIP_ERR_OK)
9274 continue;
9276 if (count==0)
9278 if (no_similar_count==0)
9279 return EQUIP_ERR_OK;
9281 if (no_space_count)
9282 *no_space_count = count + no_similar_count;
9283 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9288 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9290 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9291 if (res!=EQUIP_ERR_OK)
9292 continue;
9294 if (count==0)
9296 if (no_similar_count==0)
9297 return EQUIP_ERR_OK;
9299 if (no_space_count)
9300 *no_space_count = count + no_similar_count;
9301 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9306 // search free slot - special bag case
9307 if (pProto->BagFamily)
9309 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9311 uint32 keyringSize = GetMaxKeyringSize();
9312 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9313 if (res!=EQUIP_ERR_OK)
9315 if (no_space_count)
9316 *no_space_count = count + no_similar_count;
9317 return res;
9320 if (count==0)
9322 if (no_similar_count==0)
9323 return EQUIP_ERR_OK;
9325 if (no_space_count)
9326 *no_space_count = count + no_similar_count;
9327 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9330 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9332 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9333 if (res!=EQUIP_ERR_OK)
9335 if (no_space_count)
9336 *no_space_count = count + no_similar_count;
9337 return res;
9340 if (count==0)
9342 if (no_similar_count==0)
9343 return EQUIP_ERR_OK;
9345 if (no_space_count)
9346 *no_space_count = count + no_similar_count;
9347 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9351 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9353 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9354 if (res!=EQUIP_ERR_OK)
9355 continue;
9357 if (count==0)
9359 if (no_similar_count==0)
9360 return EQUIP_ERR_OK;
9362 if (no_space_count)
9363 *no_space_count = count + no_similar_count;
9364 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9369 // search free slot
9370 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9371 if (res!=EQUIP_ERR_OK)
9373 if (no_space_count)
9374 *no_space_count = count + no_similar_count;
9375 return res;
9378 if (count==0)
9380 if (no_similar_count==0)
9381 return EQUIP_ERR_OK;
9383 if (no_space_count)
9384 *no_space_count = count + no_similar_count;
9385 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9388 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9390 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9391 if (res!=EQUIP_ERR_OK)
9392 continue;
9394 if (count==0)
9396 if (no_similar_count==0)
9397 return EQUIP_ERR_OK;
9399 if (no_space_count)
9400 *no_space_count = count + no_similar_count;
9401 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9405 if (no_space_count)
9406 *no_space_count = count + no_similar_count;
9408 return EQUIP_ERR_INVENTORY_FULL;
9411 //////////////////////////////////////////////////////////////////////////
9412 uint8 Player::CanStoreItems( Item **pItems,int count) const
9414 Item *pItem2;
9416 // fill space table
9417 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9418 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9419 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9420 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9422 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9423 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9424 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9425 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9427 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9429 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9431 if (pItem2 && !pItem2->IsInTrade())
9433 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9437 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9439 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9441 if (pItem2 && !pItem2->IsInTrade())
9443 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9447 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9449 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9451 if (pItem2 && !pItem2->IsInTrade())
9453 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9457 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9459 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9461 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9463 pItem2 = GetItemByPos( i, j );
9464 if (pItem2 && !pItem2->IsInTrade())
9466 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9472 // check free space for all items
9473 for (int k = 0; k < count; ++k)
9475 Item *pItem = pItems[k];
9477 // no item
9478 if (!pItem) continue;
9480 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9481 ItemPrototype const *pProto = pItem->GetProto();
9483 // strange item
9484 if( !pProto )
9485 return EQUIP_ERR_ITEM_NOT_FOUND;
9487 // item it 'bind'
9488 if(pItem->IsBindedNotWith(this))
9489 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9491 Bag *pBag;
9492 ItemPrototype const *pBagProto;
9494 // item is 'one item only'
9495 uint8 res = CanTakeMoreSimilarItems(pItem);
9496 if(res != EQUIP_ERR_OK)
9497 return res;
9499 // search stack for merge to
9500 if( pProto->Stackable != 1 )
9502 bool b_found = false;
9504 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9506 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9507 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9509 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9510 b_found = true;
9511 break;
9514 if (b_found) continue;
9516 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9518 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9519 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9521 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9522 b_found = true;
9523 break;
9526 if (b_found) continue;
9528 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9530 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9531 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9533 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9534 b_found = true;
9535 break;
9538 if (b_found) continue;
9540 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9542 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9543 if( pBag )
9545 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9547 pItem2 = GetItemByPos( t, j );
9548 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9550 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9551 b_found = true;
9552 break;
9557 if (b_found) continue;
9560 // special bag case
9561 if( pProto->BagFamily )
9563 bool b_found = false;
9564 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9566 uint32 keyringSize = GetMaxKeyringSize();
9567 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9569 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9571 inv_keys[t-KEYRING_SLOT_START] = 1;
9572 b_found = true;
9573 break;
9578 if (b_found) continue;
9580 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9582 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9584 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9586 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9587 b_found = true;
9588 break;
9593 if (b_found) continue;
9595 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9597 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9598 if( pBag )
9600 pBagProto = pBag->GetProto();
9602 // not plain container check
9603 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9604 ItemCanGoIntoBag(pProto,pBagProto) )
9606 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9608 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9610 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9611 b_found = true;
9612 break;
9618 if (b_found) continue;
9621 // search free slot
9622 bool b_found = false;
9623 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9625 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9627 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9628 b_found = true;
9629 break;
9632 if (b_found) continue;
9634 // search free slot in bags
9635 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9637 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9638 if( pBag )
9640 pBagProto = pBag->GetProto();
9642 // special bag already checked
9643 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9644 continue;
9646 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9648 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9650 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9651 b_found = true;
9652 break;
9658 // no free slot found?
9659 if (!b_found)
9660 return EQUIP_ERR_INVENTORY_FULL;
9663 return EQUIP_ERR_OK;
9666 //////////////////////////////////////////////////////////////////////////
9667 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9669 dest = 0;
9670 Item *pItem = Item::CreateItem( item, 1, this );
9671 if( pItem )
9673 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9674 delete pItem;
9675 return result;
9678 return EQUIP_ERR_ITEM_NOT_FOUND;
9681 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9683 dest = 0;
9684 if( pItem )
9686 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9687 ItemPrototype const *pProto = pItem->GetProto();
9688 if( pProto )
9690 if(pItem->IsBindedNotWith(this))
9691 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9693 // check count of items (skip for auto move for same player from bank)
9694 uint8 res = CanTakeMoreSimilarItems(pItem);
9695 if(res != EQUIP_ERR_OK)
9696 return res;
9698 // check this only in game
9699 if(not_loading)
9701 // May be here should be more stronger checks; STUNNED checked
9702 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9703 if (hasUnitState(UNIT_STAT_STUNNED))
9704 return EQUIP_ERR_YOU_ARE_STUNNED;
9706 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9707 // - combat
9708 // - in-progress arenas
9709 if( !pProto->CanChangeEquipStateInCombat() )
9711 if( isInCombat() )
9712 return EQUIP_ERR_NOT_IN_COMBAT;
9714 if(BattleGround* bg = GetBattleGround())
9715 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9716 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9719 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9720 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9722 if(IsNonMeleeSpellCasted(false))
9723 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9726 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9727 if (ssd && ssd->MaxLevel < getLevel())
9728 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9730 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9731 if (eslot == NULL_SLOT)
9732 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9734 uint8 msg = CanUseItem(pItem , not_loading);
9735 if (msg != EQUIP_ERR_OK)
9736 return msg;
9737 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9738 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9740 // if swap ignore item (equipped also)
9741 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9742 return res2;
9744 // check unique-equipped special item classes
9745 if (pProto->Class == ITEM_CLASS_QUIVER)
9747 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9749 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9751 if (pBag != pItem)
9753 if (ItemPrototype const* pBagProto = pBag->GetProto())
9755 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9756 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9757 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9758 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9765 uint32 type = pProto->InventoryType;
9767 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9769 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9771 if (!CanDualWield())
9772 return EQUIP_ERR_CANT_DUAL_WIELD;
9774 else if (type == INVTYPE_2HWEAPON)
9776 if (!CanDualWield() || !CanTitanGrip())
9777 return EQUIP_ERR_CANT_DUAL_WIELD;
9780 if (IsTwoHandUsed())
9781 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9784 // equip two-hand weapon case (with possible unequip 2 items)
9785 if (type == INVTYPE_2HWEAPON)
9787 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9789 if (!CanTitanGrip())
9790 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9792 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9793 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9795 if (!CanTitanGrip())
9797 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9798 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9799 ItemPosCountVec off_dest;
9800 if (offItem && (!not_loading ||
9801 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9802 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9803 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9806 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9807 return EQUIP_ERR_OK;
9811 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9814 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9816 // Applied only to equipped items and bank bags
9817 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9818 return EQUIP_ERR_OK;
9820 Item* pItem = GetItemByPos(pos);
9822 // Applied only to existed equipped item
9823 if( !pItem )
9824 return EQUIP_ERR_OK;
9826 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9828 ItemPrototype const *pProto = pItem->GetProto();
9829 if( !pProto )
9830 return EQUIP_ERR_ITEM_NOT_FOUND;
9832 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9833 // - combat
9834 // - in-progress arenas
9835 if( !pProto->CanChangeEquipStateInCombat() )
9837 if( isInCombat() )
9838 return EQUIP_ERR_NOT_IN_COMBAT;
9840 if(BattleGround* bg = GetBattleGround())
9841 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9842 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9845 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9846 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9848 return EQUIP_ERR_OK;
9851 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9853 if (!pItem)
9854 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9856 uint32 count = pItem->GetCount();
9858 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9859 ItemPrototype const *pProto = pItem->GetProto();
9860 if (!pProto)
9861 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9863 if (pItem->IsBindedNotWith(this))
9864 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9866 // check count of items (skip for auto move for same player from bank)
9867 uint8 res = CanTakeMoreSimilarItems(pItem);
9868 if (res != EQUIP_ERR_OK)
9869 return res;
9871 // in specific slot
9872 if (bag != NULL_BAG && slot != NULL_SLOT)
9874 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9876 if (!pItem->IsBag())
9877 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9879 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9880 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9882 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9883 return cantuse;
9886 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9887 if (res!=EQUIP_ERR_OK)
9888 return res;
9890 if (count==0)
9891 return EQUIP_ERR_OK;
9894 // not specific slot or have space for partly store only in specific slot
9896 // in specific bag
9897 if( bag != NULL_BAG )
9899 if( pProto->InventoryType == INVTYPE_BAG )
9901 Bag *pBag = (Bag*)pItem;
9902 if( pBag && !pBag->IsEmpty() )
9903 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9906 // search stack in bag for merge to
9907 if( pProto->Stackable != 1 )
9909 if( bag == INVENTORY_SLOT_BAG_0 )
9911 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9912 if(res!=EQUIP_ERR_OK)
9913 return res;
9915 if(count==0)
9916 return EQUIP_ERR_OK;
9918 else
9920 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9921 if(res!=EQUIP_ERR_OK)
9922 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9924 if(res!=EQUIP_ERR_OK)
9925 return res;
9927 if(count==0)
9928 return EQUIP_ERR_OK;
9932 // search free slot in bag
9933 if( bag == INVENTORY_SLOT_BAG_0 )
9935 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9936 if(res!=EQUIP_ERR_OK)
9937 return res;
9939 if(count==0)
9940 return EQUIP_ERR_OK;
9942 else
9944 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9945 if(res != EQUIP_ERR_OK)
9946 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9948 if(res != EQUIP_ERR_OK)
9949 return res;
9951 if(count == 0)
9952 return EQUIP_ERR_OK;
9956 // not specific bag or have space for partly store only in specific bag
9958 // search stack for merge to
9959 if( pProto->Stackable != 1 )
9961 // in slots
9962 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9963 if(res != EQUIP_ERR_OK)
9964 return res;
9966 if(count == 0)
9967 return EQUIP_ERR_OK;
9969 // in special bags
9970 if( pProto->BagFamily )
9972 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9974 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9975 if(res!=EQUIP_ERR_OK)
9976 continue;
9978 if(count==0)
9979 return EQUIP_ERR_OK;
9983 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9985 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9986 if(res!=EQUIP_ERR_OK)
9987 continue;
9989 if(count==0)
9990 return EQUIP_ERR_OK;
9994 // search free place in special bag
9995 if( pProto->BagFamily )
9997 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9999 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10000 if(res!=EQUIP_ERR_OK)
10001 continue;
10003 if(count==0)
10004 return EQUIP_ERR_OK;
10008 // search free space
10009 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10010 if(res!=EQUIP_ERR_OK)
10011 return res;
10013 if(count==0)
10014 return EQUIP_ERR_OK;
10016 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10018 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10019 if(res!=EQUIP_ERR_OK)
10020 continue;
10022 if(count==0)
10023 return EQUIP_ERR_OK;
10025 return EQUIP_ERR_BANK_FULL;
10028 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10030 if (pItem)
10032 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10034 if (!isAlive() && not_loading)
10035 return EQUIP_ERR_YOU_ARE_DEAD;
10037 //if (isStunned())
10038 // return EQUIP_ERR_YOU_ARE_STUNNED;
10040 ItemPrototype const *pProto = pItem->GetProto();
10041 if (pProto)
10043 if (pItem->IsBindedNotWith(this))
10044 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10046 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10047 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10049 if (pItem->GetSkill() != 0)
10051 if (GetSkillValue( pItem->GetSkill() ) == 0)
10052 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10055 if (pProto->RequiredSkill != 0)
10057 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10058 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10060 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10061 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10064 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10065 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10067 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10068 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10070 if (getLevel() < pProto->RequiredLevel)
10071 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10073 return EQUIP_ERR_OK;
10076 return EQUIP_ERR_ITEM_NOT_FOUND;
10079 bool Player::CanUseItem( ItemPrototype const *pProto )
10081 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10083 if( pProto )
10085 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10086 return false;
10087 if( pProto->RequiredSkill != 0 )
10089 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10090 return false;
10091 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10092 return false;
10094 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10095 return false;
10096 if( getLevel() < pProto->RequiredLevel )
10097 return false;
10098 return true;
10100 return false;
10103 uint8 Player::CanUseAmmo( uint32 item ) const
10105 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10106 if( !isAlive() )
10107 return EQUIP_ERR_YOU_ARE_DEAD;
10108 //if( isStunned() )
10109 // return EQUIP_ERR_YOU_ARE_STUNNED;
10110 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10111 if( pProto )
10113 if( pProto->InventoryType!= INVTYPE_AMMO )
10114 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10115 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10116 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10117 if( pProto->RequiredSkill != 0 )
10119 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10120 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10121 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10122 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10124 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10125 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10126 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10127 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10129 if( getLevel() < pProto->RequiredLevel )
10130 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10132 // Requires No Ammo
10133 if(GetDummyAura(46699))
10134 return EQUIP_ERR_BAG_FULL6;
10136 return EQUIP_ERR_OK;
10138 return EQUIP_ERR_ITEM_NOT_FOUND;
10141 void Player::SetAmmo( uint32 item )
10143 if(!item)
10144 return;
10146 // already set
10147 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10148 return;
10150 // check ammo
10151 if(item)
10153 uint8 msg = CanUseAmmo( item );
10154 if( msg != EQUIP_ERR_OK )
10156 SendEquipError( msg, NULL, NULL );
10157 return;
10161 SetUInt32Value(PLAYER_AMMO_ID, item);
10163 _ApplyAmmoBonuses();
10166 void Player::RemoveAmmo()
10168 SetUInt32Value(PLAYER_AMMO_ID, 0);
10170 m_ammoDPS = 0.0f;
10172 if(CanModifyStats())
10173 UpdateDamagePhysical(RANGED_ATTACK);
10176 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10177 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10179 uint32 count = 0;
10180 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10181 count += itr->count;
10183 Item *pItem = Item::CreateItem( item, count, this );
10184 if( pItem )
10186 ItemAddedQuestCheck( item, count );
10187 if(randomPropertyId)
10188 pItem->SetItemRandomProperties(randomPropertyId);
10189 pItem = StoreItem( dest, pItem, update );
10191 return pItem;
10194 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10196 if( !pItem )
10197 return NULL;
10199 Item* lastItem = pItem;
10200 uint32 entry = pItem->GetEntry();
10201 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10203 uint16 pos = itr->pos;
10204 uint32 count = itr->count;
10206 ++itr;
10208 if(itr == dest.end())
10210 lastItem = _StoreItem(pos,pItem,count,false,update);
10211 break;
10214 lastItem = _StoreItem(pos,pItem,count,true,update);
10216 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10217 return lastItem;
10220 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10221 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10223 if( !pItem )
10224 return NULL;
10226 uint8 bag = pos >> 8;
10227 uint8 slot = pos & 255;
10229 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10231 Item *pItem2 = GetItemByPos( bag, slot );
10233 if (!pItem2)
10235 if (clone)
10236 pItem = pItem->CloneItem(count, this);
10237 else
10238 pItem->SetCount(count);
10240 if (!pItem)
10241 return NULL;
10243 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10244 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10245 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10246 pItem->SetBinding( true );
10248 if (bag == INVENTORY_SLOT_BAG_0)
10250 m_items[slot] = pItem;
10251 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10252 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10253 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10255 pItem->SetSlot( slot );
10256 pItem->SetContainer( NULL );
10258 // need update known currency
10259 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10260 UpdateKnownCurrencies(pItem->GetEntry(), true);
10262 if (IsInWorld() && update)
10264 pItem->AddToWorld();
10265 pItem->SendUpdateToPlayer( this );
10268 pItem->SetState(ITEM_CHANGED, this);
10270 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10272 pBag->StoreItem( slot, pItem, update );
10273 if( IsInWorld() && update )
10275 pItem->AddToWorld();
10276 pItem->SendUpdateToPlayer( this );
10278 pItem->SetState(ITEM_CHANGED, this);
10279 pBag->SetState(ITEM_CHANGED, this);
10282 AddEnchantmentDurations(pItem);
10283 AddItemDurations(pItem);
10285 return pItem;
10287 else
10289 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10290 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10291 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10292 pItem2->SetBinding( true );
10294 pItem2->SetCount( pItem2->GetCount() + count );
10295 if (IsInWorld() && update)
10296 pItem2->SendUpdateToPlayer( this );
10298 if (!clone)
10300 // delete item (it not in any slot currently)
10301 if (IsInWorld() && update)
10303 pItem->RemoveFromWorld();
10304 pItem->DestroyForPlayer( this );
10307 RemoveEnchantmentDurations(pItem);
10308 RemoveItemDurations(pItem);
10310 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10311 pItem->SetState(ITEM_REMOVED, this);
10314 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10315 AddEnchantmentDurations(pItem2);
10317 pItem2->SetState(ITEM_CHANGED, this);
10319 return pItem2;
10323 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10325 if (Item *pItem = Item::CreateItem( item, 1, this ))
10327 ItemAddedQuestCheck( item, 1 );
10328 return EquipItem( pos, pItem, update );
10331 return NULL;
10334 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10337 AddEnchantmentDurations(pItem);
10338 AddItemDurations(pItem);
10340 uint8 bag = pos >> 8;
10341 uint8 slot = pos & 255;
10343 Item *pItem2 = GetItemByPos( bag, slot );
10345 if( !pItem2 )
10347 VisualizeItem( slot, pItem);
10349 if(isAlive())
10351 ItemPrototype const *pProto = pItem->GetProto();
10353 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10354 if(pProto && pProto->ItemSet)
10355 AddItemsSetItem(this, pItem);
10357 _ApplyItemMods(pItem, slot, true);
10359 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10361 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10363 if (getClass() == CLASS_ROGUE)
10364 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10366 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10368 if (!spellProto)
10369 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10370 else
10372 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10374 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10375 data << uint64(GetGUID());
10376 data << uint8(1);
10377 data << uint32(cooldownSpell);
10378 data << uint32(0);
10379 GetSession()->SendPacket(&data);
10384 if( IsInWorld() && update )
10386 pItem->AddToWorld();
10387 pItem->SendUpdateToPlayer( this );
10390 ApplyEquipCooldown(pItem);
10392 if( slot == EQUIPMENT_SLOT_MAINHAND )
10393 UpdateExpertise(BASE_ATTACK);
10394 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10395 UpdateExpertise(OFF_ATTACK);
10397 else
10399 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10400 if( IsInWorld() && update )
10401 pItem2->SendUpdateToPlayer( this );
10403 // delete item (it not in any slot currently)
10404 //pItem->DeleteFromDB();
10405 if( IsInWorld() && update )
10407 pItem->RemoveFromWorld();
10408 pItem->DestroyForPlayer( this );
10411 RemoveEnchantmentDurations(pItem);
10412 RemoveItemDurations(pItem);
10414 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10415 pItem->SetState(ITEM_REMOVED, this);
10416 pItem2->SetState(ITEM_CHANGED, this);
10418 ApplyEquipCooldown(pItem2);
10420 return pItem2;
10423 // only for full equip instead adding to stack
10424 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10426 return pItem;
10429 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10431 if( pItem )
10433 AddEnchantmentDurations(pItem);
10434 AddItemDurations(pItem);
10436 uint8 slot = pos & 255;
10437 VisualizeItem( slot, pItem);
10439 if( IsInWorld() )
10441 pItem->AddToWorld();
10442 pItem->SendUpdateToPlayer( this );
10445 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10449 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10451 if(pItem)
10453 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10454 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10455 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10457 else
10459 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10460 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10464 void Player::VisualizeItem( uint8 slot, Item *pItem)
10466 if(!pItem)
10467 return;
10469 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10470 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10471 pItem->SetBinding( true );
10473 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10475 m_items[slot] = pItem;
10476 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10477 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10478 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10479 pItem->SetSlot( slot );
10480 pItem->SetContainer( NULL );
10482 if( slot < EQUIPMENT_SLOT_END )
10483 SetVisibleItemSlot(slot, pItem);
10485 pItem->SetState(ITEM_CHANGED, this);
10488 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10490 // note: removeitem does not actually change the item
10491 // it only takes the item out of storage temporarily
10492 // note2: if removeitem is to be used for delinking
10493 // the item must be removed from the player's updatequeue
10495 Item *pItem = GetItemByPos( bag, slot );
10496 if( pItem )
10498 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10500 RemoveEnchantmentDurations(pItem);
10501 RemoveItemDurations(pItem);
10503 if( bag == INVENTORY_SLOT_BAG_0 )
10505 if ( slot < INVENTORY_SLOT_BAG_END )
10507 ItemPrototype const *pProto = pItem->GetProto();
10508 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10510 if(pProto && pProto->ItemSet)
10511 RemoveItemsSetItem(this, pProto);
10513 _ApplyItemMods(pItem, slot, false);
10515 // remove item dependent auras and casts (only weapon and armor slots)
10516 if(slot < EQUIPMENT_SLOT_END)
10518 RemoveItemDependentAurasAndCasts(pItem);
10520 // remove held enchantments, update expertise
10521 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10523 if (pItem->GetItemSuffixFactor())
10525 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10526 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10528 else
10530 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10531 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10534 UpdateExpertise(BASE_ATTACK);
10536 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10537 UpdateExpertise(OFF_ATTACK);
10540 // need update known currency
10541 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10542 UpdateKnownCurrencies(pItem->GetEntry(), false);
10544 m_items[slot] = NULL;
10545 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10547 if ( slot < EQUIPMENT_SLOT_END )
10548 SetVisibleItemSlot(slot, NULL);
10550 else
10552 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10553 if( pBag )
10554 pBag->RemoveItem(slot, update);
10556 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10557 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10558 pItem->SetSlot( NULL_SLOT );
10559 if( IsInWorld() && update )
10560 pItem->SendUpdateToPlayer( this );
10564 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10565 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10567 if(Item* it = GetItemByPos(bag,slot))
10569 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10570 RemoveItem(bag, slot, update);
10571 it->RemoveFromUpdateQueueOf(this);
10572 if(it->IsInWorld())
10574 it->RemoveFromWorld();
10575 it->DestroyForPlayer( this );
10580 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10581 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10583 // update quest counters
10584 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10586 // store item
10587 Item* pLastItem = StoreItem(dest, pItem, update);
10589 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10590 if(pLastItem == pItem)
10592 // update owner for last item (this can be original item with wrong owner
10593 if(pLastItem->GetOwnerGUID() != GetGUID())
10594 pLastItem->SetOwnerGUID(GetGUID());
10596 // if this original item then it need create record in inventory
10597 // in case trade we already have item in other player inventory
10598 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10602 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10604 Item *pItem = GetItemByPos( bag, slot );
10605 if( pItem )
10607 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10609 // start from destroy contained items (only equipped bag can have its)
10610 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10612 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10613 DestroyItem(slot, i, update);
10616 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10617 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10619 RemoveEnchantmentDurations(pItem);
10620 RemoveItemDurations(pItem);
10622 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10624 if( bag == INVENTORY_SLOT_BAG_0 )
10626 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10628 // equipment and equipped bags can have applied bonuses
10629 if ( slot < INVENTORY_SLOT_BAG_END )
10631 ItemPrototype const *pProto = pItem->GetProto();
10633 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10634 if(pProto && pProto->ItemSet)
10635 RemoveItemsSetItem(this, pProto);
10637 _ApplyItemMods(pItem, slot, false);
10640 if ( slot < EQUIPMENT_SLOT_END )
10642 // remove item dependent auras and casts (only weapon and armor slots)
10643 RemoveItemDependentAurasAndCasts(pItem);
10645 // update expertise
10646 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10647 UpdateExpertise(BASE_ATTACK);
10648 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10649 UpdateExpertise(OFF_ATTACK);
10651 // equipment visual show
10652 SetVisibleItemSlot(slot, NULL);
10654 // need update known currency
10655 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10656 UpdateKnownCurrencies(pItem->GetEntry(), false);
10658 m_items[slot] = NULL;
10660 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10661 pBag->RemoveItem(slot, update);
10663 if( IsInWorld() && update )
10665 pItem->RemoveFromWorld();
10666 pItem->DestroyForPlayer(this);
10669 //pItem->SetOwnerGUID(0);
10670 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10671 pItem->SetSlot( NULL_SLOT );
10672 pItem->SetState(ITEM_REMOVED, this);
10676 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10678 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10679 uint32 remcount = 0;
10681 // in inventory
10682 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10684 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10686 if (pItem->GetEntry() == item)
10688 if (pItem->GetCount() + remcount <= count)
10690 // all items in inventory can unequipped
10691 remcount += pItem->GetCount();
10692 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10694 if (remcount >= count)
10695 return;
10697 else
10699 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10700 pItem->SetCount( pItem->GetCount() - count + remcount );
10701 if (IsInWorld() & update)
10702 pItem->SendUpdateToPlayer( this );
10703 pItem->SetState(ITEM_CHANGED, this);
10704 return;
10710 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10712 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10714 if (pItem->GetEntry() == item)
10716 if (pItem->GetCount() + remcount <= count)
10718 // all keys can be unequipped
10719 remcount += pItem->GetCount();
10720 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10722 if (remcount >= count)
10723 return;
10725 else
10727 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10728 pItem->SetCount( pItem->GetCount() - count + remcount );
10729 if (IsInWorld() & update)
10730 pItem->SendUpdateToPlayer( this );
10731 pItem->SetState(ITEM_CHANGED, this);
10732 return;
10738 // in inventory bags
10739 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10741 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10743 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10745 if(Item* pItem = pBag->GetItemByPos(j))
10747 if (pItem->GetEntry() == item)
10749 // all items in bags can be unequipped
10750 if (pItem->GetCount() + remcount <= count)
10752 remcount += pItem->GetCount();
10753 DestroyItem( i, j, update );
10755 if (remcount >= count)
10756 return;
10758 else
10760 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10761 pItem->SetCount( pItem->GetCount() - count + remcount );
10762 if (IsInWorld() && update)
10763 pItem->SendUpdateToPlayer( this );
10764 pItem->SetState(ITEM_CHANGED, this);
10765 return;
10773 // in equipment and bag list
10774 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10776 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10778 if (pItem && pItem->GetEntry() == item)
10780 if (pItem->GetCount() + remcount <= count)
10782 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10784 remcount += pItem->GetCount();
10785 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10787 if (remcount >= count)
10788 return;
10791 else
10793 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10794 pItem->SetCount( pItem->GetCount() - count + remcount );
10795 if (IsInWorld() & update)
10796 pItem->SendUpdateToPlayer( this );
10797 pItem->SetState(ITEM_CHANGED, this);
10798 return;
10805 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10807 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10809 // in inventory
10810 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10811 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10812 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10813 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10815 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10816 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10817 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10818 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10820 // in inventory bags
10821 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10822 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10823 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10824 if (Item* pItem = pBag->GetItemByPos(j))
10825 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10826 DestroyItem(i, j, update);
10828 // in equipment and bag list
10829 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10830 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10831 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10832 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10835 void Player::DestroyConjuredItems( bool update )
10837 // used when entering arena
10838 // destroys all conjured items
10839 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10841 // in inventory
10842 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10843 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10844 if (pItem->IsConjuredConsumable())
10845 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10847 // in inventory bags
10848 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10849 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10850 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10851 if (Item* pItem = pBag->GetItemByPos(j))
10852 if (pItem->IsConjuredConsumable())
10853 DestroyItem( i, j, update);
10855 // in equipment and bag list
10856 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10857 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10858 if (pItem->IsConjuredConsumable())
10859 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10862 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10864 if(!pItem)
10865 return;
10867 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10869 if( pItem->GetCount() <= count )
10871 count -= pItem->GetCount();
10873 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10875 else
10877 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10878 pItem->SetCount( pItem->GetCount() - count );
10879 count = 0;
10880 if( IsInWorld() & update )
10881 pItem->SendUpdateToPlayer( this );
10882 pItem->SetState(ITEM_CHANGED, this);
10886 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10888 uint8 srcbag = src >> 8;
10889 uint8 srcslot = src & 255;
10891 uint8 dstbag = dst >> 8;
10892 uint8 dstslot = dst & 255;
10894 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10895 if( !pSrcItem )
10897 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10898 return;
10901 // not let split all items (can be only at cheating)
10902 if(pSrcItem->GetCount() == count)
10904 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10905 return;
10908 // not let split more existed items (can be only at cheating)
10909 if(pSrcItem->GetCount() < count)
10911 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10912 return;
10915 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10917 //best error message found for attempting to split while looting
10918 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10919 return;
10922 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10923 Item *pNewItem = pSrcItem->CloneItem( count, this );
10924 if( !pNewItem )
10926 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10927 return;
10930 if( IsInventoryPos( dst ) )
10932 // change item amount before check (for unique max count check)
10933 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10935 ItemPosCountVec dest;
10936 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10937 if( msg != EQUIP_ERR_OK )
10939 delete pNewItem;
10940 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10941 SendEquipError( msg, pSrcItem, NULL );
10942 return;
10945 if( IsInWorld() )
10946 pSrcItem->SendUpdateToPlayer( this );
10947 pSrcItem->SetState(ITEM_CHANGED, this);
10948 StoreItem( dest, pNewItem, true);
10950 else if( IsBankPos ( dst ) )
10952 // change item amount before check (for unique max count check)
10953 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10955 ItemPosCountVec dest;
10956 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10957 if( msg != EQUIP_ERR_OK )
10959 delete pNewItem;
10960 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10961 SendEquipError( msg, pSrcItem, NULL );
10962 return;
10965 if( IsInWorld() )
10966 pSrcItem->SendUpdateToPlayer( this );
10967 pSrcItem->SetState(ITEM_CHANGED, this);
10968 BankItem( dest, pNewItem, true);
10970 else if( IsEquipmentPos ( dst ) )
10972 // change item amount before check (for unique max count check), provide space for splitted items
10973 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10975 uint16 dest;
10976 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10977 if( msg != EQUIP_ERR_OK )
10979 delete pNewItem;
10980 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10981 SendEquipError( msg, pSrcItem, NULL );
10982 return;
10985 if( IsInWorld() )
10986 pSrcItem->SendUpdateToPlayer( this );
10987 pSrcItem->SetState(ITEM_CHANGED, this);
10988 EquipItem( dest, pNewItem, true);
10989 AutoUnequipOffhandIfNeed();
10993 void Player::SwapItem( uint16 src, uint16 dst )
10995 uint8 srcbag = src >> 8;
10996 uint8 srcslot = src & 255;
10998 uint8 dstbag = dst >> 8;
10999 uint8 dstslot = dst & 255;
11001 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11002 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11004 if( !pSrcItem )
11005 return;
11007 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11009 if(!isAlive() )
11011 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11012 return;
11015 // SRC checks
11017 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11019 //best error message found for attempting to swap while looting
11020 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11021 return;
11024 // check unequip potability for equipped items and bank bags
11025 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11027 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11028 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11029 if(msg != EQUIP_ERR_OK)
11031 SendEquipError( msg, pSrcItem, pDstItem );
11032 return;
11036 // prevent put equipped/bank bag in self
11037 if( IsBagPos ( src ) && srcslot == dstbag)
11039 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11040 return;
11043 // DST checks
11045 if (pDstItem)
11047 if(pDstItem->m_lootGenerated) // prevent swap looting item
11049 //best error message found for attempting to swap while looting
11050 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11051 return;
11054 // check unequip potability for equipped items and bank bags
11055 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11057 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11058 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11059 if(msg != EQUIP_ERR_OK)
11061 SendEquipError( msg, pSrcItem, pDstItem );
11062 return;
11067 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11068 // or swap empty bag with another empty or not empty bag (with items exchange)
11070 // Move case
11071 if( !pDstItem )
11073 if( IsInventoryPos( dst ) )
11075 ItemPosCountVec dest;
11076 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11077 if( msg != EQUIP_ERR_OK )
11079 SendEquipError( msg, pSrcItem, NULL );
11080 return;
11083 RemoveItem(srcbag, srcslot, true);
11084 StoreItem( dest, pSrcItem, true);
11086 else if( IsBankPos ( dst ) )
11088 ItemPosCountVec dest;
11089 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11090 if( msg != EQUIP_ERR_OK )
11092 SendEquipError( msg, pSrcItem, NULL );
11093 return;
11096 RemoveItem(srcbag, srcslot, true);
11097 BankItem( dest, pSrcItem, true);
11099 else if( IsEquipmentPos ( dst ) )
11101 uint16 dest;
11102 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11103 if( msg != EQUIP_ERR_OK )
11105 SendEquipError( msg, pSrcItem, NULL );
11106 return;
11109 RemoveItem(srcbag, srcslot, true);
11110 EquipItem(dest, pSrcItem, true);
11111 AutoUnequipOffhandIfNeed();
11114 return;
11117 // attempt merge to / fill target item
11118 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11120 uint8 msg;
11121 ItemPosCountVec sDest;
11122 uint16 eDest;
11123 if( IsInventoryPos( dst ) )
11124 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11125 else if( IsBankPos ( dst ) )
11126 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11127 else if( IsEquipmentPos ( dst ) )
11128 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11129 else
11130 return;
11132 // can be merge/fill
11133 if(msg == EQUIP_ERR_OK)
11135 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11137 RemoveItem(srcbag, srcslot, true);
11139 if( IsInventoryPos( dst ) )
11140 StoreItem( sDest, pSrcItem, true);
11141 else if( IsBankPos ( dst ) )
11142 BankItem( sDest, pSrcItem, true);
11143 else if( IsEquipmentPos ( dst ) )
11145 EquipItem( eDest, pSrcItem, true);
11146 AutoUnequipOffhandIfNeed();
11149 else
11151 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11152 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11153 pSrcItem->SetState(ITEM_CHANGED, this);
11154 pDstItem->SetState(ITEM_CHANGED, this);
11155 if( IsInWorld() )
11157 pSrcItem->SendUpdateToPlayer( this );
11158 pDstItem->SendUpdateToPlayer( this );
11161 return;
11165 // impossible merge/fill, do real swap
11166 uint8 msg;
11168 // check src->dest move possibility
11169 ItemPosCountVec sDest;
11170 uint16 eDest = 0;
11171 if( IsInventoryPos( dst ) )
11172 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11173 else if( IsBankPos( dst ) )
11174 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11175 else if( IsEquipmentPos( dst ) )
11177 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11178 if( msg == EQUIP_ERR_OK )
11179 msg = CanUnequipItem( eDest, true );
11182 if( msg != EQUIP_ERR_OK )
11184 SendEquipError( msg, pSrcItem, pDstItem );
11185 return;
11188 // check dest->src move possibility
11189 ItemPosCountVec sDest2;
11190 uint16 eDest2 = 0;
11191 if( IsInventoryPos( src ) )
11192 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11193 else if( IsBankPos( src ) )
11194 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11195 else if( IsEquipmentPos( src ) )
11197 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11198 if( msg == EQUIP_ERR_OK )
11199 msg = CanUnequipItem( eDest2, true);
11202 if( msg != EQUIP_ERR_OK )
11204 SendEquipError( msg, pDstItem, pSrcItem );
11205 return;
11208 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11209 if(pSrcItem->IsBag() && pDstItem->IsBag())
11211 Bag* emptyBag = NULL;
11212 Bag* fullBag = NULL;
11213 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11215 emptyBag = (Bag*)pSrcItem;
11216 fullBag = (Bag*)pDstItem;
11218 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11220 emptyBag = (Bag*)pDstItem;
11221 fullBag = (Bag*)pSrcItem;
11224 // bag swap (with items exchange) case
11225 if(emptyBag && fullBag)
11227 ItemPrototype const* emotyProto = emptyBag->GetProto();
11229 uint32 count = 0;
11231 for(int i=0; i < fullBag->GetBagSize(); ++i)
11233 Item *bagItem = fullBag->GetItemByPos(i);
11234 if (!bagItem)
11235 continue;
11237 ItemPrototype const* bagItemProto = bagItem->GetProto();
11238 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11240 // one from items not go to empty target bag
11241 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11242 return;
11245 ++count;
11249 if (count > emptyBag->GetBagSize())
11251 // too small targeted bag
11252 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11253 return;
11256 // Items swap
11257 count = 0; // will pos in new bag
11258 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11260 Item *bagItem = fullBag->GetItemByPos(i);
11261 if (!bagItem)
11262 continue;
11264 fullBag->RemoveItem(i, true);
11265 emptyBag->StoreItem(count, bagItem, true);
11266 bagItem->SetState(ITEM_CHANGED, this);
11268 ++count;
11273 // now do moves, remove...
11274 RemoveItem(dstbag, dstslot, false);
11275 RemoveItem(srcbag, srcslot, false);
11277 // add to dest
11278 if( IsInventoryPos( dst ) )
11279 StoreItem(sDest, pSrcItem, true);
11280 else if( IsBankPos( dst ) )
11281 BankItem(sDest, pSrcItem, true);
11282 else if( IsEquipmentPos( dst ) )
11283 EquipItem(eDest, pSrcItem, true);
11285 // add to src
11286 if( IsInventoryPos( src ) )
11287 StoreItem(sDest2, pDstItem, true);
11288 else if( IsBankPos( src ) )
11289 BankItem(sDest2, pDstItem, true);
11290 else if( IsEquipmentPos( src ) )
11291 EquipItem(eDest2, pDstItem, true);
11293 AutoUnequipOffhandIfNeed();
11296 void Player::AddItemToBuyBackSlot( Item *pItem )
11298 if( pItem )
11300 uint32 slot = m_currentBuybackSlot;
11301 // if current back slot non-empty search oldest or free
11302 if(m_items[slot])
11304 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11305 uint32 oldest_slot = BUYBACK_SLOT_START;
11307 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11309 // found empty
11310 if(!m_items[i])
11312 slot = i;
11313 break;
11316 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11318 if(oldest_time > i_time)
11320 oldest_time = i_time;
11321 oldest_slot = i;
11325 // find oldest
11326 slot = oldest_slot;
11329 RemoveItemFromBuyBackSlot( slot, true );
11330 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11332 m_items[slot] = pItem;
11333 time_t base = time(NULL);
11334 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11335 uint32 eslot = slot - BUYBACK_SLOT_START;
11337 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11338 ItemPrototype const *pProto = pItem->GetProto();
11339 if( pProto )
11340 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11341 else
11342 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11343 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11345 // move to next (for non filled list is move most optimized choice)
11346 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11347 ++m_currentBuybackSlot;
11351 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11353 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11354 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11355 return m_items[slot];
11356 return NULL;
11359 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11361 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11362 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11364 Item *pItem = m_items[slot];
11365 if( pItem )
11367 pItem->RemoveFromWorld();
11368 if(del) pItem->SetState(ITEM_REMOVED, this);
11371 m_items[slot] = NULL;
11373 uint32 eslot = slot - BUYBACK_SLOT_START;
11374 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11375 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11376 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11378 // if current backslot is filled set to now free slot
11379 if(m_items[m_currentBuybackSlot])
11380 m_currentBuybackSlot = slot;
11384 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11386 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11387 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11388 data << uint8(msg);
11390 if(msg)
11392 data << uint64(pItem ? pItem->GetGUID() : 0);
11393 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11394 data << uint8(0); // not 0 there...
11396 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11398 uint32 level = 0;
11400 if(pItem)
11401 if(ItemPrototype const* proto = pItem->GetProto())
11402 level = proto->RequiredLevel;
11404 data << uint32(level); // new 2.4.0
11407 GetSession()->SendPacket(&data);
11410 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11412 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11413 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11414 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11415 data << uint32(item);
11416 if( param > 0 )
11417 data << uint32(param);
11418 data << uint8(msg);
11419 GetSession()->SendPacket(&data);
11422 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11424 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11425 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11426 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11427 data << uint64(guid);
11428 if( param > 0 )
11429 data << uint32(param);
11430 data << uint8(msg);
11431 GetSession()->SendPacket(&data);
11434 void Player::ClearTrade()
11436 tradeGold = 0;
11437 acceptTrade = false;
11438 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11439 tradeItems[i] = NULL_SLOT;
11442 void Player::TradeCancel(bool sendback)
11444 if(pTrader)
11446 // send yellow "Trade canceled" message to both traders
11447 WorldSession* ws;
11448 ws = GetSession();
11449 if(sendback)
11450 ws->SendCancelTrade();
11451 ws = pTrader->GetSession();
11452 if(!ws->PlayerLogout())
11453 ws->SendCancelTrade();
11455 // cleanup
11456 ClearTrade();
11457 pTrader->ClearTrade();
11458 // prevent loss of reference
11459 pTrader->pTrader = NULL;
11460 pTrader = NULL;
11464 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11466 if(m_itemDuration.empty())
11467 return;
11469 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11471 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11473 Item* item = *itr;
11474 ++itr; // current element can be erased in UpdateDuration
11476 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11477 item->UpdateDuration(this,time);
11481 void Player::UpdateEnchantTime(uint32 time)
11483 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11485 assert(itr->item);
11486 next = itr;
11487 if(!itr->item->GetEnchantmentId(itr->slot))
11489 next = m_enchantDuration.erase(itr);
11491 else if(itr->leftduration <= time)
11493 ApplyEnchantment(itr->item, itr->slot, false, false);
11494 itr->item->ClearEnchantment(itr->slot);
11495 next = m_enchantDuration.erase(itr);
11497 else if(itr->leftduration > time)
11499 itr->leftduration -= time;
11500 ++next;
11505 void Player::AddEnchantmentDurations(Item *item)
11507 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11509 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11510 continue;
11512 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11513 if( duration > 0 )
11514 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11518 void Player::RemoveEnchantmentDurations(Item *item)
11520 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11522 if(itr->item == item)
11524 // save duration in item
11525 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11526 itr = m_enchantDuration.erase(itr);
11528 else
11529 ++itr;
11533 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11535 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11536 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11538 next = itr;
11539 if(itr->slot == slot)
11541 if(itr->item && itr->item->GetEnchantmentId(slot))
11543 // remove from stats
11544 ApplyEnchantment(itr->item, slot, false, false);
11545 // remove visual
11546 itr->item->ClearEnchantment(slot);
11548 // remove from update list
11549 next = m_enchantDuration.erase(itr);
11551 else
11552 ++next;
11555 // remove enchants from inventory items
11556 // NOTE: no need to remove these from stats, since these aren't equipped
11557 // in inventory
11558 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11560 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11561 if( pItem && pItem->GetEnchantmentId(slot) )
11562 pItem->ClearEnchantment(slot);
11565 // in inventory bags
11566 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11568 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11569 if( pBag )
11571 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11573 Item* pItem = pBag->GetItemByPos(j);
11574 if( pItem && pItem->GetEnchantmentId(slot) )
11575 pItem->ClearEnchantment(slot);
11581 // duration == 0 will remove item enchant
11582 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11584 if(!item)
11585 return;
11587 if(slot >= MAX_ENCHANTMENT_SLOT)
11588 return;
11590 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11592 if(itr->item == item && itr->slot == slot)
11594 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11595 m_enchantDuration.erase(itr);
11596 break;
11599 if(item && duration > 0 )
11601 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11602 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11606 void Player::ApplyEnchantment(Item *item,bool apply)
11608 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11609 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11612 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11614 if(!item)
11615 return;
11617 if(!item->IsEquipped())
11618 return;
11620 if(slot >= MAX_ENCHANTMENT_SLOT)
11621 return;
11623 uint32 enchant_id = item->GetEnchantmentId(slot);
11624 if(!enchant_id)
11625 return;
11627 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11628 if(!pEnchant)
11629 return;
11631 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11632 return;
11634 if (!item->IsBroken())
11636 for (int s = 0; s < 3; ++s)
11638 uint32 enchant_display_type = pEnchant->type[s];
11639 uint32 enchant_amount = pEnchant->amount[s];
11640 uint32 enchant_spell_id = pEnchant->spellid[s];
11642 switch(enchant_display_type)
11644 case ITEM_ENCHANTMENT_TYPE_NONE:
11645 break;
11646 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11647 // processed in Player::CastItemCombatSpell
11648 break;
11649 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11650 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11651 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11652 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11653 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11654 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11655 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11656 break;
11657 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11658 if(enchant_spell_id)
11660 if(apply)
11662 int32 basepoints = 0;
11663 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11664 if (item->GetItemRandomPropertyId())
11666 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11667 if (item_rand)
11669 // Search enchant_amount
11670 for (int k = 0; k < 3; ++k)
11672 if(item_rand->enchant_id[k] == enchant_id)
11674 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11675 break;
11680 // Cast custom spell vs all equal basepoints getted from enchant_amount
11681 if (basepoints)
11682 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11683 else
11684 CastSpell(this, enchant_spell_id, true, item);
11686 else
11687 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11689 break;
11690 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11691 if (!enchant_amount)
11693 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11694 if(item_rand)
11696 for (int k = 0; k < 3; ++k)
11698 if(item_rand->enchant_id[k] == enchant_id)
11700 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11701 break;
11707 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11708 break;
11709 case ITEM_ENCHANTMENT_TYPE_STAT:
11711 if (!enchant_amount)
11713 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11714 if(item_rand_suffix)
11716 for (int k = 0; k < 3; ++k)
11718 if(item_rand_suffix->enchant_id[k] == enchant_id)
11720 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11721 break;
11727 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11728 switch (enchant_spell_id)
11730 case ITEM_MOD_MANA:
11731 sLog.outDebug("+ %u MANA",enchant_amount);
11732 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11733 break;
11734 case ITEM_MOD_HEALTH:
11735 sLog.outDebug("+ %u HEALTH",enchant_amount);
11736 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11737 break;
11738 case ITEM_MOD_AGILITY:
11739 sLog.outDebug("+ %u AGILITY",enchant_amount);
11740 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11741 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11742 break;
11743 case ITEM_MOD_STRENGTH:
11744 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11745 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11746 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11747 break;
11748 case ITEM_MOD_INTELLECT:
11749 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11750 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11751 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11752 break;
11753 case ITEM_MOD_SPIRIT:
11754 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11755 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11756 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11757 break;
11758 case ITEM_MOD_STAMINA:
11759 sLog.outDebug("+ %u STAMINA",enchant_amount);
11760 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11761 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11762 break;
11763 case ITEM_MOD_DEFENSE_SKILL_RATING:
11764 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11765 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11766 break;
11767 case ITEM_MOD_DODGE_RATING:
11768 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11769 sLog.outDebug("+ %u DODGE", enchant_amount);
11770 break;
11771 case ITEM_MOD_PARRY_RATING:
11772 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11773 sLog.outDebug("+ %u PARRY", enchant_amount);
11774 break;
11775 case ITEM_MOD_BLOCK_RATING:
11776 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11777 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11778 break;
11779 case ITEM_MOD_HIT_MELEE_RATING:
11780 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11781 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11782 break;
11783 case ITEM_MOD_HIT_RANGED_RATING:
11784 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11785 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11786 break;
11787 case ITEM_MOD_HIT_SPELL_RATING:
11788 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11789 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11790 break;
11791 case ITEM_MOD_CRIT_MELEE_RATING:
11792 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11793 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11794 break;
11795 case ITEM_MOD_CRIT_RANGED_RATING:
11796 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11797 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11798 break;
11799 case ITEM_MOD_CRIT_SPELL_RATING:
11800 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11801 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11802 break;
11803 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11804 // in Enchantments
11805 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11806 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11807 // break;
11808 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11809 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11810 // break;
11811 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11812 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11813 // break;
11814 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11815 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11816 // break;
11817 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11818 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11819 // break;
11820 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11821 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11822 // break;
11823 // case ITEM_MOD_HASTE_MELEE_RATING:
11824 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11825 // break;
11826 // case ITEM_MOD_HASTE_RANGED_RATING:
11827 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11828 // break;
11829 case ITEM_MOD_HASTE_SPELL_RATING:
11830 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11831 break;
11832 case ITEM_MOD_HIT_RATING:
11833 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11834 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11835 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11836 sLog.outDebug("+ %u HIT", enchant_amount);
11837 break;
11838 case ITEM_MOD_CRIT_RATING:
11839 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11840 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11841 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11842 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11843 break;
11844 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11845 // case ITEM_MOD_HIT_TAKEN_RATING:
11846 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11847 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11848 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11849 // break;
11850 // case ITEM_MOD_CRIT_TAKEN_RATING:
11851 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11852 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11853 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11854 // break;
11855 case ITEM_MOD_RESILIENCE_RATING:
11856 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11857 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11858 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11859 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11860 break;
11861 case ITEM_MOD_HASTE_RATING:
11862 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11863 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11864 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11865 sLog.outDebug("+ %u HASTE", enchant_amount);
11866 break;
11867 case ITEM_MOD_EXPERTISE_RATING:
11868 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11869 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11870 break;
11871 case ITEM_MOD_ATTACK_POWER:
11872 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11873 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11874 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11875 break;
11876 case ITEM_MOD_RANGED_ATTACK_POWER:
11877 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11878 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11879 break;
11880 case ITEM_MOD_FERAL_ATTACK_POWER:
11881 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11882 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11883 break;
11884 case ITEM_MOD_SPELL_HEALING_DONE:
11885 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11886 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11887 break;
11888 case ITEM_MOD_SPELL_DAMAGE_DONE:
11889 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11890 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11891 break;
11892 case ITEM_MOD_MANA_REGENERATION:
11893 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11894 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11895 break;
11896 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11897 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11898 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11899 break;
11900 case ITEM_MOD_SPELL_POWER:
11901 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11902 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11903 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11904 break;
11905 default:
11906 break;
11908 break;
11910 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11912 if(getClass() == CLASS_SHAMAN)
11914 float addValue = 0.0f;
11915 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11917 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11918 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11920 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11922 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11923 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11926 break;
11928 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11929 // processed in Player::CastItemUseSpell
11930 break;
11931 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11932 // nothing do..
11933 break;
11934 default:
11935 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11936 break;
11937 } /*switch(enchant_display_type)*/
11938 } /*for*/
11941 // visualize enchantment at player and equipped items
11942 if(slot == PERM_ENCHANTMENT_SLOT)
11943 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11945 if(slot == TEMP_ENCHANTMENT_SLOT)
11946 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11949 if(apply_dur)
11951 if(apply)
11953 // set duration
11954 uint32 duration = item->GetEnchantmentDuration(slot);
11955 if(duration > 0)
11956 AddEnchantmentDuration(item, slot, duration);
11958 else
11960 // duration == 0 will remove EnchantDuration
11961 AddEnchantmentDuration(item, slot, 0);
11966 void Player::SendEnchantmentDurations()
11968 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11970 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11974 void Player::SendItemDurations()
11976 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11978 (*itr)->SendTimeUpdate(this);
11982 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11984 if(!item) // prevent crash
11985 return;
11987 // last check 2.0.10
11988 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11989 data << uint64(GetGUID()); // player GUID
11990 data << uint32(received); // 0=looted, 1=from npc
11991 data << uint32(created); // 0=received, 1=created
11992 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11993 data << uint8(item->GetBagSlot()); // bagslot
11994 // item slot, but when added to stack: 0xFFFFFFFF
11995 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11996 data << uint32(item->GetEntry()); // item id
11997 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11998 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11999 data << uint32(count); // count of items
12000 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12002 if (broadcast && GetGroup())
12003 GetGroup()->BroadcastPacket(&data, true);
12004 else
12005 GetSession()->SendPacket(&data);
12008 /*********************************************************/
12009 /*** QUEST SYSTEM ***/
12010 /*********************************************************/
12012 void Player::PrepareQuestMenu( uint64 guid )
12014 Object *pObject;
12015 QuestRelations* pObjectQR;
12016 QuestRelations* pObjectQIR;
12018 // pets also can have quests
12019 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
12020 if( pCreature )
12022 pObject = (Object*)pCreature;
12023 pObjectQR = &objmgr.mCreatureQuestRelations;
12024 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12026 else
12028 GameObject *pGameObject = GetMap()->GetGameObject(guid);
12029 if( pGameObject )
12031 pObject = (Object*)pGameObject;
12032 pObjectQR = &objmgr.mGOQuestRelations;
12033 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12035 else
12036 return;
12039 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12040 qm.ClearMenu();
12042 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12044 uint32 quest_id = i->second;
12045 QuestStatus status = GetQuestStatus( quest_id );
12046 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12047 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12048 else if ( status == QUEST_STATUS_INCOMPLETE )
12049 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12050 else if (status == QUEST_STATUS_AVAILABLE )
12051 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12054 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12056 uint32 quest_id = i->second;
12057 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12058 if(!pQuest) continue;
12060 QuestStatus status = GetQuestStatus( quest_id );
12062 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12063 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12064 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12065 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12069 void Player::SendPreparedQuest( uint64 guid )
12071 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12072 if( questMenu.Empty() )
12073 return;
12075 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12077 uint32 status = qmi0.m_qIcon;
12079 // single element case
12080 if ( questMenu.MenuItemCount() == 1 )
12082 // Auto open -- maybe also should verify there is no greeting
12083 uint32 quest_id = qmi0.m_qId;
12084 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12086 if ( pQuest )
12088 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
12089 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12090 else if( status == DIALOG_STATUS_UNK2 )
12091 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12092 // Send completable on repeatable quest if player don't have quest
12093 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12094 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12095 else
12096 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12099 // multiply entries
12100 else
12102 QEmote qe;
12103 qe._Delay = 0;
12104 qe._Emote = 0;
12105 std::string title = "";
12107 // need pet case for some quests
12108 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12109 if( pCreature )
12111 uint32 textid = pCreature->GetNpcTextId();
12112 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12113 if( !gossiptext )
12115 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12116 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12117 title = "";
12119 else
12121 qe = gossiptext->Options[0].Emotes[0];
12123 if(!gossiptext->Options[0].Text_0.empty())
12125 title = gossiptext->Options[0].Text_0;
12127 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12128 if (loc_idx >= 0)
12130 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12131 if (nl)
12133 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12134 title = nl->Text_0[0][loc_idx];
12138 else
12140 title = gossiptext->Options[0].Text_1;
12142 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12143 if (loc_idx >= 0)
12145 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12146 if (nl)
12148 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12149 title = nl->Text_1[0][loc_idx];
12155 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12159 bool Player::IsActiveQuest( uint32 quest_id ) const
12161 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12163 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12166 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12168 Object *pObject;
12169 QuestRelations* pObjectQR;
12170 QuestRelations* pObjectQIR;
12172 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12173 if( pCreature )
12175 pObject = (Object*)pCreature;
12176 pObjectQR = &objmgr.mCreatureQuestRelations;
12177 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12179 else
12181 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12182 //only for quests which cast teleport spells on player
12183 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12184 ASSERT(_map);
12185 GameObject *pGameObject = _map->GetGameObject(guid);
12186 if( pGameObject )
12188 pObject = (Object*)pGameObject;
12189 pObjectQR = &objmgr.mGOQuestRelations;
12190 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12192 else
12193 return NULL;
12196 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12197 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12199 if (itr->second == nextQuestID)
12200 return objmgr.GetQuestTemplate(nextQuestID);
12203 return NULL;
12206 bool Player::CanSeeStartQuest( Quest const *pQuest )
12208 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12209 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12210 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12211 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12213 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12216 return false;
12219 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12221 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12222 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12223 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12224 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12225 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12226 && SatisfyQuestDay( pQuest, msg );
12229 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12231 if( !SatisfyQuestLog( msg ) )
12232 return false;
12234 uint32 srcitem = pQuest->GetSrcItemId();
12235 if( srcitem > 0 )
12237 uint32 count = pQuest->GetSrcItemCount();
12238 ItemPosCountVec dest;
12239 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12241 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12242 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12243 return true;
12244 else if( msg2 != EQUIP_ERR_OK )
12246 SendEquipError( msg2, NULL, NULL );
12247 return false;
12250 return true;
12253 bool Player::CanCompleteQuest( uint32 quest_id )
12255 if( quest_id )
12257 QuestStatusData& q_status = mQuestStatus[quest_id];
12258 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12259 return false; // not allow re-complete quest
12261 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12263 if(!qInfo)
12264 return false;
12266 // auto complete quest
12267 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12268 return true;
12270 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12273 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12275 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12277 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12278 return false;
12282 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12284 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12286 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12287 continue;
12289 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12290 return false;
12294 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12295 return false;
12297 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12298 return false;
12300 if ( qInfo->GetRewOrReqMoney() < 0 )
12302 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12303 return false;
12306 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12307 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12308 return false;
12310 return true;
12313 return false;
12316 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12318 // Solve problem that player don't have the quest and try complete it.
12319 // if repeatable she must be able to complete event if player don't have it.
12320 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12321 if( !CanTakeQuest(pQuest, false) )
12322 return false;
12324 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12325 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12326 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12327 return false;
12329 if( !CanRewardQuest(pQuest, false) )
12330 return false;
12332 return true;
12335 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12337 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12338 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12339 return false;
12341 // daily quest can't be rewarded (25 daily quest already completed)
12342 if(!SatisfyQuestDay(pQuest,true))
12343 return false;
12345 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12346 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12347 return false;
12349 // prevent receive reward with quest items in bank
12350 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12352 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12354 if( pQuest->ReqItemCount[i]!= 0 &&
12355 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12357 if(msg)
12358 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12359 return false;
12364 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12365 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12366 return false;
12368 return true;
12371 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12373 // prevent receive reward with quest items in bank or for not completed quest
12374 if(!CanRewardQuest(pQuest,msg))
12375 return false;
12377 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12379 if( pQuest->RewChoiceItemId[reward] )
12381 ItemPosCountVec dest;
12382 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12383 if( res != EQUIP_ERR_OK )
12385 SendEquipError( res, NULL, NULL );
12386 return false;
12391 if ( pQuest->GetRewItemsCount() > 0 )
12393 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12395 if( pQuest->RewItemId[i] )
12397 ItemPosCountVec dest;
12398 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12399 if( res != EQUIP_ERR_OK )
12401 SendEquipError( res, NULL, NULL );
12402 return false;
12408 return true;
12411 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12413 uint16 log_slot = FindQuestSlot( 0 );
12414 assert(log_slot < MAX_QUEST_LOG_SIZE);
12416 uint32 quest_id = pQuest->GetQuestId();
12418 // if not exist then created with set uState==NEW and rewarded=false
12419 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12421 // check for repeatable quests status reset
12422 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12423 questStatusData.m_explored = false;
12425 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12427 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12428 questStatusData.m_itemcount[i] = 0;
12431 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12433 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12434 questStatusData.m_creatureOrGOcount[i] = 0;
12437 GiveQuestSourceItem( pQuest );
12438 AdjustQuestReqItemCount( pQuest, questStatusData );
12440 if( pQuest->GetRepObjectiveFaction() )
12441 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12442 GetReputationMgr().SetVisible(factionEntry);
12444 uint32 qtime = 0;
12445 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12447 uint32 limittime = pQuest->GetLimitTime();
12449 // shared timed quest
12450 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12451 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12453 AddTimedQuest( quest_id );
12454 questStatusData.m_timer = limittime * IN_MILISECONDS;
12455 qtime = static_cast<uint32>(time(NULL)) + limittime;
12457 else
12458 questStatusData.m_timer = 0;
12460 SetQuestSlot(log_slot, quest_id, qtime);
12462 if (questStatusData.uState != QUEST_NEW)
12463 questStatusData.uState = QUEST_CHANGED;
12465 //starting initial quest script
12466 if(questGiver && pQuest->GetQuestStartScript()!=0)
12467 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12469 // Some spells applied at quest activation
12470 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12471 if(saBounds.first != saBounds.second)
12473 uint32 zone, area;
12474 GetZoneAndAreaId(zone,area);
12476 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12477 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12478 if( !HasAura(itr->second->spellId,0) )
12479 CastSpell(this,itr->second->spellId,true);
12482 UpdateForQuestWorldObjects();
12485 void Player::CompleteQuest( uint32 quest_id )
12487 if( quest_id )
12489 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12491 uint16 log_slot = FindQuestSlot( quest_id );
12492 if( log_slot < MAX_QUEST_LOG_SIZE)
12493 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12495 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12497 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12498 RewardQuest(qInfo,0,this,false);
12499 else
12500 SendQuestComplete( quest_id );
12505 void Player::IncompleteQuest( uint32 quest_id )
12507 if( quest_id )
12509 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12511 uint16 log_slot = FindQuestSlot( quest_id );
12512 if( log_slot < MAX_QUEST_LOG_SIZE)
12513 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12517 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12519 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
12520 //should work fine, cause far teleport will be executed in Player::Update()
12521 SetCanDelayTeleport(true);
12523 uint32 quest_id = pQuest->GetQuestId();
12525 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12527 if (pQuest->ReqItemId[i])
12528 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12531 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12532 // SetTimedQuest( 0 );
12533 m_timedquests.erase(pQuest->GetQuestId());
12535 if (pQuest->GetRewChoiceItemsCount() > 0)
12537 if (pQuest->RewChoiceItemId[reward])
12539 ItemPosCountVec dest;
12540 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
12542 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12543 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12548 if (pQuest->GetRewItemsCount() > 0)
12550 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12552 if (pQuest->RewItemId[i])
12554 ItemPosCountVec dest;
12555 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
12557 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12558 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12564 RewardReputation( pQuest );
12566 uint16 log_slot = FindQuestSlot( quest_id );
12567 if (log_slot < MAX_QUEST_LOG_SIZE)
12568 SetQuestSlot(log_slot,0);
12570 QuestStatusData& q_status = mQuestStatus[quest_id];
12572 // Not give XP in case already completed once repeatable quest
12573 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12575 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
12576 GiveXP( XP , NULL );
12577 else
12579 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12580 ModifyMoney( money );
12581 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12584 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12585 if (pQuest->GetRewOrReqMoney())
12587 ModifyMoney( pQuest->GetRewOrReqMoney() );
12589 if (pQuest->GetRewOrReqMoney() > 0)
12590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12593 // honor reward
12594 if (pQuest->GetRewHonorableKills())
12595 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12597 // title reward
12598 if (pQuest->GetCharTitleId())
12600 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12601 SetTitle(titleEntry);
12604 if (pQuest->GetBonusTalents())
12606 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12607 InitTalentForLevel();
12610 // Send reward mail
12611 if (pQuest->GetRewMailTemplateId())
12613 MailMessageType mailType;
12614 uint32 senderGuidOrEntry;
12615 switch(questGiver->GetTypeId())
12617 case TYPEID_UNIT:
12618 mailType = MAIL_CREATURE;
12619 senderGuidOrEntry = questGiver->GetEntry();
12620 break;
12621 case TYPEID_GAMEOBJECT:
12622 mailType = MAIL_GAMEOBJECT;
12623 senderGuidOrEntry = questGiver->GetEntry();
12624 break;
12625 case TYPEID_ITEM:
12626 mailType = MAIL_ITEM;
12627 senderGuidOrEntry = questGiver->GetEntry();
12628 break;
12629 case TYPEID_PLAYER:
12630 mailType = MAIL_NORMAL;
12631 senderGuidOrEntry = questGiver->GetGUIDLow();
12632 break;
12633 default:
12634 mailType = MAIL_NORMAL;
12635 senderGuidOrEntry = GetGUIDLow();
12636 break;
12639 Loot questMailLoot;
12641 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12643 // fill mail
12644 MailItemsInfo mi; // item list preparing
12646 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12647 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12649 if (LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12651 if (Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12653 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12654 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12659 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12662 if (pQuest->IsDaily())
12664 SetDailyQuestStatus(quest_id);
12665 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12668 if (!pQuest->IsRepeatable())
12669 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12670 else
12671 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12673 q_status.m_rewarded = true;
12674 if (q_status.uState != QUEST_NEW)
12675 q_status.uState = QUEST_CHANGED;
12677 if (announce)
12678 SendQuestReward( pQuest, XP, questGiver );
12680 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
12681 if (pQuest->GetRewSpellCast() > 0)
12682 CastSpell( this, pQuest->GetRewSpellCast(), true);
12683 else if ( pQuest->GetRewSpell() > 0)
12684 CastSpell( this, pQuest->GetRewSpell(), true);
12686 if (pQuest->GetZoneOrSort() > 0)
12687 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12688 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12689 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12691 uint32 zone = 0;
12692 uint32 area = 0;
12694 // remove auras from spells with quest reward state limitations
12695 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12696 if(saEndBounds.first != saEndBounds.second)
12698 GetZoneAndAreaId(zone,area);
12700 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12701 if(!itr->second->IsFitToRequirements(this,zone,area))
12702 RemoveAurasDueToSpell(itr->second->spellId);
12705 // Some spells applied at quest reward
12706 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12707 if(saBounds.first != saBounds.second)
12709 if(!zone || !area)
12710 GetZoneAndAreaId(zone,area);
12712 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12713 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12714 if( !HasAura(itr->second->spellId,0) )
12715 CastSpell(this,itr->second->spellId,true);
12718 //lets remove flag for delayed teleports
12719 SetCanDelayTeleport(false);
12722 void Player::FailQuest( uint32 quest_id )
12724 if( quest_id )
12726 IncompleteQuest( quest_id );
12728 uint16 log_slot = FindQuestSlot( quest_id );
12729 if( log_slot < MAX_QUEST_LOG_SIZE)
12731 SetQuestSlotTimer(log_slot, 1 );
12732 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12734 SendQuestFailed( quest_id );
12738 void Player::FailTimedQuest( uint32 quest_id )
12740 if( quest_id )
12742 QuestStatusData& q_status = mQuestStatus[quest_id];
12744 q_status.m_timer = 0;
12745 if (q_status.uState != QUEST_NEW)
12746 q_status.uState = QUEST_CHANGED;
12748 IncompleteQuest( quest_id );
12750 uint16 log_slot = FindQuestSlot( quest_id );
12751 if( log_slot < MAX_QUEST_LOG_SIZE)
12753 SetQuestSlotTimer(log_slot, 1 );
12754 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12756 SendQuestTimerFailed( quest_id );
12760 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12762 int32 zoneOrSort = qInfo->GetZoneOrSort();
12763 int32 skillOrClass = qInfo->GetSkillOrClass();
12765 // skip zone zoneOrSort and 0 case skillOrClass
12766 if( zoneOrSort >= 0 && skillOrClass == 0 )
12767 return true;
12769 int32 questSort = -zoneOrSort;
12770 uint8 reqSortClass = ClassByQuestSort(questSort);
12772 // check class sort cases in zoneOrSort
12773 if( reqSortClass != 0 && getClass() != reqSortClass)
12775 if( msg )
12776 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12777 return false;
12780 // check class
12781 if( skillOrClass < 0 )
12783 uint8 reqClass = -int32(skillOrClass);
12784 if(getClass() != reqClass)
12786 if( msg )
12787 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12788 return false;
12791 // check skill
12792 else if( skillOrClass > 0 )
12794 uint32 reqSkill = skillOrClass;
12795 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12797 if( msg )
12798 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12799 return false;
12803 return true;
12806 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12808 if( getLevel() < qInfo->GetMinLevel() )
12810 if( msg )
12811 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12812 return false;
12814 return true;
12817 bool Player::SatisfyQuestLog( bool msg )
12819 // exist free slot
12820 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12821 return true;
12823 if( msg )
12825 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12826 GetSession()->SendPacket( &data );
12827 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12829 return false;
12832 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12834 // No previous quest (might be first quest in a series)
12835 if( qInfo->prevQuests.empty())
12836 return true;
12838 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12840 uint32 prevId = abs(*iter);
12842 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12843 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12845 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12847 // If any of the positive previous quests completed, return true
12848 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12850 // skip one-from-all exclusive group
12851 if(qPrevInfo->GetExclusiveGroup() >= 0)
12852 return true;
12854 // each-from-all exclusive group ( < 0)
12855 // can be start if only all quests in prev quest exclusive group completed and rewarded
12856 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12857 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12859 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12861 for(; iter2 != end; ++iter2)
12863 uint32 exclude_Id = iter2->second;
12865 // skip checked quest id, only state of other quests in group is interesting
12866 if(exclude_Id == prevId)
12867 continue;
12869 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12871 // alternative quest from group also must be completed and rewarded(reported)
12872 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12874 if( msg )
12875 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12876 return false;
12879 return true;
12881 // If any of the negative previous quests active, return true
12882 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12883 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12885 // skip one-from-all exclusive group
12886 if(qPrevInfo->GetExclusiveGroup() >= 0)
12887 return true;
12889 // each-from-all exclusive group ( < 0)
12890 // can be start if only all quests in prev quest exclusive group active
12891 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12892 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12894 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12896 for(; iter2 != end; ++iter2)
12898 uint32 exclude_Id = iter2->second;
12900 // skip checked quest id, only state of other quests in group is interesting
12901 if(exclude_Id == prevId)
12902 continue;
12904 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12906 // alternative quest from group also must be active
12907 if( i_exstatus == mQuestStatus.end() ||
12908 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12909 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12911 if( msg )
12912 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12913 return false;
12916 return true;
12921 // Has only positive prev. quests in non-rewarded state
12922 // and negative prev. quests in non-active state
12923 if( msg )
12924 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12926 return false;
12929 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12931 uint32 reqraces = qInfo->GetRequiredRaces();
12932 if ( reqraces == 0 )
12933 return true;
12934 if( (reqraces & getRaceMask()) == 0 )
12936 if( msg )
12937 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12938 return false;
12940 return true;
12943 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12945 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12946 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12948 if( msg )
12949 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12950 return false;
12953 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12954 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12956 if( msg )
12957 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12958 return false;
12961 return true;
12964 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12966 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12967 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12969 if( msg )
12970 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12971 return false;
12973 return true;
12976 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12978 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12980 if( msg )
12981 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12982 return false;
12984 return true;
12987 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12989 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12990 if(qInfo->GetExclusiveGroup() <= 0)
12991 return true;
12993 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12994 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12996 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12998 for(; iter != end; ++iter)
13000 uint32 exclude_Id = iter->second;
13002 // skip checked quest id, only state of other quests in group is interesting
13003 if(exclude_Id == qInfo->GetQuestId())
13004 continue;
13006 // not allow have daily quest if daily quest from exclusive group already recently completed
13007 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13008 if( !SatisfyQuestDay(Nquest, false) )
13010 if( msg )
13011 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13012 return false;
13015 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13017 // alternative quest already started or completed
13018 if( i_exstatus != mQuestStatus.end()
13019 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13021 if( msg )
13022 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13023 return false;
13026 return true;
13029 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13031 if(!qInfo->GetNextQuestInChain())
13032 return true;
13034 // next quest in chain already started or completed
13035 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13036 if( itr != mQuestStatus.end()
13037 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13039 if( msg )
13040 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13041 return false;
13044 // check for all quests further up the chain
13045 // only necessary if there are quest chains with more than one quest that can be skipped
13046 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13047 return true;
13050 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13052 // No previous quest in chain
13053 if( qInfo->prevChainQuests.empty())
13054 return true;
13056 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13058 uint32 prevId = *iter;
13060 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13062 if( i_prevstatus != mQuestStatus.end() )
13064 // If any of the previous quests in chain active, return false
13065 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13066 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13068 if( msg )
13069 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13070 return false;
13074 // check for all quests further down the chain
13075 // only necessary if there are quest chains with more than one quest that can be skipped
13076 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13077 // return false;
13080 // No previous quest in chain active
13081 return true;
13084 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13086 if(!qInfo->IsDaily())
13087 return true;
13089 bool have_slot = false;
13090 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13092 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13093 if(qInfo->GetQuestId()==id)
13094 return false;
13096 if(!id)
13097 have_slot = true;
13100 if(!have_slot)
13102 if( msg )
13103 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13104 return false;
13107 return true;
13110 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13112 uint32 srcitem = pQuest->GetSrcItemId();
13113 if( srcitem > 0 )
13115 uint32 count = pQuest->GetSrcItemCount();
13116 if( count <= 0 )
13117 count = 1;
13119 ItemPosCountVec dest;
13120 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13121 if( msg == EQUIP_ERR_OK )
13123 Item * item = StoreNewItem(dest, srcitem, true);
13124 SendNewItem(item, count, true, false);
13125 return true;
13127 // player already have max amount required item, just report success
13128 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13129 return true;
13130 else
13131 SendEquipError( msg, NULL, NULL );
13132 return false;
13135 return true;
13138 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13140 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13141 if( qInfo )
13143 uint32 srcitem = qInfo->GetSrcItemId();
13144 if( srcitem > 0 )
13146 uint32 count = qInfo->GetSrcItemCount();
13147 if( count <= 0 )
13148 count = 1;
13150 // exist one case when destroy source quest item not possible:
13151 // non un-equippable item (equipped non-empty bag, for example)
13152 uint8 res = CanUnequipItems(srcitem,count);
13153 if(res != EQUIP_ERR_OK)
13155 if(msg)
13156 SendEquipError( res, NULL, NULL );
13157 return false;
13160 DestroyItemCount(srcitem, count, true, true);
13163 return true;
13166 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13168 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13169 if( qInfo )
13171 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13172 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13173 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13174 && !qInfo->IsRepeatable() )
13175 return itr->second.m_rewarded;
13177 return false;
13179 return false;
13182 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13184 if( quest_id )
13186 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13187 if( itr != mQuestStatus.end() )
13188 return itr->second.m_status;
13190 return QUEST_STATUS_NONE;
13193 bool Player::CanShareQuest(uint32 quest_id) const
13195 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13196 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13198 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13199 if( itr != mQuestStatus.end() )
13200 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13202 return false;
13205 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13207 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13208 if( qInfo )
13210 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13212 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13213 m_timedquests.erase(qInfo->GetQuestId());
13216 QuestStatusData& q_status = mQuestStatus[quest_id];
13218 q_status.m_status = status;
13219 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13222 UpdateForQuestWorldObjects();
13225 // not used in MaNGOS, but used in scripting code
13226 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13228 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13229 if( !qInfo )
13230 return 0;
13232 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13233 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13234 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13236 return 0;
13239 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13241 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13243 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13245 uint32 reqitemcount = pQuest->ReqItemCount[i];
13246 if( reqitemcount != 0 )
13248 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13250 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13251 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13257 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13259 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13260 if ( GetQuestSlotQuestId(i) == quest_id )
13261 return i;
13263 return MAX_QUEST_LOG_SIZE;
13266 void Player::AreaExploredOrEventHappens( uint32 questId )
13268 if( questId )
13270 uint16 log_slot = FindQuestSlot( questId );
13271 if( log_slot < MAX_QUEST_LOG_SIZE)
13273 QuestStatusData& q_status = mQuestStatus[questId];
13275 if(!q_status.m_explored)
13277 q_status.m_explored = true;
13278 if (q_status.uState != QUEST_NEW)
13279 q_status.uState = QUEST_CHANGED;
13282 if( CanCompleteQuest( questId ) )
13283 CompleteQuest( questId );
13287 //not used in mangosd, function for external script library
13288 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13290 if( Group *pGroup = GetGroup() )
13292 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13294 Player *pGroupGuy = itr->getSource();
13296 // for any leave or dead (with not released body) group member at appropriate distance
13297 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13298 pGroupGuy->AreaExploredOrEventHappens(questId);
13301 else
13302 AreaExploredOrEventHappens(questId);
13305 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13307 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13309 uint32 questid = GetQuestSlotQuestId(i);
13310 if ( questid == 0 )
13311 continue;
13313 QuestStatusData& q_status = mQuestStatus[questid];
13315 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13316 continue;
13318 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13319 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13320 continue;
13322 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13324 uint32 reqitem = qInfo->ReqItemId[j];
13325 if ( reqitem == entry )
13327 uint32 reqitemcount = qInfo->ReqItemCount[j];
13328 uint32 curitemcount = q_status.m_itemcount[j];
13329 if ( curitemcount < reqitemcount )
13331 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13332 q_status.m_itemcount[j] += additemcount;
13333 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13335 SendQuestUpdateAddItem( qInfo, j, additemcount );
13337 if ( CanCompleteQuest( questid ) )
13338 CompleteQuest( questid );
13339 return;
13343 UpdateForQuestWorldObjects();
13346 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13348 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13350 uint32 questid = GetQuestSlotQuestId(i);
13351 if(!questid)
13352 continue;
13353 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13354 if ( !qInfo )
13355 continue;
13356 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13357 continue;
13359 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13361 uint32 reqitem = qInfo->ReqItemId[j];
13362 if ( reqitem == entry )
13364 QuestStatusData& q_status = mQuestStatus[questid];
13366 uint32 reqitemcount = qInfo->ReqItemCount[j];
13367 uint32 curitemcount;
13368 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13369 curitemcount = q_status.m_itemcount[j];
13370 else
13371 curitemcount = GetItemCount(entry,true);
13372 if ( curitemcount < reqitemcount + count )
13374 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13375 q_status.m_itemcount[j] = curitemcount - remitemcount;
13376 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13378 IncompleteQuest( questid );
13380 return;
13384 UpdateForQuestWorldObjects();
13387 void Player::KilledMonster( uint32 entry, uint64 guid )
13389 uint32 addkillcount = 1;
13390 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13391 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13393 uint32 questid = GetQuestSlotQuestId(i);
13394 if(!questid)
13395 continue;
13397 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13398 if( !qInfo )
13399 continue;
13400 // just if !ingroup || !noraidgroup || raidgroup
13401 QuestStatusData& q_status = mQuestStatus[questid];
13402 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13404 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13406 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13408 // skip GO activate objective or none
13409 if(qInfo->ReqCreatureOrGOId[j] <=0)
13410 continue;
13412 // skip Cast at creature objective
13413 if(qInfo->ReqSpell[j] !=0 )
13414 continue;
13416 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13418 if ( reqkill == entry )
13420 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13421 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13422 if ( curkillcount < reqkillcount )
13424 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13425 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13427 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13429 if ( CanCompleteQuest( questid ) )
13430 CompleteQuest( questid );
13432 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13433 continue;
13441 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13443 bool isCreature = IS_CREATURE_GUID(guid);
13445 uint32 addCastCount = 1;
13446 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13448 uint32 questid = GetQuestSlotQuestId(i);
13449 if(!questid)
13450 continue;
13452 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13453 if ( !qInfo )
13454 continue;
13456 QuestStatusData& q_status = mQuestStatus[questid];
13458 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13460 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13462 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13464 // skip kill creature objective (0) or wrong spell casts
13465 if(qInfo->ReqSpell[j] != spell_id )
13466 continue;
13468 uint32 reqTarget = 0;
13470 if(isCreature)
13472 // creature activate objectives
13473 if(qInfo->ReqCreatureOrGOId[j] > 0)
13474 // checked at quest_template loading
13475 reqTarget = qInfo->ReqCreatureOrGOId[j];
13477 else
13479 // GO activate objective
13480 if(qInfo->ReqCreatureOrGOId[j] < 0)
13481 // checked at quest_template loading
13482 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13485 // other not this creature/GO related objectives
13486 if( reqTarget != entry )
13487 continue;
13489 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13490 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13491 if ( curCastCount < reqCastCount )
13493 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13494 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13496 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13499 if ( CanCompleteQuest( questid ) )
13500 CompleteQuest( questid );
13502 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13503 break;
13510 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13512 uint32 addTalkCount = 1;
13513 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13515 uint32 questid = GetQuestSlotQuestId(i);
13516 if(!questid)
13517 continue;
13519 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13520 if ( !qInfo )
13521 continue;
13523 QuestStatusData& q_status = mQuestStatus[questid];
13525 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13527 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13529 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13531 // skip spell casts and Gameobject objectives
13532 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13533 continue;
13535 uint32 reqTarget = 0;
13537 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13538 // checked at quest_template loading
13539 reqTarget = qInfo->ReqCreatureOrGOId[j];
13540 else
13541 continue;
13543 if ( reqTarget == entry )
13545 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13546 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13547 if ( curTalkCount < reqTalkCount )
13549 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13550 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13552 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13554 if ( CanCompleteQuest( questid ) )
13555 CompleteQuest( questid );
13557 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13558 continue;
13566 void Player::MoneyChanged( uint32 count )
13568 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13570 uint32 questid = GetQuestSlotQuestId(i);
13571 if (!questid)
13572 continue;
13574 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13575 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13577 QuestStatusData& q_status = mQuestStatus[questid];
13579 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13581 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13583 if ( CanCompleteQuest( questid ) )
13584 CompleteQuest( questid );
13587 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13589 if(int32(count) < -qInfo->GetRewOrReqMoney())
13590 IncompleteQuest( questid );
13596 void Player::ReputationChanged(FactionEntry const* factionEntry )
13598 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13600 if(uint32 questid = GetQuestSlotQuestId(i))
13602 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13604 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13606 QuestStatusData& q_status = mQuestStatus[questid];
13607 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13609 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13610 if ( CanCompleteQuest( questid ) )
13611 CompleteQuest( questid );
13613 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13615 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13616 IncompleteQuest( questid );
13624 bool Player::HasQuestForItem( uint32 itemid ) const
13626 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13628 uint32 questid = GetQuestSlotQuestId(i);
13629 if ( questid == 0 )
13630 continue;
13632 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13633 if(qs_itr == mQuestStatus.end())
13634 continue;
13636 QuestStatusData const& q_status = qs_itr->second;
13638 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13640 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13641 if(!qinfo)
13642 continue;
13644 // hide quest if player is in raid-group and quest is no raid quest
13645 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13646 continue;
13648 // There should be no mixed ReqItem/ReqSource drop
13649 // This part for ReqItem drop
13650 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13652 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13653 return true;
13655 // This part - for ReqSource
13656 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13658 // examined item is a source item
13659 if (qinfo->ReqSourceId[j] == itemid)
13661 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13663 // 'unique' item
13664 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13665 return true;
13667 // allows custom amount drop when not 0
13668 if (qinfo->ReqSourceCount[j])
13670 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13671 return true;
13672 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13673 return true;
13678 return false;
13681 void Player::SendQuestComplete( uint32 quest_id )
13683 if( quest_id )
13685 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13686 data << uint32(quest_id);
13687 GetSession()->SendPacket( &data );
13688 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13692 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13694 uint32 questid = pQuest->GetQuestId();
13695 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13696 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13697 data << uint32(questid);
13699 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13701 data << uint32(XP);
13702 data << uint32(pQuest->GetRewOrReqMoney());
13704 else
13706 data << uint32(0);
13707 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13710 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13711 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13712 GetSession()->SendPacket( &data );
13714 if (pQuest->GetQuestCompleteScript() != 0)
13715 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13718 void Player::SendQuestFailed( uint32 quest_id )
13720 if( quest_id )
13722 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13723 data << quest_id;
13724 data << uint32(0); // failed reason (4 for inventory is full)
13725 GetSession()->SendPacket( &data );
13726 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13730 void Player::SendQuestTimerFailed( uint32 quest_id )
13732 if( quest_id )
13734 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13735 data << quest_id;
13736 GetSession()->SendPacket( &data );
13737 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13741 void Player::SendCanTakeQuestResponse( uint32 msg )
13743 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13744 data << uint32(msg);
13745 GetSession()->SendPacket( &data );
13746 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13749 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13751 if( pPlayer )
13753 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13754 data << uint64(pPlayer->GetGUID());
13755 data << uint8(msg); // valid values: 0-8
13756 GetSession()->SendPacket( &data );
13757 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13761 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13763 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13764 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13765 //data << pQuest->ReqItemId[item_idx];
13766 //data << count;
13767 GetSession()->SendPacket( &data );
13770 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13772 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13774 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13775 if (entry < 0)
13776 // client expected gameobject template id in form (id|0x80000000)
13777 entry = (-entry) | 0x80000000;
13779 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13780 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13781 data << uint32(pQuest->GetQuestId());
13782 data << uint32(entry);
13783 data << uint32(old_count + add_count);
13784 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13785 data << uint64(guid);
13786 GetSession()->SendPacket(&data);
13788 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13789 if( log_slot < MAX_QUEST_LOG_SIZE)
13790 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13793 /*********************************************************/
13794 /*** LOAD SYSTEM ***/
13795 /*********************************************************/
13797 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13799 bool delete_result = true;
13800 if (!result)
13802 // 0 1 2 3 4 5 6 7 8 9 10 11
13803 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone, level FROM characters WHERE guid = '%u'",guid);
13804 if (!result)
13805 return false;
13807 else
13808 delete_result = false;
13810 Field *fields = result->Fetch();
13812 if (!LoadValues( fields[1].GetString()))
13814 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13815 if (delete_result)
13816 delete result;
13817 return false;
13820 // overwrite possible wrong/corrupted guid
13821 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13823 m_name = fields[2].GetCppString();
13825 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13826 SetMapId(fields[6].GetUInt32());
13827 // the instance id is not needed at character enum
13829 m_Played_time[0] = fields[7].GetUInt32();
13830 m_Played_time[1] = fields[8].GetUInt32();
13832 m_atLoginFlags = fields[9].GetUInt32();
13834 // I don't see these used anywhere ..
13835 /*_LoadGroup();
13837 _LoadBoundInstances();*/
13839 if (delete_result)
13840 delete result;
13842 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13843 m_items[i] = NULL;
13845 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
13846 m_deathState = DEAD;
13848 return true;
13851 void Player::_LoadDeclinedNames(QueryResult* result)
13853 if(!result)
13854 return;
13856 if(m_declinedname)
13857 delete m_declinedname;
13859 m_declinedname = new DeclinedName;
13860 Field *fields = result->Fetch();
13861 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13862 m_declinedname->name[i] = fields[i].GetCppString();
13864 delete result;
13867 void Player::_LoadArenaTeamInfo(QueryResult *result)
13869 // arenateamid, played_week, played_season, personal_rating
13870 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13871 if (!result)
13872 return;
13876 Field *fields = result->Fetch();
13878 uint32 arenateamid = fields[0].GetUInt32();
13879 uint32 played_week = fields[1].GetUInt32();
13880 uint32 played_season = fields[2].GetUInt32();
13881 uint32 personal_rating = fields[3].GetUInt32();
13883 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13884 if(!aTeam)
13886 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13887 continue;
13889 uint8 arenaSlot = aTeam->GetSlot();
13891 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13892 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13893 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13894 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13895 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13896 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13898 }while (result->NextRow());
13899 delete result;
13902 void Player::_LoadEquipmentSets(QueryResult *result)
13904 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13905 if (!result)
13906 return;
13908 uint32 count = 0;
13911 Field *fields = result->Fetch();
13913 EquipmentSet eqSet;
13915 eqSet.Guid = fields[0].GetUInt64();
13916 uint32 index = fields[1].GetUInt32();
13917 eqSet.Name = fields[2].GetCppString();
13918 eqSet.IconName = fields[3].GetCppString();
13919 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13921 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13922 eqSet.Items[i] = fields[4+i].GetUInt32();
13924 m_EquipmentSets[index] = eqSet;
13926 ++count;
13928 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13929 break;
13930 } while (result->NextRow());
13931 delete result;
13934 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13936 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13937 if(!result)
13938 return false;
13940 Field *fields = result->Fetch();
13942 x = fields[0].GetFloat();
13943 y = fields[1].GetFloat();
13944 z = fields[2].GetFloat();
13945 o = fields[3].GetFloat();
13946 mapid = fields[4].GetUInt32();
13947 in_flight = !fields[5].GetCppString().empty();
13949 delete result;
13950 return true;
13953 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13955 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13956 if( !result )
13957 return false;
13959 Field *fields = result->Fetch();
13961 data = StrSplit(fields[0].GetCppString(), " ");
13963 delete result;
13965 return true;
13968 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13970 if(index >= data.size())
13971 return 0;
13973 return (uint32)atoi(data[index].c_str());
13976 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13978 float result;
13979 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13980 memcpy(&result, &temp, sizeof(result));
13982 return result;
13985 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13987 Tokens data;
13988 if(!LoadValuesArrayFromDB(data,guid))
13989 return 0;
13991 return GetUInt32ValueFromArray(data,index);
13994 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13996 float result;
13997 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13998 memcpy(&result, &temp, sizeof(result));
14000 return result;
14003 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14005 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
14006 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
14007 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14009 if(!result)
14011 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14012 return false;
14015 Field *fields = result->Fetch();
14017 uint32 dbAccountId = fields[1].GetUInt32();
14019 // check if the character's account in the db and the logged in account match.
14020 // player should be able to load/delete character only with correct account!
14021 if( dbAccountId != GetSession()->GetAccountId() )
14023 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14024 delete result;
14025 return false;
14028 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14030 m_name = fields[3].GetCppString();
14032 // check name limitations
14033 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14034 GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14036 delete result;
14037 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14038 return false;
14041 if(!LoadValues( fields[2].GetString()))
14043 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14044 delete result;
14045 return false;
14048 // overwrite possible wrong/corrupted guid
14049 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14051 // overwrite some data fields
14052 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14053 bytes0 |= fields[4].GetUInt8(); // race
14054 bytes0 |= fields[5].GetUInt8() << 8; // class
14055 bytes0 |= fields[6].GetUInt8() << 16; // gender
14056 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14058 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14059 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14060 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14061 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14062 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14063 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14064 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14066 InitDisplayIds();
14068 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14069 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14071 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14072 SetVisibleItemSlot(slot, NULL);
14074 if (m_items[slot])
14076 delete m_items[slot];
14077 m_items[slot] = NULL;
14081 // update money limits
14082 if(GetMoney() > MAX_MONEY_AMOUNT)
14083 SetMoney(MAX_MONEY_AMOUNT);
14085 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14086 outDebugValues();
14088 //Need to call it to initialize m_team (m_team can be calculated from race)
14089 //Other way is to saves m_team into characters table.
14090 setFactionForRace(getRace());
14091 SetCharm(NULL);
14093 // load home bind and check in same time class/race pair, it used later for restore broken positions
14094 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14096 delete result;
14097 return false;
14100 InitPrimaryProfessions(); // to max set before any spell loaded
14102 // init saved position, and fix it later if problematic
14103 uint32 transGUID = fields[31].GetUInt32();
14104 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14105 SetMapId(fields[16].GetUInt32());
14106 SetDifficulty(fields[39].GetUInt32()); // may be changed in _LoadGroup
14108 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14110 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14112 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14113 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14114 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14116 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14118 // check arena teams integrity
14119 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14121 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14122 if(!arena_team_id)
14123 continue;
14125 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14126 if(at->HaveMember(GetGUID()))
14127 continue;
14129 // arena team not exist or not member, cleanup fields
14130 for(int j =0; j < 6; ++j)
14131 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14134 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14136 if(!IsPositionValid())
14138 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14139 RelocateToHomebind();
14141 transGUID = 0;
14143 m_movementInfo.t_x = 0.0f;
14144 m_movementInfo.t_y = 0.0f;
14145 m_movementInfo.t_z = 0.0f;
14146 m_movementInfo.t_o = 0.0f;
14149 uint32 bgid = fields[41].GetUInt32();
14150 uint32 bgteam = fields[42].GetUInt32();
14152 if(bgid) //saved in BattleGround
14154 SetBattleGroundEntryPoint(fields[43].GetUInt32(),fields[44].GetFloat(),fields[45].GetFloat(),fields[46].GetFloat(),fields[47].GetFloat());
14156 // check entry point and fix to homebind if need
14157 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14158 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14159 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14161 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14163 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14165 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14166 AddBattleGroundQueueId(bgQueueTypeId);
14168 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14169 SetBGTeam(bgteam);
14171 //join player to battleground group
14172 currentBg->EventPlayerLoggedIn(this, GetGUID());
14173 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14175 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14177 else
14179 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14180 SetMapId(_loc.mapid);
14181 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14182 //RemoveArenaAuras(true);
14185 else
14187 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14188 // if server restart after player save in BG or area
14189 // player can have current coordinates in to BG/Arean map, fix this
14190 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14192 // return to BG master
14193 SetMapId(fields[43].GetUInt32());
14194 Relocate(fields[44].GetFloat(),fields[45].GetFloat(),fields[46].GetFloat(),fields[47].GetFloat());
14196 // check entry point and fix to homebind if need
14197 mapEntry = sMapStore.LookupEntry(GetMapId());
14198 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14199 RelocateToHomebind();
14203 if (transGUID != 0)
14205 m_movementInfo.t_x = fields[27].GetFloat();
14206 m_movementInfo.t_y = fields[28].GetFloat();
14207 m_movementInfo.t_z = fields[29].GetFloat();
14208 m_movementInfo.t_o = fields[30].GetFloat();
14210 if( !MaNGOS::IsValidMapCoord(
14211 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14212 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14213 // transport size limited
14214 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14216 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14217 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14218 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14220 RelocateToHomebind();
14222 m_movementInfo.t_x = 0.0f;
14223 m_movementInfo.t_y = 0.0f;
14224 m_movementInfo.t_z = 0.0f;
14225 m_movementInfo.t_o = 0.0f;
14227 transGUID = 0;
14231 if (transGUID != 0)
14233 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14235 if( (*iter)->GetGUIDLow() == transGUID)
14237 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14238 // client without expansion support
14239 if(GetSession()->Expansion() < transMapEntry->Expansion())
14241 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14242 break;
14245 m_transport = *iter;
14246 m_transport->AddPassenger(this);
14247 SetMapId(m_transport->GetMapId());
14248 break;
14252 if(!m_transport)
14254 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14255 guid,transGUID);
14257 RelocateToHomebind();
14259 m_movementInfo.t_x = 0.0f;
14260 m_movementInfo.t_y = 0.0f;
14261 m_movementInfo.t_z = 0.0f;
14262 m_movementInfo.t_o = 0.0f;
14264 transGUID = 0;
14267 else // not transport case
14269 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14270 // client without expansion support
14271 if(GetSession()->Expansion() < mapEntry->Expansion())
14273 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14274 RelocateToHomebind();
14278 // NOW player must have valid map
14279 // load the player's map here if it's not already loaded
14280 Map *map = GetMap();
14282 // since the player may not be bound to the map yet, make sure subsequent
14283 // getmap calls won't create new maps
14284 SetInstanceId(map->GetInstanceId());
14286 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14287 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14289 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14290 if(at)
14291 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14292 else
14293 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14296 SaveRecallPosition();
14298 time_t now = time(NULL);
14299 time_t logoutTime = time_t(fields[23].GetUInt64());
14301 // since last logout (in seconds)
14302 uint64 time_diff = uint64(now - logoutTime);
14304 // set value, including drunk invisibility detection
14305 // calculate sobering. after 15 minutes logged out, the player will be sober again
14306 float soberFactor;
14307 if(time_diff > 15*MINUTE)
14308 soberFactor = 0;
14309 else
14310 soberFactor = 1-time_diff/(15.0f*MINUTE);
14311 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14312 SetDrunkValue(newDrunkenValue);
14314 m_rest_bonus = fields[22].GetFloat();
14315 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14316 float bubble0 = 0.031;
14317 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14318 float bubble1 = 0.125;
14320 if(time_diff > 0)
14322 float bubble = fields[24].GetUInt32() > 0
14323 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14324 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14326 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14329 m_cinematic = fields[19].GetUInt32();
14330 m_Played_time[0]= fields[20].GetUInt32();
14331 m_Played_time[1]= fields[21].GetUInt32();
14333 m_resetTalentsCost = fields[25].GetUInt32();
14334 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14336 // reserve some flags
14337 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14339 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14340 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14342 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14344 uint32 extraflags = fields[32].GetUInt32();
14346 m_stableSlots = fields[33].GetUInt32();
14347 if(m_stableSlots > MAX_PET_STABLES)
14349 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14350 m_stableSlots = MAX_PET_STABLES;
14353 m_atLoginFlags = fields[34].GetUInt32();
14355 // Honor system
14356 // Update Honor kills data
14357 m_lastHonorUpdateTime = logoutTime;
14358 UpdateHonorFields();
14360 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14361 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14362 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14364 std::string taxi_nodes = fields[38].GetCppString();
14366 delete result;
14368 // clear channel spell data (if saved at channel spell casting)
14369 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14370 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14372 // clear charm/summon related fields
14373 SetCharm(NULL);
14374 SetPet(NULL);
14375 SetCharmerGUID(0);
14376 SetOwnerGUID(0);
14377 SetCreatorGUID(0);
14379 // reset some aura modifiers before aura apply
14380 SetFarSightGUID(0);
14381 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14382 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14384 _LoadSkills();
14386 // make sure the unit is considered out of combat for proper loading
14387 ClearInCombat();
14389 // make sure the unit is considered not in duel for proper loading
14390 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14391 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14393 // remember loaded power/health values to restore after stats initialization and modifier applying
14394 uint32 savedHealth = GetHealth();
14395 uint32 savedPower[MAX_POWERS];
14396 for(uint32 i = 0; i < MAX_POWERS; ++i)
14397 savedPower[i] = GetPower(Powers(i));
14399 // reset stats before loading any modifiers
14400 InitStatsForLevel();
14401 InitTaxiNodesForLevel();
14402 InitGlyphsForLevel();
14403 InitRunes();
14405 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14407 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14408 //_LoadMail();
14410 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14411 _LoadGlyphAuras();
14413 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14414 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14415 m_deathState = DEAD;
14417 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14419 // after spell load, learn rewarded spell if need also
14420 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14421 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14423 // after spell and quest load
14424 InitTalentForLevel();
14425 learnDefaultSpells();
14427 // must be before inventory (some items required reputation check)
14428 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14430 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14432 // update items with duration and realtime
14433 UpdateItemDuration(time_diff, true);
14435 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14437 // unread mails and next delivery time, actual mails not loaded
14438 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14440 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14442 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14443 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14444 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14446 if(!HasTitle(curTitle))
14447 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14450 // Not finish taxi flight path
14451 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14453 // problems with taxi path loading
14454 TaxiNodesEntry const* nodeEntry = NULL;
14455 if(uint32 node_id = m_taxi.GetTaxiSource())
14456 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14458 if(!nodeEntry) // don't know taxi start node, to homebind
14460 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14461 RelocateToHomebind();
14462 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14464 else // have start node, to it
14466 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14467 SetMapId(nodeEntry->map_id);
14468 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14469 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14471 m_taxi.ClearTaxiDestinations();
14473 else if(uint32 node_id = m_taxi.GetTaxiSource())
14475 // save source node as recall coord to prevent recall and fall from sky
14476 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14477 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14478 m_recallMap = nodeEntry->map_id;
14479 m_recallX = nodeEntry->x;
14480 m_recallY = nodeEntry->y;
14481 m_recallZ = nodeEntry->z;
14483 // flight will started later
14486 // has to be called after last Relocate() in Player::LoadFromDB
14487 SetFallInformation(0, GetPositionZ());
14489 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14491 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14492 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14493 if(!isAlive())
14494 RemoveAllAurasOnDeath();
14496 //apply all stat bonuses from items and auras
14497 SetCanModifyStats(true);
14498 UpdateAllStats();
14500 // restore remembered power/health values (but not more max values)
14501 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14502 for(uint32 i = 0; i < MAX_POWERS; ++i)
14503 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14505 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14506 outDebugValues();
14508 // GM state
14509 if(GetSession()->GetSecurity() > SEC_PLAYER)
14511 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14513 default:
14514 case 0: break; // disable
14515 case 1: SetGameMaster(true); break; // enable
14516 case 2: // save state
14517 if(extraflags & PLAYER_EXTRA_GM_ON)
14518 SetGameMaster(true);
14519 break;
14522 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14524 default:
14525 case 0: SetGMVisible(false); break; // invisible
14526 case 1: break; // visible
14527 case 2: // save state
14528 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14529 SetGMVisible(false);
14530 break;
14533 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14535 default:
14536 case 0: break; // disable
14537 case 1: SetAcceptTicket(true); break; // enable
14538 case 2: // save state
14539 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14540 SetAcceptTicket(true);
14541 break;
14544 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14546 default:
14547 case 0: break; // disable
14548 case 1: SetGMChat(true); break; // enable
14549 case 2: // save state
14550 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14551 SetGMChat(true);
14552 break;
14555 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14557 default:
14558 case 0: break; // disable
14559 case 1: SetAcceptWhispers(true); break; // enable
14560 case 2: // save state
14561 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14562 SetAcceptWhispers(true);
14563 break;
14567 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14569 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14570 m_achievementMgr.CheckAllAchievementCriteria();
14572 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14574 return true;
14577 bool Player::isAllowedToLoot(Creature* creature)
14579 if(Player* recipient = creature->GetLootRecipient())
14581 if (recipient == this)
14582 return true;
14583 if( Group* otherGroup = recipient->GetGroup())
14585 Group* thisGroup = GetGroup();
14586 if(!thisGroup)
14587 return false;
14588 return thisGroup == otherGroup;
14590 return false;
14592 else
14593 // prevent other players from looting if the recipient got disconnected
14594 return !creature->hasLootRecipient();
14597 void Player::_LoadActions(QueryResult *result)
14599 m_actionButtons.clear();
14601 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14603 if(result)
14607 Field *fields = result->Fetch();
14609 uint8 button = fields[0].GetUInt8();
14610 uint32 action = fields[1].GetUInt32();
14611 uint8 type = fields[2].GetUInt8();
14613 if(ActionButton* ab = addActionButton(button, action, type))
14614 ab->uState = ACTIONBUTTON_UNCHANGED;
14615 else
14617 sLog.outError( " ...at loading, and will deleted in DB also");
14619 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14620 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14623 while( result->NextRow() );
14625 delete result;
14629 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14631 m_Auras.clear();
14632 for (int i = 0; i < TOTAL_AURAS; ++i)
14633 m_modAuras[i].clear();
14635 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14637 if(result)
14641 Field *fields = result->Fetch();
14642 uint64 caster_guid = fields[0].GetUInt64();
14643 uint32 spellid = fields[1].GetUInt32();
14644 uint32 effindex = fields[2].GetUInt32();
14645 uint32 stackcount = fields[3].GetUInt32();
14646 int32 damage = (int32)fields[4].GetUInt32();
14647 int32 maxduration = (int32)fields[5].GetUInt32();
14648 int32 remaintime = (int32)fields[6].GetUInt32();
14649 int32 remaincharges = (int32)fields[7].GetUInt32();
14651 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14652 if(!spellproto)
14654 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14655 continue;
14658 if(effindex >= 3)
14660 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14661 continue;
14664 // negative effects should continue counting down after logout
14665 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14667 if(remaintime <= int32(timediff))
14668 continue;
14670 remaintime -= timediff;
14673 // prevent wrong values of remaincharges
14674 if(spellproto->procCharges)
14676 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14677 remaincharges = spellproto->procCharges;
14679 else
14680 remaincharges = 0;
14683 for(uint32 i=0; i<stackcount; ++i)
14685 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14686 if(!damage)
14687 damage = aura->GetModifier()->m_amount;
14689 // reset stolen single target auras
14690 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14691 aura->SetIsSingleTarget(false);
14693 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14694 AddAura(aura);
14695 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14698 while( result->NextRow() );
14700 delete result;
14703 if(getClass() == CLASS_WARRIOR)
14704 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14707 void Player::_LoadGlyphAuras()
14709 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14711 if (uint32 glyph = GetGlyph(i))
14713 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14715 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14717 if(gp->TypeFlags == gs->TypeFlags)
14719 CastSpell(this, gp->SpellId, true);
14720 continue;
14722 else
14723 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14725 else
14726 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14728 else
14729 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14731 // On any error remove glyph
14732 SetGlyph(i, 0);
14737 void Player::LoadCorpse()
14739 if( isAlive() )
14741 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14743 else
14745 if(Corpse *corpse = GetCorpse())
14747 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14749 else
14751 //Prevent Dead Player login without corpse
14752 ResurrectPlayer(0.5f);
14757 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14759 //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());
14760 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14761 //NOTE: the "order by `bag`" is important because it makes sure
14762 //the bagMap is filled before items in the bags are loaded
14763 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14764 //expected to be equipped before offhand items (TODO: fixme)
14766 uint32 zone = GetZoneId();
14768 if (result)
14770 std::list<Item*> problematicItems;
14772 // prevent items from being added to the queue when stored
14773 m_itemUpdateQueueBlocked = true;
14776 Field *fields = result->Fetch();
14777 uint32 bag_guid = fields[1].GetUInt32();
14778 uint8 slot = fields[2].GetUInt8();
14779 uint32 item_guid = fields[3].GetUInt32();
14780 uint32 item_id = fields[4].GetUInt32();
14782 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14784 if(!proto)
14786 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14787 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14788 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14789 continue;
14792 Item *item = NewItemOrBag(proto);
14794 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14796 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14797 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14798 item->FSetState(ITEM_REMOVED);
14799 item->SaveToDB(); // it also deletes item object !
14800 continue;
14803 // not allow have in alive state item limited to another map/zone
14804 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14806 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14807 item->FSetState(ITEM_REMOVED);
14808 item->SaveToDB(); // it also deletes item object !
14809 continue;
14812 // "Conjured items disappear if you are logged out for more than 15 minutes"
14813 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14815 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14816 item->FSetState(ITEM_REMOVED);
14817 item->SaveToDB(); // it also deletes item object !
14818 continue;
14821 bool success = true;
14823 if (!bag_guid)
14825 // the item is not in a bag
14826 item->SetContainer( NULL );
14827 item->SetSlot(slot);
14829 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14831 ItemPosCountVec dest;
14832 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14833 item = StoreItem(dest, item, true);
14834 else
14835 success = false;
14837 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14839 uint16 dest;
14840 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14841 QuickEquipItem(dest, item);
14842 else
14843 success = false;
14845 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14847 ItemPosCountVec dest;
14848 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14849 item = BankItem(dest, item, true);
14850 else
14851 success = false;
14854 if(success)
14856 // store bags that may contain items in them
14857 if(item->IsBag() && IsBagPos(item->GetPos()))
14858 bagMap[item_guid] = (Bag*)item;
14861 else
14863 item->SetSlot(NULL_SLOT);
14864 // the item is in a bag, find the bag
14865 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14866 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
14867 itr->second->StoreItem(slot, item, true );
14868 else
14869 success = false;
14872 // item's state may have changed after stored
14873 if (success)
14874 item->SetState(ITEM_UNCHANGED, this);
14875 else
14877 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);
14878 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14879 problematicItems.push_back(item);
14881 } while (result->NextRow());
14883 delete result;
14884 m_itemUpdateQueueBlocked = false;
14886 // send by mail problematic items
14887 while(!problematicItems.empty())
14889 // fill mail
14890 MailItemsInfo mi; // item list preparing
14892 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14894 Item* item = problematicItems.front();
14895 problematicItems.pop_front();
14897 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14900 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14902 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14905 //if(isAlive())
14906 _ApplyAllItemMods();
14909 // load mailed item which should receive current player
14910 void Player::_LoadMailedItems(Mail *mail)
14912 // data needs to be at first place for Item::LoadFromDB
14913 QueryResult* result = CharacterDatabase.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail->messageID);
14914 if(!result)
14915 return;
14919 Field *fields = result->Fetch();
14920 uint32 item_guid_low = fields[1].GetUInt32();
14921 uint32 item_template = fields[2].GetUInt32();
14923 mail->AddItem(item_guid_low, item_template);
14925 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14927 if(!proto)
14929 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14930 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14931 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14932 continue;
14935 Item *item = NewItemOrBag(proto);
14937 if(!item->LoadFromDB(item_guid_low, 0, result))
14939 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14940 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14941 item->FSetState(ITEM_REMOVED);
14942 item->SaveToDB(); // it also deletes item object !
14943 continue;
14946 AddMItem(item);
14947 } while (result->NextRow());
14949 delete result;
14952 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14954 //set a count of unread mails
14955 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14956 if (resultUnread)
14958 Field *fieldMail = resultUnread->Fetch();
14959 unReadMails = fieldMail[0].GetUInt8();
14960 delete resultUnread;
14963 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14964 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14965 if (resultDelivery)
14967 Field *fieldMail = resultDelivery->Fetch();
14968 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14969 delete resultDelivery;
14973 void Player::_LoadMail()
14975 m_mail.clear();
14976 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14977 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());
14978 if(result)
14982 Field *fields = result->Fetch();
14983 Mail *m = new Mail;
14984 m->messageID = fields[0].GetUInt32();
14985 m->messageType = fields[1].GetUInt8();
14986 m->sender = fields[2].GetUInt32();
14987 m->receiver = fields[3].GetUInt32();
14988 m->subject = fields[4].GetCppString();
14989 m->itemTextId = fields[5].GetUInt32();
14990 bool has_items = fields[6].GetBool();
14991 m->expire_time = (time_t)fields[7].GetUInt64();
14992 m->deliver_time = (time_t)fields[8].GetUInt64();
14993 m->money = fields[9].GetUInt32();
14994 m->COD = fields[10].GetUInt32();
14995 m->checked = fields[11].GetUInt32();
14996 m->stationery = fields[12].GetUInt8();
14997 m->mailTemplateId = fields[13].GetInt16();
14999 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15001 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15002 m->mailTemplateId = 0;
15005 m->state = MAIL_STATE_UNCHANGED;
15007 if (has_items)
15008 _LoadMailedItems(m);
15010 m_mail.push_back(m);
15011 } while( result->NextRow() );
15012 delete result;
15014 m_mailsLoaded = true;
15017 void Player::LoadPet()
15019 //fixme: the pet should still be loaded if the player is not in world
15020 // just not added to the map
15021 if(IsInWorld())
15023 Pet *pet = new Pet;
15024 if(!pet->LoadPetFromDB(this,0,0,true))
15025 delete pet;
15029 void Player::_LoadQuestStatus(QueryResult *result)
15031 mQuestStatus.clear();
15033 uint32 slot = 0;
15035 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15036 //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());
15038 if(result)
15042 Field *fields = result->Fetch();
15044 uint32 quest_id = fields[0].GetUInt32();
15045 // used to be new, no delete?
15046 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15047 if( pQuest )
15049 // find or create
15050 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15052 uint32 qstatus = fields[1].GetUInt32();
15053 if(qstatus < MAX_QUEST_STATUS)
15054 questStatusData.m_status = QuestStatus(qstatus);
15055 else
15057 questStatusData.m_status = QUEST_STATUS_NONE;
15058 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15061 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15062 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15064 time_t quest_time = time_t(fields[4].GetUInt64());
15066 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15068 AddTimedQuest( quest_id );
15070 if (quest_time <= sWorld.GetGameTime())
15071 questStatusData.m_timer = 1;
15072 else
15073 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15075 else
15076 quest_time = 0;
15078 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15079 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15080 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15081 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15082 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15083 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15084 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15085 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15087 questStatusData.uState = QUEST_UNCHANGED;
15089 // add to quest log
15090 if( slot < MAX_QUEST_LOG_SIZE &&
15091 ( questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15092 questStatusData.m_status == QUEST_STATUS_COMPLETE &&
15093 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15095 SetQuestSlot(slot, quest_id, quest_time);
15097 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15098 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15100 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15101 if(questStatusData.m_creatureOrGOcount[idx])
15102 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15104 ++slot;
15107 if(questStatusData.m_rewarded)
15109 // learn rewarded spell if unknown
15110 learnQuestRewardedSpells(pQuest);
15112 // set rewarded title if any
15113 if(pQuest->GetCharTitleId())
15115 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15116 SetTitle(titleEntry);
15119 if(pQuest->GetBonusTalents())
15120 m_questRewardTalentCount += pQuest->GetBonusTalents();
15123 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15126 while( result->NextRow() );
15128 delete result;
15131 // clear quest log tail
15132 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15133 SetQuestSlot(i, 0);
15136 void Player::_LoadDailyQuestStatus(QueryResult *result)
15138 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15139 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15141 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15143 if(result)
15145 uint32 quest_daily_idx = 0;
15149 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15151 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15152 break;
15155 Field *fields = result->Fetch();
15157 uint32 quest_id = fields[0].GetUInt32();
15159 // save _any_ from daily quest times (it must be after last reset anyway)
15160 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15162 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15163 if( !pQuest )
15164 continue;
15166 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15167 ++quest_daily_idx;
15169 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15171 while( result->NextRow() );
15173 delete result;
15176 m_DailyQuestChanged = false;
15179 void Player::_LoadSpells(QueryResult *result)
15181 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15183 if(result)
15187 Field *fields = result->Fetch();
15189 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15191 while( result->NextRow() );
15193 delete result;
15197 void Player::_LoadGroup(QueryResult *result)
15199 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15200 if(result)
15202 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15203 delete result;
15204 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15205 if(group)
15207 uint8 subgroup = group->GetMemberGroup(GetGUID());
15208 SetGroup(group, subgroup);
15209 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15211 // the group leader may change the instance difficulty while the player is offline
15212 SetDifficulty(group->GetDifficulty());
15218 void Player::_LoadBoundInstances(QueryResult *result)
15220 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15221 m_boundInstances[i].clear();
15223 Group *group = GetGroup();
15225 //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));
15226 if(result)
15230 Field *fields = result->Fetch();
15231 bool perm = fields[1].GetBool();
15232 uint32 mapId = fields[2].GetUInt32();
15233 uint32 instanceId = fields[0].GetUInt32();
15234 uint8 difficulty = fields[3].GetUInt8();
15235 time_t resetTime = (time_t)fields[4].GetUInt64();
15236 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15237 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15238 // and in that case it is not used
15240 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15241 if(!mapEntry || !mapEntry->IsDungeon())
15243 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15244 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15245 continue;
15248 if(!perm && group)
15250 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);
15251 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15252 continue;
15255 // since non permanent binds are always solo bind, they can always be reset
15256 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15257 if(save) BindToInstance(save, perm, true);
15258 } while(result->NextRow());
15259 delete result;
15263 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15265 // some instances only have one difficulty
15266 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15267 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15269 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15270 if(itr != m_boundInstances[difficulty].end())
15271 return &itr->second;
15272 else
15273 return NULL;
15276 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15278 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15279 UnbindInstance(itr, difficulty, unload);
15282 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15284 if(itr != m_boundInstances[difficulty].end())
15286 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15287 itr->second.save->RemovePlayer(this); // save can become invalid
15288 m_boundInstances[difficulty].erase(itr++);
15292 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15294 if(save)
15296 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15297 if(bind.save)
15299 // update the save when the group kills a boss
15300 if(permanent != bind.perm || save != bind.save)
15301 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());
15303 else
15304 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15306 if(bind.save != save)
15308 if(bind.save) bind.save->RemovePlayer(this);
15309 save->AddPlayer(this);
15312 if(permanent) save->SetCanReset(false);
15314 bind.save = save;
15315 bind.perm = permanent;
15316 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());
15317 return &bind;
15319 else
15320 return NULL;
15323 void Player::SendRaidInfo()
15325 uint32 counter = 0;
15327 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15329 size_t p_counter = data.wpos();
15330 data << uint32(counter); // placeholder
15332 time_t now = time(NULL);
15334 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15336 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15338 if(itr->second.perm)
15340 InstanceSave *save = itr->second.save;
15341 data << uint32(save->GetMapId()); // map id
15342 data << uint32(save->GetDifficulty()); // difficulty
15343 data << uint64(save->GetInstanceId()); // instance id
15344 data << uint32(save->GetResetTime() - now); // reset time
15345 data << uint32(0); // is extended
15346 ++counter;
15350 data.put<uint32>(p_counter, counter);
15351 GetSession()->SendPacket(&data);
15355 - called on every successful teleportation to a map
15357 void Player::SendSavedInstances()
15359 bool hasBeenSaved = false;
15360 WorldPacket data;
15362 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15364 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15366 if(itr->second.perm) // only permanent binds are sent
15368 hasBeenSaved = true;
15369 break;
15374 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15375 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15376 data << uint32(hasBeenSaved);
15377 GetSession()->SendPacket(&data);
15379 if(!hasBeenSaved)
15380 return;
15382 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15384 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15386 if(itr->second.perm)
15388 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15389 data << uint32(itr->second.save->GetMapId());
15390 GetSession()->SendPacket(&data);
15396 /// convert the player's binds to the group
15397 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15399 bool has_binds = false;
15400 bool has_solo = false;
15402 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15403 assert(player_guid);
15405 // copy all binds to the group, when changing leader it's assumed the character
15406 // will not have any solo binds
15408 if(player)
15410 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15412 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15414 has_binds = true;
15415 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15416 // permanent binds are not removed
15417 if(!itr->second.perm)
15419 player->UnbindInstance(itr, i, true); // increments itr
15420 has_solo = true;
15422 else
15423 ++itr;
15428 // if the player's not online we don't know what binds it has
15429 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));
15430 // the following should not get executed when changing leaders
15431 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15434 bool Player::_LoadHomeBind(QueryResult *result)
15436 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15437 if(!info)
15439 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15440 return false;
15443 bool ok = false;
15444 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15445 if (result)
15447 Field *fields = result->Fetch();
15448 m_homebindMapId = fields[0].GetUInt32();
15449 m_homebindZoneId = fields[1].GetUInt16();
15450 m_homebindX = fields[2].GetFloat();
15451 m_homebindY = fields[3].GetFloat();
15452 m_homebindZ = fields[4].GetFloat();
15453 delete result;
15455 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15457 // accept saved data only for valid position (and non instanceable), and accessable
15458 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15459 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15461 ok = true;
15463 else
15464 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15467 if(!ok)
15469 m_homebindMapId = info->mapId;
15470 m_homebindZoneId = info->zoneId;
15471 m_homebindX = info->positionX;
15472 m_homebindY = info->positionY;
15473 m_homebindZ = info->positionZ;
15475 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);
15478 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15479 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15481 return true;
15484 /*********************************************************/
15485 /*** SAVE SYSTEM ***/
15486 /*********************************************************/
15488 void Player::SaveToDB()
15490 // delay auto save at any saves (manual, in code, or autosave)
15491 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15493 //lets allow only players in world to be saved
15494 if(IsBeingTeleportedFar())
15496 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
15497 return;
15500 // first save/honor gain after midnight will also update the player's honor fields
15501 UpdateHonorFields();
15503 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15504 //save, far from tavern/city
15505 //save, but in tavern/city
15506 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15507 outDebugValues();
15509 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15510 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15511 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15512 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15513 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15514 uint32 tmp_displayid = GetDisplayId();
15516 // Set player sit state to standing on save, also stealth and shifted form
15517 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15518 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15519 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15521 bool inworld = IsInWorld();
15523 CharacterDatabase.BeginTransaction();
15525 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15527 std::string sql_name = m_name;
15528 CharacterDatabase.escape_string(sql_name);
15530 std::ostringstream ss;
15531 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
15532 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15533 "taximask, online, cinematic, "
15534 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15535 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15536 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15537 << GetGUIDLow() << ", "
15538 << GetSession()->GetAccountId() << ", '"
15539 << sql_name << "', "
15540 << (uint32)getRace() << ", "
15541 << (uint32)getClass() << ", "
15542 << (uint32)getGender() << ", "
15543 << getLevel() << ", "
15544 << GetUInt32Value(PLAYER_XP) << ", "
15545 << GetMoney() << ", "
15546 << GetUInt32Value(PLAYER_BYTES) << ", "
15547 << GetUInt32Value(PLAYER_BYTES_2) << ", "
15548 << GetUInt32Value(PLAYER_FLAGS) << ", ";
15550 if(!IsBeingTeleported())
15552 ss << GetMapId() << ", "
15553 << (uint32)GetDifficulty() << ", "
15554 << finiteAlways(GetPositionX()) << ", "
15555 << finiteAlways(GetPositionY()) << ", "
15556 << finiteAlways(GetPositionZ()) << ", "
15557 << finiteAlways(GetOrientation()) << ", '";
15559 else
15561 ss << GetTeleportDest().mapid << ", "
15562 << (uint32)GetDifficulty() << ", "
15563 << finiteAlways(GetTeleportDest().coord_x) << ", "
15564 << finiteAlways(GetTeleportDest().coord_y) << ", "
15565 << finiteAlways(GetTeleportDest().coord_z) << ", "
15566 << finiteAlways(GetTeleportDest().orientation) << ", '";
15569 uint16 i;
15570 for( i = 0; i < m_valuesCount; ++i )
15572 ss << GetUInt32Value(i) << " ";
15575 ss << "', ";
15577 ss << m_taxi; // string with TaxiMaskSize numbers
15579 ss << ", ";
15580 ss << (inworld ? 1 : 0);
15582 ss << ", ";
15583 ss << m_cinematic;
15585 ss << ", ";
15586 ss << m_Played_time[0];
15587 ss << ", ";
15588 ss << m_Played_time[1];
15590 ss << ", ";
15591 ss << finiteAlways(m_rest_bonus);
15592 ss << ", ";
15593 ss << (uint64)time(NULL);
15594 ss << ", ";
15595 ss << is_save_resting;
15596 ss << ", ";
15597 ss << m_resetTalentsCost;
15598 ss << ", ";
15599 ss << (uint64)m_resetTalentsTime;
15601 ss << ", ";
15602 ss << finiteAlways(m_movementInfo.t_x);
15603 ss << ", ";
15604 ss << finiteAlways(m_movementInfo.t_y);
15605 ss << ", ";
15606 ss << finiteAlways(m_movementInfo.t_z);
15607 ss << ", ";
15608 ss << finiteAlways(m_movementInfo.t_o);
15609 ss << ", ";
15610 if (m_transport)
15611 ss << m_transport->GetGUIDLow();
15612 else
15613 ss << "0";
15615 ss << ", ";
15616 ss << m_ExtraFlags;
15618 ss << ", ";
15619 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15621 ss << ", ";
15622 ss << uint32(m_atLoginFlags);
15624 ss << ", ";
15625 ss << GetZoneId();
15627 ss << ", ";
15628 ss << (uint64)m_deathExpireTime;
15630 ss << ", '";
15631 ss << m_taxi.SaveTaxiDestinationsToString();
15632 ss << "', '0', ";
15633 ss << GetBattleGroundId();
15634 ss << ", ";
15635 ss << GetBGTeam();
15636 ss << ", ";
15637 ss << m_bgEntryPoint.mapid << ", "
15638 << finiteAlways(m_bgEntryPoint.coord_x) << ", "
15639 << finiteAlways(m_bgEntryPoint.coord_y) << ", "
15640 << finiteAlways(m_bgEntryPoint.coord_z) << ", "
15641 << finiteAlways(m_bgEntryPoint.orientation);
15642 ss << ")";
15644 CharacterDatabase.Execute( ss.str().c_str() );
15646 if(m_mailsUpdated) //save mails only when needed
15647 _SaveMail();
15649 _SaveInventory();
15650 _SaveQuestStatus();
15651 _SaveDailyQuestStatus();
15652 _SaveSpells();
15653 _SaveSpellCooldowns();
15654 _SaveActions();
15655 _SaveAuras();
15656 m_achievementMgr.SaveToDB();
15657 m_reputationMgr.SaveToDB();
15658 _SaveEquipmentSets();
15659 GetSession()->SaveTutorialsData(); // changed only while character in game
15661 CharacterDatabase.CommitTransaction();
15663 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15664 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15665 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15666 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15667 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15669 // save pet (hunter pet level and experience and all type pets health/mana).
15670 if(Pet* pet = GetPet())
15671 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15674 // fast save function for item/money cheating preventing - save only inventory and money state
15675 void Player::SaveInventoryAndGoldToDB()
15677 _SaveInventory();
15678 SaveGoldToDB();
15681 void Player::SaveGoldToDB()
15683 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
15686 void Player::_SaveActions()
15688 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15690 switch (itr->second.uState)
15692 case ACTIONBUTTON_NEW:
15693 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
15694 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
15695 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15696 ++itr;
15697 break;
15698 case ACTIONBUTTON_CHANGED:
15699 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
15700 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
15701 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15702 ++itr;
15703 break;
15704 case ACTIONBUTTON_DELETED:
15705 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15706 m_actionButtons.erase(itr++);
15707 break;
15708 default:
15709 ++itr;
15710 break;
15715 void Player::_SaveAuras()
15717 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15719 AuraMap const& auras = GetAuras();
15721 if (auras.empty())
15722 return;
15724 spellEffectPair lastEffectPair = auras.begin()->first;
15725 uint32 stackCounter = 1;
15727 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15729 if(itr == auras.end() || lastEffectPair != itr->first)
15731 AuraMap::const_iterator itr2 = itr;
15732 // save previous spellEffectPair to db
15733 itr2--;
15735 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15737 //skip all auras from spells that are passive or need a shapeshift
15738 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15740 //do not save single target auras (unless they were cast by the player)
15741 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15743 uint8 i;
15744 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15745 for (i = 0; i < 3; ++i)
15746 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15747 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15748 break;
15750 if (i == 3)
15752 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15753 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15754 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->GetAuraCharges()));
15759 if(itr == auras.end())
15760 break;
15763 if (lastEffectPair == itr->first)
15764 stackCounter++;
15765 else
15767 lastEffectPair = itr->first;
15768 stackCounter = 1;
15773 void Player::_SaveInventory()
15775 // force items in buyback slots to new state
15776 // and remove those that aren't already
15777 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15779 Item *item = m_items[i];
15780 if (!item || item->GetState() == ITEM_NEW) continue;
15781 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15782 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15783 m_items[i]->FSetState(ITEM_NEW);
15786 // update enchantment durations
15787 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15789 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15792 // if no changes
15793 if (m_itemUpdateQueue.empty()) return;
15795 // do not save if the update queue is corrupt
15796 bool error = false;
15797 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15799 Item *item = m_itemUpdateQueue[i];
15800 if(!item || item->GetState() == ITEM_REMOVED) continue;
15801 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15803 if (test == NULL)
15805 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());
15806 error = true;
15808 else if (test != item)
15810 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());
15811 error = true;
15815 if (error)
15817 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15818 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15819 return;
15822 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15824 Item *item = m_itemUpdateQueue[i];
15825 if(!item) continue;
15827 Bag *container = item->GetContainer();
15828 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15830 switch(item->GetState())
15832 case ITEM_NEW:
15833 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());
15834 break;
15835 case ITEM_CHANGED:
15836 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());
15837 break;
15838 case ITEM_REMOVED:
15839 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15840 break;
15841 case ITEM_UNCHANGED:
15842 break;
15845 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15847 m_itemUpdateQueue.clear();
15850 void Player::_SaveMail()
15852 if (!m_mailsLoaded)
15853 return;
15855 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15857 Mail *m = (*itr);
15858 if (m->state == MAIL_STATE_CHANGED)
15860 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15861 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15862 if(m->removedItems.size())
15864 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15865 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15866 m->removedItems.clear();
15868 m->state = MAIL_STATE_UNCHANGED;
15870 else if (m->state == MAIL_STATE_DELETED)
15872 if (m->HasItems())
15873 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15874 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15875 if (m->itemTextId)
15876 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15877 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15878 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15882 //deallocate deleted mails...
15883 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15885 if ((*itr)->state == MAIL_STATE_DELETED)
15887 Mail* m = *itr;
15888 m_mail.erase(itr);
15889 delete m;
15890 itr = m_mail.begin();
15892 else
15893 ++itr;
15896 m_mailsUpdated = false;
15899 void Player::_SaveQuestStatus()
15901 // we don't need transactions here.
15902 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15904 switch (i->second.uState)
15906 case QUEST_NEW :
15907 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15908 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15909 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15910 break;
15911 case QUEST_CHANGED :
15912 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15913 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15914 break;
15915 case QUEST_UNCHANGED:
15916 break;
15918 i->second.uState = QUEST_UNCHANGED;
15922 void Player::_SaveDailyQuestStatus()
15924 if(!m_DailyQuestChanged)
15925 return;
15927 m_DailyQuestChanged = false;
15929 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15931 // we don't need transactions here.
15932 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15933 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15934 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15935 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15936 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15939 void Player::_SaveSpells()
15941 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15943 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15944 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15946 // add only changed/new not dependent spells
15947 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15948 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
15950 if (itr->second->state == PLAYERSPELL_REMOVED)
15952 delete itr->second;
15953 m_spells.erase(itr++);
15955 else
15957 itr->second->state = PLAYERSPELL_UNCHANGED;
15958 ++itr;
15964 void Player::outDebugValues() const
15966 if(!sLog.IsOutDebug()) // optimize disabled debug output
15967 return;
15969 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15970 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15971 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15972 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15973 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15974 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15975 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15976 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15977 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15978 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15979 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15980 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15983 /*********************************************************/
15984 /*** FLOOD FILTER SYSTEM ***/
15985 /*********************************************************/
15987 void Player::UpdateSpeakTime()
15989 // ignore chat spam protection for GMs in any mode
15990 if(GetSession()->GetSecurity() > SEC_PLAYER)
15991 return;
15993 time_t current = time (NULL);
15994 if(m_speakTime > current)
15996 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15997 if(!max_count)
15998 return;
16000 ++m_speakCount;
16001 if(m_speakCount >= max_count)
16003 // prevent overwrite mute time, if message send just before mutes set, for example.
16004 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16005 if(GetSession()->m_muteTime < new_mute)
16006 GetSession()->m_muteTime = new_mute;
16008 m_speakCount = 0;
16011 else
16012 m_speakCount = 0;
16014 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16017 bool Player::CanSpeak() const
16019 return GetSession()->m_muteTime <= time (NULL);
16022 /*********************************************************/
16023 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16024 /*********************************************************/
16026 void Player::SendAttackSwingNotInRange()
16028 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16029 GetSession()->SendPacket( &data );
16032 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16034 std::ostringstream ss;
16035 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16036 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16037 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16038 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16039 sLog.outDebug(ss.str().c_str());
16040 CharacterDatabase.Execute(ss.str().c_str());
16043 void Player::SaveDataFieldToDB()
16045 std::ostringstream ss;
16046 ss<<"UPDATE characters SET data='";
16048 for(uint16 i = 0; i < m_valuesCount; ++i )
16050 ss << GetUInt32Value(i) << " ";
16052 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16054 CharacterDatabase.Execute(ss.str().c_str());
16057 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16059 std::ostringstream ss2;
16060 ss2<<"UPDATE characters SET data='";
16061 int i=0;
16062 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16064 ss2<<tokens[i]<<" ";
16066 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16068 return CharacterDatabase.Execute(ss2.str().c_str());
16071 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16073 char buf[11];
16074 snprintf(buf,11,"%u",value);
16076 if(index >= tokens.size())
16077 return;
16079 tokens[index] = buf;
16082 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16084 Tokens tokens;
16085 if(!LoadValuesArrayFromDB(tokens,guid))
16086 return;
16088 if(index >= tokens.size())
16089 return;
16091 char buf[11];
16092 snprintf(buf,11,"%u",value);
16093 tokens[index] = buf;
16095 SaveValuesArrayInDB(tokens,guid);
16098 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16100 uint32 temp;
16101 memcpy(&temp, &value, sizeof(value));
16102 Player::SetUInt32ValueInDB(index, temp, guid);
16105 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16107 // 0
16108 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16109 if(!result)
16110 return;
16112 Field* fields = result->Fetch();
16114 uint32 player_bytes2 = fields[0].GetUInt32();
16115 player_bytes2 &= ~0xFF;
16116 player_bytes2 |= facialHair;
16118 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
16120 delete result;
16123 void Player::SendAttackSwingDeadTarget()
16125 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16126 GetSession()->SendPacket( &data );
16129 void Player::SendAttackSwingCantAttack()
16131 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16132 GetSession()->SendPacket( &data );
16135 void Player::SendAttackSwingCancelAttack()
16137 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16138 GetSession()->SendPacket( &data );
16141 void Player::SendAttackSwingBadFacingAttack()
16143 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16144 GetSession()->SendPacket( &data );
16147 void Player::SendAutoRepeatCancel()
16149 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16150 data.append(GetPackGUID()); // may be it's target guid
16151 GetSession()->SendPacket( &data );
16154 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16156 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16157 data << Area;
16158 data << Experience;
16159 GetSession()->SendPacket(&data);
16162 void Player::SendDungeonDifficulty(bool IsInGroup)
16164 uint8 val = 0x00000001;
16165 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16166 data << (uint32)GetDifficulty();
16167 data << uint32(val);
16168 data << uint32(IsInGroup);
16169 GetSession()->SendPacket(&data);
16172 void Player::SendResetFailedNotify(uint32 mapid)
16174 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16175 data << uint32(mapid);
16176 GetSession()->SendPacket(&data);
16179 /// Reset all solo instances and optionally send a message on success for each
16180 void Player::ResetInstances(uint8 method)
16182 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16184 // we assume that when the difficulty changes, all instances that can be reset will be
16185 uint8 dif = GetDifficulty();
16187 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16189 InstanceSave *p = itr->second.save;
16190 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16191 if(!entry || !p->CanReset())
16193 ++itr;
16194 continue;
16197 if(method == INSTANCE_RESET_ALL)
16199 // the "reset all instances" method can only reset normal maps
16200 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16202 ++itr;
16203 continue;
16207 // if the map is loaded, reset it
16208 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16209 if(map && map->IsDungeon())
16210 ((InstanceMap*)map)->Reset(method);
16212 // since this is a solo instance there should not be any players inside
16213 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16214 SendResetInstanceSuccess(p->GetMapId());
16216 p->DeleteFromDB();
16217 m_boundInstances[dif].erase(itr++);
16219 // the following should remove the instance save from the manager and delete it as well
16220 p->RemovePlayer(this);
16224 void Player::SendResetInstanceSuccess(uint32 MapId)
16226 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16227 data << MapId;
16228 GetSession()->SendPacket(&data);
16231 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16233 // TODO: find what other fail reasons there are besides players in the instance
16234 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16235 data << reason;
16236 data << MapId;
16237 GetSession()->SendPacket(&data);
16240 /*********************************************************/
16241 /*** Update timers ***/
16242 /*********************************************************/
16244 ///checks the 15 afk reports per 5 minutes limit
16245 void Player::UpdateAfkReport(time_t currTime)
16247 if(m_bgAfkReportedTimer <= currTime)
16249 m_bgAfkReportedCount = 0;
16250 m_bgAfkReportedTimer = currTime+5*MINUTE;
16254 void Player::UpdateContestedPvP(uint32 diff)
16256 if(!m_contestedPvPTimer||isInCombat())
16257 return;
16258 if(m_contestedPvPTimer <= diff)
16260 ResetContestedPvP();
16262 else
16263 m_contestedPvPTimer -= diff;
16266 void Player::UpdatePvPFlag(time_t currTime)
16268 if(!IsPvP())
16269 return;
16270 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16271 return;
16273 UpdatePvP(false);
16276 void Player::UpdateDuelFlag(time_t currTime)
16278 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16279 return;
16281 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16282 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16284 duel->startTimer = 0;
16285 duel->startTime = currTime;
16286 duel->opponent->duel->startTimer = 0;
16287 duel->opponent->duel->startTime = currTime;
16290 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16292 if(!pet)
16293 pet = GetPet();
16295 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16297 //returning of reagents only for players, so best done here
16298 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16299 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16301 if(spellInfo)
16303 for(uint32 i = 0; i < 7; ++i)
16305 if(spellInfo->Reagent[i] > 0)
16307 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16308 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16309 if( msg == EQUIP_ERR_OK )
16311 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16312 if(IsInWorld())
16313 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16318 m_temporaryUnsummonedPetNumber = 0;
16321 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16322 return;
16324 // only if current pet in slot
16325 switch(pet->getPetType())
16327 case MINI_PET:
16328 m_miniPet = 0;
16329 break;
16330 case GUARDIAN_PET:
16331 RemoveGuardian(pet);
16332 break;
16333 default:
16334 if(GetPetGUID() == pet->GetGUID())
16335 SetPet(NULL);
16336 break;
16339 pet->CombatStop();
16341 if(returnreagent)
16343 switch(pet->GetEntry())
16345 //warlock pets except imp are removed(?) when logging out
16346 case 1860:
16347 case 1863:
16348 case 417:
16349 case 17252:
16350 mode = PET_SAVE_NOT_IN_SLOT;
16351 break;
16355 pet->SavePetToDB(mode);
16357 pet->AddObjectToRemoveList();
16358 pet->m_removed = true;
16360 if(pet->isControlled())
16362 RemovePetActionBar();
16364 if(GetGroup())
16365 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16369 void Player::RemoveMiniPet()
16371 if(Pet* pet = GetMiniPet())
16373 pet->Remove(PET_SAVE_AS_DELETED);
16374 m_miniPet = 0;
16378 Pet* Player::GetMiniPet()
16380 if(!m_miniPet)
16381 return NULL;
16382 return ObjectAccessor::GetPet(m_miniPet);
16385 void Player::Uncharm()
16387 Unit* charm = GetCharm();
16388 if(!charm)
16389 return;
16391 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16392 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16395 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16397 *data << (uint8)msgtype;
16398 *data << (uint32)language;
16399 *data << (uint64)GetGUID();
16400 *data << (uint32)language; //language 2.1.0 ?
16401 *data << (uint64)GetGUID();
16402 *data << (uint32)(text.length()+1);
16403 *data << text;
16404 *data << (uint8)chatTag();
16407 void Player::Say(const std::string& text, const uint32 language)
16409 WorldPacket data(SMSG_MESSAGECHAT, 200);
16410 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16411 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16414 void Player::Yell(const std::string& text, const uint32 language)
16416 WorldPacket data(SMSG_MESSAGECHAT, 200);
16417 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16418 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16421 void Player::TextEmote(const std::string& text)
16423 WorldPacket data(SMSG_MESSAGECHAT, 200);
16424 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16425 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16428 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16430 if (language != LANG_ADDON) // if not addon data
16431 language = LANG_UNIVERSAL; // whispers should always be readable
16433 Player *rPlayer = objmgr.GetPlayer(receiver);
16435 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16436 if(!rPlayer->isDND() || isGameMaster())
16438 WorldPacket data(SMSG_MESSAGECHAT, 200);
16439 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16440 rPlayer->GetSession()->SendPacket(&data);
16442 data.Initialize(SMSG_MESSAGECHAT, 200);
16443 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16444 GetSession()->SendPacket(&data);
16446 else
16448 // announce to player that player he is whispering to is dnd and cannot receive his message
16449 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16452 if(!isAcceptWhispers())
16454 SetAcceptWhispers(true);
16455 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16458 // announce to player that player he is whispering to is afk
16459 if(rPlayer->isAFK())
16460 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16462 // if player whisper someone, auto turn of dnd to be able to receive an answer
16463 if(isDND() && !rPlayer->isGameMaster())
16464 ToggleDND();
16467 void Player::PetSpellInitialize()
16469 Pet* pet = GetPet();
16471 if(!pet)
16472 return;
16474 sLog.outDebug("Pet Spells Groups");
16476 CharmInfo *charmInfo = pet->GetCharmInfo();
16478 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16479 data << uint64(pet->GetGUID());
16480 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16481 data << uint32(0);
16482 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16484 // action bar loop
16485 charmInfo->BuildActionBar(&data);
16487 size_t spellsCountPos = data.wpos();
16489 // spells count
16490 uint8 addlist = 0;
16491 data << uint8(addlist); // placeholder
16493 if (pet->IsPermanentPetFor(this))
16495 // spells loop
16496 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16498 if(itr->second.state == PETSPELL_REMOVED)
16499 continue;
16501 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
16502 ++addlist;
16506 data.put<uint8>(spellsCountPos, addlist);
16508 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16509 data << uint8(cooldownsCount);
16511 time_t curTime = time(NULL);
16513 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16515 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16517 data << uint32(itr->first); // spellid
16518 data << uint16(0); // spell category?
16519 data << uint32(cooldown); // cooldown
16520 data << uint32(0); // category cooldown
16523 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16525 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16527 data << uint32(itr->first); // spellid
16528 data << uint16(0); // spell category?
16529 data << uint32(0); // cooldown
16530 data << uint32(cooldown); // category cooldown
16533 GetSession()->SendPacket(&data);
16536 void Player::PossessSpellInitialize()
16538 Unit* charm = GetCharm();
16540 if(!charm)
16541 return;
16543 CharmInfo *charmInfo = charm->GetCharmInfo();
16545 if(!charmInfo)
16547 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16548 return;
16551 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16552 data << uint64(charm->GetGUID());
16553 data << uint16(0);
16554 data << uint32(0);
16555 data << uint32(0);
16557 charmInfo->BuildActionBar(&data);
16559 data << uint8(0); // spells count
16560 data << uint8(0); // cooldowns count
16562 GetSession()->SendPacket(&data);
16565 void Player::CharmSpellInitialize()
16567 Unit* charm = GetCharm();
16569 if(!charm)
16570 return;
16572 CharmInfo *charmInfo = charm->GetCharmInfo();
16573 if(!charmInfo)
16575 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16576 return;
16579 uint8 addlist = 0;
16581 if(charm->GetTypeId() != TYPEID_PLAYER)
16583 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16585 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16587 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16589 if(charmInfo->GetCharmSpell(i)->GetAction())
16590 ++addlist;
16595 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16596 data << uint64(charm->GetGUID());
16597 data << uint16(0);
16598 data << uint32(0);
16600 if(charm->GetTypeId() != TYPEID_PLAYER)
16601 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16602 else
16603 data << uint8(0) << uint8(0) << uint16(0);
16605 charmInfo->BuildActionBar(&data);
16607 data << uint8(addlist);
16609 if(addlist)
16611 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16613 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16614 if(cspell->GetAction())
16615 data << uint32(cspell->packedData);
16619 data << uint8(0); // cooldowns count
16621 GetSession()->SendPacket(&data);
16624 void Player::RemovePetActionBar()
16626 WorldPacket data(SMSG_PET_SPELLS, 8);
16627 data << uint64(0);
16628 SendDirectMessage(&data);
16631 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16633 if (!mod || !spellInfo)
16634 return false;
16636 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16638 // prevent apply to any spell except spell that trigger expire
16639 if(spell)
16641 if(mod->lastAffected != spell)
16642 return false;
16644 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16645 return false;
16648 return spellmgr.IsAffectedByMod(spellInfo, mod);
16651 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16653 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16655 for(int eff=0;eff<96;++eff)
16657 uint64 _mask = 0;
16658 uint64 _mask2= 0;
16659 if (eff<64) _mask = uint64(1) << (eff- 0);
16660 else _mask2= uint64(1) << (eff-64);
16661 if ( mod->mask & _mask || mod->mask2 & _mask2)
16663 int32 val = 0;
16664 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16666 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16667 val += (*itr)->value;
16669 val += apply ? mod->value : -(mod->value);
16670 WorldPacket data(Opcode, (1+1+4));
16671 data << uint8(eff);
16672 data << uint8(mod->op);
16673 data << int32(val);
16674 SendDirectMessage(&data);
16678 if (apply)
16679 m_spellMods[mod->op].push_back(mod);
16680 else
16682 if (mod->charges == -1)
16683 --m_SpellModRemoveCount;
16684 m_spellMods[mod->op].remove(mod);
16685 delete mod;
16689 void Player::RemoveSpellMods(Spell const* spell)
16691 if(!spell || (m_SpellModRemoveCount == 0))
16692 return;
16694 for(int i=0;i<MAX_SPELLMOD;++i)
16696 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16698 SpellModifier *mod = *itr;
16699 ++itr;
16701 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16703 RemoveAurasDueToSpell(mod->spellId);
16704 if (m_spellMods[i].empty())
16705 break;
16706 else
16707 itr = m_spellMods[i].begin();
16713 // send Proficiency
16714 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16716 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16717 data << pr1 << pr2;
16718 GetSession()->SendPacket (&data);
16721 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16723 QueryResult *result = NULL;
16724 if(type==10)
16725 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16726 else
16727 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16728 if(result)
16730 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.
16731 { // and SendPetitionQueryOpcode reads data from the DB
16732 Field *fields = result->Fetch();
16733 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16734 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16736 // send update if charter owner in game
16737 Player* owner = objmgr.GetPlayer(ownerguid);
16738 if(owner)
16739 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16741 } while ( result->NextRow() );
16743 delete result;
16745 if(type==10)
16746 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16747 else
16748 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16751 CharacterDatabase.BeginTransaction();
16752 if(type == 10)
16754 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16755 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16757 else
16759 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16760 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16762 CharacterDatabase.CommitTransaction();
16765 void Player::LeaveAllArenaTeams(uint64 guid)
16767 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid));
16768 if(!result)
16769 return;
16773 Field *fields = result->Fetch();
16774 uint32 at_id = fields[0].GetUInt32();
16775 if(at_id != 0)
16777 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16778 if(at)
16779 at->DelMember(guid);
16781 } while (result->NextRow());
16783 delete result;
16786 void Player::SetRestBonus (float rest_bonus_new)
16788 // Prevent resting on max level
16789 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16790 rest_bonus_new = 0;
16792 if(rest_bonus_new < 0)
16793 rest_bonus_new = 0;
16795 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16797 if(rest_bonus_new > rest_bonus_max)
16798 m_rest_bonus = rest_bonus_max;
16799 else
16800 m_rest_bonus = rest_bonus_new;
16802 // update data for client
16803 if(m_rest_bonus>10)
16804 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16805 else if(m_rest_bonus<=1)
16806 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16808 //RestTickUpdate
16809 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16812 void Player::HandleStealthedUnitsDetection()
16814 std::list<Unit*> stealthedUnits;
16816 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16817 Cell cell(p);
16818 cell.data.Part.reserved = ALL_DISTRICT;
16819 cell.SetNoCreate();
16821 MaNGOS::AnyStealthedCheck u_check;
16822 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16824 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16825 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16827 CellLock<GridReadGuard> cell_lock(cell, p);
16828 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16829 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16831 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16833 if((*i)==this)
16835 i = stealthedUnits.erase(i);
16836 continue;
16839 if ((*i)->isVisibleForOrDetect(this,true))
16842 (*i)->SendUpdateToPlayer(this);
16843 m_clientGUIDs.insert((*i)->GetGUID());
16845 #ifdef MANGOS_DEBUG
16846 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16847 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16848 #endif
16850 // target aura duration for caster show only if target exist at caster client
16851 // send data at target visibility change (adding to client)
16852 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16853 SendAurasForTarget(*i);
16855 i = stealthedUnits.erase(i);
16856 continue;
16859 ++i;
16863 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16865 if(nodes.size() < 2)
16866 return false;
16868 // 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
16869 if(GetSession()->isLogingOut() || isInCombat())
16871 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16872 data << uint32(ERR_TAXIPLAYERBUSY);
16873 GetSession()->SendPacket(&data);
16874 return false;
16877 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16878 return false;
16880 // taximaster case
16881 if(npc)
16883 // not let cheating with start flight mounted
16884 if(IsMounted())
16886 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16887 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16888 GetSession()->SendPacket(&data);
16889 return false;
16892 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16894 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16895 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16896 GetSession()->SendPacket(&data);
16897 return false;
16900 // 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
16901 if(IsNonMeleeSpellCasted(false))
16903 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16904 data << uint32(ERR_TAXIPLAYERBUSY);
16905 GetSession()->SendPacket(&data);
16906 return false;
16909 // cast case or scripted call case
16910 else
16912 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16914 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16915 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16917 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16918 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16920 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16922 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16923 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16926 uint32 sourcenode = nodes[0];
16928 // starting node too far away (cheat?)
16929 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16930 if (!node)
16932 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16933 data << uint32(ERR_TAXINOSUCHPATH);
16934 GetSession()->SendPacket(&data);
16935 return false;
16938 // check node starting pos data set case if provided
16939 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16941 if (node->map_id != GetMapId() ||
16942 (node->x - GetPositionX())*(node->x - GetPositionX())+
16943 (node->y - GetPositionY())*(node->y - GetPositionY())+
16944 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16945 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16947 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16948 data << uint32(ERR_TAXITOOFARAWAY);
16949 GetSession()->SendPacket(&data);
16950 return false;
16953 // node must have pos if taxi master case (npc != NULL)
16954 else if (npc)
16956 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16957 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16958 GetSession()->SendPacket(&data);
16959 return false;
16962 // Prepare to flight start now
16964 // stop combat at start taxi flight if any
16965 CombatStop();
16967 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16968 TradeCancel(true);
16970 // clean not finished taxi path if any
16971 m_taxi.ClearTaxiDestinations();
16973 // 0 element current node
16974 m_taxi.AddTaxiDestination(sourcenode);
16976 // fill destinations path tail
16977 uint32 sourcepath = 0;
16978 uint32 totalcost = 0;
16980 uint32 prevnode = sourcenode;
16981 uint32 lastnode = 0;
16983 for(uint32 i = 1; i < nodes.size(); ++i)
16985 uint32 path, cost;
16987 lastnode = nodes[i];
16988 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16990 if(!path)
16992 m_taxi.ClearTaxiDestinations();
16993 return false;
16996 totalcost += cost;
16998 if(prevnode == sourcenode)
16999 sourcepath = path;
17001 m_taxi.AddTaxiDestination(lastnode);
17003 prevnode = lastnode;
17006 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17007 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17009 // in spell case allow 0 model
17010 if (mount_display_id == 0 && spellid == 0 || sourcepath == 0)
17012 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17013 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17014 GetSession()->SendPacket(&data);
17015 m_taxi.ClearTaxiDestinations();
17016 return false;
17019 uint32 money = GetMoney();
17021 if (npc)
17022 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17024 if(money < totalcost)
17026 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17027 data << uint32(ERR_TAXINOTENOUGHMONEY);
17028 GetSession()->SendPacket(&data);
17029 m_taxi.ClearTaxiDestinations();
17030 return false;
17033 //Checks and preparations done, DO FLIGHT
17034 ModifyMoney(-(int32)totalcost);
17035 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17036 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17038 // prevent stealth flight
17039 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17041 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17042 data << uint32(ERR_TAXIOK);
17043 GetSession()->SendPacket(&data);
17045 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17047 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17049 return true;
17052 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17054 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17055 if(!entry)
17056 return false;
17058 std::vector<uint32> nodes;
17060 nodes.resize(2);
17061 nodes[0] = entry->from;
17062 nodes[1] = entry->to;
17064 return ActivateTaxiPathTo(nodes,NULL,spellid);
17067 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17069 // last check 2.0.10
17070 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17071 data << GetGUID();
17072 data << uint8(0x0); // flags (0x1, 0x2)
17073 time_t curTime = time(NULL);
17074 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17076 if (itr->second->state == PLAYERSPELL_REMOVED)
17077 continue;
17078 uint32 unSpellId = itr->first;
17079 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17080 if (!spellInfo)
17082 ASSERT(spellInfo);
17083 continue;
17086 // Not send cooldown for this spells
17087 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17088 continue;
17090 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17092 data << uint32(unSpellId);
17093 data << uint32(unTimeMs); // in m.secs
17094 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17097 GetSession()->SendPacket(&data);
17100 void Player::InitDataForForm(bool reapplyMods)
17102 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17103 if(ssEntry && ssEntry->attackSpeed)
17105 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17106 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17107 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17109 else
17110 SetRegularAttackTime();
17112 switch(m_form)
17114 case FORM_CAT:
17116 if(getPowerType()!=POWER_ENERGY)
17117 setPowerType(POWER_ENERGY);
17118 break;
17120 case FORM_BEAR:
17121 case FORM_DIREBEAR:
17123 if(getPowerType()!=POWER_RAGE)
17124 setPowerType(POWER_RAGE);
17125 break;
17127 default: // 0, for example
17129 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17130 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17131 setPowerType(Powers(cEntry->powerType));
17132 break;
17136 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17137 if (!reapplyMods)
17138 UpdateEquipSpellsAtFormChange();
17140 UpdateAttackPowerAndDamage();
17141 UpdateAttackPowerAndDamage(true);
17144 void Player::InitDisplayIds()
17146 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
17147 if(!info)
17149 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17150 return;
17153 uint8 gender = getGender();
17154 switch(gender)
17156 case GENDER_FEMALE:
17157 SetDisplayId(info->displayId_f );
17158 SetNativeDisplayId(info->displayId_f );
17159 break;
17160 case GENDER_MALE:
17161 SetDisplayId(info->displayId_m );
17162 SetNativeDisplayId(info->displayId_m );
17163 break;
17164 default:
17165 sLog.outError("Invalid gender %u for player",gender);
17166 return;
17170 // Return true is the bought item has a max count to force refresh of window by caller
17171 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17173 // cheating attempt
17174 if (count < 1) count = 1;
17176 if (!isAlive())
17177 return false;
17179 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17180 if (!pProto)
17182 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17183 return false;
17186 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17187 if (!pCreature)
17189 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17190 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17191 return false;
17194 VendorItemData const* vItems = pCreature->GetVendorItems();
17195 if(!vItems || vItems->Empty())
17197 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17198 return false;
17201 size_t vendor_slot = vItems->FindItemSlot(item);
17202 if (vendor_slot >= vItems->GetItemCount())
17204 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17205 return false;
17208 VendorItem const* crItem = vItems->m_items[vendor_slot];
17210 // check current item amount if it limited
17211 if (crItem->maxcount != 0)
17213 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17215 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17216 return false;
17220 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17222 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17223 return false;
17226 if (crItem->ExtendedCost)
17228 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17229 if (!iece)
17231 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17232 return false;
17235 // honor points price
17236 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17238 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17239 return false;
17242 // arena points price
17243 if (GetArenaPoints() < (iece->reqarenapoints * count))
17245 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17246 return false;
17249 // item base price
17250 for (uint8 i = 0; i < 5; ++i)
17252 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17254 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17255 return false;
17259 // check for personal arena rating requirement
17260 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17262 // probably not the proper equip err
17263 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17264 return false;
17268 uint32 price = pProto->BuyPrice * count;
17270 // reputation discount
17271 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17273 if (GetMoney() < price)
17275 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17276 return false;
17279 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17281 ItemPosCountVec dest;
17282 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17283 if (msg != EQUIP_ERR_OK)
17285 SendEquipError( msg, NULL, NULL );
17286 return false;
17289 ModifyMoney( -(int32)price );
17290 if (crItem->ExtendedCost) // case for new honor system
17292 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17293 if (iece->reqhonorpoints)
17294 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17295 if (iece->reqarenapoints)
17296 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17297 for (uint8 i = 0; i < 5; ++i)
17299 if (iece->reqitem[i])
17300 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17304 if (Item *it = StoreNewItem( dest, item, true ))
17306 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17308 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17309 data << pCreature->GetGUID();
17310 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17311 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17312 data << (uint32)count;
17313 GetSession()->SendPacket(&data);
17315 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17318 else if (IsEquipmentPos(bag, slot))
17320 if (pProto->BuyCount * count != 1)
17322 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17323 return false;
17326 uint16 dest;
17327 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17328 if (msg != EQUIP_ERR_OK)
17330 SendEquipError( msg, NULL, NULL );
17331 return false;
17334 ModifyMoney( -(int32)price );
17335 if (crItem->ExtendedCost) // case for new honor system
17337 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17338 if (iece->reqhonorpoints)
17339 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17340 if (iece->reqarenapoints)
17341 ModifyArenaPoints( - int32(iece->reqarenapoints));
17342 for (uint8 i = 0; i < 5; ++i)
17344 if(iece->reqitem[i])
17345 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17349 if (Item *it = EquipNewItem( dest, item, true ))
17351 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17353 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17354 data << pCreature->GetGUID();
17355 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17356 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17357 data << (uint32)count;
17358 GetSession()->SendPacket(&data);
17360 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17362 AutoUnequipOffhandIfNeed();
17365 else
17367 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17368 return false;
17371 return crItem->maxcount != 0;
17374 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17376 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17377 // the personal rating of the arena team must match the required limit as well
17378 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17379 uint32 max_personal_rating = 0;
17380 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17382 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17384 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17385 uint32 t_rating = at->GetRating();
17386 p_rating = p_rating<t_rating? p_rating : t_rating;
17387 if(max_personal_rating < p_rating)
17388 max_personal_rating = p_rating;
17391 return max_personal_rating;
17394 void Player::UpdateHomebindTime(uint32 time)
17396 // GMs never get homebind timer online
17397 if (m_InstanceValid || isGameMaster())
17399 if(m_HomebindTimer) // instance valid, but timer not reset
17401 // hide reminder
17402 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17403 data << uint32(0);
17404 data << uint32(0);
17405 GetSession()->SendPacket(&data);
17407 // instance is valid, reset homebind timer
17408 m_HomebindTimer = 0;
17410 else if (m_HomebindTimer > 0)
17412 if (time >= m_HomebindTimer)
17414 // teleport to nearest graveyard
17415 RepopAtGraveyard();
17417 else
17418 m_HomebindTimer -= time;
17420 else
17422 // instance is invalid, start homebind timer
17423 m_HomebindTimer = 60000;
17424 // send message to player
17425 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17426 data << m_HomebindTimer;
17427 data << uint32(1);
17428 GetSession()->SendPacket(&data);
17429 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17433 void Player::UpdatePvP(bool state, bool ovrride)
17435 if(!state || ovrride)
17437 SetPvP(state);
17438 pvpInfo.endTimer = 0;
17440 else
17442 if(pvpInfo.endTimer != 0)
17443 pvpInfo.endTimer = time(NULL);
17444 else
17445 SetPvP(state);
17449 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17451 // init cooldown values
17452 uint32 cat = 0;
17453 int32 rec = -1;
17454 int32 catrec = -1;
17456 // some special item spells without correct cooldown in SpellInfo
17457 // cooldown information stored in item prototype
17458 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17460 if(itemId)
17462 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17464 for(int idx = 0; idx < 5; ++idx)
17466 if(proto->Spells[idx].SpellId == spellInfo->Id)
17468 cat = proto->Spells[idx].SpellCategory;
17469 rec = proto->Spells[idx].SpellCooldown;
17470 catrec = proto->Spells[idx].SpellCategoryCooldown;
17471 break;
17477 // if no cooldown found above then base at DBC data
17478 if(rec < 0 && catrec < 0)
17480 cat = spellInfo->Category;
17481 rec = spellInfo->RecoveryTime;
17482 catrec = spellInfo->CategoryRecoveryTime;
17485 time_t curTime = time(NULL);
17487 time_t catrecTime;
17488 time_t recTime;
17490 // overwrite time for selected category
17491 if(infinityCooldown)
17493 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17494 // but not allow ignore until reset or re-login
17495 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
17496 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
17498 else
17500 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17501 // prevent 0 cooldowns set by another way
17502 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17503 rec = GetAttackTime(RANGED_ATTACK);
17505 // Now we have cooldown data (if found any), time to apply mods
17506 if(rec > 0)
17507 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17509 if(catrec > 0)
17510 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17512 // replace negative cooldowns by 0
17513 if (rec < 0) rec = 0;
17514 if (catrec < 0) catrec = 0;
17516 // no cooldown after applying spell mods
17517 if( rec == 0 && catrec == 0)
17518 return;
17520 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17521 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17524 // self spell cooldown
17525 if(recTime > 0)
17526 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17528 // category spells
17529 if (cat && catrec > 0)
17531 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17532 if(i_scstore != sSpellCategoryStore.end())
17534 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17536 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17537 continue;
17539 AddSpellCooldown(*i_scset, itemId, catrecTime);
17545 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17547 SpellCooldown sc;
17548 sc.end = end_time;
17549 sc.itemid = itemid;
17550 m_spellCooldowns[spellid] = sc;
17553 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17555 // start cooldowns at server side, if any
17556 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17558 // Send activate cooldown timer (possible 0) at client side
17559 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17560 data << spellInfo->Id;
17561 data << GetGUID();
17562 SendDirectMessage(&data);
17565 void Player::UpdatePotionCooldown(Spell* spell)
17567 // no potion used i combat or still in combat
17568 if(!m_lastPotionId || isInCombat())
17569 return;
17571 // Call not from spell cast, send cooldown event for item spells if no in combat
17572 if(!spell)
17574 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17575 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17576 for(int idx = 0; idx < 5; ++idx)
17577 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17578 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17579 SendCooldownEvent(spellInfo,m_lastPotionId);
17581 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17582 else
17583 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17585 m_lastPotionId = 0;
17588 //slot to be excluded while counting
17589 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17591 if(!enchantmentcondition)
17592 return true;
17594 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17596 if(!Condition)
17597 return true;
17599 uint8 curcount[4] = {0, 0, 0, 0};
17601 //counting current equipped gem colors
17602 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17604 if(i == slot)
17605 continue;
17606 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17607 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17609 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17611 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17612 if(!enchant_id)
17613 continue;
17615 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17616 if(!enchantEntry)
17617 continue;
17619 uint32 gemid = enchantEntry->GemID;
17620 if(!gemid)
17621 continue;
17623 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17624 if(!gemProto)
17625 continue;
17627 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17628 if(!gemProperty)
17629 continue;
17631 uint8 GemColor = gemProperty->color;
17633 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17635 if(tmpcolormask & GemColor)
17636 ++curcount[b];
17642 bool activate = true;
17644 for(int i = 0; i < 5; ++i)
17646 if(!Condition->Color[i])
17647 continue;
17649 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17651 // if have <CompareColor> use them as count, else use <value> from Condition
17652 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17654 switch(Condition->Comparator[i])
17656 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17657 activate &= (_cur_gem < _cmp_gem) ? true : false;
17658 break;
17659 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17660 activate &= (_cur_gem > _cmp_gem) ? true : false;
17661 break;
17662 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17663 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17664 break;
17668 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");
17670 return activate;
17673 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17675 //cycle all equipped items
17676 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17678 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17679 if(slot == exceptslot)
17680 continue;
17682 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17684 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17685 continue;
17687 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17689 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17690 if(!enchant_id)
17691 continue;
17693 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17694 if(!enchantEntry)
17695 continue;
17697 uint32 condition = enchantEntry->EnchantmentCondition;
17698 if(condition)
17700 //was enchant active with/without item?
17701 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17702 //should it now be?
17703 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17705 // ignore item gem conditions
17706 //if state changed, (dis)apply enchant
17707 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17714 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17715 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17717 //cycle all equipped items
17718 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17720 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17721 if(slot == exceptslot)
17722 continue;
17724 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17726 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17727 continue;
17729 //cycle all (gem)enchants
17730 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17732 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17733 if(!enchant_id) //if no enchant go to next enchant(slot)
17734 continue;
17736 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17737 if(!enchantEntry)
17738 continue;
17740 //only metagems to be (de)activated, so only enchants with condition
17741 uint32 condition = enchantEntry->EnchantmentCondition;
17742 if(condition)
17743 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17748 void Player::LeaveBattleground(bool teleportToEntryPoint)
17750 if(BattleGround *bg = GetBattleGround())
17752 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17754 // call after remove to be sure that player resurrected for correct cast
17755 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17757 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17759 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
17760 if(IsBeingTeleportedFar())
17762 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
17763 return;
17766 CastSpell(this, 26013, true); // Deserter
17772 bool Player::CanJoinToBattleground() const
17774 // check Deserter debuff
17775 if(GetDummyAura(26013))
17776 return false;
17778 return true;
17781 bool Player::CanReportAfkDueToLimit()
17783 // a player can complain about 15 people per 5 minutes
17784 if(m_bgAfkReportedCount >= 15)
17785 return false;
17786 ++m_bgAfkReportedCount;
17787 return true;
17790 ///This player has been blamed to be inactive in a battleground
17791 void Player::ReportedAfkBy(Player* reporter)
17793 BattleGround *bg = GetBattleGround();
17794 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17795 return;
17797 // check if player has 'Idle' or 'Inactive' debuff
17798 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17800 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17801 // 3 players have to complain to apply debuff
17802 if(m_bgAfkReporter.size() >= 3)
17804 // cast 'Idle' spell
17805 CastSpell(this, 43680, true);
17806 m_bgAfkReporter.clear();
17811 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17813 // gamemaster in GM mode see all, including ghosts
17814 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17815 return true;
17817 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17818 if (InBattleGround())
17820 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17821 return false;
17822 return true;
17825 // Live player see live player or dead player with not realized corpse
17826 if(pl->isAlive() || pl->m_deathTimer > 0)
17828 return isAlive() || m_deathTimer > 0;
17831 // Ghost see other friendly ghosts, that's for sure
17832 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17833 return true;
17835 // Dead player see live players near own corpse
17836 if(isAlive())
17838 Corpse *corpse = pl->GetCorpse();
17839 if(corpse)
17841 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17842 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17843 return true;
17847 // and not see any other
17848 return false;
17851 bool Player::IsVisibleGloballyFor( Player* u ) const
17853 if(!u)
17854 return false;
17856 // Always can see self
17857 if (u==this)
17858 return true;
17860 // Visible units, always are visible for all players
17861 if (GetVisibility() == VISIBILITY_ON)
17862 return true;
17864 // GMs are visible for higher gms (or players are visible for gms)
17865 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17866 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17868 // non faction visibility non-breakable for non-GMs
17869 if (GetVisibility() == VISIBILITY_OFF)
17870 return false;
17872 // non-gm stealth/invisibility not hide from global player lists
17873 return true;
17876 void Player::UpdateVisibilityOf(WorldObject* target)
17878 if(HaveAtClient(target))
17880 if(!target->isVisibleForInState(this,true))
17882 target->DestroyForPlayer(this);
17883 m_clientGUIDs.erase(target->GetGUID());
17885 #ifdef MANGOS_DEBUG
17886 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17887 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17888 #endif
17891 else
17893 if(target->isVisibleForInState(this,false))
17895 target->SendUpdateToPlayer(this);
17896 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17897 m_clientGUIDs.insert(target->GetGUID());
17899 #ifdef MANGOS_DEBUG
17900 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17901 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17902 #endif
17904 // target aura duration for caster show only if target exist at caster client
17905 // send data at target visibility change (adding to client)
17906 if(target!=this && target->isType(TYPEMASK_UNIT))
17907 SendAurasForTarget((Unit*)target);
17909 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17910 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17915 template<class T>
17916 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17918 s64.insert(target->GetGUID());
17921 template<>
17922 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17924 if(!target->IsTransport())
17925 s64.insert(target->GetGUID());
17928 template<class T>
17929 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17931 if(HaveAtClient(target))
17933 if(!target->isVisibleForInState(this,true))
17935 target->BuildOutOfRangeUpdateBlock(&data);
17936 m_clientGUIDs.erase(target->GetGUID());
17938 #ifdef MANGOS_DEBUG
17939 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17940 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));
17941 #endif
17944 else
17946 if(target->isVisibleForInState(this,false))
17948 visibleNow.insert(target);
17949 target->BuildUpdate(data_updates);
17950 target->BuildCreateUpdateBlockForPlayer(&data, this);
17951 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17953 #ifdef MANGOS_DEBUG
17954 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17955 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));
17956 #endif
17961 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17962 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17963 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17964 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17965 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17967 void Player::InitPrimaryProfessions()
17969 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17972 void Player::SendComboPoints()
17974 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17975 if (combotarget)
17977 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17978 data.append(combotarget->GetPackGUID());
17979 data << uint8(m_comboPoints);
17980 GetSession()->SendPacket(&data);
17984 void Player::AddComboPoints(Unit* target, int8 count)
17986 if(!count)
17987 return;
17989 // without combo points lost (duration checked in aura)
17990 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17992 if(target->GetGUID() == m_comboTarget)
17994 m_comboPoints += count;
17996 else
17998 if(m_comboTarget)
17999 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18000 target2->RemoveComboPointHolder(GetGUIDLow());
18002 m_comboTarget = target->GetGUID();
18003 m_comboPoints = count;
18005 target->AddComboPointHolder(GetGUIDLow());
18008 if (m_comboPoints > 5) m_comboPoints = 5;
18009 if (m_comboPoints < 0) m_comboPoints = 0;
18011 SendComboPoints();
18014 void Player::ClearComboPoints()
18016 if(!m_comboTarget)
18017 return;
18019 // without combopoints lost (duration checked in aura)
18020 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18022 m_comboPoints = 0;
18024 SendComboPoints();
18026 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18027 target->RemoveComboPointHolder(GetGUIDLow());
18029 m_comboTarget = 0;
18032 void Player::SetGroup(Group *group, int8 subgroup)
18034 if(group == NULL)
18035 m_group.unlink();
18036 else
18038 // never use SetGroup without a subgroup unless you specify NULL for group
18039 assert(subgroup >= 0);
18040 m_group.link(group, this);
18041 m_group.setSubGroup((uint8)subgroup);
18045 void Player::SendInitialPacketsBeforeAddToMap()
18047 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18048 data << uint32(0); // unknown, may be rest state time or experience
18049 GetSession()->SendPacket(&data);
18051 GetSocial()->SendSocialList();
18053 // Homebind
18054 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18055 data << m_homebindX << m_homebindY << m_homebindZ;
18056 data << (uint32) m_homebindMapId;
18057 data << (uint32) m_homebindZoneId;
18058 GetSession()->SendPacket(&data);
18060 // SMSG_SET_PROFICIENCY
18061 // SMSG_UPDATE_AURA_DURATION
18063 SendTalentsInfoData(false);
18064 SendInitialSpells();
18066 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18067 data << uint32(0); // count, for(count) uint32;
18068 GetSession()->SendPacket(&data);
18070 SendInitialActionButtons();
18071 m_reputationMgr.SendInitialReputations();
18072 m_achievementMgr.SendAllAchievementData();
18074 // update zone
18075 uint32 newzone, newarea;
18076 GetZoneAndAreaId(newzone,newarea);
18077 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18079 SendEquipmentSetList();
18081 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18082 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18083 data << (float)0.01666667f; // game speed
18084 data << uint32(0); // added in 3.1.2
18085 GetSession()->SendPacket( &data );
18087 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18088 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18089 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING2);
18091 m_mover = this;
18094 void Player::SendInitialPacketsAfterAddToMap()
18096 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18097 data << uint32(0x00000000); // on blizz it increments periodically
18098 GetSession()->SendPacket(&data);
18100 CastSpell(this, 836, true); // LOGINEFFECT
18102 // set some aura effects that send packet to player client after add player to map
18103 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18104 // same auras state lost at far teleport, send it one more time in this case also
18105 static const AuraType auratypes[] =
18107 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18108 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18109 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18111 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18113 Unit::AuraList const& auraList = GetAurasByType(*itr);
18114 if(!auraList.empty())
18115 auraList.front()->ApplyModifier(true,true);
18118 if(HasAuraType(SPELL_AURA_MOD_STUN))
18119 SetMovement(MOVE_ROOT);
18121 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18122 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18124 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18125 data2.append(GetPackGUID());
18126 data2 << (uint32)2;
18127 SendMessageToSet(&data2,true);
18130 SendAurasForTarget(this);
18131 SendEnchantmentDurations(); // must be after add to map
18132 SendItemDurations(); // must be after add to map
18135 void Player::SendUpdateToOutOfRangeGroupMembers()
18137 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18138 return;
18139 if(Group* group = GetGroup())
18140 group->UpdatePlayerOutOfRange(this);
18142 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18143 m_auraUpdateMask = 0;
18144 if(Pet *pet = GetPet())
18145 pet->ResetAuraUpdateMask();
18148 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18150 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18151 data << uint32(mapid);
18152 data << uint8(reason); // transfer abort reason
18153 switch(reason)
18155 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18156 case TRANSFER_ABORT_DIFFICULTY:
18157 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18158 data << uint8(arg);
18159 break;
18161 GetSession()->SendPacket(&data);
18164 void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time )
18166 // type of warning, based on the time remaining until reset
18167 uint32 type;
18168 if(time > 3600)
18169 type = RAID_INSTANCE_WELCOME;
18170 else if(time > 900 && time <= 3600)
18171 type = RAID_INSTANCE_WARNING_HOURS;
18172 else if(time > 300 && time <= 900)
18173 type = RAID_INSTANCE_WARNING_MIN;
18174 else
18175 type = RAID_INSTANCE_WARNING_MIN_SOON;
18177 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18178 data << uint32(type);
18179 data << uint32(mapid);
18180 data << uint32(difficulty); // difficulty
18181 data << uint32(time);
18182 if(type == RAID_INSTANCE_WELCOME)
18184 data << uint8(0); // is your (1)
18185 data << uint8(0); // is extended (1), ignored if prev field is 0
18187 GetSession()->SendPacket(&data);
18190 void Player::ApplyEquipCooldown( Item * pItem )
18192 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18194 _Spell const& spellData = pItem->GetProto()->Spells[i];
18196 // no spell
18197 if( !spellData.SpellId )
18198 continue;
18200 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18201 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18202 continue;
18204 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18206 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18207 data << pItem->GetGUID();
18208 data << uint32(spellData.SpellId);
18209 GetSession()->SendPacket(&data);
18213 void Player::resetSpells()
18215 // not need after this call
18216 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18217 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18219 // make full copy of map (spells removed and marked as deleted at another spell remove
18220 // and we can't use original map for safe iterative with visit each spell at loop end
18221 PlayerSpellMap smap = GetSpellMap();
18223 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18224 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18226 learnDefaultSpells();
18227 learnQuestRewardedSpells();
18230 void Player::learnDefaultSpells()
18232 // learn default race/class spells
18233 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18234 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18236 uint32 tspell = *itr;
18237 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18238 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18239 addSpell(tspell,true,true,true,false);
18240 else // but send in normal spell in game learn case
18241 learnSpell(tspell,true);
18245 void Player::learnQuestRewardedSpells(Quest const* quest)
18247 uint32 spell_id = quest->GetRewSpellCast();
18249 // skip quests without rewarded spell
18250 if( !spell_id )
18251 return;
18253 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18254 if(!spellInfo)
18255 return;
18257 // check learned spells state
18258 bool found = false;
18259 for(int i=0; i < 3; ++i)
18261 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18263 found = true;
18264 break;
18268 // skip quests with not teaching spell or already known spell
18269 if(!found)
18270 return;
18272 // prevent learn non first rank unknown profession and second specialization for same profession)
18273 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18274 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18276 // not have first rank learned (unlearned prof?)
18277 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18278 if( !HasSpell(first_spell) )
18279 return;
18281 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18282 if(!learnedInfo)
18283 return;
18285 // specialization
18286 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18288 // search other specialization for same prof
18289 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18291 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18292 continue;
18294 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18295 if(!itrInfo)
18296 return;
18298 // compare only specializations
18299 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18300 continue;
18302 // compare same chain spells
18303 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18304 continue;
18306 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18307 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18308 return;
18313 CastSpell( this, spell_id, true);
18316 void Player::learnQuestRewardedSpells()
18318 // learn spells received from quest completing
18319 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18321 // skip no rewarded quests
18322 if(!itr->second.m_rewarded)
18323 continue;
18325 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18326 if( !quest )
18327 continue;
18329 learnQuestRewardedSpells(quest);
18333 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18335 uint32 raceMask = getRaceMask();
18336 uint32 classMask = getClassMask();
18337 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18339 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18340 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18341 continue;
18342 // Check race if set
18343 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18344 continue;
18345 // Check class if set
18346 if (pAbility->classmask && !(pAbility->classmask & classMask))
18347 continue;
18349 if (sSpellStore.LookupEntry(pAbility->spellId))
18351 // need unlearn spell
18352 if (skill_value < pAbility->req_skill_value)
18353 removeSpell(pAbility->spellId);
18354 // need learn
18355 else if (!IsInWorld())
18356 addSpell(pAbility->spellId,true,true,true,false);
18357 else
18358 learnSpell(pAbility->spellId,true);
18363 void Player::SendAurasForTarget(Unit *target)
18365 if(target->GetVisibleAuras()->empty()) // speedup things
18366 return;
18368 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18369 data.append(target->GetPackGUID());
18371 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18372 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18374 for(uint32 j = 0; j < 3; ++j)
18376 if(Aura *aura = target->GetAura(itr->second, j))
18378 data << uint8(aura->GetAuraSlot());
18379 data << uint32(aura->GetId());
18381 if(aura->GetId())
18383 uint8 auraFlags = aura->GetAuraFlags();
18384 // flags
18385 data << uint8(auraFlags);
18386 // level
18387 data << uint8(aura->GetAuraLevel());
18388 // charges
18389 data << uint8(aura->GetAuraCharges());
18391 if(!(auraFlags & AFLAG_NOT_CASTER))
18393 data << uint8(0); // packed GUID of someone (caster?)
18396 if(auraFlags & AFLAG_DURATION) // include aura duration
18398 data << uint32(aura->GetAuraMaxDuration());
18399 data << uint32(aura->GetAuraDuration());
18402 break;
18407 GetSession()->SendPacket(&data);
18410 void Player::SetDailyQuestStatus( uint32 quest_id )
18412 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18414 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18416 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18417 m_lastDailyQuestTime = time(NULL); // last daily quest time
18418 m_DailyQuestChanged = true;
18419 break;
18424 void Player::ResetDailyQuestStatus()
18426 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18427 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18429 // DB data deleted in caller
18430 m_DailyQuestChanged = false;
18431 m_lastDailyQuestTime = 0;
18434 BattleGround* Player::GetBattleGround() const
18436 if(GetBattleGroundId()==0)
18437 return NULL;
18439 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18442 bool Player::InArena() const
18444 BattleGround *bg = GetBattleGround();
18445 if(!bg || !bg->isArena())
18446 return false;
18448 return true;
18451 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18453 // get a template bg instead of running one
18454 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18455 if(!bg)
18456 return false;
18458 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18459 return false;
18461 return true;
18464 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18466 //returned to hardcoded version of this function, because there is no way to code it dynamic
18467 uint32 level = getLevel();
18468 if( bgTypeId == BATTLEGROUND_AV )
18469 level--;
18471 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18472 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18474 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18475 return QUEUE_ID_MAX_LEVEL_80;
18477 return BGQueueIdBasedOnLevel(queue_id);
18480 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18482 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18483 if(!vendor_faction || !vendor_faction->faction)
18484 return 1.0f;
18486 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18487 if(rank <= REP_NEUTRAL)
18488 return 1.0f;
18490 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18493 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18495 uint32 racemask = getRaceMask();
18496 uint32 classmask = getClassMask();
18498 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18499 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18500 if(lower==upper)
18501 return true;
18503 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18505 // skip wrong race skills
18506 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18507 continue;
18509 // skip wrong class skills
18510 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18511 continue;
18513 return true;
18516 return false;
18519 bool Player::HasQuestForGO(int32 GOId) const
18521 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18523 uint32 questid = GetQuestSlotQuestId(i);
18524 if ( questid == 0 )
18525 continue;
18527 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18528 if(qs_itr == mQuestStatus.end())
18529 continue;
18531 QuestStatusData const& qs = qs_itr->second;
18533 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18535 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18536 if(!qinfo)
18537 continue;
18539 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18540 continue;
18542 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18544 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18545 continue;
18547 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18548 return true;
18552 return false;
18555 void Player::UpdateForQuestWorldObjects()
18557 if(m_clientGUIDs.empty())
18558 return;
18560 UpdateData udata;
18561 WorldPacket packet;
18562 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18564 if(IS_GAMEOBJECT_GUID(*itr))
18566 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18567 if(obj)
18568 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18570 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18572 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18573 if(!obj)
18574 continue;
18576 // check if this unit requires quest specific flags
18577 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18578 continue;
18580 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18581 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
18583 if(itr->second.questStart || itr->second.questEnd)
18585 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18586 break;
18591 udata.BuildPacket(&packet);
18592 GetSession()->SendPacket(&packet);
18595 void Player::SummonIfPossible(bool agree)
18597 if(!agree)
18599 m_summon_expire = 0;
18600 return;
18603 // expire and auto declined
18604 if(m_summon_expire < time(NULL))
18605 return;
18607 // stop taxi flight at summon
18608 if(isInFlight())
18610 GetMotionMaster()->MovementExpired();
18611 m_taxi.ClearTaxiDestinations();
18614 // drop flag at summon
18615 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18616 if(BattleGround *bg = GetBattleGround())
18617 bg->EventPlayerDroppedFlag(this);
18619 m_summon_expire = 0;
18621 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18623 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18626 void Player::RemoveItemDurations( Item *item )
18628 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18630 if(*itr==item)
18632 m_itemDuration.erase(itr);
18633 break;
18638 void Player::AddItemDurations( Item *item )
18640 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18642 m_itemDuration.push_back(item);
18643 item->SendTimeUpdate(this);
18647 void Player::AutoUnequipOffhandIfNeed()
18649 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18650 if(!offItem)
18651 return;
18653 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18654 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18655 return;
18657 ItemPosCountVec off_dest;
18658 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18659 if( off_msg == EQUIP_ERR_OK )
18661 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18662 StoreItem( off_dest, offItem, true );
18664 else
18666 MailItemsInfo mi;
18667 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18668 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18669 CharacterDatabase.BeginTransaction();
18670 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18671 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18672 CharacterDatabase.CommitTransaction();
18674 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18675 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18679 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18681 if(spellInfo->EquippedItemClass < 0)
18682 return true;
18684 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18685 // for optimize check 2 used cases only
18686 switch(spellInfo->EquippedItemClass)
18688 case ITEM_CLASS_WEAPON:
18690 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18691 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18692 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18693 return true;
18694 break;
18696 case ITEM_CLASS_ARMOR:
18698 // tabard not have dependent spells
18699 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18700 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18701 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18702 return true;
18704 // shields can be equipped to offhand slot
18705 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18706 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18707 return true;
18709 // ranged slot can have some armor subclasses
18710 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18711 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18712 return true;
18714 break;
18716 default:
18717 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18718 break;
18721 return false;
18724 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18726 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18727 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18728 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18729 return true;
18731 // Check no reagent use mask
18732 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18733 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18734 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18735 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18736 return true;
18738 return false;
18741 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18743 AuraMap& auras = GetAuras();
18744 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18746 Aura* aura = itr->second;
18748 // skip passive (passive item dependent spells work in another way) and not self applied auras
18749 SpellEntry const* spellInfo = aura->GetSpellProto();
18750 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18752 ++itr;
18753 continue;
18756 // skip if not item dependent or have alternative item
18757 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18759 ++itr;
18760 continue;
18763 // no alt item, remove aura, restart check
18764 RemoveAurasDueToSpell(aura->GetId());
18765 itr = auras.begin();
18768 // currently casted spells can be dependent from item
18769 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18771 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18772 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18773 InterruptSpell(i);
18777 uint32 Player::GetResurrectionSpellId()
18779 // search priceless resurrection possibilities
18780 uint32 prio = 0;
18781 uint32 spell_id = 0;
18782 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18783 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18785 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18786 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18788 switch((*itr)->GetId())
18790 case 20707: spell_id = 3026; break; // rank 1
18791 case 20762: spell_id = 20758; break; // rank 2
18792 case 20763: spell_id = 20759; break; // rank 3
18793 case 20764: spell_id = 20760; break; // rank 4
18794 case 20765: spell_id = 20761; break; // rank 5
18795 case 27239: spell_id = 27240; break; // rank 6
18796 case 47883: spell_id = 47882; break; // rank 7
18797 default:
18798 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18799 continue;
18802 prio = 3;
18804 // Twisting Nether // prio: 2 (max)
18805 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18807 prio = 2;
18808 spell_id = 23700;
18812 // Reincarnation (passive spell) // prio: 1
18813 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18814 spell_id = 21169;
18816 return spell_id;
18819 // Used in triggers for check "Only to targets that grant experience or honor" req
18820 bool Player::isHonorOrXPTarget(Unit* pVictim)
18822 uint32 v_level = pVictim->getLevel();
18823 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18825 // Victim level less gray level
18826 if(v_level<=k_grey)
18827 return false;
18829 if(pVictim->GetTypeId() == TYPEID_UNIT)
18831 if (((Creature*)pVictim)->isTotem() ||
18832 ((Creature*)pVictim)->isPet() ||
18833 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18834 return false;
18836 return true;
18839 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18841 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18843 // prepare data for near group iteration (PvP and !PvP cases)
18844 uint32 xp = 0;
18845 bool honored_kill = false;
18847 if(Group *pGroup = GetGroup())
18849 uint32 count = 0;
18850 uint32 sum_level = 0;
18851 Player* member_with_max_level = NULL;
18852 Player* not_gray_member_with_max_level = NULL;
18854 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18856 if(member_with_max_level)
18858 /// not get Xp in PvP or no not gray players in group
18859 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18861 /// skip in check PvP case (for speed, not used)
18862 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18863 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18864 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18866 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18868 Player* pGroupGuy = itr->getSource();
18869 if(!pGroupGuy)
18870 continue;
18872 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18873 continue; // member (alive or dead) or his corpse at req. distance
18875 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18876 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18877 honored_kill = true;
18879 // xp and reputation only in !PvP case
18880 if(!PvP)
18882 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18884 // if is in dungeon then all receive full reputation at kill
18885 // rewarded any alive/dead/near_corpse group member
18886 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18888 // XP updated only for alive group member
18889 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18890 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18892 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18894 pGroupGuy->GiveXP(itr_xp, pVictim);
18895 if(Pet* pet = pGroupGuy->GetPet())
18896 pet->GivePetXP(itr_xp/2);
18899 // quest objectives updated only for alive group member or dead but with not released body
18900 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18902 // normal creature (not pet/etc) can be only in !PvP case
18903 if(pVictim->GetTypeId()==TYPEID_UNIT)
18904 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18910 else // if (!pGroup)
18912 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18914 // honor can be in PvP and !PvP (racial leader) cases
18915 if(RewardHonor(pVictim,1))
18916 honored_kill = true;
18918 // xp and reputation only in !PvP case
18919 if(!PvP)
18921 RewardReputation(pVictim,1);
18922 GiveXP(xp, pVictim);
18924 if(Pet* pet = GetPet())
18925 pet->GivePetXP(xp);
18927 // normal creature (not pet/etc) can be only in !PvP case
18928 if(pVictim->GetTypeId()==TYPEID_UNIT)
18929 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18932 return xp || honored_kill;
18935 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18937 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18939 // prepare data for near group iteration
18940 if(Group *pGroup = GetGroup())
18942 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18944 Player* pGroupGuy = itr->getSource();
18945 if(!pGroupGuy)
18946 continue;
18948 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18949 continue; // member (alive or dead) or his corpse at req. distance
18951 // quest objectives updated only for alive group member or dead but with not released body
18952 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18953 pGroupGuy->KilledMonster(creature_id, creature_guid);
18956 else // if (!pGroup)
18957 KilledMonster(creature_id, creature_guid);
18960 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18962 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18963 return true;
18965 if (isAlive())
18966 return false;
18968 Corpse* corpse = GetCorpse();
18969 if (!corpse)
18970 return false;
18972 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18975 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18977 Item* item = GetWeaponForAttack(attType,true);
18979 // unarmed only with base attack
18980 if(attType != BASE_ATTACK && !item)
18981 return 0;
18983 // weapon skill or (unarmed for base attack)
18984 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18985 return GetBaseSkillValue(skill);
18988 void Player::ResurectUsingRequestData()
18990 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
18991 if(IS_PLAYER_GUID(m_resurrectGUID))
18992 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18994 //we cannot resurrect player when we triggered far teleport
18995 //player will be resurrected upon teleportation
18996 if(IsBeingTeleportedFar())
18998 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
18999 return;
19002 ResurrectPlayer(0.0f,false);
19004 if(GetMaxHealth() > m_resurrectHealth)
19005 SetHealth( m_resurrectHealth );
19006 else
19007 SetHealth( GetMaxHealth() );
19009 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19010 SetPower(POWER_MANA, m_resurrectMana );
19011 else
19012 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19014 SetPower(POWER_RAGE, 0 );
19016 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19018 SpawnCorpseBones();
19021 void Player::SetClientControl(Unit* target, uint8 allowMove)
19023 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19024 data.append(target->GetPackGUID());
19025 data << uint8(allowMove);
19026 GetSession()->SendPacket(&data);
19029 void Player::UpdateZoneDependentAuras( uint32 newZone )
19031 // remove new continent flight forms
19032 if( !IsAllowUseFlyMountsHere() )
19034 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
19035 RemoveSpellsCausingAura(SPELL_AURA_FLY);
19038 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19039 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19040 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19041 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19042 if( !HasAura(itr->second->spellId,0) )
19043 CastSpell(this,itr->second->spellId,true);
19046 void Player::UpdateAreaDependentAuras( uint32 newArea )
19048 // remove auras from spells with area limitations
19049 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19051 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19052 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19053 RemoveAura(iter);
19054 else
19055 ++iter;
19058 // some auras applied at subzone enter
19059 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19060 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19061 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19062 if( !HasAura(itr->second->spellId,0) )
19063 CastSpell(this,itr->second->spellId,true);
19066 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19068 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19069 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19071 return copseReclaimDelay[0];
19074 time_t now = time(NULL);
19075 // 0..2 full period
19076 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19077 return copseReclaimDelay[count];
19080 void Player::UpdateCorpseReclaimDelay()
19082 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19084 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19085 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19086 return;
19088 time_t now = time(NULL);
19089 if(now < m_deathExpireTime)
19091 // full and partly periods 1..3
19092 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19093 if(count < MAX_DEATH_COUNT)
19094 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19095 else
19096 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19098 else
19099 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19102 void Player::SendCorpseReclaimDelay(bool load)
19104 Corpse* corpse = GetCorpse();
19105 if(!corpse)
19106 return;
19108 uint32 delay;
19109 if(load)
19111 if(corpse->GetGhostTime() > m_deathExpireTime)
19112 return;
19114 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19116 uint32 count;
19117 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19118 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19120 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19121 if(count>=MAX_DEATH_COUNT)
19122 count = MAX_DEATH_COUNT-1;
19124 else
19125 count=0;
19127 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19129 time_t now = time(NULL);
19130 if(now >= expected_time)
19131 return;
19133 delay = expected_time-now;
19135 else
19136 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19138 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19139 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19140 data << uint32(delay*IN_MILISECONDS);
19141 GetSession()->SendPacket( &data );
19144 Player* Player::GetNextRandomRaidMember(float radius)
19146 Group *pGroup = GetGroup();
19147 if(!pGroup)
19148 return NULL;
19150 std::vector<Player*> nearMembers;
19151 nearMembers.reserve(pGroup->GetMembersCount());
19153 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19155 Player* Target = itr->getSource();
19157 // IsHostileTo check duel and controlled by enemy
19158 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19159 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19160 nearMembers.push_back(Target);
19163 if (nearMembers.empty())
19164 return NULL;
19166 uint32 randTarget = urand(0,nearMembers.size()-1);
19167 return nearMembers[randTarget];
19170 PartyResult Player::CanUninviteFromGroup() const
19172 const Group* grp = GetGroup();
19173 if(!grp)
19174 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19176 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19177 return PARTY_RESULT_YOU_NOT_LEADER;
19179 if(InBattleGround())
19180 return PARTY_RESULT_INVITE_RESTRICTED;
19182 return PARTY_RESULT_OK;
19185 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19187 //we must move references from m_group to m_originalGroup
19188 SetOriginalGroup(GetGroup(), GetSubGroup());
19190 m_group.unlink();
19191 m_group.link(group, this);
19192 m_group.setSubGroup((uint8)subgroup);
19195 void Player::RemoveFromBattleGroundRaid()
19197 //remove existing reference
19198 m_group.unlink();
19199 if( Group* group = GetOriginalGroup() )
19201 m_group.link(group, this);
19202 m_group.setSubGroup(GetOriginalSubGroup());
19204 SetOriginalGroup(NULL);
19207 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19209 if( group == NULL )
19210 m_originalGroup.unlink();
19211 else
19213 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19214 assert(subgroup >= 0);
19215 m_originalGroup.link(group, this);
19216 m_originalGroup.setSubGroup((uint8)subgroup);
19220 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19222 LiquidData liquid_status;
19223 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19224 if (!res)
19226 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19227 // Small hack for enable breath in WMO
19228 if (IsInWater())
19229 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19230 return;
19233 // All liquids type - check under water position
19234 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19236 if ( res & LIQUID_MAP_UNDER_WATER)
19237 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19238 else
19239 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19242 // Allow travel in dark water on taxi or transport
19243 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19244 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19245 else
19246 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19248 // in lava check, anywhere in lava level
19249 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19251 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19252 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19253 else
19254 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19256 // in slime check, anywhere in slime level
19257 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19259 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19260 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19261 else
19262 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19266 void Player::SetCanParry( bool value )
19268 if(m_canParry==value)
19269 return;
19271 m_canParry = value;
19272 UpdateParryPercentage();
19275 void Player::SetCanBlock( bool value )
19277 if(m_canBlock==value)
19278 return;
19280 m_canBlock = value;
19281 UpdateBlockPercentage();
19284 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19286 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19287 if(itr->pos == pos)
19288 return true;
19290 return false;
19293 bool Player::CanUseBattleGroundObject()
19295 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19296 // maybe gameobject code should handle that ForceReaction usage
19297 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19298 return ( //InBattleGround() && // in battleground - not need, check in other cases
19299 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19300 //player cannot use object when he is invulnerable (immune)
19301 !isTotalImmune() && // not totally immune
19302 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19303 !HasStealthAura() && // not stealthed
19304 !HasInvisibilityAura() && // not invisible
19305 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19306 isAlive() // live player
19310 bool Player::CanCaptureTowerPoint()
19312 return ( !HasStealthAura() && // not stealthed
19313 !HasInvisibilityAura() && // not invisible
19314 isAlive() // live player
19318 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19320 uint32 level = getLevel();
19322 if(level > GT_MAX_LEVEL)
19323 level = GT_MAX_LEVEL; // max level in this dbc
19325 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19326 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19327 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19329 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19330 return 0;
19332 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19334 if(!bsc) // shouldn't happen
19335 return 0xFFFFFFFF;
19337 float cost = 0;
19339 if(hairstyle != newhairstyle)
19340 cost += bsc->cost; // full price
19342 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19343 cost += bsc->cost * 0.5f; // +1/2 of price
19345 if(facialhair != newfacialhair)
19346 cost += bsc->cost * 0.75f; // +3/4 of price
19348 return uint32(cost);
19351 void Player::InitGlyphsForLevel()
19353 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19354 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19355 if(gs->Order)
19356 SetGlyphSlot(gs->Order - 1, gs->Id);
19358 uint32 level = getLevel();
19359 uint32 value = 0;
19361 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19362 if(level >= 15)
19363 value |= (0x01 | 0x02);
19364 if(level >= 30)
19365 value |= 0x08;
19366 if(level >= 50)
19367 value |= 0x04;
19368 if(level >= 70)
19369 value |= 0x10;
19370 if(level >= 80)
19371 value |= 0x20;
19373 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19376 void Player::EnterVehicle(Vehicle *vehicle)
19378 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19379 if(!ve)
19380 return;
19382 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19383 if(!veSeat)
19384 return;
19386 vehicle->SetCharmerGUID(GetGUID());
19387 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19388 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19389 vehicle->setFaction(getFaction());
19391 SetCharm(vehicle); // charm
19392 SetFarSightGUID(vehicle->GetGUID()); // set view
19394 SetClientControl(vehicle, 1); // redirect controls to vehicle
19395 SetMover(vehicle);
19397 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19398 GetSession()->SendPacket(&data);
19400 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19401 data.append(GetPackGUID());
19402 data << uint32(0); // counter?
19403 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19404 data << uint16(0); // special flags
19405 data << uint32(getMSTime()); // time
19406 data << vehicle->GetPositionX(); // x
19407 data << vehicle->GetPositionY(); // y
19408 data << vehicle->GetPositionZ(); // z
19409 data << vehicle->GetOrientation(); // o
19410 // transport part, TODO: load/calculate seat offsets
19411 data << uint64(vehicle->GetGUID()); // transport guid
19412 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19413 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19414 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19415 data << float(0); // transport orientation
19416 data << uint32(getMSTime()); // transport time
19417 data << uint8(0); // seat
19418 // end of transport part
19419 data << uint32(0); // fall time
19420 GetSession()->SendPacket(&data);
19422 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19423 data << uint64(vehicle->GetGUID());
19424 data << uint16(0);
19425 data << uint32(0);
19426 data << uint32(0x00000101);
19428 for(uint32 i = 0; i < 10; ++i)
19429 data << uint16(0) << uint8(0) << uint8(i+8);
19431 data << uint8(0);
19432 data << uint8(0);
19433 GetSession()->SendPacket(&data);
19436 void Player::ExitVehicle(Vehicle *vehicle)
19438 vehicle->SetCharmerGUID(0);
19439 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19440 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19441 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19443 SetCharm(NULL);
19444 SetFarSightGUID(0);
19446 SetClientControl(vehicle, 0);
19447 SetMover(NULL);
19449 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19450 data.append(GetPackGUID());
19451 data << uint32(0); // counter?
19452 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19453 data << uint16(0x40); // special flags
19454 data << uint32(getMSTime()); // time
19455 data << vehicle->GetPositionX(); // x
19456 data << vehicle->GetPositionY(); // y
19457 data << vehicle->GetPositionZ(); // z
19458 data << vehicle->GetOrientation(); // o
19459 data << uint32(0); // fall time
19460 GetSession()->SendPacket(&data);
19462 RemovePetActionBar();
19464 // maybe called at dummy aura remove?
19465 // CastSpell(this, 45472, true); // Parachute
19468 bool Player::isTotalImmune()
19470 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19472 uint32 immuneMask = 0;
19473 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19475 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19476 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19477 return true;
19479 return false;
19482 bool Player::HasTitle(uint32 bitIndex)
19484 if (bitIndex > 192)
19485 return false;
19487 uint32 fieldIndexOffset = bitIndex / 32;
19488 uint32 flag = 1 << (bitIndex % 32);
19489 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19492 void Player::SetTitle(CharTitlesEntry const* title)
19494 uint32 fieldIndexOffset = title->bit_index / 32;
19495 uint32 flag = 1 << (title->bit_index % 32);
19496 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19499 void Player::ConvertRune(uint8 index, uint8 newType)
19501 SetCurrentRune(index, newType);
19503 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19504 data << uint8(index);
19505 data << uint8(newType);
19506 GetSession()->SendPacket(&data);
19509 void Player::ResyncRunes(uint8 count)
19511 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19512 for(uint32 i = 0; i < count; ++i)
19514 data << uint8(GetCurrentRune(i)); // rune type
19515 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19517 GetSession()->SendPacket(&data);
19520 void Player::AddRunePower(uint8 index)
19522 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19523 data << uint32(1 << index); // mask (0x00-0x3F probably)
19524 GetSession()->SendPacket(&data);
19527 void Player::InitRunes()
19529 if(getClass() != CLASS_DEATH_KNIGHT)
19530 return;
19532 m_runes = new Runes;
19534 m_runes->runeState = 0;
19536 for(uint32 i = 0; i < MAX_RUNES; ++i)
19538 SetBaseRune(i, i / 2); // init base types
19539 SetCurrentRune(i, i / 2); // init current types
19540 SetRuneCooldown(i, 0); // reset cooldowns
19541 m_runes->SetRuneState(i);
19544 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19545 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19548 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19550 Loot loot;
19551 loot.FillLoot (loot_id,store,this,true);
19553 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19554 for(uint32 i = 0; i < max_slot; ++i)
19556 LootItem* lootItem = loot.LootItemInSlot(i,this);
19558 ItemPosCountVec dest;
19559 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19560 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19561 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19562 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19563 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19564 if(msg != EQUIP_ERR_OK)
19566 SendEquipError( msg, NULL, NULL );
19567 continue;
19570 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19571 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19575 uint32 Player::CalculateTalentsPoints() const
19577 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
19579 if(getClass() != CLASS_DEATH_KNIGHT)
19580 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
19582 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55 + m_questRewardTalentCount;
19584 if(talentPointsForLevel > base_talent)
19585 talentPointsForLevel = base_talent;
19587 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
19590 bool Player::IsAllowUseFlyMountsHere() const
19592 if (isGameMaster())
19593 return true;
19595 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19596 return v_map == 530 || v_map == 571 && HasSpell(54197);
19599 void Player::learnSpellHighRank(uint32 spellid)
19601 learnSpell(spellid,false);
19603 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19604 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19605 learnSpellHighRank(itr->second);
19608 void Player::_LoadSkills()
19610 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19612 // reset skill modifiers and set correct unlearn flags
19613 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19615 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19617 // set correct unlearn bit
19618 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19619 if(!id) continue;
19621 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19622 if(!pSkill) continue;
19624 // enable unlearn button for primary professions only
19625 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19626 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19627 else
19628 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19630 // set fixed skill ranges
19631 switch(GetSkillRangeType(pSkill,false))
19633 case SKILL_RANGE_LANGUAGE: // 300..300
19634 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19635 break;
19636 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19637 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19638 break;
19639 default:
19640 break;
19643 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19644 learnSkillRewardedSpells(id, vskill);
19647 // special settings
19648 if(getClass()==CLASS_DEATH_KNIGHT)
19650 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19651 if(base_level < 1)
19652 base_level = 1;
19653 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19654 if(base_skill < 1)
19655 base_skill = 1; // skill mast be known and then > 0 in any case
19657 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19658 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19659 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19660 SetSkill(SKILL_AXES, base_skill,base_skill);
19661 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19662 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19663 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19664 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19665 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19666 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19667 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19668 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19669 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19670 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19671 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19672 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19676 uint32 Player::GetPhaseMaskForSpawn() const
19678 uint32 phase = PHASEMASK_NORMAL;
19679 if(!isGameMaster())
19680 phase = GetPhaseMask();
19681 else
19683 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19684 if(!phases.empty())
19685 phase = phases.front()->GetMiscValue();
19688 // some aura phases include 1 normal map in addition to phase itself
19689 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19690 return n_phase;
19692 return PHASEMASK_NORMAL;
19695 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19697 ItemPrototype const* pProto = pItem->GetProto();
19699 // proto based limitations
19700 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19701 return res;
19703 // check unique-equipped on gems
19704 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19706 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19707 if(!enchant_id)
19708 continue;
19709 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19710 if(!enchantEntry)
19711 continue;
19713 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19714 if(!pGem)
19715 continue;
19717 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19718 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19719 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19721 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19722 return res;
19725 return EQUIP_ERR_OK;
19728 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19730 // check unique-equipped on item
19731 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19733 // there is an equip limit on this item
19734 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19735 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19738 // check unique-equipped limit
19739 if (itemProto->ItemLimitCategory)
19741 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19742 if(!limitEntry)
19743 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19745 if(limit_count > limitEntry->maxCount)
19746 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19748 // there is an equip limit on this item
19749 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19750 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19753 return EQUIP_ERR_OK;
19756 void Player::HandleFall(MovementInfo const& movementInfo)
19758 // calculate total z distance of the fall
19759 float z_diff = m_lastFallZ - movementInfo.z;
19760 sLog.outDebug("zDiff = %f", z_diff);
19762 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19763 // 14.57 can be calculated by resolving damageperc formula below to 0
19764 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19765 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19766 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19768 //Safe fall, fall height reduction
19769 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19771 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19773 if(damageperc >0 )
19775 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19777 float height = movementInfo.z;
19778 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19780 if (damage > 0)
19782 //Prevent fall damage from being more than the player maximum health
19783 if (damage > GetMaxHealth())
19784 damage = GetMaxHealth();
19786 // Gust of Wind
19787 if (GetDummyAura(43621))
19788 damage = GetMaxHealth()/2;
19790 EnvironmentalDamage(DAMAGE_FALL, damage);
19792 // recheck alive, might have died of EnvironmentalDamage
19793 if (isAlive())
19794 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19797 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19798 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19803 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19805 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19808 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19810 uint32 CurTalentPoints = GetFreeTalentPoints();
19812 if(CurTalentPoints == 0)
19813 return;
19815 if (talentRank >= MAX_TALENT_RANK)
19816 return;
19818 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19820 if(!talentInfo)
19821 return;
19823 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19825 if(!talentTabInfo)
19826 return;
19828 // prevent learn talent for different class (cheating)
19829 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19830 return;
19832 // find current max talent rank
19833 int32 curtalent_maxrank = 0;
19834 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19836 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19838 curtalent_maxrank = k + 1;
19839 break;
19843 // we already have same or higher talent rank learned
19844 if(curtalent_maxrank >= (talentRank + 1))
19845 return;
19847 // check if we have enough talent points
19848 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19849 return;
19851 // Check if it requires another talent
19852 if (talentInfo->DependsOn > 0)
19854 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19856 bool hasEnoughRank = false;
19857 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19859 if (depTalentInfo->RankID[i] != 0)
19860 if (HasSpell(depTalentInfo->RankID[i]))
19861 hasEnoughRank = true;
19863 if (!hasEnoughRank)
19864 return;
19868 // Find out how many points we have in this field
19869 uint32 spentPoints = 0;
19871 uint32 tTab = talentInfo->TalentTab;
19872 if (talentInfo->Row > 0)
19874 unsigned int numRows = sTalentStore.GetNumRows();
19875 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19877 // Someday, someone needs to revamp
19878 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19879 if (tmpTalent) // the way talents are tracked
19881 if (tmpTalent->TalentTab == tTab)
19883 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19885 if (tmpTalent->RankID[j] != 0)
19887 if (HasSpell(tmpTalent->RankID[j]))
19889 spentPoints += j + 1;
19898 // not have required min points spent in talent tree
19899 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19900 return;
19902 // spell not set in talent.dbc
19903 uint32 spellid = talentInfo->RankID[talentRank];
19904 if( spellid == 0 )
19906 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19907 return;
19910 // already known
19911 if(HasSpell(spellid))
19912 return;
19914 // learn! (other talent ranks will unlearned at learning)
19915 learnSpell(spellid, false);
19916 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19918 // update free talent points
19919 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19922 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19924 Pet *pet = GetPet();
19926 if(!pet)
19927 return;
19929 if(petGuid != pet->GetGUID())
19930 return;
19932 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19934 if(CurTalentPoints == 0)
19935 return;
19937 if (talentRank >= MAX_PET_TALENT_RANK)
19938 return;
19940 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19942 if(!talentInfo)
19943 return;
19945 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19947 if(!talentTabInfo)
19948 return;
19950 CreatureInfo const *ci = pet->GetCreatureInfo();
19952 if(!ci)
19953 return;
19955 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19957 if(!pet_family)
19958 return;
19960 if(pet_family->petTalentType < 0) // not hunter pet
19961 return;
19963 // prevent learn talent for different family (cheating)
19964 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19965 return;
19967 // find current max talent rank
19968 int32 curtalent_maxrank = 0;
19969 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19971 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19973 curtalent_maxrank = k + 1;
19974 break;
19978 // we already have same or higher talent rank learned
19979 if(curtalent_maxrank >= (talentRank + 1))
19980 return;
19982 // check if we have enough talent points
19983 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19984 return;
19986 // Check if it requires another talent
19987 if (talentInfo->DependsOn > 0)
19989 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19991 bool hasEnoughRank = false;
19992 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19994 if (depTalentInfo->RankID[i] != 0)
19995 if (pet->HasSpell(depTalentInfo->RankID[i]))
19996 hasEnoughRank = true;
19998 if (!hasEnoughRank)
19999 return;
20003 // Find out how many points we have in this field
20004 uint32 spentPoints = 0;
20006 uint32 tTab = talentInfo->TalentTab;
20007 if (talentInfo->Row > 0)
20009 unsigned int numRows = sTalentStore.GetNumRows();
20010 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20012 // Someday, someone needs to revamp
20013 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20014 if (tmpTalent) // the way talents are tracked
20016 if (tmpTalent->TalentTab == tTab)
20018 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20020 if (tmpTalent->RankID[j] != 0)
20022 if (pet->HasSpell(tmpTalent->RankID[j]))
20024 spentPoints += j + 1;
20033 // not have required min points spent in talent tree
20034 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20035 return;
20037 // spell not set in talent.dbc
20038 uint32 spellid = talentInfo->RankID[talentRank];
20039 if( spellid == 0 )
20041 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20042 return;
20045 // already known
20046 if(pet->HasSpell(spellid))
20047 return;
20049 // learn! (other talent ranks will unlearned at learning)
20050 pet->learnSpell(spellid);
20051 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20053 // update free talent points
20054 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20057 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20059 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20061 if(apply)
20062 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20063 else
20064 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20068 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20070 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20071 SetFallInformation(minfo.fallTime, minfo.z);
20074 void Player::UnsummonPetTemporaryIfAny()
20076 Pet* pet = GetPet();
20077 if(!pet)
20078 return;
20080 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20082 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20083 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20086 RemovePet(pet, PET_SAVE_AS_CURRENT);
20089 void Player::ResummonPetTemporaryUnSummonedIfAny()
20091 if(!m_temporaryUnsummonedPetNumber)
20092 return;
20094 // not resummon in not appropriate state
20095 if(IsPetNeedBeTemporaryUnsummoned())
20096 return;
20098 if(GetPetGUID())
20099 return;
20101 Pet* NewPet = new Pet;
20102 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20103 delete NewPet;
20105 m_temporaryUnsummonedPetNumber = 0;
20108 bool Player::canSeeSpellClickOn(Creature const *c) const
20110 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20111 return false;
20113 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
20114 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20115 if(itr->second.IsFitToRequirements(this))
20116 return true;
20118 return false;
20121 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20123 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20124 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20125 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20127 if(m_specsCount)
20129 // loop through all specs (only 1 for now)
20130 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20132 uint8 talentIdCount = 0;
20133 size_t pos = data->wpos();
20134 *data << uint8(talentIdCount); // [PH], talentIdCount
20136 // find class talent tabs (all players have 3 talent tabs)
20137 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20139 for(uint32 i = 0; i < 3; ++i)
20141 uint32 talentTabId = talentTabIds[i];
20143 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20145 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20146 if(!talentInfo)
20147 continue;
20149 // skip another tab talents
20150 if(talentInfo->TalentTab != talentTabId)
20151 continue;
20153 // find max talent rank
20154 int32 curtalent_maxrank = -1;
20155 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20157 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20159 curtalent_maxrank = k;
20160 break;
20164 // not learned talent
20165 if(curtalent_maxrank < 0)
20166 continue;
20168 *data << uint32(talentInfo->TalentID); // Talent.dbc
20169 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20171 ++talentIdCount;
20175 data->put<uint8>(pos, talentIdCount); // put real count
20177 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20179 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20180 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20185 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20187 uint32 unspentTalentPoints = 0;
20188 size_t pointsPos = data->wpos();
20189 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20191 uint8 talentIdCount = 0;
20192 size_t countPos = data->wpos();
20193 *data << uint8(talentIdCount); // [PH], talentIdCount
20195 Pet *pet = GetPet();
20196 if(!pet)
20197 return;
20199 unspentTalentPoints = pet->GetFreeTalentPoints();
20201 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20203 CreatureInfo const *ci = pet->GetCreatureInfo();
20204 if(!ci)
20205 return;
20207 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20208 if(!pet_family || pet_family->petTalentType < 0)
20209 return;
20211 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20213 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20214 if(!talentTabInfo)
20215 continue;
20217 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20218 continue;
20220 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20222 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20223 if(!talentInfo)
20224 continue;
20226 // skip another tab talents
20227 if(talentInfo->TalentTab != talentTabId)
20228 continue;
20230 // find max talent rank
20231 int32 curtalent_maxrank = -1;
20232 for(int32 k = 4; k > -1; --k)
20234 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20236 curtalent_maxrank = k;
20237 break;
20241 // not learned talent
20242 if(curtalent_maxrank < 0)
20243 continue;
20245 *data << uint32(talentInfo->TalentID); // Talent.dbc
20246 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20248 ++talentIdCount;
20251 data->put<uint8>(countPos, talentIdCount); // put real count
20253 break;
20257 void Player::SendTalentsInfoData(bool pet)
20259 WorldPacket data(SMSG_TALENTS_INFO, 50);
20260 data << uint8(pet ? 1 : 0);
20261 if(pet)
20262 BuildPetTalentsInfoData(&data);
20263 else
20264 BuildPlayerTalentsInfoData(&data);
20265 GetSession()->SendPacket(&data);
20268 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20270 uint32 slotUsedMask = 0;
20271 size_t slotUsedMaskPos = data->wpos();
20272 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20274 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20276 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20278 if(!item)
20279 continue;
20281 slotUsedMask |= (1 << i);
20283 *data << uint32(item->GetEntry()); // item entry
20285 uint16 enchantmentMask = 0;
20286 size_t enchantmentMaskPos = data->wpos();
20287 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20289 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20291 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20293 if(!enchId)
20294 continue;
20296 enchantmentMask |= (1 << j);
20298 *data << uint16(enchId); // enchantmentId?
20301 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20303 *data << uint16(0); // ?
20304 *data << uint8(0); // PGUID!
20305 *data << uint32(0); // seed?
20308 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20311 void Player::SendEquipmentSetList()
20313 uint32 count = 0;
20314 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20315 size_t count_pos = data.wpos();
20316 data << uint32(count); // count placeholder
20317 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20319 if(itr->second.state==EQUIPMENT_SET_DELETED)
20320 continue;
20321 data.appendPackGUID(itr->second.Guid);
20322 data << uint32(itr->first);
20323 data << itr->second.Name;
20324 data << itr->second.IconName;
20325 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20326 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20328 ++count; // client have limit but it checked at loading and set
20330 data.put<uint32>(count_pos, count);
20331 GetSession()->SendPacket(&data);
20334 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20336 if(eqset.Guid != 0)
20338 bool found = false;
20340 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20342 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20344 found = true;
20345 break;
20349 if(!found) // something wrong...
20351 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20352 return;
20356 EquipmentSet& eqslot = m_EquipmentSets[index];
20358 EquipmentSetUpdateState old_state = eqslot.state;
20360 eqslot = eqset;
20362 if(eqset.Guid == 0)
20364 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20366 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20367 data << uint32(index);
20368 data.appendPackGUID(eqslot.Guid);
20369 GetSession()->SendPacket(&data);
20372 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20375 void Player::_SaveEquipmentSets()
20377 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20379 uint32 index = itr->first;
20380 EquipmentSet& eqset = itr->second;
20381 switch(eqset.state)
20383 case EQUIPMENT_SET_UNCHANGED:
20384 ++itr;
20385 break; // nothing do
20386 case EQUIPMENT_SET_CHANGED:
20387 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
20388 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20389 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
20390 eqset.state = EQUIPMENT_SET_UNCHANGED;
20391 ++itr;
20392 break;
20393 case EQUIPMENT_SET_NEW:
20394 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20395 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20396 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
20397 eqset.state = EQUIPMENT_SET_UNCHANGED;
20398 ++itr;
20399 break;
20400 case EQUIPMENT_SET_DELETED:
20401 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20402 m_EquipmentSets.erase(itr++);
20403 break;
20408 void Player::DeleteEquipmentSet(uint64 setGuid)
20410 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20412 if(itr->second.Guid == setGuid)
20414 if(itr->second.state == EQUIPMENT_SET_NEW)
20415 m_EquipmentSets.erase(itr);
20416 else
20417 itr->second.state = EQUIPMENT_SET_DELETED;
20418 break;
20423 void Player::ActivateSpec(uint32 specNum)
20425 if(GetActiveSpec() == specNum)
20426 return;
20428 resetTalents(true);
20431 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
20433 m_atLoginFlags &= ~f;
20435 if(in_db_also)
20436 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
20439 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
20441 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
20442 data << uint32(spell_id);
20443 data << uint64(target->GetGUID());
20444 SendDirectMessage(&data);
20447 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
20449 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
20450 data->append(GetPackGUID());
20451 *data << uint32(0); // this value increments every time
20452 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
20453 *data << uint16(0); // 2.3.0
20454 *data << uint32(getMSTime()); // time
20455 *data << x;
20456 *data << y;
20457 *data << z;
20458 *data << ang;
20459 *data << uint32(0);
20462 bool Player::HasMovementFlag( MovementFlags f ) const
20464 return m_movementInfo.HasMovementFlag(f);