diff --git a/src/game/Pet.cpp b/src/game/Pet.cpp
index 9bf67fae2c1..e9082221450 100644
--- a/src/game/Pet.cpp
+++ b/src/game/Pet.cpp
@@ -1,1773 +1,1781 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS
- *
- * Copyright (C) 2008 Trinity
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "Common.h"
-#include "Database/DatabaseEnv.h"
-#include "Log.h"
-#include "WorldSession.h"
-#include "WorldPacket.h"
-#include "ObjectMgr.h"
-#include "SpellMgr.h"
-#include "Pet.h"
-#include "MapManager.h"
-#include "Formulas.h"
-#include "SpellAuras.h"
-#include "CreatureAI.h"
-#include "Unit.h"
-#include "Util.h"
-
-char const* petTypeSuffix[MAX_PET_TYPE] =
-{
- "'s Minion", // SUMMON_PET
- "'s Pet", // HUNTER_PET
- "'s Guardian", // GUARDIAN_PET
- "'s Companion" // MINI_PET
-};
-
-//numbers represent minutes * 100 while happy (you get 100 loyalty points per min while happy)
-uint32 const LevelUpLoyalty[6] =
-{
- 5500,
- 11500,
- 17000,
- 23500,
- 31000,
- 39500,
-};
-
-uint32 const LevelStartLoyalty[6] =
-{
- 2000,
- 4500,
- 7000,
- 10000,
- 13500,
- 17500,
-};
-
-Pet::Pet(PetType type) : Creature()
-{
- m_isPet = true;
- m_name = "Pet";
- m_petType = type;
-
- m_removed = false;
- m_regenTimer = 4000;
- m_happinessTimer = 7500;
- m_loyaltyTimer = 12000;
- m_duration = 0;
- m_bonusdamage = 0;
-
- m_loyaltyPoints = 0;
- m_TrainingPoints = 0;
- m_resetTalentsCost = 0;
- m_resetTalentsTime = 0;
-
- m_auraUpdateMask = 0;
-
- // pets always have a charminfo, even if they are not actually charmed
- CharmInfo* charmInfo = InitCharmInfo(this);
-
- if(type == MINI_PET) // always passive
- charmInfo->SetReactState(REACT_PASSIVE);
- else if(type == GUARDIAN_PET) // always aggressive
- charmInfo->SetReactState(REACT_AGGRESSIVE);
-
- m_spells.clear();
- m_Auras.clear();
- m_CreatureSpellCooldowns.clear();
- m_CreatureCategoryCooldowns.clear();
- m_autospells.clear();
- m_declinedname = NULL;
- m_isActive = true;
-}
-
-Pet::~Pet()
-{
- if(m_uint32Values) // only for fully created Object
- {
- for (PetSpellMap::iterator i = m_spells.begin(); i != m_spells.end(); ++i)
- delete i->second;
- ObjectAccessor::Instance().RemoveObject(this);
- }
-
- delete m_declinedname;
-}
-
-void Pet::AddToWorld()
-{
- ///- Register the pet for guid lookup
- if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
- Unit::AddToWorld();
-}
-
-void Pet::RemoveFromWorld()
-{
- ///- Remove the pet from the accessor
- if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
- ///- Don't call the function for Creature, normal mobs + totems go in a different storage
- Unit::RemoveFromWorld();
-}
-
-bool Pet::LoadPetFromDB( Unit* owner, uint32 petentry, uint32 petnumber, bool current )
-{
- uint32 ownerid = owner->GetGUIDLow();
-
- QueryResult *result;
-
- if(petnumber)
- // known petnumber entry 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
- result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND id = '%u'",ownerid, petnumber);
- else if(current)
- // current pet (slot 0) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
- result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND slot = '0'",ownerid );
- else if(petentry)
- // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
- // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
- result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '0' OR slot = '3') ",ownerid, petentry );
- else
- // any current or other non-stabled pet (for hunter "call pet")
- // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
- result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3') ",ownerid);
-
- if(!result)
- return false;
-
- Field *fields = result->Fetch();
-
- // update for case of current pet "slot = 0"
- petentry = fields[1].GetUInt32();
- if(!petentry)
- {
- delete result;
- return false;
- }
-
- uint32 summon_spell_id = fields[21].GetUInt32();
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
-
- bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
-
- // check temporary summoned pets like mage water elemental
- if(current && is_temporary_summoned)
- {
- delete result;
- return false;
- }
-
- Map *map = owner->GetMap();
- uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
- uint32 pet_number = fields[0].GetUInt32();
- if(!Create(guid, map, petentry, pet_number))
- {
- delete result;
- return false;
- }
-
- float px, py, pz;
- owner->GetClosePoint(px, py, pz,GetObjectSize(),PET_FOLLOW_DIST,PET_FOLLOW_ANGLE);
-
- Relocate(px, py, pz, owner->GetOrientation());
-
- if(!IsPositionValid())
- {
- sLog.outError("ERROR: Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
- GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
- delete result;
- return false;
- }
-
- setPetType(PetType(fields[22].GetUInt8()));
- SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,owner->getFaction());
- SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
-
- CreatureInfo const *cinfo = GetCreatureInfo();
- if(cinfo->type == CREATURE_TYPE_CRITTER)
- {
- AIM_Initialize();
- map->Add((Creature*)this);
- delete result;
- return true;
- }
- if(getPetType()==HUNTER_PET || (getPetType()==SUMMON_PET && cinfo->type == CREATURE_TYPE_DEMON && owner->getClass() == CLASS_WARLOCK))
- m_charmInfo->SetPetNumber(pet_number, true);
- else
- m_charmInfo->SetPetNumber(pet_number, false);
- SetUInt64Value(UNIT_FIELD_SUMMONEDBY, owner->GetGUID());
- SetDisplayId(fields[3].GetUInt32());
- SetNativeDisplayId(fields[3].GetUInt32());
- uint32 petlevel=fields[4].GetUInt32();
- SetUInt32Value(UNIT_NPC_FLAGS , 0);
- SetName(fields[11].GetString());
-
- switch(getPetType())
- {
-
- case SUMMON_PET:
- petlevel=owner->getLevel();
-
- SetUInt32Value(UNIT_FIELD_BYTES_0,2048);
- SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- // this enables popup window (pet dismiss, cancel)
- break;
- case HUNTER_PET:
- SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
- SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[8].GetUInt32());
- SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
- SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
-
- if(fields[12].GetBool())
- SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_NOT_ALLOWED);
- else
- SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
-
- SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- // this enables popup window (pet abandon, cancel)
- SetTP(fields[9].GetInt32());
- SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
- SetPower( POWER_HAPPINESS,fields[15].GetUInt32());
- setPowerType(POWER_FOCUS);
- break;
- default:
- sLog.outError("Pet have incorrect type (%u) for pet loading.",getPetType());
- }
- InitStatsForLevel( petlevel);
- SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
- SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
- SetUInt64Value(UNIT_FIELD_CREATEDBY, owner->GetGUID());
-
- m_charmInfo->SetReactState( ReactStates( fields[6].GetUInt8() ));
- m_loyaltyPoints = fields[7].GetInt32();
-
- uint32 savedhealth = fields[13].GetUInt32();
- uint32 savedmana = fields[14].GetUInt32();
-
- // set current pet as current
- if(fields[10].GetUInt32() != 0)
- {
- CharacterDatabase.BeginTransaction();
- CharacterDatabase.PExecute("UPDATE character_pet SET slot = '3' WHERE owner = '%u' AND slot = '0' AND id <> '%u'",ownerid, m_charmInfo->GetPetNumber());
- CharacterDatabase.PExecute("UPDATE character_pet SET slot = '0' WHERE owner = '%u' AND id = '%u'",ownerid, m_charmInfo->GetPetNumber());
- CharacterDatabase.CommitTransaction();
- }
-
- if(!is_temporary_summoned)
- {
- // permanent controlled pets store state in DB
- Tokens tokens = StrSplit(fields[16].GetString(), " ");
-
- if(tokens.size() != 20)
- {
- delete result;
- return false;
- }
-
- int index;
- Tokens::iterator iter;
- for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
- {
- m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
- ++iter;
- m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
- }
-
- //init teach spells
- tokens = StrSplit(fields[17].GetString(), " ");
- for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
- {
- uint32 tmp = atol((*iter).c_str());
-
- ++iter;
-
- if(tmp)
- AddTeachSpell(tmp, atol((*iter).c_str()));
- else
- break;
- }
- }
-
- // since last save (in seconds)
- uint32 timediff = (time(NULL) - fields[18].GetUInt32());
-
- delete result;
-
- //load spells/cooldowns/auras
- SetCanModifyStats(true);
- _LoadAuras(timediff);
-
- //init AB
- if(is_temporary_summoned)
- {
- // Temporary summoned pets always have initial spell list at load
- InitPetCreateSpells();
- }
- else
- {
- LearnPetPassives();
- CastPetAuras(current);
- }
-
- if(getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
- {
- SetHealth(GetMaxHealth());
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
- }
- else
- {
- SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
- SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
- }
-
- AIM_Initialize();
- map->Add((Creature*)this);
-
- // Spells should be loaded after pet is added to map, because in CanCast is check on it
- _LoadSpells();
- _LoadSpellCooldowns();
-
- owner->SetPet(this); // in DB stored only full controlled creature
- sLog.outDebug("New Pet has guid %u", GetGUIDLow());
-
- if(owner->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)owner)->PetSpellInitialize();
- if(((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
- }
-
- if(owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
- {
- result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'",owner->GetGUIDLow(),GetCharmInfo()->GetPetNumber());
-
- if(result)
- {
- if(m_declinedname)
- delete m_declinedname;
-
- m_declinedname = new DeclinedName;
- Field *fields = result->Fetch();
- for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
- {
- m_declinedname->name[i] = fields[i].GetCppString();
- }
- }
- }
-
- return true;
-}
-
-void Pet::SavePetToDB(PetSaveMode mode)
-{
- if(!GetEntry())
- return;
-
- // save only fully controlled creature
- if(!isControlled())
- return;
-
- uint32 curhealth = GetHealth();
- uint32 curmana = GetPower(POWER_MANA);
-
- switch(mode)
- {
- case PET_SAVE_IN_STABLE_SLOT_1:
- case PET_SAVE_IN_STABLE_SLOT_2:
- case PET_SAVE_NOT_IN_SLOT:
- {
- RemoveAllAuras();
-
- //only alive hunter pets get auras saved, the others don't
- if(!(getPetType() == HUNTER_PET && isAlive()))
- m_Auras.clear();
- }
- default:
- break;
- }
-
- _SaveSpells();
- _SaveSpellCooldowns();
- _SaveAuras();
-
- switch(mode)
- {
- case PET_SAVE_AS_CURRENT:
- case PET_SAVE_IN_STABLE_SLOT_1:
- case PET_SAVE_IN_STABLE_SLOT_2:
- case PET_SAVE_NOT_IN_SLOT:
- {
- uint32 loyalty =1;
- if(getPetType()!=HUNTER_PET)
- loyalty = GetLoyaltyLevel();
-
- uint32 owner = GUID_LOPART(GetOwnerGUID());
- std::string name = m_name;
- CharacterDatabase.escape_string(name);
- CharacterDatabase.BeginTransaction();
- // remove current data
- CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner,m_charmInfo->GetPetNumber() );
-
- // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
- if(mode!=PET_SAVE_NOT_IN_SLOT)
- CharacterDatabase.PExecute("UPDATE character_pet SET slot = 3 WHERE owner = '%u' AND slot = '%u'", owner, uint32(mode) );
-
- // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
- if(getPetType()==HUNTER_PET && (mode==PET_SAVE_AS_CURRENT||mode==PET_SAVE_NOT_IN_SLOT))
- CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3')", owner );
- // save pet
- std::ostringstream ss;
- ss << "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata,TeachSpelldata,savetime,resettalents_cost,resettalents_time,CreatedBySpell,PetType) "
- << "VALUES ("
- << m_charmInfo->GetPetNumber() << ", "
- << GetEntry() << ", "
- << owner << ", "
- << GetNativeDisplayId() << ", "
- << getLevel() << ", "
- << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE) << ", "
- << uint32(m_charmInfo->GetReactState()) << ", "
- << m_loyaltyPoints << ", "
- << GetLoyaltyLevel() << ", "
- << m_TrainingPoints << ", "
- << uint32(mode) << ", '"
- << name.c_str() << "', "
- << uint32((GetByteValue(UNIT_FIELD_BYTES_2, 2) == UNIT_RENAME_ALLOWED)?0:1) << ", "
- << (curhealth<1?1:curhealth) << ", "
- << curmana << ", "
- << GetPower(POWER_HAPPINESS) << ", '";
-
- for(uint32 i = 0; i < 10; i++)
- ss << uint32(m_charmInfo->GetActionBarEntry(i)->Type) << " " << uint32(m_charmInfo->GetActionBarEntry(i)->SpellOrAction) << " ";
- ss << "', '";
-
- //save spells the pet can teach to it's Master
- {
- int i = 0;
- for(TeachSpellMap::iterator itr = m_teachspells.begin(); i < 4 && itr != m_teachspells.end(); ++i, ++itr)
- ss << itr->first << " " << itr->second << " ";
- for(; i < 4; ++i)
- ss << uint32(0) << " " << uint32(0) << " ";
- }
-
- ss << "', "
- << time(NULL) << ", "
- << uint32(m_resetTalentsCost) << ", "
- << uint64(m_resetTalentsTime) << ", "
- << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ", "
- << uint32(getPetType()) << ")";
-
- CharacterDatabase.Execute( ss.str().c_str() );
-
- CharacterDatabase.CommitTransaction();
- break;
- }
- case PET_SAVE_AS_DELETED:
- {
- RemoveAllAuras();
- uint32 owner = GUID_LOPART(GetOwnerGUID());
- DeleteFromDB(m_charmInfo->GetPetNumber());
- break;
- }
- default:
- sLog.outError("Unknown pet save/remove mode: %d",mode);
- }
-}
-
-void Pet::DeleteFromDB(uint32 guidlow)
-{
- CharacterDatabase.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow);
- CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow);
- CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow);
- CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow);
- CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow);
-}
-
-void Pet::setDeathState(DeathState s) // overwrite virtual Creature::setDeathState and Unit::setDeathState
-{
- Creature::setDeathState(s);
- if(getDeathState()==CORPSE)
- {
- //remove summoned pet (no corpse)
- if(getPetType()==SUMMON_PET)
- Remove(PET_SAVE_NOT_IN_SLOT);
- // other will despawn at corpse desppawning (Pet::Update code)
- else
- {
- // pet corpse non lootable and non skinnable
- SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
- RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
-
- //lose happiness when died and not in BG/Arena
- MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
- if(!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND))
- ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE);
-
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
- }
- }
- else if(getDeathState()==ALIVE)
- {
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
- CastPetAuras(true);
- }
-}
-
-void Pet::Update(uint32 diff)
-{
- if(m_removed) // pet already removed, just wait in remove queue, no updates
- return;
-
- switch( m_deathState )
- {
- case CORPSE:
- {
- if( m_deathTimer <= diff )
- {
- assert(getPetType()!=SUMMON_PET && "Must be already removed.");
- Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER!
- return;
- }
- break;
- }
- case ALIVE:
- {
- // unsummon pet that lost owner
- Unit* owner = GetOwner();
- if(!owner || (!IsWithinDistInMap(owner, OWNER_MAX_DISTANCE) && !isPossessed()) || isControlled() && !owner->GetPetGUID())
- {
- Remove(PET_SAVE_NOT_IN_SLOT, true);
- return;
- }
-
- if(isControlled())
- {
- if( owner->GetPetGUID() != GetGUID() )
- {
- Remove(getPetType()==HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
- return;
- }
- }
-
- if(m_duration > 0)
- {
- if(m_duration > diff)
- m_duration -= diff;
- else
- {
- Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
- return;
- }
- }
-
- if(getPetType() != HUNTER_PET)
- break;
-
- //regenerate Focus
- if(m_regenTimer <= diff)
- {
- RegenerateFocus();
- m_regenTimer = 4000;
- }
- else
- m_regenTimer -= diff;
-
- if(m_happinessTimer <= diff)
- {
- LooseHappiness();
- m_happinessTimer = 7500;
- }
- else
- m_happinessTimer -= diff;
-
- if(m_loyaltyTimer <= diff)
- {
- TickLoyaltyChange();
- m_loyaltyTimer = 12000;
- }
- else
- m_loyaltyTimer -= diff;
-
- break;
- }
- default:
- break;
- }
- Creature::Update(diff);
-}
-
-void Pet::RegenerateFocus()
-{
- uint32 curValue = GetPower(POWER_FOCUS);
- uint32 maxValue = GetMaxPower(POWER_FOCUS);
-
- if (curValue >= maxValue)
- return;
-
- float addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
-
- AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
- for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
- if ((*i)->GetModifier()->m_miscvalue == POWER_FOCUS)
- addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
-
- ModifyPower(POWER_FOCUS, (int32)addvalue);
-}
-
-void Pet::LooseHappiness()
-{
- uint32 curValue = GetPower(POWER_HAPPINESS);
- if (curValue <= 0)
- return;
- int32 addvalue = (140 >> GetLoyaltyLevel()) * 125; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
- if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
- addvalue = int32(addvalue * 1.5);
- ModifyPower(POWER_HAPPINESS, -addvalue);
-}
-
-void Pet::ModifyLoyalty(int32 addvalue)
-{
- uint32 loyaltylevel = GetLoyaltyLevel();
-
- if(addvalue > 0) //only gain influenced, not loss
- addvalue = int32((float)addvalue * sWorld.getRate(RATE_LOYALTY));
-
- if(loyaltylevel >= BEST_FRIEND && (addvalue + m_loyaltyPoints) > int32(GetMaxLoyaltyPoints(loyaltylevel)))
- return;
-
- m_loyaltyPoints += addvalue;
-
- if(m_loyaltyPoints < 0)
- {
- if(loyaltylevel > REBELLIOUS)
- {
- //level down
- --loyaltylevel;
- SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
- m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
- SetTP(m_TrainingPoints - int32(getLevel()));
- }
- else
- {
- m_loyaltyPoints = 0;
- Unit* owner = GetOwner();
- if(owner && owner->GetTypeId() == TYPEID_PLAYER)
- {
- WorldPacket data(SMSG_PET_BROKEN, 0);
- ((Player*)owner)->GetSession()->SendPacket(&data);
-
- //run away
- ((Player*)owner)->RemovePet(this,PET_SAVE_AS_DELETED);
- }
- }
- }
- //level up
- else if(m_loyaltyPoints > int32(GetMaxLoyaltyPoints(loyaltylevel)))
- {
- ++loyaltylevel;
- SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
- m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
- SetTP(m_TrainingPoints + getLevel());
- }
-}
-
-void Pet::TickLoyaltyChange()
-{
- int32 addvalue;
-
- switch(GetHappinessState())
- {
- case HAPPY: addvalue = 20; break;
- case CONTENT: addvalue = 10; break;
- case UNHAPPY: addvalue = -20; break;
- default:
- return;
- }
- ModifyLoyalty(addvalue);
-}
-
-void Pet::KillLoyaltyBonus(uint32 level)
-{
- if(level > 100)
- return;
-
- //at lower levels gain is faster | the lower loyalty the more loyalty is gained
- uint32 bonus = uint32(((100 - level) / 10) + (6 - GetLoyaltyLevel()));
- ModifyLoyalty(bonus);
-}
-
-HappinessState Pet::GetHappinessState()
-{
- if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
- return UNHAPPY;
- else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
- return HAPPY;
- else
- return CONTENT;
-}
-
-void Pet::SetLoyaltyLevel(LoyaltyLevel level)
-{
- SetByteValue(UNIT_FIELD_BYTES_1, 1, level);
-}
-
-bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
-{
- uint8 activecount = 1;
- uint32 chainstartstore[ACTIVE_SPELLS_MAX];
-
- if(IsPassiveSpell(spellid))
- return true;
-
- chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
-
- for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if(IsPassiveSpell(itr->first))
- continue;
-
- uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
-
- uint8 x;
-
- for(x = 0; x < activecount; x++)
- {
- if(chainstart == chainstartstore[x])
- break;
- }
-
- if(x == activecount) //spellchain not yet saved -> add active count
- {
- ++activecount;
- if(activecount > ACTIVE_SPELLS_MAX)
- return false;
- chainstartstore[x] = chainstart;
- }
- }
- return true;
-}
-
-bool Pet::HasTPForSpell(uint32 spellid)
-{
- int32 neededtrainp = GetTPForSpell(spellid);
- if((m_TrainingPoints - neededtrainp < 0 || neededtrainp < 0) && neededtrainp != 0)
- return false;
- return true;
-}
-
-int32 Pet::GetTPForSpell(uint32 spellid)
-{
- uint32 basetrainp = 0;
-
- SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
- SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
- for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
- {
- if(!_spell_idx->second->reqtrainpoints)
- return 0;
-
- basetrainp = _spell_idx->second->reqtrainpoints;
- break;
- }
-
- uint32 spenttrainp = 0;
- uint32 chainstart = spellmgr.GetFirstSpellInChain(spellid);
-
- for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if(itr->second->state == PETSPELL_REMOVED)
- continue;
-
- if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
- {
- SkillLineAbilityMap::const_iterator _lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
- SkillLineAbilityMap::const_iterator _upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
-
- for(SkillLineAbilityMap::const_iterator _spell_idx2 = _lower; _spell_idx2 != _upper; ++_spell_idx2)
- {
- if(_spell_idx2->second->reqtrainpoints > spenttrainp)
- {
- spenttrainp = _spell_idx2->second->reqtrainpoints;
- break;
- }
- }
- }
- }
-
- return int32(basetrainp) - int32(spenttrainp);
-}
-
-uint32 Pet::GetMaxLoyaltyPoints(uint32 level)
-{
- return LevelUpLoyalty[level - 1];
-}
-
-uint32 Pet::GetStartLoyaltyPoints(uint32 level)
-{
- return LevelStartLoyalty[level - 1];
-}
-
-void Pet::SetTP(int32 TP)
-{
- m_TrainingPoints = TP;
- SetUInt32Value(UNIT_TRAINING_POINTS, (uint32)GetDispTP());
-}
-
-int32 Pet::GetDispTP()
-{
- if(getPetType()!= HUNTER_PET)
- return(0);
- if(m_TrainingPoints < 0)
- return -m_TrainingPoints;
- else
- return -(m_TrainingPoints + 1);
-}
-
-void Pet::Remove(PetSaveMode mode, bool returnreagent)
-{
- Unit* owner = GetOwner();
-
- if(owner)
- {
- if(owner->GetTypeId()==TYPEID_PLAYER)
- {
- ((Player*)owner)->RemovePet(this,mode,returnreagent);
- return;
- }
-
- // only if current pet in slot
- if(owner->GetPetGUID()==GetGUID())
- owner->SetPet(0);
- }
-
- CleanupsBeforeDelete();
- AddObjectToRemoveList();
- m_removed = true;
-}
-
-void Pet::GivePetXP(uint32 xp)
-{
- if(getPetType() != HUNTER_PET)
- return;
-
- if ( xp < 1 )
- return;
-
- if(!isAlive())
- return;
-
- uint32 level = getLevel();
-
- // XP to money conversion processed in Player::RewardQuest
- if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
- return;
-
- uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
- uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
- uint32 newXP = curXP + xp;
-
- if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
- {
- SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
- return;
- }
-
- while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
- {
- newXP -= nextLvlXP;
-
- SetLevel( level + 1 );
- SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(level+1))/4));
-
- level = getLevel();
- nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
- GivePetLevel(level);
- }
-
- SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
-
- if(getPetType() == HUNTER_PET)
- KillLoyaltyBonus(level);
-}
-
-void Pet::GivePetLevel(uint32 level)
-{
- if(!level)
- return;
-
- InitStatsForLevel( level);
-
- SetTP(m_TrainingPoints + (GetLoyaltyLevel() - 1));
-}
-
-bool Pet::CreateBaseAtCreature(Creature* creature)
-{
- if(!creature)
- {
- sLog.outError("CRITICAL ERROR: NULL pointer parsed into CreateBaseAtCreature()");
- return false;
- }
- uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
-
- sLog.outBasic("SetInstanceID()");
- SetInstanceId(creature->GetInstanceId());
-
- sLog.outBasic("Create pet");
- uint32 pet_number = objmgr.GeneratePetNumber();
- if(!Create(guid, creature->GetMap(), creature->GetEntry(), pet_number))
- return false;
-
- Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
-
- if(!IsPositionValid())
- {
- sLog.outError("ERROR: Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
- GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
- return false;
- }
-
- CreatureInfo const *cinfo = GetCreatureInfo();
- if(!cinfo)
- {
- sLog.outError("ERROR: CreateBaseAtCreature() failed, creatureInfo is missing!");
- return false;
- }
-
- if(cinfo->type == CREATURE_TYPE_CRITTER)
- {
- setPetType(MINI_PET);
- return true;
- }
- SetDisplayId(creature->GetDisplayId());
- SetNativeDisplayId(creature->GetNativeDisplayId());
- SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
- SetPower( POWER_HAPPINESS,166500);
- setPowerType(POWER_FOCUS);
- SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP,0);
- SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
- SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(creature->getLevel()))/4));
- SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- SetUInt32Value(UNIT_NPC_FLAGS , 0);
-
- CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(creature->GetCreatureInfo()->family);
- if( char* familyname = cFamily->Name[sWorld.GetDefaultDbcLocale()] )
- SetName(familyname);
- else
- SetName(creature->GetName());
-
- m_loyaltyPoints = 1000;
- if(cinfo->type == CREATURE_TYPE_BEAST)
- {
- SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
- SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
- SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
- SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
-
- SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED) );
- SetLoyaltyLevel(REBELLIOUS);
- }
- return true;
-}
-
-bool Pet::InitStatsForLevel(uint32 petlevel)
-{
- CreatureInfo const *cinfo = GetCreatureInfo();
- assert(cinfo);
-
- Unit* owner = GetOwner();
- if(!owner)
- {
- sLog.outError("ERROR: attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
- return false;
- }
-
- uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
-
- SetLevel( petlevel);
-
- SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
-
- SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
-
- SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
- SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
- SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
-
- SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
-
- CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
- if(cFamily && cFamily->minScale > 0.0f)
- {
- float scale;
- if (getLevel() >= cFamily->maxScaleLevel)
- scale = cFamily->maxScale;
- else if (getLevel() <= cFamily->minScaleLevel)
- scale = cFamily->minScale;
- else
- scale = cFamily->minScale + (getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
-
- SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
- }
- m_bonusdamage = 0;
-
- int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
-
- if(cinfo && getPetType() != HUNTER_PET)
- {
- createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
- createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
- createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
- createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
- createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
- createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
- }
-
- switch(getPetType())
- {
- case SUMMON_PET:
- {
- if(owner->GetTypeId() == TYPEID_PLAYER)
- {
- switch(owner->getClass())
- {
- case CLASS_WARLOCK:
- {
-
- //the damage bonus used for pets is either fire or shadow damage, whatever is higher
- uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
- uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
- uint32 val = (fire > shadow) ? fire : shadow;
-
- SetBonusDamage(int32 (val * 0.15f));
- //bonusAP += val * 0.57;
- break;
- }
- case CLASS_MAGE:
- {
- //40% damage bonus of mage's frost damage
- float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
- if(val < 0)
- val = 0;
- SetBonusDamage( int32(val));
- break;
- }
- default:
- break;
- }
- }
-
- SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
- SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
-
- //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
-
- PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
- if(pInfo) // exist in DB
- {
- SetCreateHealth(pInfo->health);
- SetCreateMana(pInfo->mana);
-
- if(pInfo->armor > 0)
- SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
-
- for(int stat = 0; stat < MAX_STATS; ++stat)
- {
- SetCreateStat(Stats(stat),float(pInfo->stats[stat]));
- }
- }
- else // not exist in DB, use some default fake data
- {
- sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
-
- // remove elite bonuses included in DB values
- SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
- SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
-
- SetCreateStat(STAT_STRENGTH,22);
- SetCreateStat(STAT_AGILITY,22);
- SetCreateStat(STAT_STAMINA,25);
- SetCreateStat(STAT_INTELLECT,28);
- SetCreateStat(STAT_SPIRIT,27);
- }
- break;
- }
- case HUNTER_PET:
- {
- SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(petlevel))/4));
-
- //these formula may not be correct; however, it is designed to be close to what it should be
- //this makes dps 0.5 of pets level
- SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
- //damage range is then petlevel / 2
- SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
- //damage is increased afterwards as strength and pet scaling modify attack power
-
- //stored standard pet stats are entry 1 in pet_levelinfo
- PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
- if(pInfo) // exist in DB
- {
- SetCreateHealth(pInfo->health);
- SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
- //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
-
- for( int i = STAT_STRENGTH; i < MAX_STATS; i++)
- {
- SetCreateStat(Stats(i), float(pInfo->stats[i]));
- }
- }
- else // not exist in DB, use some default fake data
- {
- sLog.outErrorDb("Hunter pet levelstats missing in DB");
-
- // remove elite bonuses included in DB values
- SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
-
- SetCreateStat(STAT_STRENGTH,22);
- SetCreateStat(STAT_AGILITY,22);
- SetCreateStat(STAT_STAMINA,25);
- SetCreateStat(STAT_INTELLECT,28);
- SetCreateStat(STAT_SPIRIT,27);
- }
- break;
- }
- case GUARDIAN_PET:
- SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
- SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP,1000);
-
- SetCreateMana( 28 + 10*petlevel );
- SetCreateHealth( 28 + 30*petlevel );
-
- // FIXME: this is wrong formula, possible each guardian pet have own damage formula
- //these formula may not be correct; however, it is designed to be close to what it should be
- //this makes dps 0.5 of pets level
- SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
- //damage range is then petlevel / 2
- SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
- break;
- default:
- sLog.outError("Pet have incorrect type (%u) for levelup.",getPetType()); break;
- }
-
- for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
- SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]) );
-
- UpdateAllStats();
-
- SetHealth(GetMaxHealth());
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
-
- return true;
-}
-
-bool Pet::HaveInDiet(ItemPrototype const* item) const
-{
- if (!item->FoodType)
- return false;
-
- CreatureInfo const* cInfo = GetCreatureInfo();
- if(!cInfo)
- return false;
-
- CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
- if(!cFamily)
- return false;
-
- uint32 diet = cFamily->petFoodMask;
- uint32 FoodMask = 1 << (item->FoodType-1);
- return diet & FoodMask;
-}
-
-uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
-{
- // -5 or greater food level
- if(getLevel() <= itemlevel +5) //possible to feed level 60 pet with level 55 level food for full effect
- return 35000;
- // -10..-6
- else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
- return 17000;
- // -14..-11
- else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
- return 8000;
- // -15 or less
- else
- return 0; //food too low level
-}
-
-void Pet::_LoadSpellCooldowns()
-{
- m_CreatureSpellCooldowns.clear();
- m_CreatureCategoryCooldowns.clear();
-
- QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
-
- if(result)
- {
- time_t curTime = time(NULL);
-
- WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
- data << GetGUID();
- data << uint8(0x0); // flags (0x1, 0x2)
-
- do
- {
- Field *fields = result->Fetch();
-
- uint32 spell_id = fields[0].GetUInt32();
- time_t db_time = (time_t)fields[1].GetUInt64();
-
- if(!sSpellStore.LookupEntry(spell_id))
- {
- sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
- continue;
- }
-
- // skip outdated cooldown
- if(db_time <= curTime)
- continue;
-
- data << uint32(spell_id);
- data << uint32(uint32(db_time-curTime)*1000); // in m.secs
-
- _AddCreatureSpellCooldown(spell_id,db_time);
-
- sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).",m_charmInfo->GetPetNumber(),spell_id,uint32(db_time-curTime));
- }
- while( result->NextRow() );
-
- delete result;
-
- if(!m_CreatureSpellCooldowns.empty() && GetOwner())
- {
- ((Player*)GetOwner())->GetSession()->SendPacket(&data);
- }
- }
-}
-
-void Pet::_SaveSpellCooldowns()
-{
- CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
-
- time_t curTime = time(NULL);
-
- // remove oudated and save active
- for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
- {
- if(itr->second <= curTime)
- m_CreatureSpellCooldowns.erase(itr++);
- else
- {
- CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
- ++itr;
- }
- }
-}
-
-void Pet::_LoadSpells()
-{
- QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
-
- if(result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- addSpell(fields[0].GetUInt16(), fields[2].GetUInt16(), PETSPELL_UNCHANGED, fields[1].GetUInt16());
- }
- while( result->NextRow() );
-
- delete result;
- }
-}
-
-void Pet::_SaveSpells()
-{
- for (PetSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
- {
- ++next;
- if (itr->second->type == PETSPELL_FAMILY) continue; // prevent saving family passives to DB
- if (itr->second->state == PETSPELL_REMOVED || itr->second->state == PETSPELL_CHANGED)
- CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
- if (itr->second->state == PETSPELL_NEW || itr->second->state == PETSPELL_CHANGED)
- CharacterDatabase.PExecute("INSERT INTO pet_spell (guid,spell,slot,active) VALUES ('%u', '%u', '%u','%u')", m_charmInfo->GetPetNumber(), itr->first, itr->second->slotId,itr->second->active);
-
- if (itr->second->state == PETSPELL_REMOVED)
- _removeSpell(itr->first);
- else
- itr->second->state = PETSPELL_UNCHANGED;
- }
-}
-
-void Pet::_LoadAuras(uint32 timediff)
-{
- m_Auras.clear();
- for (int i = 0; i < TOTAL_AURAS; i++)
- m_modAuras[i].clear();
-
- // all aura related fields
- for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
- SetUInt32Value(i, 0);
-
- QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
-
- if(result)
- {
- do
- {
- Field *fields = result->Fetch();
- uint64 caster_guid = fields[0].GetUInt64();
- uint32 spellid = fields[1].GetUInt32();
- uint32 effindex = fields[2].GetUInt32();
- int32 damage = (int32)fields[3].GetUInt32();
- int32 maxduration = (int32)fields[4].GetUInt32();
- int32 remaintime = (int32)fields[5].GetUInt32();
- int32 remaincharges = (int32)fields[6].GetUInt32();
-
- SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
- if(!spellproto)
- {
- sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
- continue;
- }
-
- if(effindex >= 3)
- {
- sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
- continue;
- }
-
- // negative effects should continue counting down after logout
- if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
- {
- if(remaintime <= int32(timediff))
- continue;
-
- remaintime -= timediff;
- }
-
- // prevent wrong values of remaincharges
- if(spellproto->procCharges)
- {
- if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
- remaincharges = spellproto->procCharges;
- }
- else
- remaincharges = -1;
-
- /// do not load single target auras (unless they were cast by the player)
- if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
- continue;
-
- Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
-
- if(!damage)
- damage = aura->GetModifier()->m_amount;
- aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
- AddAura(aura);
- }
- while( result->NextRow() );
-
- delete result;
- }
-}
-
-void Pet::_SaveAuras()
-{
- CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
-
- AuraMap const& auras = GetAuras();
- for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
- {
- // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
- SpellEntry const *spellInfo = itr->second->GetSpellProto();
- uint8 i;
- for (i = 0; i < 3; i++)
- if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
- spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
- spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
- break;
-
- if (i != 3)
- continue;
-
- if(itr->second->IsPassive())
- continue;
-
- /// do not save single target auras (unless they were cast by the player)
- if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
- continue;
-
- CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
- "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%d', '%d', '%d', '%d')",
- m_charmInfo->GetPetNumber(), itr->second->GetCasterGUID(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(),(*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
- }
-}
-
-bool Pet::addSpell(uint16 spell_id, uint16 active, PetSpellState state, uint16 slot_id, PetSpellType type)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
- if (!spellInfo)
- {
- // do pet spell book cleanup
- if(state == PETSPELL_UNCHANGED) // spell load case
- {
- sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
- CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
- }
- else
- sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
-
- return false;
- }
-
- PetSpellMap::iterator itr = m_spells.find(spell_id);
- if (itr != m_spells.end())
- {
- if (itr->second->state == PETSPELL_REMOVED)
- {
- delete itr->second;
- m_spells.erase(itr);
- state = PETSPELL_CHANGED;
- }
- else if (state == PETSPELL_UNCHANGED && itr->second->state != PETSPELL_UNCHANGED)
- {
- // can be in case spell loading but learned at some previous spell loading
- itr->second->state = PETSPELL_UNCHANGED;
- return false;
- }
- else
- return false;
- }
-
- uint32 oldspell_id = 0;
-
- PetSpell *newspell = new PetSpell;
- newspell->state = state;
- newspell->type = type;
-
- if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
- {
- if(IsPassiveSpell(spell_id))
- newspell->active = ACT_PASSIVE;
- else
- newspell->active = ACT_DISABLED;
- }
- else
- newspell->active = active;
-
- uint32 chainstart = spellmgr.GetFirstSpellInChain(spell_id);
-
- for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); itr++)
- {
- if(itr->second->state == PETSPELL_REMOVED) continue;
-
- if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
- {
- slot_id = itr->second->slotId;
- newspell->active = itr->second->active;
-
- if(newspell->active == ACT_ENABLED)
- ToggleAutocast(itr->first, false);
-
- oldspell_id = itr->first;
- removeSpell(itr->first);
- }
- }
-
- uint16 tmpslot=slot_id;
-
- if (tmpslot == 0xffff)
- {
- uint16 maxid = 0;
- PetSpellMap::iterator itr;
- for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if(itr->second->state == PETSPELL_REMOVED) continue;
- if (itr->second->slotId > maxid) maxid = itr->second->slotId;
- }
- tmpslot = maxid + 1;
- }
-
- newspell->slotId = tmpslot;
- m_spells[spell_id] = newspell;
-
- if (IsPassiveSpell(spell_id))
- CastSpell(this, spell_id, true);
- else if(state == PETSPELL_NEW)
- m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
-
- if(newspell->active == ACT_ENABLED)
- ToggleAutocast(spell_id, true);
-
- return true;
-}
-
-bool Pet::learnSpell(uint16 spell_id)
-{
- // prevent duplicated entires in spell book
- if (!addSpell(spell_id))
- return false;
-
- Unit* owner = GetOwner();
- if(owner->GetTypeId()==TYPEID_PLAYER)
- ((Player*)owner)->PetSpellInitialize();
- return true;
-}
-
-void Pet::removeSpell(uint16 spell_id)
-{
- PetSpellMap::iterator itr = m_spells.find(spell_id);
- if (itr == m_spells.end())
- return;
-
- if(itr->second->state == PETSPELL_REMOVED)
- return;
-
- if(itr->second->state == PETSPELL_NEW)
- {
- delete itr->second;
- m_spells.erase(itr);
- }
- else
- itr->second->state = PETSPELL_REMOVED;
-
- RemoveAurasDueToSpell(spell_id);
-}
-
-bool Pet::_removeSpell(uint16 spell_id)
-{
- PetSpellMap::iterator itr = m_spells.find(spell_id);
- if (itr != m_spells.end())
- {
- delete itr->second;
- m_spells.erase(itr);
- return true;
- }
- return false;
-}
-
-void Pet::InitPetCreateSpells()
-{
- m_charmInfo->InitPetActionBar();
-
- m_spells.clear();
- int32 usedtrainpoints = 0, petspellid;
- PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
- if(CreateSpells)
- {
- for(uint8 i = 0; i < 4; i++)
- {
- if(!CreateSpells->spellid[i])
- break;
-
- SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
- if(!learn_spellproto)
- continue;
-
- if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
- {
- petspellid = learn_spellproto->EffectTriggerSpell[0];
- Unit* owner = GetOwner();
- if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
- {
- if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
- ((Player*)owner)->learnSpell(learn_spellproto->Id);
- else
- AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
- }
- }
- else
- petspellid = learn_spellproto->Id;
-
- addSpell(petspellid);
-
- SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
- SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
-
- for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
- {
- usedtrainpoints += _spell_idx->second->reqtrainpoints;
- break;
- }
- }
- }
-
- LearnPetPassives();
-
- CastPetAuras(false);
-
- SetTP(-usedtrainpoints);
-}
-
-void Pet::CheckLearning(uint32 spellid)
-{
- //charmed case -> prevent crash
- if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
- return;
-
- Unit* owner = GetOwner();
-
- if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
- return;
-
- TeachSpellMap::iterator itr = m_teachspells.find(spellid);
- if(itr == m_teachspells.end())
- return;
-
- if(urand(0, 100) < 10)
- {
- ((Player*)owner)->learnSpell(itr->second);
- m_teachspells.erase(itr);
- }
-}
-
-uint32 Pet::resetTalentsCost() const
-{
- uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
-
- // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
- if(m_resetTalentsCost < 10*SILVER || days > 0)
- return 10*SILVER;
- // then 50 silver
- else if(m_resetTalentsCost < 50*SILVER)
- return 50*SILVER;
- // then 1 gold
- else if(m_resetTalentsCost < 1*GOLD)
- return 1*GOLD;
- // then increasing at a rate of 1 gold; cap 10 gold
- else
- return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
-}
-
-void Pet::ToggleAutocast(uint32 spellid, bool apply)
-{
- if(IsPassiveSpell(spellid))
- return;
-
- if(const SpellEntry *tempSpell = GetSpellStore()->LookupEntry(spellid))
- if(tempSpell->EffectImplicitTargetA[0] != TARGET_ALL_AROUND_CASTER
- && tempSpell->EffectImplicitTargetA[0] != TARGET_CHAIN_DAMAGE)
- return;
-
- PetSpellMap::const_iterator itr = m_spells.find((uint16)spellid);
-
- int i;
-
- if(apply)
- {
- for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++);
- if (i == m_autospells.size())
- {
- m_autospells.push_back(spellid);
- itr->second->active = ACT_ENABLED;
- itr->second->state = PETSPELL_CHANGED;
- }
- }
- else
- {
- AutoSpellList::iterator itr2 = m_autospells.begin();
- for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++, itr2++);
- if (i < m_autospells.size())
- {
- m_autospells.erase(itr2);
- itr->second->active = ACT_DISABLED;
- itr->second->state = PETSPELL_CHANGED;
- }
- }
-}
-
-bool Pet::Create(uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number)
-{
- SetMapId(map->GetId());
- SetInstanceId(map->GetInstanceId());
-
- Object::_Create(guidlow, pet_number, HIGHGUID_PET);
-
- m_DBTableGuid = guidlow;
- m_originalEntry = Entry;
-
- if(!InitEntry(Entry))
- return false;
-
- SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
- SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
-
- if(getPetType() == MINI_PET) // always non-attackable
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
-
- return true;
-}
-
-bool Pet::HasSpell(uint32 spell) const
-{
- return (m_spells.find(spell) != m_spells.end());
-}
-
-// Get all passive spells in our skill line
-void Pet::LearnPetPassives()
-{
- CreatureInfo const* cInfo = GetCreatureInfo();
- if(!cInfo)
- return;
-
- CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
- if(!cFamily)
- return;
-
- PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
- if(petStore != sPetFamilySpellsStore.end())
- {
- for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
- addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, 0xffff, PETSPELL_FAMILY);
- }
-}
-
-void Pet::CastPetAuras(bool current)
-{
- Unit* owner = GetOwner();
- if(!owner)
- return;
-
- if(getPetType() != HUNTER_PET && (getPetType() != SUMMON_PET || owner->getClass() != CLASS_WARLOCK))
- return;
-
- for(PetAuraSet::iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end(); )
- {
- PetAura const* pa = *itr;
- ++itr;
-
- if(!current && pa->IsRemovedOnChangePet())
- owner->RemovePetAura(pa);
- else
- CastPetAura(pa);
- }
-}
-
-void Pet::CastPetAura(PetAura const* aura)
-{
- uint16 auraId = aura->GetAura(GetEntry());
- if(!auraId)
- return;
-
- if(auraId == 35696) // Demonic Knowledge
- {
- int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
- CastCustomSpell(this,auraId,&basePoints, NULL, NULL, true );
- }
- else
- CastSpell(this, auraId, true);
-}
+/*
+ * Copyright (C) 2005-2008 MaNGOS
+ *
+ * Copyright (C) 2008 Trinity
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Common.h"
+#include "Database/DatabaseEnv.h"
+#include "Log.h"
+#include "WorldSession.h"
+#include "WorldPacket.h"
+#include "ObjectMgr.h"
+#include "SpellMgr.h"
+#include "Pet.h"
+#include "MapManager.h"
+#include "Formulas.h"
+#include "SpellAuras.h"
+#include "CreatureAI.h"
+#include "Unit.h"
+#include "Util.h"
+
+char const* petTypeSuffix[MAX_PET_TYPE] =
+{
+ "'s Minion", // SUMMON_PET
+ "'s Pet", // HUNTER_PET
+ "'s Guardian", // GUARDIAN_PET
+ "'s Companion" // MINI_PET
+};
+
+//numbers represent minutes * 100 while happy (you get 100 loyalty points per min while happy)
+uint32 const LevelUpLoyalty[6] =
+{
+ 5500,
+ 11500,
+ 17000,
+ 23500,
+ 31000,
+ 39500,
+};
+
+uint32 const LevelStartLoyalty[6] =
+{
+ 2000,
+ 4500,
+ 7000,
+ 10000,
+ 13500,
+ 17500,
+};
+
+Pet::Pet(PetType type) : Creature()
+{
+ m_isPet = true;
+ m_name = "Pet";
+ m_petType = type;
+
+ m_removed = false;
+ m_regenTimer = 4000;
+ m_happinessTimer = 7500;
+ m_loyaltyTimer = 12000;
+ m_duration = 0;
+ m_bonusdamage = 0;
+
+ m_loyaltyPoints = 0;
+ m_TrainingPoints = 0;
+ m_resetTalentsCost = 0;
+ m_resetTalentsTime = 0;
+
+ m_auraUpdateMask = 0;
+
+ // pets always have a charminfo, even if they are not actually charmed
+ CharmInfo* charmInfo = InitCharmInfo(this);
+
+ if(type == MINI_PET) // always passive
+ charmInfo->SetReactState(REACT_PASSIVE);
+ else if(type == GUARDIAN_PET) // always aggressive
+ charmInfo->SetReactState(REACT_AGGRESSIVE);
+
+ m_spells.clear();
+ m_Auras.clear();
+ m_CreatureSpellCooldowns.clear();
+ m_CreatureCategoryCooldowns.clear();
+ m_autospells.clear();
+ m_declinedname = NULL;
+ m_isActive = true;
+}
+
+Pet::~Pet()
+{
+ if(m_uint32Values) // only for fully created Object
+ {
+ for (PetSpellMap::iterator i = m_spells.begin(); i != m_spells.end(); ++i)
+ delete i->second;
+ ObjectAccessor::Instance().RemoveObject(this);
+ }
+
+ delete m_declinedname;
+}
+
+void Pet::AddToWorld()
+{
+ ///- Register the pet for guid lookup
+ if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
+ Unit::AddToWorld();
+}
+
+void Pet::RemoveFromWorld()
+{
+ ///- Remove the pet from the accessor
+ if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
+ ///- Don't call the function for Creature, normal mobs + totems go in a different storage
+ Unit::RemoveFromWorld();
+}
+
+bool Pet::LoadPetFromDB( Unit* owner, uint32 petentry, uint32 petnumber, bool current )
+{
+ uint32 ownerid = owner->GetGUIDLow();
+
+ QueryResult *result;
+
+ if(petnumber)
+ // known petnumber entry 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
+ result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND id = '%u'",ownerid, petnumber);
+ else if(current)
+ // current pet (slot 0) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
+ result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND slot = '0'",ownerid );
+ else if(petentry)
+ // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
+ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
+ result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '0' OR slot = '3') ",ownerid, petentry );
+ else
+ // any current or other non-stabled pet (for hunter "call pet")
+ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
+ result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3') ",ownerid);
+
+ if(!result)
+ return false;
+
+ Field *fields = result->Fetch();
+
+ // update for case of current pet "slot = 0"
+ petentry = fields[1].GetUInt32();
+ if(!petentry)
+ {
+ delete result;
+ return false;
+ }
+
+ uint32 summon_spell_id = fields[21].GetUInt32();
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
+
+ bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
+
+ // check temporary summoned pets like mage water elemental
+ if(current && is_temporary_summoned)
+ {
+ delete result;
+ return false;
+ }
+
+ Map *map = owner->GetMap();
+ uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
+ uint32 pet_number = fields[0].GetUInt32();
+ if(!Create(guid, map, petentry, pet_number))
+ {
+ delete result;
+ return false;
+ }
+
+ float px, py, pz;
+ owner->GetClosePoint(px, py, pz,GetObjectSize(),PET_FOLLOW_DIST,PET_FOLLOW_ANGLE);
+
+ Relocate(px, py, pz, owner->GetOrientation());
+
+ if(!IsPositionValid())
+ {
+ sLog.outError("ERROR: Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
+ GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
+ delete result;
+ return false;
+ }
+
+ setPetType(PetType(fields[22].GetUInt8()));
+ SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,owner->getFaction());
+ SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
+
+ CreatureInfo const *cinfo = GetCreatureInfo();
+ if(cinfo->type == CREATURE_TYPE_CRITTER)
+ {
+ AIM_Initialize();
+ map->Add((Creature*)this);
+ delete result;
+ return true;
+ }
+ if(getPetType()==HUNTER_PET || (getPetType()==SUMMON_PET && cinfo->type == CREATURE_TYPE_DEMON && owner->getClass() == CLASS_WARLOCK))
+ m_charmInfo->SetPetNumber(pet_number, true);
+ else
+ m_charmInfo->SetPetNumber(pet_number, false);
+ SetUInt64Value(UNIT_FIELD_SUMMONEDBY, owner->GetGUID());
+ SetDisplayId(fields[3].GetUInt32());
+ SetNativeDisplayId(fields[3].GetUInt32());
+ uint32 petlevel=fields[4].GetUInt32();
+ SetUInt32Value(UNIT_NPC_FLAGS , 0);
+ SetName(fields[11].GetString());
+
+ switch(getPetType())
+ {
+
+ case SUMMON_PET:
+ petlevel=owner->getLevel();
+
+ SetUInt32Value(UNIT_FIELD_BYTES_0,2048);
+ SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ // this enables popup window (pet dismiss, cancel)
+ break;
+ case HUNTER_PET:
+ SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
+ SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[8].GetUInt32());
+ SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
+ SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
+
+ if(fields[12].GetBool())
+ SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_NOT_ALLOWED);
+ else
+ SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
+
+ SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ // this enables popup window (pet abandon, cancel)
+ SetTP(fields[9].GetInt32());
+ SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
+ SetPower( POWER_HAPPINESS,fields[15].GetUInt32());
+ setPowerType(POWER_FOCUS);
+ break;
+ default:
+ sLog.outError("Pet have incorrect type (%u) for pet loading.",getPetType());
+ }
+ InitStatsForLevel( petlevel);
+ SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
+ SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
+ SetUInt64Value(UNIT_FIELD_CREATEDBY, owner->GetGUID());
+
+ m_charmInfo->SetReactState( ReactStates( fields[6].GetUInt8() ));
+ m_loyaltyPoints = fields[7].GetInt32();
+
+ uint32 savedhealth = fields[13].GetUInt32();
+ uint32 savedmana = fields[14].GetUInt32();
+
+ // set current pet as current
+ if(fields[10].GetUInt32() != 0)
+ {
+ CharacterDatabase.BeginTransaction();
+ CharacterDatabase.PExecute("UPDATE character_pet SET slot = '3' WHERE owner = '%u' AND slot = '0' AND id <> '%u'",ownerid, m_charmInfo->GetPetNumber());
+ CharacterDatabase.PExecute("UPDATE character_pet SET slot = '0' WHERE owner = '%u' AND id = '%u'",ownerid, m_charmInfo->GetPetNumber());
+ CharacterDatabase.CommitTransaction();
+ }
+
+ if(!is_temporary_summoned)
+ {
+ // permanent controlled pets store state in DB
+ Tokens tokens = StrSplit(fields[16].GetString(), " ");
+
+ if(tokens.size() != 20)
+ {
+ delete result;
+ return false;
+ }
+
+ int index;
+ Tokens::iterator iter;
+ for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
+ {
+ m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
+ ++iter;
+ m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
+ // patch for old data where some spells have ACT_DECIDE but should have ACT_CAST
+ // so overwrite old state
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_charmInfo->GetActionBarEntry(index)->SpellOrAction);
+ if (spellInfo && spellInfo->AttributesEx & SPELL_ATTR_EX_PET_NOT_AUTOCAST)
+ m_charmInfo->GetActionBarEntry(index)->Type = ACT_CAST;
+ }
+
+ //init teach spells
+ tokens = StrSplit(fields[17].GetString(), " ");
+ for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
+ {
+ uint32 tmp = atol((*iter).c_str());
+
+ ++iter;
+
+ if(tmp)
+ AddTeachSpell(tmp, atol((*iter).c_str()));
+ else
+ break;
+ }
+ }
+
+ // since last save (in seconds)
+ uint32 timediff = (time(NULL) - fields[18].GetUInt32());
+
+ delete result;
+
+ //load spells/cooldowns/auras
+ SetCanModifyStats(true);
+ _LoadAuras(timediff);
+
+ //init AB
+ if(is_temporary_summoned)
+ {
+ // Temporary summoned pets always have initial spell list at load
+ InitPetCreateSpells();
+ }
+ else
+ {
+ LearnPetPassives();
+ CastPetAuras(current);
+ }
+
+ if(getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
+ {
+ SetHealth(GetMaxHealth());
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
+ }
+ else
+ {
+ SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
+ SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
+ }
+
+ AIM_Initialize();
+ map->Add((Creature*)this);
+
+ // Spells should be loaded after pet is added to map, because in CanCast is check on it
+ _LoadSpells();
+ _LoadSpellCooldowns();
+
+ owner->SetPet(this); // in DB stored only full controlled creature
+ sLog.outDebug("New Pet has guid %u", GetGUIDLow());
+
+ if(owner->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)owner)->PetSpellInitialize();
+ if(((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
+ }
+
+ if(owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
+ {
+ result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'",owner->GetGUIDLow(),GetCharmInfo()->GetPetNumber());
+
+ if(result)
+ {
+ if(m_declinedname)
+ delete m_declinedname;
+
+ m_declinedname = new DeclinedName;
+ Field *fields = result->Fetch();
+ for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
+ {
+ m_declinedname->name[i] = fields[i].GetCppString();
+ }
+ }
+ }
+
+ return true;
+}
+
+void Pet::SavePetToDB(PetSaveMode mode)
+{
+ if(!GetEntry())
+ return;
+
+ // save only fully controlled creature
+ if(!isControlled())
+ return;
+
+ uint32 curhealth = GetHealth();
+ uint32 curmana = GetPower(POWER_MANA);
+
+ switch(mode)
+ {
+ case PET_SAVE_IN_STABLE_SLOT_1:
+ case PET_SAVE_IN_STABLE_SLOT_2:
+ case PET_SAVE_NOT_IN_SLOT:
+ {
+ RemoveAllAuras();
+
+ //only alive hunter pets get auras saved, the others don't
+ if(!(getPetType() == HUNTER_PET && isAlive()))
+ m_Auras.clear();
+ }
+ default:
+ break;
+ }
+
+ _SaveSpells();
+ _SaveSpellCooldowns();
+ _SaveAuras();
+
+ switch(mode)
+ {
+ case PET_SAVE_AS_CURRENT:
+ case PET_SAVE_IN_STABLE_SLOT_1:
+ case PET_SAVE_IN_STABLE_SLOT_2:
+ case PET_SAVE_NOT_IN_SLOT:
+ {
+ uint32 loyalty =1;
+ if(getPetType()!=HUNTER_PET)
+ loyalty = GetLoyaltyLevel();
+
+ uint32 owner = GUID_LOPART(GetOwnerGUID());
+ std::string name = m_name;
+ CharacterDatabase.escape_string(name);
+ CharacterDatabase.BeginTransaction();
+ // remove current data
+ CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner,m_charmInfo->GetPetNumber() );
+
+ // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
+ if(mode!=PET_SAVE_NOT_IN_SLOT)
+ CharacterDatabase.PExecute("UPDATE character_pet SET slot = 3 WHERE owner = '%u' AND slot = '%u'", owner, uint32(mode) );
+
+ // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
+ if(getPetType()==HUNTER_PET && (mode==PET_SAVE_AS_CURRENT||mode==PET_SAVE_NOT_IN_SLOT))
+ CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3')", owner );
+ // save pet
+ std::ostringstream ss;
+ ss << "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata,TeachSpelldata,savetime,resettalents_cost,resettalents_time,CreatedBySpell,PetType) "
+ << "VALUES ("
+ << m_charmInfo->GetPetNumber() << ", "
+ << GetEntry() << ", "
+ << owner << ", "
+ << GetNativeDisplayId() << ", "
+ << getLevel() << ", "
+ << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE) << ", "
+ << uint32(m_charmInfo->GetReactState()) << ", "
+ << m_loyaltyPoints << ", "
+ << GetLoyaltyLevel() << ", "
+ << m_TrainingPoints << ", "
+ << uint32(mode) << ", '"
+ << name.c_str() << "', "
+ << uint32((GetByteValue(UNIT_FIELD_BYTES_2, 2) == UNIT_RENAME_ALLOWED)?0:1) << ", "
+ << (curhealth<1?1:curhealth) << ", "
+ << curmana << ", "
+ << GetPower(POWER_HAPPINESS) << ", '";
+
+ for(uint32 i = 0; i < 10; i++)
+ ss << uint32(m_charmInfo->GetActionBarEntry(i)->Type) << " " << uint32(m_charmInfo->GetActionBarEntry(i)->SpellOrAction) << " ";
+ ss << "', '";
+
+ //save spells the pet can teach to it's Master
+ {
+ int i = 0;
+ for(TeachSpellMap::iterator itr = m_teachspells.begin(); i < 4 && itr != m_teachspells.end(); ++i, ++itr)
+ ss << itr->first << " " << itr->second << " ";
+ for(; i < 4; ++i)
+ ss << uint32(0) << " " << uint32(0) << " ";
+ }
+
+ ss << "', "
+ << time(NULL) << ", "
+ << uint32(m_resetTalentsCost) << ", "
+ << uint64(m_resetTalentsTime) << ", "
+ << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ", "
+ << uint32(getPetType()) << ")";
+
+ CharacterDatabase.Execute( ss.str().c_str() );
+
+ CharacterDatabase.CommitTransaction();
+ break;
+ }
+ case PET_SAVE_AS_DELETED:
+ {
+ RemoveAllAuras();
+ uint32 owner = GUID_LOPART(GetOwnerGUID());
+ DeleteFromDB(m_charmInfo->GetPetNumber());
+ break;
+ }
+ default:
+ sLog.outError("Unknown pet save/remove mode: %d",mode);
+ }
+}
+
+void Pet::DeleteFromDB(uint32 guidlow)
+{
+ CharacterDatabase.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow);
+ CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow);
+ CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow);
+ CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow);
+ CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow);
+}
+
+void Pet::setDeathState(DeathState s) // overwrite virtual Creature::setDeathState and Unit::setDeathState
+{
+ Creature::setDeathState(s);
+ if(getDeathState()==CORPSE)
+ {
+ //remove summoned pet (no corpse)
+ if(getPetType()==SUMMON_PET)
+ Remove(PET_SAVE_NOT_IN_SLOT);
+ // other will despawn at corpse desppawning (Pet::Update code)
+ else
+ {
+ // pet corpse non lootable and non skinnable
+ SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
+ RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
+
+ //lose happiness when died and not in BG/Arena
+ MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
+ if(!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND))
+ ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE);
+
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
+ }
+ }
+ else if(getDeathState()==ALIVE)
+ {
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
+ CastPetAuras(true);
+ }
+}
+
+void Pet::Update(uint32 diff)
+{
+ if(m_removed) // pet already removed, just wait in remove queue, no updates
+ return;
+
+ switch( m_deathState )
+ {
+ case CORPSE:
+ {
+ if( m_deathTimer <= diff )
+ {
+ assert(getPetType()!=SUMMON_PET && "Must be already removed.");
+ Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER!
+ return;
+ }
+ break;
+ }
+ case ALIVE:
+ {
+ // unsummon pet that lost owner
+ Unit* owner = GetOwner();
+ if(!owner || (!IsWithinDistInMap(owner, OWNER_MAX_DISTANCE) && !isPossessed()) || isControlled() && !owner->GetPetGUID())
+ {
+ Remove(PET_SAVE_NOT_IN_SLOT, true);
+ return;
+ }
+
+ if(isControlled())
+ {
+ if( owner->GetPetGUID() != GetGUID() )
+ {
+ Remove(getPetType()==HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
+ return;
+ }
+ }
+
+ if(m_duration > 0)
+ {
+ if(m_duration > diff)
+ m_duration -= diff;
+ else
+ {
+ Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
+ return;
+ }
+ }
+
+ if(getPetType() != HUNTER_PET)
+ break;
+
+ //regenerate Focus
+ if(m_regenTimer <= diff)
+ {
+ RegenerateFocus();
+ m_regenTimer = 4000;
+ }
+ else
+ m_regenTimer -= diff;
+
+ if(m_happinessTimer <= diff)
+ {
+ LooseHappiness();
+ m_happinessTimer = 7500;
+ }
+ else
+ m_happinessTimer -= diff;
+
+ if(m_loyaltyTimer <= diff)
+ {
+ TickLoyaltyChange();
+ m_loyaltyTimer = 12000;
+ }
+ else
+ m_loyaltyTimer -= diff;
+
+ break;
+ }
+ default:
+ break;
+ }
+ Creature::Update(diff);
+}
+
+void Pet::RegenerateFocus()
+{
+ uint32 curValue = GetPower(POWER_FOCUS);
+ uint32 maxValue = GetMaxPower(POWER_FOCUS);
+
+ if (curValue >= maxValue)
+ return;
+
+ float addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
+
+ AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
+ for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
+ if ((*i)->GetModifier()->m_miscvalue == POWER_FOCUS)
+ addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
+
+ ModifyPower(POWER_FOCUS, (int32)addvalue);
+}
+
+void Pet::LooseHappiness()
+{
+ uint32 curValue = GetPower(POWER_HAPPINESS);
+ if (curValue <= 0)
+ return;
+ int32 addvalue = (140 >> GetLoyaltyLevel()) * 125; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
+ if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
+ addvalue = int32(addvalue * 1.5);
+ ModifyPower(POWER_HAPPINESS, -addvalue);
+}
+
+void Pet::ModifyLoyalty(int32 addvalue)
+{
+ uint32 loyaltylevel = GetLoyaltyLevel();
+
+ if(addvalue > 0) //only gain influenced, not loss
+ addvalue = int32((float)addvalue * sWorld.getRate(RATE_LOYALTY));
+
+ if(loyaltylevel >= BEST_FRIEND && (addvalue + m_loyaltyPoints) > int32(GetMaxLoyaltyPoints(loyaltylevel)))
+ return;
+
+ m_loyaltyPoints += addvalue;
+
+ if(m_loyaltyPoints < 0)
+ {
+ if(loyaltylevel > REBELLIOUS)
+ {
+ //level down
+ --loyaltylevel;
+ SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
+ m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
+ SetTP(m_TrainingPoints - int32(getLevel()));
+ }
+ else
+ {
+ m_loyaltyPoints = 0;
+ Unit* owner = GetOwner();
+ if(owner && owner->GetTypeId() == TYPEID_PLAYER)
+ {
+ WorldPacket data(SMSG_PET_BROKEN, 0);
+ ((Player*)owner)->GetSession()->SendPacket(&data);
+
+ //run away
+ ((Player*)owner)->RemovePet(this,PET_SAVE_AS_DELETED);
+ }
+ }
+ }
+ //level up
+ else if(m_loyaltyPoints > int32(GetMaxLoyaltyPoints(loyaltylevel)))
+ {
+ ++loyaltylevel;
+ SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
+ m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
+ SetTP(m_TrainingPoints + getLevel());
+ }
+}
+
+void Pet::TickLoyaltyChange()
+{
+ int32 addvalue;
+
+ switch(GetHappinessState())
+ {
+ case HAPPY: addvalue = 20; break;
+ case CONTENT: addvalue = 10; break;
+ case UNHAPPY: addvalue = -20; break;
+ default:
+ return;
+ }
+ ModifyLoyalty(addvalue);
+}
+
+void Pet::KillLoyaltyBonus(uint32 level)
+{
+ if(level > 100)
+ return;
+
+ //at lower levels gain is faster | the lower loyalty the more loyalty is gained
+ uint32 bonus = uint32(((100 - level) / 10) + (6 - GetLoyaltyLevel()));
+ ModifyLoyalty(bonus);
+}
+
+HappinessState Pet::GetHappinessState()
+{
+ if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
+ return UNHAPPY;
+ else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
+ return HAPPY;
+ else
+ return CONTENT;
+}
+
+void Pet::SetLoyaltyLevel(LoyaltyLevel level)
+{
+ SetByteValue(UNIT_FIELD_BYTES_1, 1, level);
+}
+
+bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
+{
+ uint8 activecount = 1;
+ uint32 chainstartstore[ACTIVE_SPELLS_MAX];
+
+ if(IsPassiveSpell(spellid))
+ return true;
+
+ chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
+
+ for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if(IsPassiveSpell(itr->first))
+ continue;
+
+ uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
+
+ uint8 x;
+
+ for(x = 0; x < activecount; x++)
+ {
+ if(chainstart == chainstartstore[x])
+ break;
+ }
+
+ if(x == activecount) //spellchain not yet saved -> add active count
+ {
+ ++activecount;
+ if(activecount > ACTIVE_SPELLS_MAX)
+ return false;
+ chainstartstore[x] = chainstart;
+ }
+ }
+ return true;
+}
+
+bool Pet::HasTPForSpell(uint32 spellid)
+{
+ int32 neededtrainp = GetTPForSpell(spellid);
+ if((m_TrainingPoints - neededtrainp < 0 || neededtrainp < 0) && neededtrainp != 0)
+ return false;
+ return true;
+}
+
+int32 Pet::GetTPForSpell(uint32 spellid)
+{
+ uint32 basetrainp = 0;
+
+ SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
+ SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
+ for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
+ {
+ if(!_spell_idx->second->reqtrainpoints)
+ return 0;
+
+ basetrainp = _spell_idx->second->reqtrainpoints;
+ break;
+ }
+
+ uint32 spenttrainp = 0;
+ uint32 chainstart = spellmgr.GetFirstSpellInChain(spellid);
+
+ for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if(itr->second->state == PETSPELL_REMOVED)
+ continue;
+
+ if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
+ {
+ SkillLineAbilityMap::const_iterator _lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
+ SkillLineAbilityMap::const_iterator _upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
+
+ for(SkillLineAbilityMap::const_iterator _spell_idx2 = _lower; _spell_idx2 != _upper; ++_spell_idx2)
+ {
+ if(_spell_idx2->second->reqtrainpoints > spenttrainp)
+ {
+ spenttrainp = _spell_idx2->second->reqtrainpoints;
+ break;
+ }
+ }
+ }
+ }
+
+ return int32(basetrainp) - int32(spenttrainp);
+}
+
+uint32 Pet::GetMaxLoyaltyPoints(uint32 level)
+{
+ return LevelUpLoyalty[level - 1];
+}
+
+uint32 Pet::GetStartLoyaltyPoints(uint32 level)
+{
+ return LevelStartLoyalty[level - 1];
+}
+
+void Pet::SetTP(int32 TP)
+{
+ m_TrainingPoints = TP;
+ SetUInt32Value(UNIT_TRAINING_POINTS, (uint32)GetDispTP());
+}
+
+int32 Pet::GetDispTP()
+{
+ if(getPetType()!= HUNTER_PET)
+ return(0);
+ if(m_TrainingPoints < 0)
+ return -m_TrainingPoints;
+ else
+ return -(m_TrainingPoints + 1);
+}
+
+void Pet::Remove(PetSaveMode mode, bool returnreagent)
+{
+ Unit* owner = GetOwner();
+
+ if(owner)
+ {
+ if(owner->GetTypeId()==TYPEID_PLAYER)
+ {
+ ((Player*)owner)->RemovePet(this,mode,returnreagent);
+ return;
+ }
+
+ // only if current pet in slot
+ if(owner->GetPetGUID()==GetGUID())
+ owner->SetPet(0);
+ }
+
+ CleanupsBeforeDelete();
+ AddObjectToRemoveList();
+ m_removed = true;
+}
+
+void Pet::GivePetXP(uint32 xp)
+{
+ if(getPetType() != HUNTER_PET)
+ return;
+
+ if ( xp < 1 )
+ return;
+
+ if(!isAlive())
+ return;
+
+ uint32 level = getLevel();
+
+ // XP to money conversion processed in Player::RewardQuest
+ if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
+ return;
+
+ uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
+ uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
+ uint32 newXP = curXP + xp;
+
+ if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
+ {
+ SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
+ return;
+ }
+
+ while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
+ {
+ newXP -= nextLvlXP;
+
+ SetLevel( level + 1 );
+ SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(level+1))/4));
+
+ level = getLevel();
+ nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
+ GivePetLevel(level);
+ }
+
+ SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
+
+ if(getPetType() == HUNTER_PET)
+ KillLoyaltyBonus(level);
+}
+
+void Pet::GivePetLevel(uint32 level)
+{
+ if(!level)
+ return;
+
+ InitStatsForLevel( level);
+
+ SetTP(m_TrainingPoints + (GetLoyaltyLevel() - 1));
+}
+
+bool Pet::CreateBaseAtCreature(Creature* creature)
+{
+ if(!creature)
+ {
+ sLog.outError("CRITICAL ERROR: NULL pointer parsed into CreateBaseAtCreature()");
+ return false;
+ }
+ uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
+
+ sLog.outBasic("SetInstanceID()");
+ SetInstanceId(creature->GetInstanceId());
+
+ sLog.outBasic("Create pet");
+ uint32 pet_number = objmgr.GeneratePetNumber();
+ if(!Create(guid, creature->GetMap(), creature->GetEntry(), pet_number))
+ return false;
+
+ Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
+
+ if(!IsPositionValid())
+ {
+ sLog.outError("ERROR: Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
+ GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
+ return false;
+ }
+
+ CreatureInfo const *cinfo = GetCreatureInfo();
+ if(!cinfo)
+ {
+ sLog.outError("ERROR: CreateBaseAtCreature() failed, creatureInfo is missing!");
+ return false;
+ }
+
+ if(cinfo->type == CREATURE_TYPE_CRITTER)
+ {
+ setPetType(MINI_PET);
+ return true;
+ }
+ SetDisplayId(creature->GetDisplayId());
+ SetNativeDisplayId(creature->GetNativeDisplayId());
+ SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
+ SetPower( POWER_HAPPINESS,166500);
+ setPowerType(POWER_FOCUS);
+ SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP,0);
+ SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
+ SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(creature->getLevel()))/4));
+ SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ SetUInt32Value(UNIT_NPC_FLAGS , 0);
+
+ CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(creature->GetCreatureInfo()->family);
+ if( char* familyname = cFamily->Name[sWorld.GetDefaultDbcLocale()] )
+ SetName(familyname);
+ else
+ SetName(creature->GetName());
+
+ m_loyaltyPoints = 1000;
+ if(cinfo->type == CREATURE_TYPE_BEAST)
+ {
+ SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
+ SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
+ SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
+ SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
+
+ SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED) );
+ SetLoyaltyLevel(REBELLIOUS);
+ }
+ return true;
+}
+
+bool Pet::InitStatsForLevel(uint32 petlevel)
+{
+ CreatureInfo const *cinfo = GetCreatureInfo();
+ assert(cinfo);
+
+ Unit* owner = GetOwner();
+ if(!owner)
+ {
+ sLog.outError("ERROR: attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
+ return false;
+ }
+
+ uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
+
+ SetLevel( petlevel);
+
+ SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
+
+ SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
+
+ SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
+ SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
+ SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
+
+ SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
+
+ CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
+ if(cFamily && cFamily->minScale > 0.0f)
+ {
+ float scale;
+ if (getLevel() >= cFamily->maxScaleLevel)
+ scale = cFamily->maxScale;
+ else if (getLevel() <= cFamily->minScaleLevel)
+ scale = cFamily->minScale;
+ else
+ scale = cFamily->minScale + (getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
+
+ SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
+ }
+ m_bonusdamage = 0;
+
+ int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
+
+ if(cinfo && getPetType() != HUNTER_PET)
+ {
+ createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
+ createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
+ createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
+ createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
+ createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
+ createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
+ }
+
+ switch(getPetType())
+ {
+ case SUMMON_PET:
+ {
+ if(owner->GetTypeId() == TYPEID_PLAYER)
+ {
+ switch(owner->getClass())
+ {
+ case CLASS_WARLOCK:
+ {
+
+ //the damage bonus used for pets is either fire or shadow damage, whatever is higher
+ uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
+ uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
+ uint32 val = (fire > shadow) ? fire : shadow;
+
+ SetBonusDamage(int32 (val * 0.15f));
+ //bonusAP += val * 0.57;
+ break;
+ }
+ case CLASS_MAGE:
+ {
+ //40% damage bonus of mage's frost damage
+ float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
+ if(val < 0)
+ val = 0;
+ SetBonusDamage( int32(val));
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
+ SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
+
+ //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
+
+ PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
+ if(pInfo) // exist in DB
+ {
+ SetCreateHealth(pInfo->health);
+ SetCreateMana(pInfo->mana);
+
+ if(pInfo->armor > 0)
+ SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
+
+ for(int stat = 0; stat < MAX_STATS; ++stat)
+ {
+ SetCreateStat(Stats(stat),float(pInfo->stats[stat]));
+ }
+ }
+ else // not exist in DB, use some default fake data
+ {
+ sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
+
+ // remove elite bonuses included in DB values
+ SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
+ SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
+
+ SetCreateStat(STAT_STRENGTH,22);
+ SetCreateStat(STAT_AGILITY,22);
+ SetCreateStat(STAT_STAMINA,25);
+ SetCreateStat(STAT_INTELLECT,28);
+ SetCreateStat(STAT_SPIRIT,27);
+ }
+ break;
+ }
+ case HUNTER_PET:
+ {
+ SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((Trinity::XP::xp_to_level(petlevel))/4));
+
+ //these formula may not be correct; however, it is designed to be close to what it should be
+ //this makes dps 0.5 of pets level
+ SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
+ //damage range is then petlevel / 2
+ SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
+ //damage is increased afterwards as strength and pet scaling modify attack power
+
+ //stored standard pet stats are entry 1 in pet_levelinfo
+ PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
+ if(pInfo) // exist in DB
+ {
+ SetCreateHealth(pInfo->health);
+ SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
+ //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
+
+ for( int i = STAT_STRENGTH; i < MAX_STATS; i++)
+ {
+ SetCreateStat(Stats(i), float(pInfo->stats[i]));
+ }
+ }
+ else // not exist in DB, use some default fake data
+ {
+ sLog.outErrorDb("Hunter pet levelstats missing in DB");
+
+ // remove elite bonuses included in DB values
+ SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
+
+ SetCreateStat(STAT_STRENGTH,22);
+ SetCreateStat(STAT_AGILITY,22);
+ SetCreateStat(STAT_STAMINA,25);
+ SetCreateStat(STAT_INTELLECT,28);
+ SetCreateStat(STAT_SPIRIT,27);
+ }
+ break;
+ }
+ case GUARDIAN_PET:
+ SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
+ SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP,1000);
+
+ SetCreateMana( 28 + 10*petlevel );
+ SetCreateHealth( 28 + 30*petlevel );
+
+ // FIXME: this is wrong formula, possible each guardian pet have own damage formula
+ //these formula may not be correct; however, it is designed to be close to what it should be
+ //this makes dps 0.5 of pets level
+ SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
+ //damage range is then petlevel / 2
+ SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
+ break;
+ default:
+ sLog.outError("Pet have incorrect type (%u) for levelup.",getPetType()); break;
+ }
+
+ for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
+ SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]) );
+
+ UpdateAllStats();
+
+ SetHealth(GetMaxHealth());
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
+
+ return true;
+}
+
+bool Pet::HaveInDiet(ItemPrototype const* item) const
+{
+ if (!item->FoodType)
+ return false;
+
+ CreatureInfo const* cInfo = GetCreatureInfo();
+ if(!cInfo)
+ return false;
+
+ CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
+ if(!cFamily)
+ return false;
+
+ uint32 diet = cFamily->petFoodMask;
+ uint32 FoodMask = 1 << (item->FoodType-1);
+ return diet & FoodMask;
+}
+
+uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
+{
+ // -5 or greater food level
+ if(getLevel() <= itemlevel +5) //possible to feed level 60 pet with level 55 level food for full effect
+ return 35000;
+ // -10..-6
+ else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
+ return 17000;
+ // -14..-11
+ else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
+ return 8000;
+ // -15 or less
+ else
+ return 0; //food too low level
+}
+
+void Pet::_LoadSpellCooldowns()
+{
+ m_CreatureSpellCooldowns.clear();
+ m_CreatureCategoryCooldowns.clear();
+
+ QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
+
+ if(result)
+ {
+ time_t curTime = time(NULL);
+
+ WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
+ data << GetGUID();
+ data << uint8(0x0); // flags (0x1, 0x2)
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint32 spell_id = fields[0].GetUInt32();
+ time_t db_time = (time_t)fields[1].GetUInt64();
+
+ if(!sSpellStore.LookupEntry(spell_id))
+ {
+ sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
+ continue;
+ }
+
+ // skip outdated cooldown
+ if(db_time <= curTime)
+ continue;
+
+ data << uint32(spell_id);
+ data << uint32(uint32(db_time-curTime)*1000); // in m.secs
+
+ _AddCreatureSpellCooldown(spell_id,db_time);
+
+ sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).",m_charmInfo->GetPetNumber(),spell_id,uint32(db_time-curTime));
+ }
+ while( result->NextRow() );
+
+ delete result;
+
+ if(!m_CreatureSpellCooldowns.empty() && GetOwner())
+ {
+ ((Player*)GetOwner())->GetSession()->SendPacket(&data);
+ }
+ }
+}
+
+void Pet::_SaveSpellCooldowns()
+{
+ CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
+
+ time_t curTime = time(NULL);
+
+ // remove oudated and save active
+ for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
+ {
+ if(itr->second <= curTime)
+ m_CreatureSpellCooldowns.erase(itr++);
+ else
+ {
+ CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
+ ++itr;
+ }
+ }
+}
+
+void Pet::_LoadSpells()
+{
+ QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
+
+ if(result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ addSpell(fields[0].GetUInt16(), (ActiveStates)fields[2].GetUInt16(), PETSPELL_UNCHANGED, fields[1].GetUInt16());
+ }
+ while( result->NextRow() );
+
+ delete result;
+ }
+}
+
+void Pet::_SaveSpells()
+{
+ for (PetSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
+ {
+ ++next;
+ if (itr->second->type == PETSPELL_FAMILY) continue; // prevent saving family passives to DB
+ if (itr->second->state == PETSPELL_REMOVED || itr->second->state == PETSPELL_CHANGED)
+ CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
+ if (itr->second->state == PETSPELL_NEW || itr->second->state == PETSPELL_CHANGED)
+ CharacterDatabase.PExecute("INSERT INTO pet_spell (guid,spell,slot,active) VALUES ('%u', '%u', '%u','%u')", m_charmInfo->GetPetNumber(), itr->first, itr->second->slotId,itr->second->active);
+
+ if (itr->second->state == PETSPELL_REMOVED)
+ _removeSpell(itr->first);
+ else
+ itr->second->state = PETSPELL_UNCHANGED;
+ }
+}
+
+void Pet::_LoadAuras(uint32 timediff)
+{
+ m_Auras.clear();
+ for (int i = 0; i < TOTAL_AURAS; i++)
+ m_modAuras[i].clear();
+
+ // all aura related fields
+ for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
+ SetUInt32Value(i, 0);
+
+ QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
+
+ if(result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+ uint64 caster_guid = fields[0].GetUInt64();
+ uint32 spellid = fields[1].GetUInt32();
+ uint32 effindex = fields[2].GetUInt32();
+ int32 damage = (int32)fields[3].GetUInt32();
+ int32 maxduration = (int32)fields[4].GetUInt32();
+ int32 remaintime = (int32)fields[5].GetUInt32();
+ int32 remaincharges = (int32)fields[6].GetUInt32();
+
+ SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
+ if(!spellproto)
+ {
+ sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
+ continue;
+ }
+
+ if(effindex >= 3)
+ {
+ sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
+ continue;
+ }
+
+ // negative effects should continue counting down after logout
+ if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
+ {
+ if(remaintime <= int32(timediff))
+ continue;
+
+ remaintime -= timediff;
+ }
+
+ // prevent wrong values of remaincharges
+ if(spellproto->procCharges)
+ {
+ if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
+ remaincharges = spellproto->procCharges;
+ }
+ else
+ remaincharges = -1;
+
+ /// do not load single target auras (unless they were cast by the player)
+ if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
+ continue;
+
+ Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
+
+ if(!damage)
+ damage = aura->GetModifier()->m_amount;
+ aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
+ AddAura(aura);
+ }
+ while( result->NextRow() );
+
+ delete result;
+ }
+}
+
+void Pet::_SaveAuras()
+{
+ CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
+
+ AuraMap const& auras = GetAuras();
+ for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+ {
+ // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
+ SpellEntry const *spellInfo = itr->second->GetSpellProto();
+ uint8 i;
+ for (i = 0; i < 3; i++)
+ if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
+ spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
+ spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
+ break;
+
+ if (i != 3)
+ continue;
+
+ if(itr->second->IsPassive())
+ continue;
+
+ /// do not save single target auras (unless they were cast by the player)
+ if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
+ continue;
+
+ CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
+ "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%d', '%d', '%d', '%d')",
+ m_charmInfo->GetPetNumber(), itr->second->GetCasterGUID(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(),(*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
+ }
+}
+
+bool Pet::addSpell(uint16 spell_id, ActiveStates active, PetSpellState state, uint16 slot_id, PetSpellType type)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
+ if (!spellInfo)
+ {
+ // do pet spell book cleanup
+ if(state == PETSPELL_UNCHANGED) // spell load case
+ {
+ sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
+ CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
+ }
+ else
+ sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
+
+ return false;
+ }
+ // same spells don't have autocast option
+ if (spellInfo->AttributesEx & SPELL_ATTR_EX_PET_NOT_AUTOCAST)
+ active = ACT_CAST;
+
+ PetSpellMap::iterator itr = m_spells.find(spell_id);
+ if (itr != m_spells.end())
+ {
+ if (itr->second->state == PETSPELL_REMOVED)
+ {
+ delete itr->second;
+ m_spells.erase(itr);
+ state = PETSPELL_CHANGED;
+ }
+ else if (state == PETSPELL_UNCHANGED && itr->second->state != PETSPELL_UNCHANGED)
+ {
+ // can be in case spell loading but learned at some previous spell loading
+ itr->second->state = PETSPELL_UNCHANGED;
+ return false;
+ }
+ else
+ return false;
+ }
+
+ uint32 oldspell_id = 0;
+
+ PetSpell *newspell = new PetSpell;
+ newspell->state = state;
+ newspell->type = type;
+
+ if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
+ {
+ if(IsPassiveSpell(spell_id))
+ newspell->active = ACT_PASSIVE;
+ else
+ newspell->active = ACT_DISABLED;
+ }
+ else
+ newspell->active = active;
+
+ uint32 chainstart = spellmgr.GetFirstSpellInChain(spell_id);
+
+ for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); itr++)
+ {
+ if(itr->second->state == PETSPELL_REMOVED) continue;
+
+ if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
+ {
+ slot_id = itr->second->slotId;
+ newspell->active = itr->second->active;
+
+ if(newspell->active == ACT_ENABLED)
+ ToggleAutocast(itr->first, false);
+
+ oldspell_id = itr->first;
+ removeSpell(itr->first);
+ }
+ }
+
+ uint16 tmpslot=slot_id;
+
+ if (tmpslot == 0xffff)
+ {
+ uint16 maxid = 0;
+ PetSpellMap::iterator itr;
+ for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if(itr->second->state == PETSPELL_REMOVED) continue;
+ if (itr->second->slotId > maxid) maxid = itr->second->slotId;
+ }
+ tmpslot = maxid + 1;
+ }
+
+ newspell->slotId = tmpslot;
+ m_spells[spell_id] = newspell;
+
+ if (IsPassiveSpell(spell_id))
+ CastSpell(this, spell_id, true);
+ else if(state == PETSPELL_NEW)
+ m_charmInfo->AddSpellToAB(oldspell_id, spell_id, active);
+
+ if(newspell->active == ACT_ENABLED)
+ ToggleAutocast(spell_id, true);
+
+ return true;
+}
+
+bool Pet::learnSpell(uint16 spell_id)
+{
+ // prevent duplicated entires in spell book
+ if (!addSpell(spell_id))
+ return false;
+
+ Unit* owner = GetOwner();
+ if(owner->GetTypeId()==TYPEID_PLAYER)
+ ((Player*)owner)->PetSpellInitialize();
+ return true;
+}
+
+void Pet::removeSpell(uint16 spell_id)
+{
+ PetSpellMap::iterator itr = m_spells.find(spell_id);
+ if (itr == m_spells.end())
+ return;
+
+ if(itr->second->state == PETSPELL_REMOVED)
+ return;
+
+ if(itr->second->state == PETSPELL_NEW)
+ {
+ delete itr->second;
+ m_spells.erase(itr);
+ }
+ else
+ itr->second->state = PETSPELL_REMOVED;
+
+ RemoveAurasDueToSpell(spell_id);
+}
+
+bool Pet::_removeSpell(uint16 spell_id)
+{
+ PetSpellMap::iterator itr = m_spells.find(spell_id);
+ if (itr != m_spells.end())
+ {
+ delete itr->second;
+ m_spells.erase(itr);
+ return true;
+ }
+ return false;
+}
+
+void Pet::InitPetCreateSpells()
+{
+ m_charmInfo->InitPetActionBar();
+
+ m_spells.clear();
+ int32 usedtrainpoints = 0, petspellid;
+ PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
+ if(CreateSpells)
+ {
+ for(uint8 i = 0; i < 4; i++)
+ {
+ if(!CreateSpells->spellid[i])
+ break;
+
+ SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
+ if(!learn_spellproto)
+ continue;
+
+ if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
+ {
+ petspellid = learn_spellproto->EffectTriggerSpell[0];
+ Unit* owner = GetOwner();
+ if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
+ {
+ if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
+ ((Player*)owner)->learnSpell(learn_spellproto->Id);
+ else
+ AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
+ }
+ }
+ else
+ petspellid = learn_spellproto->Id;
+
+ addSpell(petspellid);
+
+ SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
+ SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
+
+ for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
+ {
+ usedtrainpoints += _spell_idx->second->reqtrainpoints;
+ break;
+ }
+ }
+ }
+
+ LearnPetPassives();
+
+ CastPetAuras(false);
+
+ SetTP(-usedtrainpoints);
+}
+
+void Pet::CheckLearning(uint32 spellid)
+{
+ //charmed case -> prevent crash
+ if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
+ return;
+
+ Unit* owner = GetOwner();
+
+ if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ TeachSpellMap::iterator itr = m_teachspells.find(spellid);
+ if(itr == m_teachspells.end())
+ return;
+
+ if(urand(0, 100) < 10)
+ {
+ ((Player*)owner)->learnSpell(itr->second);
+ m_teachspells.erase(itr);
+ }
+}
+
+uint32 Pet::resetTalentsCost() const
+{
+ uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
+
+ // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
+ if(m_resetTalentsCost < 10*SILVER || days > 0)
+ return 10*SILVER;
+ // then 50 silver
+ else if(m_resetTalentsCost < 50*SILVER)
+ return 50*SILVER;
+ // then 1 gold
+ else if(m_resetTalentsCost < 1*GOLD)
+ return 1*GOLD;
+ // then increasing at a rate of 1 gold; cap 10 gold
+ else
+ return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
+}
+
+void Pet::ToggleAutocast(uint32 spellid, bool apply)
+{
+ if(IsPassiveSpell(spellid))
+ return;
+
+ /*if(const SpellEntry *tempSpell = GetSpellStore()->LookupEntry(spellid))
+ if(tempSpell->EffectImplicitTargetA[0] != TARGET_ALL_AROUND_CASTER
+ && tempSpell->EffectImplicitTargetA[0] != TARGET_CHAIN_DAMAGE)
+ return; */
+
+ PetSpellMap::const_iterator itr = m_spells.find((uint16)spellid);
+
+ int i;
+
+ if(apply)
+ {
+ for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++);
+ if (i == m_autospells.size())
+ {
+ m_autospells.push_back(spellid);
+ itr->second->active = ACT_ENABLED;
+ itr->second->state = PETSPELL_CHANGED;
+ }
+ }
+ else
+ {
+ AutoSpellList::iterator itr2 = m_autospells.begin();
+ for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++, itr2++);
+ if (i < m_autospells.size())
+ {
+ m_autospells.erase(itr2);
+ itr->second->active = ACT_DISABLED;
+ itr->second->state = PETSPELL_CHANGED;
+ }
+ }
+}
+
+bool Pet::Create(uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number)
+{
+ SetMapId(map->GetId());
+ SetInstanceId(map->GetInstanceId());
+
+ Object::_Create(guidlow, pet_number, HIGHGUID_PET);
+
+ m_DBTableGuid = guidlow;
+ m_originalEntry = Entry;
+
+ if(!InitEntry(Entry))
+ return false;
+
+ SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
+ SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
+
+ if(getPetType() == MINI_PET) // always non-attackable
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
+
+ return true;
+}
+
+bool Pet::HasSpell(uint32 spell) const
+{
+ return (m_spells.find(spell) != m_spells.end());
+}
+
+// Get all passive spells in our skill line
+void Pet::LearnPetPassives()
+{
+ CreatureInfo const* cInfo = GetCreatureInfo();
+ if(!cInfo)
+ return;
+
+ CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
+ if(!cFamily)
+ return;
+
+ PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
+ if(petStore != sPetFamilySpellsStore.end())
+ {
+ for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
+ addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, 0xffff, PETSPELL_FAMILY);
+ }
+}
+
+void Pet::CastPetAuras(bool current)
+{
+ Unit* owner = GetOwner();
+ if(!owner)
+ return;
+
+ if(getPetType() != HUNTER_PET && (getPetType() != SUMMON_PET || owner->getClass() != CLASS_WARLOCK))
+ return;
+
+ for(PetAuraSet::iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end(); )
+ {
+ PetAura const* pa = *itr;
+ ++itr;
+
+ if(!current && pa->IsRemovedOnChangePet())
+ owner->RemovePetAura(pa);
+ else
+ CastPetAura(pa);
+ }
+}
+
+void Pet::CastPetAura(PetAura const* aura)
+{
+ uint16 auraId = aura->GetAura(GetEntry());
+ if(!auraId)
+ return;
+
+ if(auraId == 35696) // Demonic Knowledge
+ {
+ int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
+ CastCustomSpell(this,auraId,&basePoints, NULL, NULL, true );
+ }
+ else
+ CastSpell(this, auraId, true);
+}
diff --git a/src/game/Pet.h b/src/game/Pet.h
index ea13bd5d0dc..90f7584dd2c 100644
--- a/src/game/Pet.h
+++ b/src/game/Pet.h
@@ -1,264 +1,264 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS
- *
- * Copyright (C) 2008 Trinity
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef TRINITYCORE_PET_H
-#define TRINITYCORE_PET_H
-
-#include "ObjectDefines.h"
-#include "Creature.h"
-#include "Unit.h"
-
-enum PetType
-{
- SUMMON_PET = 0,
- HUNTER_PET = 1,
- GUARDIAN_PET = 2,
- MINI_PET = 3,
- MAX_PET_TYPE = 4
-};
-
-extern char const* petTypeSuffix[MAX_PET_TYPE];
-
-enum PetSaveMode
-{
- PET_SAVE_AS_DELETED =-1,
- PET_SAVE_AS_CURRENT = 0,
- PET_SAVE_IN_STABLE_SLOT_1 = 1,
- PET_SAVE_IN_STABLE_SLOT_2 = 2,
- PET_SAVE_NOT_IN_SLOT = 3
-};
-
-enum HappinessState
-{
- UNHAPPY = 1,
- CONTENT = 2,
- HAPPY = 3
-};
-
-enum LoyaltyLevel
-{
- REBELLIOUS = 1,
- UNRULY = 2,
- SUBMISSIVE = 3,
- DEPENDABLE = 4,
- FAITHFUL = 5,
- BEST_FRIEND = 6
-};
-
-enum PetSpellState
-{
- PETSPELL_UNCHANGED = 0,
- PETSPELL_CHANGED = 1,
- PETSPELL_NEW = 2,
- PETSPELL_REMOVED = 3
-};
-
-enum PetSpellType
-{
- PETSPELL_NORMAL = 0,
- PETSPELL_FAMILY = 1,
-};
-
-struct PetSpell
-{
- uint16 slotId;
- uint16 active;
- PetSpellState state : 16;
- PetSpellType type : 16;
-};
-
-enum ActionFeedback
-{
- FEEDBACK_NONE = 0,
- FEEDBACK_PET_DEAD = 1,
- FEEDBACK_NOTHING_TO_ATT = 2,
- FEEDBACK_CANT_ATT_TARGET = 3
-};
-
-enum PetTalk
-{
- PET_TALK_SPECIAL_SPELL = 0,
- PET_TALK_ATTACK = 1
-};
-
-enum PetNameInvalidReason
-{
- PET_NAME_INVALID = 1,
- PET_NAME_NO_NAME = 2,
- PET_NAME_TOO_SHORT = 3,
- PET_NAME_TOO_LONG = 4,
- PET_NAME_MIXED_LANGUAGES = 6,
- PET_NAME_PROFANE = 7,
- PET_NAME_RESERVED = 8,
- PET_NAME_THREE_CONSECUTIVE = 11,
- PET_NAME_INVALID_SPACE = 12,
- PET_NAME_CONSECUTIVE_SPACES = 13,
- PET_NAME_RUSSIAN_CONSECUTIVE_SILENT_CHARACTERS = 14,
- PET_NAME_RUSSIAN_SILENT_CHARACTER_AT_BEGINNING_OR_END = 15,
- PET_NAME_DECLENSION_DOESNT_MATCH_BASE_NAME = 16
-};
-
-typedef UNORDERED_MAP PetSpellMap;
-typedef std::map TeachSpellMap;
-typedef std::vector AutoSpellList;
-
-#define HAPPINESS_LEVEL_SIZE 333000
-
-extern const uint32 LevelUpLoyalty[6];
-extern const uint32 LevelStartLoyalty[6];
-
-#define ACTIVE_SPELLS_MAX 4
-
-#define OWNER_MAX_DISTANCE 100
-
-#define PET_FOLLOW_DIST 1
-#define PET_FOLLOW_ANGLE (M_PI/2)
-
-class Pet : public Creature
-{
- public:
- explicit Pet(PetType type = MAX_PET_TYPE);
- virtual ~Pet();
-
- void AddToWorld();
- void RemoveFromWorld();
-
- PetType getPetType() const { return m_petType; }
- void setPetType(PetType type) { m_petType = type; }
- bool isControlled() const { return getPetType()==SUMMON_PET || getPetType()==HUNTER_PET; }
- bool isTemporarySummoned() const { return m_duration > 0; }
-
- bool Create (uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number);
- bool CreateBaseAtCreature( Creature* creature );
- bool LoadPetFromDB( Unit* owner,uint32 petentry = 0,uint32 petnumber = 0, bool current = false );
- void SavePetToDB(PetSaveMode mode);
- void Remove(PetSaveMode mode, bool returnreagent = false);
- static void DeleteFromDB(uint32 guidlow);
-
- void setDeathState(DeathState s); // overwrite virtual Creature::setDeathState and Unit::setDeathState
- void Update(uint32 diff); // overwrite virtual Creature::Update and Unit::Update
-
- uint8 GetPetAutoSpellSize() const { return m_autospells.size(); }
- uint32 GetPetAutoSpellOnPos(uint8 pos) const
- {
- if (pos >= m_autospells.size())
- return 0;
- else
- return m_autospells[pos];
- }
-
- void RegenerateFocus();
- void LooseHappiness();
- void TickLoyaltyChange();
- void ModifyLoyalty(int32 addvalue);
- HappinessState GetHappinessState();
- uint32 GetMaxLoyaltyPoints(uint32 level);
- uint32 GetStartLoyaltyPoints(uint32 level);
- void KillLoyaltyBonus(uint32 level);
- uint32 GetLoyaltyLevel() { return GetByteValue(UNIT_FIELD_BYTES_1, 1); }
- void SetLoyaltyLevel(LoyaltyLevel level);
- void GivePetXP(uint32 xp);
- void GivePetLevel(uint32 level);
- bool InitStatsForLevel(uint32 level);
- bool HaveInDiet(ItemPrototype const* item) const;
- uint32 GetCurrentFoodBenefitLevel(uint32 itemlevel);
- void SetDuration(int32 dur) { m_duration = dur; }
-
- int32 GetBonusDamage() { return m_bonusdamage; }
- void SetBonusDamage(int32 damage) { m_bonusdamage = damage; }
-
- bool UpdateStats(Stats stat);
- bool UpdateAllStats();
- void UpdateResistances(uint32 school);
- void UpdateArmor();
- void UpdateMaxHealth();
- void UpdateMaxPower(Powers power);
- void UpdateAttackPowerAndDamage(bool ranged = false);
- void UpdateDamagePhysical(WeaponAttackType attType);
-
- bool CanTakeMoreActiveSpells(uint32 SpellIconID);
- void ToggleAutocast(uint32 spellid, bool apply);
- bool HasTPForSpell(uint32 spellid);
- int32 GetTPForSpell(uint32 spellid);
-
- bool HasSpell(uint32 spell) const;
- void AddTeachSpell(uint32 learned_id, uint32 source_id) { m_teachspells[learned_id] = source_id; }
-
- void LearnPetPassives();
- void CastPetAuras(bool current);
- void CastPetAura(PetAura const* aura);
-
- void _LoadSpellCooldowns();
- void _SaveSpellCooldowns();
- void _LoadAuras(uint32 timediff);
- void _SaveAuras();
- void _LoadSpells();
- void _SaveSpells();
-
- bool addSpell(uint16 spell_id,uint16 active = ACT_DECIDE, PetSpellState state = PETSPELL_NEW, uint16 slot_id=0xffff, PetSpellType type = PETSPELL_NORMAL);
- bool learnSpell(uint16 spell_id);
- void removeSpell(uint16 spell_id);
- bool _removeSpell(uint16 spell_id);
-
- PetSpellMap m_spells;
- TeachSpellMap m_teachspells;
- AutoSpellList m_autospells;
-
- void InitPetCreateSpells();
- void CheckLearning(uint32 spellid);
- uint32 resetTalentsCost() const;
-
- void SetTP(int32 TP);
- int32 GetDispTP();
-
- int32 m_TrainingPoints;
- uint32 m_resetTalentsCost;
- time_t m_resetTalentsTime;
-
- uint64 GetAuraUpdateMask() { return m_auraUpdateMask; }
- void SetAuraUpdateMask(uint8 slot) { m_auraUpdateMask |= (uint64(1) << slot); }
- void ResetAuraUpdateMask() { m_auraUpdateMask = 0; }
-
- DeclinedName const* GetDeclinedNames() const { return m_declinedname; }
-
- bool m_removed; // prevent overwrite pet state in DB at next Pet::Update if pet already removed(saved)
- protected:
- uint32 m_regenTimer;
- uint32 m_happinessTimer;
- uint32 m_loyaltyTimer;
- PetType m_petType;
- int32 m_duration; // time until unsummon (used mostly for summoned guardians and not used for controlled pets)
- int32 m_loyaltyPoints;
- int32 m_bonusdamage;
- uint64 m_auraUpdateMask;
-
- DeclinedName *m_declinedname;
-
- private:
- void SaveToDB(uint32, uint8) // overwrited of Creature::SaveToDB - don't must be called
- {
- assert(false);
- }
- void DeleteFromDB() // overwrited of Creature::DeleteFromDB - don't must be called
- {
- assert(false);
- }
-};
-#endif
+/*
+ * Copyright (C) 2005-2008 MaNGOS
+ *
+ * Copyright (C) 2008 Trinity
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITYCORE_PET_H
+#define TRINITYCORE_PET_H
+
+#include "ObjectDefines.h"
+#include "Creature.h"
+#include "Unit.h"
+
+enum PetType
+{
+ SUMMON_PET = 0,
+ HUNTER_PET = 1,
+ GUARDIAN_PET = 2,
+ MINI_PET = 3,
+ MAX_PET_TYPE = 4
+};
+
+extern char const* petTypeSuffix[MAX_PET_TYPE];
+
+enum PetSaveMode
+{
+ PET_SAVE_AS_DELETED =-1,
+ PET_SAVE_AS_CURRENT = 0,
+ PET_SAVE_IN_STABLE_SLOT_1 = 1,
+ PET_SAVE_IN_STABLE_SLOT_2 = 2,
+ PET_SAVE_NOT_IN_SLOT = 3
+};
+
+enum HappinessState
+{
+ UNHAPPY = 1,
+ CONTENT = 2,
+ HAPPY = 3
+};
+
+enum LoyaltyLevel
+{
+ REBELLIOUS = 1,
+ UNRULY = 2,
+ SUBMISSIVE = 3,
+ DEPENDABLE = 4,
+ FAITHFUL = 5,
+ BEST_FRIEND = 6
+};
+
+enum PetSpellState
+{
+ PETSPELL_UNCHANGED = 0,
+ PETSPELL_CHANGED = 1,
+ PETSPELL_NEW = 2,
+ PETSPELL_REMOVED = 3
+};
+
+enum PetSpellType
+{
+ PETSPELL_NORMAL = 0,
+ PETSPELL_FAMILY = 1,
+};
+
+struct PetSpell
+{
+ uint16 slotId;
+ uint16 active;
+ PetSpellState state : 16;
+ PetSpellType type : 16;
+};
+
+enum ActionFeedback
+{
+ FEEDBACK_NONE = 0,
+ FEEDBACK_PET_DEAD = 1,
+ FEEDBACK_NOTHING_TO_ATT = 2,
+ FEEDBACK_CANT_ATT_TARGET = 3
+};
+
+enum PetTalk
+{
+ PET_TALK_SPECIAL_SPELL = 0,
+ PET_TALK_ATTACK = 1
+};
+
+enum PetNameInvalidReason
+{
+ PET_NAME_INVALID = 1,
+ PET_NAME_NO_NAME = 2,
+ PET_NAME_TOO_SHORT = 3,
+ PET_NAME_TOO_LONG = 4,
+ PET_NAME_MIXED_LANGUAGES = 6,
+ PET_NAME_PROFANE = 7,
+ PET_NAME_RESERVED = 8,
+ PET_NAME_THREE_CONSECUTIVE = 11,
+ PET_NAME_INVALID_SPACE = 12,
+ PET_NAME_CONSECUTIVE_SPACES = 13,
+ PET_NAME_RUSSIAN_CONSECUTIVE_SILENT_CHARACTERS = 14,
+ PET_NAME_RUSSIAN_SILENT_CHARACTER_AT_BEGINNING_OR_END = 15,
+ PET_NAME_DECLENSION_DOESNT_MATCH_BASE_NAME = 16
+};
+
+typedef UNORDERED_MAP PetSpellMap;
+typedef std::map TeachSpellMap;
+typedef std::vector AutoSpellList;
+
+#define HAPPINESS_LEVEL_SIZE 333000
+
+extern const uint32 LevelUpLoyalty[6];
+extern const uint32 LevelStartLoyalty[6];
+
+#define ACTIVE_SPELLS_MAX 4
+
+#define OWNER_MAX_DISTANCE 100
+
+#define PET_FOLLOW_DIST 1
+#define PET_FOLLOW_ANGLE (M_PI/2)
+
+class Pet : public Creature
+{
+ public:
+ explicit Pet(PetType type = MAX_PET_TYPE);
+ virtual ~Pet();
+
+ void AddToWorld();
+ void RemoveFromWorld();
+
+ PetType getPetType() const { return m_petType; }
+ void setPetType(PetType type) { m_petType = type; }
+ bool isControlled() const { return getPetType()==SUMMON_PET || getPetType()==HUNTER_PET; }
+ bool isTemporarySummoned() const { return m_duration > 0; }
+
+ bool Create (uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number);
+ bool CreateBaseAtCreature( Creature* creature );
+ bool LoadPetFromDB( Unit* owner,uint32 petentry = 0,uint32 petnumber = 0, bool current = false );
+ void SavePetToDB(PetSaveMode mode);
+ void Remove(PetSaveMode mode, bool returnreagent = false);
+ static void DeleteFromDB(uint32 guidlow);
+
+ void setDeathState(DeathState s); // overwrite virtual Creature::setDeathState and Unit::setDeathState
+ void Update(uint32 diff); // overwrite virtual Creature::Update and Unit::Update
+
+ uint8 GetPetAutoSpellSize() const { return m_autospells.size(); }
+ uint32 GetPetAutoSpellOnPos(uint8 pos) const
+ {
+ if (pos >= m_autospells.size())
+ return 0;
+ else
+ return m_autospells[pos];
+ }
+
+ void RegenerateFocus();
+ void LooseHappiness();
+ void TickLoyaltyChange();
+ void ModifyLoyalty(int32 addvalue);
+ HappinessState GetHappinessState();
+ uint32 GetMaxLoyaltyPoints(uint32 level);
+ uint32 GetStartLoyaltyPoints(uint32 level);
+ void KillLoyaltyBonus(uint32 level);
+ uint32 GetLoyaltyLevel() { return GetByteValue(UNIT_FIELD_BYTES_1, 1); }
+ void SetLoyaltyLevel(LoyaltyLevel level);
+ void GivePetXP(uint32 xp);
+ void GivePetLevel(uint32 level);
+ bool InitStatsForLevel(uint32 level);
+ bool HaveInDiet(ItemPrototype const* item) const;
+ uint32 GetCurrentFoodBenefitLevel(uint32 itemlevel);
+ void SetDuration(int32 dur) { m_duration = dur; }
+
+ int32 GetBonusDamage() { return m_bonusdamage; }
+ void SetBonusDamage(int32 damage) { m_bonusdamage = damage; }
+
+ bool UpdateStats(Stats stat);
+ bool UpdateAllStats();
+ void UpdateResistances(uint32 school);
+ void UpdateArmor();
+ void UpdateMaxHealth();
+ void UpdateMaxPower(Powers power);
+ void UpdateAttackPowerAndDamage(bool ranged = false);
+ void UpdateDamagePhysical(WeaponAttackType attType);
+
+ bool CanTakeMoreActiveSpells(uint32 SpellIconID);
+ void ToggleAutocast(uint32 spellid, bool apply);
+ bool HasTPForSpell(uint32 spellid);
+ int32 GetTPForSpell(uint32 spellid);
+
+ bool HasSpell(uint32 spell) const;
+ void AddTeachSpell(uint32 learned_id, uint32 source_id) { m_teachspells[learned_id] = source_id; }
+
+ void LearnPetPassives();
+ void CastPetAuras(bool current);
+ void CastPetAura(PetAura const* aura);
+
+ void _LoadSpellCooldowns();
+ void _SaveSpellCooldowns();
+ void _LoadAuras(uint32 timediff);
+ void _SaveAuras();
+ void _LoadSpells();
+ void _SaveSpells();
+
+ bool addSpell(uint16 spell_id, ActiveStates active = ACT_DECIDE, PetSpellState state = PETSPELL_NEW, uint16 slot_id=0xffff, PetSpellType type = PETSPELL_NORMAL);
+ bool learnSpell(uint16 spell_id);
+ void removeSpell(uint16 spell_id);
+ bool _removeSpell(uint16 spell_id);
+
+ PetSpellMap m_spells;
+ TeachSpellMap m_teachspells;
+ AutoSpellList m_autospells;
+
+ void InitPetCreateSpells();
+ void CheckLearning(uint32 spellid);
+ uint32 resetTalentsCost() const;
+
+ void SetTP(int32 TP);
+ int32 GetDispTP();
+
+ int32 m_TrainingPoints;
+ uint32 m_resetTalentsCost;
+ time_t m_resetTalentsTime;
+
+ uint64 GetAuraUpdateMask() { return m_auraUpdateMask; }
+ void SetAuraUpdateMask(uint8 slot) { m_auraUpdateMask |= (uint64(1) << slot); }
+ void ResetAuraUpdateMask() { m_auraUpdateMask = 0; }
+
+ DeclinedName const* GetDeclinedNames() const { return m_declinedname; }
+
+ bool m_removed; // prevent overwrite pet state in DB at next Pet::Update if pet already removed(saved)
+ protected:
+ uint32 m_regenTimer;
+ uint32 m_happinessTimer;
+ uint32 m_loyaltyTimer;
+ PetType m_petType;
+ int32 m_duration; // time until unsummon (used mostly for summoned guardians and not used for controlled pets)
+ int32 m_loyaltyPoints;
+ int32 m_bonusdamage;
+ uint64 m_auraUpdateMask;
+
+ DeclinedName *m_declinedname;
+
+ private:
+ void SaveToDB(uint32, uint8) // overwrited of Creature::SaveToDB - don't must be called
+ {
+ assert(false);
+ }
+ void DeleteFromDB() // overwrited of Creature::DeleteFromDB - don't must be called
+ {
+ assert(false);
+ }
+};
+#endif
diff --git a/src/game/SharedDefines.h b/src/game/SharedDefines.h
index 481598f71ea..a9c66fa3028 100644
--- a/src/game/SharedDefines.h
+++ b/src/game/SharedDefines.h
@@ -248,7 +248,7 @@ enum ItemQualities
#define SPELL_ATTR_EX_UNK14 0x00004000 // 14
#define SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY 0x00008000 // 15 remove auras on immunity
#define SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE 0x00010000 // 16 unaffected by school immunity
-#define SPELL_ATTR_EX_UNK17 0x00020000 // 17
+#define SPELL_ATTR_EX_PET_NOT_AUTOCAST 0x00020000 // 17
#define SPELL_ATTR_EX_UNK18 0x00040000 // 18
#define SPELL_ATTR_EX_UNK19 0x00080000 // 19
#define SPELL_ATTR_EX_REQ_COMBO_POINTS1 0x00100000 // 20 Req combo points on target
diff --git a/src/game/SpellMgr.cpp b/src/game/SpellMgr.cpp
index 07a0df04450..97bf4b0d109 100644
--- a/src/game/SpellMgr.cpp
+++ b/src/game/SpellMgr.cpp
@@ -1,2077 +1,2120 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS
- *
- * Copyright (C) 2008 Trinity
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "SpellMgr.h"
-#include "ObjectMgr.h"
-#include "SpellAuraDefines.h"
-#include "ProgressBar.h"
-#include "Database/DBCStores.h"
-#include "World.h"
-#include "Chat.h"
-#include "Spell.h"
-
-SpellMgr::SpellMgr()
-{
-}
-
-SpellMgr::~SpellMgr()
-{
-}
-
-SpellMgr& SpellMgr::Instance()
-{
- static SpellMgr spellMgr;
- return spellMgr;
-}
-
-int32 GetSpellDuration(SpellEntry const *spellInfo)
-{
- if(!spellInfo)
- return 0;
- SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
- if(!du)
- return 0;
- return (du->Duration[0] == -1) ? -1 : abs(du->Duration[0]);
-}
-
-int32 GetSpellMaxDuration(SpellEntry const *spellInfo)
-{
- if(!spellInfo)
- return 0;
- SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
- if(!du)
- return 0;
- return (du->Duration[2] == -1) ? -1 : abs(du->Duration[2]);
-}
-
-uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell)
-{
- SpellCastTimesEntry const *spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->CastingTimeIndex);
-
- // not all spells have cast time index and this is all is pasiive abilities
- if(!spellCastTimeEntry)
- return 0;
-
- int32 castTime = spellCastTimeEntry->CastTime;
-
- if (spell)
- {
- if(Player* modOwner = spell->GetCaster()->GetSpellModOwner())
- modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell);
-
- if( !(spellInfo->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_UNK5)) )
- castTime = int32(castTime * spell->GetCaster()->GetFloatValue(UNIT_MOD_CAST_SPEED));
- else
- {
- if (spell->IsRangedSpell() && !spell->IsAutoRepeat())
- castTime = int32(castTime * spell->GetCaster()->m_modAttackSpeedPct[RANGED_ATTACK]);
- }
- }
-
- if (spellInfo->Attributes & SPELL_ATTR_RANGED && (!spell || !(spell->IsAutoRepeat())))
- castTime += 500;
-
- return (castTime > 0) ? uint32(castTime) : 0;
-}
-
-bool IsPassiveSpell(uint32 spellId)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if (!spellInfo)
- return false;
- return (spellInfo->Attributes & SPELL_ATTR_PASSIVE) != 0;
-}
-
-bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
-{
- SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
- SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
- if(!spellInfo_1 || !spellInfo_2) return false;
- if(spellInfo_1->Id == spellId_2) return false;
-
- if (spellInfo_1->Effect[effIndex_1] != spellInfo_2->Effect[effIndex_2] ||
- spellInfo_1->EffectItemType[effIndex_1] != spellInfo_2->EffectItemType[effIndex_2] ||
- spellInfo_1->EffectMiscValue[effIndex_1] != spellInfo_2->EffectMiscValue[effIndex_2] ||
- spellInfo_1->EffectApplyAuraName[effIndex_1] != spellInfo_2->EffectApplyAuraName[effIndex_2])
- return false;
-
- return true;
-}
-
-int32 CompareAuraRanks(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
-{
- SpellEntry const*spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
- SpellEntry const*spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
- if(!spellInfo_1 || !spellInfo_2) return 0;
- if (spellId_1 == spellId_2) return 0;
-
- int32 diff = spellInfo_1->EffectBasePoints[effIndex_1] - spellInfo_2->EffectBasePoints[effIndex_2];
- if (spellInfo_1->EffectBasePoints[effIndex_1]+1 < 0 && spellInfo_2->EffectBasePoints[effIndex_2]+1 < 0) return -diff;
- else return diff;
-}
-
-SpellSpecific GetSpellSpecific(uint32 spellId)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if(!spellInfo)
- return SPELL_NORMAL;
-
- switch(spellInfo->SpellFamilyName)
- {
- case SPELLFAMILY_MAGE:
- {
- // family flags 18(Molten), 25(Frost/Ice), 28(Mage)
- if (spellInfo->SpellFamilyFlags & 0x12040000)
- return SPELL_MAGE_ARMOR;
-
- if ((spellInfo->SpellFamilyFlags & 0x1000000) && spellInfo->EffectApplyAuraName[0]==SPELL_AURA_MOD_CONFUSE)
- return SPELL_MAGE_POLYMORPH;
-
- break;
- }
- case SPELLFAMILY_WARRIOR:
- {
- if (spellInfo->SpellFamilyFlags & 0x00008000010000LL)
- return SPELL_POSITIVE_SHOUT;
-
- break;
- }
- case SPELLFAMILY_WARLOCK:
- {
- // only warlock curses have this
- if (spellInfo->Dispel == DISPEL_CURSE)
- return SPELL_CURSE;
-
- // family flag 37 (only part spells have family name)
- if (spellInfo->SpellFamilyFlags & 0x2000000000LL)
- return SPELL_WARLOCK_ARMOR;
-
- //seed of corruption and corruption
- if (spellInfo->SpellFamilyFlags & 0x1000000002LL)
- return SPELL_WARLOCK_CORRUPTION;
- break;
- }
- case SPELLFAMILY_HUNTER:
- {
- // only hunter stings have this
- if (spellInfo->Dispel == DISPEL_POISON)
- return SPELL_STING;
-
- break;
- }
- case SPELLFAMILY_PALADIN:
- {
- if (IsSealSpell(spellInfo))
- return SPELL_SEAL;
-
- if (spellInfo->SpellFamilyFlags & 0x10000100LL)
- return SPELL_BLESSING;
-
- if ((spellInfo->SpellFamilyFlags & 0x00000820180400LL) && (spellInfo->AttributesEx3 & 0x200))
- return SPELL_JUDGEMENT;
-
- for (int i = 0; i < 3; i++)
- {
- // only paladin auras have this
- if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
- return SPELL_AURA;
- }
- break;
- }
- case SPELLFAMILY_SHAMAN:
- {
- if (IsElementalShield(spellInfo))
- return SPELL_ELEMENTAL_SHIELD;
-
- break;
- }
-
- case SPELLFAMILY_POTION:
- return spellmgr.GetSpellElixirSpecific(spellInfo->Id);
- }
-
- // only warlock armor/skin have this (in additional to family cases)
- if( spellInfo->SpellVisual == 130 && spellInfo->SpellIconID == 89)
- {
- return SPELL_WARLOCK_ARMOR;
- }
-
- // only hunter aspects have this (but not all aspects in hunter family)
- if( spellInfo->activeIconID == 122 && (GetSpellSchoolMask(spellInfo) & SPELL_SCHOOL_MASK_NATURE) &&
- (spellInfo->Attributes & 0x50000) != 0 && (spellInfo->Attributes & 0x9000010) == 0)
- {
- return SPELL_ASPECT;
- }
-
- for(int i = 0; i < 3; i++)
- if( spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA && (
- spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_CREATURES ||
- spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_RESOURCES ||
- spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_STEALTHED ) )
- return SPELL_TRACKER;
-
- // elixirs can have different families, but potion most ofc.
- if(SpellSpecific sp = spellmgr.GetSpellElixirSpecific(spellInfo->Id))
- return sp;
-
- return SPELL_NORMAL;
-}
-
-bool IsSingleFromSpellSpecificPerCaster(uint32 spellSpec1,uint32 spellSpec2)
-{
- switch(spellSpec1)
- {
- case SPELL_SEAL:
- case SPELL_BLESSING:
- case SPELL_AURA:
- case SPELL_STING:
- case SPELL_CURSE:
- case SPELL_ASPECT:
- case SPELL_TRACKER:
- case SPELL_WARLOCK_ARMOR:
- case SPELL_MAGE_ARMOR:
- case SPELL_ELEMENTAL_SHIELD:
- case SPELL_MAGE_POLYMORPH:
- case SPELL_POSITIVE_SHOUT:
- case SPELL_JUDGEMENT:
- case SPELL_WARLOCK_CORRUPTION:
- return spellSpec1==spellSpec2;
- case SPELL_BATTLE_ELIXIR:
- return spellSpec2==SPELL_BATTLE_ELIXIR
- || spellSpec2==SPELL_FLASK_ELIXIR;
- case SPELL_GUARDIAN_ELIXIR:
- return spellSpec2==SPELL_GUARDIAN_ELIXIR
- || spellSpec2==SPELL_FLASK_ELIXIR;
- case SPELL_FLASK_ELIXIR:
- return spellSpec2==SPELL_BATTLE_ELIXIR
- || spellSpec2==SPELL_GUARDIAN_ELIXIR
- || spellSpec2==SPELL_FLASK_ELIXIR;
- default:
- return false;
- }
-}
-
-bool IsPositiveTarget(uint32 targetA, uint32 targetB)
-{
- // non-positive targets
- switch(targetA)
- {
- case TARGET_CHAIN_DAMAGE:
- case TARGET_ALL_ENEMY_IN_AREA:
- case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
- case TARGET_IN_FRONT_OF_CASTER:
- case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
- case TARGET_CURRENT_ENEMY_COORDINATES:
- case TARGET_SINGLE_ENEMY:
- return false;
- case TARGET_ALL_AROUND_CASTER:
- return (targetB == TARGET_ALL_PARTY || targetB == TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER);
- default:
- break;
- }
- if (targetB)
- return IsPositiveTarget(targetB, 0);
- return true;
-}
-
-bool IsPositiveEffect(uint32 spellId, uint32 effIndex)
-{
- SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
- if (!spellproto) return false;
-
- switch(spellId)
- {
- case 23333: // BG spell
- case 23335: // BG spell
- case 34976: // BG spell
- return true;
- case 28441: // not positive dummy spell
- case 37675: // Chaos Blast
- return false;
- }
-
- switch(spellproto->Effect[effIndex])
- {
- // always positive effects (check before target checks that provided non-positive result in some case for positive effects)
- case SPELL_EFFECT_HEAL:
- case SPELL_EFFECT_LEARN_SPELL:
- case SPELL_EFFECT_SKILL_STEP:
- case SPELL_EFFECT_HEAL_PCT:
- case SPELL_EFFECT_ENERGIZE_PCT:
- return true;
-
- // non-positive aura use
- case SPELL_EFFECT_APPLY_AURA:
- case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
- {
- switch(spellproto->EffectApplyAuraName[effIndex])
- {
- case SPELL_AURA_DUMMY:
- {
- // dummy aura can be positive or negative dependent from casted spell
- switch(spellproto->Id)
- {
- case 13139: // net-o-matic special effect
- case 23445: // evil twin
- case 38637: // Nether Exhaustion (red)
- case 38638: // Nether Exhaustion (green)
- case 38639: // Nether Exhaustion (blue)
- return false;
- default:
- break;
- }
- } break;
- case SPELL_AURA_MOD_STAT:
- case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from bas point sign (negative -> negative)
- case SPELL_AURA_MOD_HEALING_DONE:
- {
- if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
- return false;
- break;
- }
- case SPELL_AURA_ADD_TARGET_TRIGGER:
- return true;
- case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
- if(spellId != spellproto->EffectTriggerSpell[effIndex])
- {
- uint32 spellTriggeredId = spellproto->EffectTriggerSpell[effIndex];
- SpellEntry const *spellTriggeredProto = sSpellStore.LookupEntry(spellTriggeredId);
-
- if(spellTriggeredProto)
- {
- // non-positive targets of main spell return early
- for(int i = 0; i < 3; ++i)
- {
- // if non-positive trigger cast targeted to positive target this main cast is non-positive
- // this will place this spell auras as debuffs
- if(IsPositiveTarget(spellTriggeredProto->EffectImplicitTargetA[effIndex],spellTriggeredProto->EffectImplicitTargetB[effIndex]) && !IsPositiveEffect(spellTriggeredId,i))
- return false;
- }
- }
- }
- break;
- case SPELL_AURA_PROC_TRIGGER_SPELL:
- // many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example)
- break;
- case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment.
- if(effIndex==0 && spellproto->Effect[1]==0 && spellproto->Effect[2]==0)
- return false; // but all single stun aura spells is negative
-
- // Petrification
- if(spellproto->Id == 17624)
- return false;
- break;
- case SPELL_AURA_MOD_ROOT:
- case SPELL_AURA_MOD_SILENCE:
- case SPELL_AURA_GHOST:
- case SPELL_AURA_PERIODIC_LEECH:
- case SPELL_AURA_MOD_PACIFY_SILENCE:
- case SPELL_AURA_MOD_STALKED:
- case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
- return false;
- case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also.
- // part of negative spell if casted at self (prevent cancel)
- if(spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF)
- return false;
- break;
- case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also
- // part of positive spell if casted at self
- if(spellproto->EffectImplicitTargetA[effIndex] != TARGET_SELF)
- return false;
- // but not this if this first effect (don't found batter check)
- if(spellproto->Attributes & 0x4000000 && effIndex==0)
- return false;
- break;
- case SPELL_AURA_TRANSFORM:
- // some spells negative
- switch(spellproto->Id)
- {
- case 36897: // Transporter Malfunction (race mutation to horde)
- case 36899: // Transporter Malfunction (race mutation to alliance)
- return false;
- }
- break;
- case SPELL_AURA_MOD_SCALE:
- // some spells negative
- switch(spellproto->Id)
- {
- case 36900: // Soul Split: Evil!
- case 36901: // Soul Split: Good
- case 36893: // Transporter Malfunction (decrease size case)
- case 36895: // Transporter Malfunction (increase size case)
- return false;
- }
- break;
- case SPELL_AURA_MECHANIC_IMMUNITY:
- {
- // non-positive immunities
- switch(spellproto->EffectMiscValue[effIndex])
- {
- case MECHANIC_BANDAGE:
- case MECHANIC_SHIELD:
- case MECHANIC_MOUNT:
- case MECHANIC_INVULNERABILITY:
- return false;
- default:
- break;
- }
- } break;
- case SPELL_AURA_ADD_FLAT_MODIFIER: // mods
- case SPELL_AURA_ADD_PCT_MODIFIER:
- {
- // non-positive mods
- switch(spellproto->EffectMiscValue[effIndex])
- {
- case SPELLMOD_COST: // dependent from bas point sign (negative -> positive)
- if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) > 0)
- return false;
- break;
- default:
- break;
- }
- } break;
- case SPELL_AURA_MOD_HEALING_PCT:
- if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
- return false;
- break;
- case SPELL_AURA_MOD_SKILL:
- if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
- return false;
- break;
- case SPELL_AURA_FORCE_REACTION:
- if(spellproto->Id==42792) // Recently Dropped Flag (prevent cancel)
- return false;
- break;
- default:
- break;
- }
- break;
- }
- default:
- break;
- }
-
- // non-positive targets
- if(!IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex]))
- return false;
-
- // AttributesEx check
- if(spellproto->AttributesEx & (1<<7))
- return false;
-
- // ok, positive
- return true;
-}
-
-bool IsPositiveSpell(uint32 spellId)
-{
- SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
- if (!spellproto) return false;
-
- // spells with at least one negative effect are considered negative
- // some self-applied spells have negative effects but in self casting case negative check ignored.
- for (int i = 0; i < 3; i++)
- if (!IsPositiveEffect(spellId, i))
- return false;
- return true;
-}
-
-bool IsSingleTargetSpell(SpellEntry const *spellInfo)
-{
- // all other single target spells have if it has AttributesEx5
- if ( spellInfo->AttributesEx5 & SPELL_ATTR_EX5_SINGLE_TARGET_SPELL )
- return true;
-
- // TODO - need found Judgements rule
- switch(GetSpellSpecific(spellInfo->Id))
- {
- case SPELL_JUDGEMENT:
- return true;
- }
-
- // single target triggered spell.
- // Not real client side single target spell, but it' not triggered until prev. aura expired.
- // This is allow store it in single target spells list for caster for spell proc checking
- if(spellInfo->Id==38324) // Regeneration (triggered by 38299 (HoTs on Heals))
- return true;
-
- return false;
-}
-
-bool IsSingleTargetSpells(SpellEntry const *spellInfo1, SpellEntry const *spellInfo2)
-{
- // TODO - need better check
- // Equal icon and spellfamily
- if( spellInfo1->SpellFamilyName == spellInfo2->SpellFamilyName &&
- spellInfo1->SpellIconID == spellInfo2->SpellIconID )
- return true;
-
- // TODO - need found Judgements rule
- SpellSpecific spec1 = GetSpellSpecific(spellInfo1->Id);
- // spell with single target specific types
- switch(spec1)
- {
- case SPELL_JUDGEMENT:
- if(GetSpellSpecific(spellInfo2->Id) == spec1)
- return true;
- break;
- }
-
- return false;
-}
-
-uint8 GetErrorAtShapeshiftedCast (SpellEntry const *spellInfo, uint32 form)
-{
- // talents that learn spells can have stance requirements that need ignore
- // (this requirement only for client-side stance show in talent description)
- if( GetTalentSpellCost(spellInfo->Id) > 0 &&
- (spellInfo->Effect[0]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[1]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[2]==SPELL_EFFECT_LEARN_SPELL) )
- return 0;
-
- uint32 stanceMask = (form ? 1 << (form - 1) : 0);
-
- if (stanceMask & spellInfo->StancesNot) // can explicitly not be casted in this stance
- return SPELL_FAILED_NOT_SHAPESHIFT;
-
- if (stanceMask & spellInfo->Stances) // can explicitly be casted in this stance
- return 0;
-
- bool actAsShifted = false;
- if (form > 0)
- {
- SpellShapeshiftEntry const *shapeInfo = sSpellShapeshiftStore.LookupEntry(form);
- if (!shapeInfo)
- {
- sLog.outError("GetErrorAtShapeshiftedCast: unknown shapeshift %u", form);
- return 0;
- }
- actAsShifted = !(shapeInfo->flags1 & 1); // shapeshift acts as normal form for spells
- }
-
- if(actAsShifted)
- {
- if (spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT) // not while shapeshifted
- return SPELL_FAILED_NOT_SHAPESHIFT;
- else if (spellInfo->Stances != 0) // needs other shapeshift
- return SPELL_FAILED_ONLY_SHAPESHIFT;
- }
- else
- {
- // needs shapeshift
- if(!(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && spellInfo->Stances != 0)
- return SPELL_FAILED_ONLY_SHAPESHIFT;
- }
-
- return 0;
-}
-
-void SpellMgr::LoadSpellTargetPositions()
-{
- mSpellTargetPositions.clear(); // need for reload case
-
- uint32 count = 0;
-
- // 0 1 2 3 4 5
- QueryResult *result = WorldDatabase.Query("SELECT id, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM spell_target_position");
- if( !result )
- {
-
- barGoLink bar( 1 );
-
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell target coordinates", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- ++count;
-
- uint32 Spell_ID = fields[0].GetUInt32();
-
- SpellTargetPosition st;
-
- st.target_mapId = fields[1].GetUInt32();
- st.target_X = fields[2].GetFloat();
- st.target_Y = fields[3].GetFloat();
- st.target_Z = fields[4].GetFloat();
- st.target_Orientation = fields[5].GetFloat();
-
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(Spell_ID);
- if(!spellInfo)
- {
- sLog.outErrorDb("Spell (ID:%u) listed in `spell_target_position` does not exist.",Spell_ID);
- continue;
- }
-
- bool found = false;
- for(int i = 0; i < 3; ++i)
- {
- if( spellInfo->EffectImplicitTargetA[i]==TARGET_TABLE_X_Y_Z_COORDINATES || spellInfo->EffectImplicitTargetB[i]==TARGET_TABLE_X_Y_Z_COORDINATES )
- {
- found = true;
- break;
- }
- }
- if(!found)
- {
- sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` does not have target TARGET_TABLE_X_Y_Z_COORDINATES (17).",Spell_ID);
- continue;
- }
-
- MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId);
- if(!mapEntry)
- {
- sLog.outErrorDb("Spell (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Spell_ID,st.target_mapId);
- continue;
- }
-
- if(st.target_X==0 && st.target_Y==0 && st.target_Z==0)
- {
- sLog.outErrorDb("Spell (ID:%u) target coordinates not provided.",Spell_ID);
- continue;
- }
-
- mSpellTargetPositions[Spell_ID] = st;
-
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell teleport coordinates", count );
-}
-
-void SpellMgr::LoadSpellAffects()
-{
- mSpellAffectMap.clear(); // need for reload case
-
- uint32 count = 0;
-
- // 0 1 2
- QueryResult *result = WorldDatabase.Query("SELECT entry, effectId, SpellFamilyMask FROM spell_affect");
- if( !result )
- {
-
- barGoLink bar( 1 );
-
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell affect definitions", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- uint16 entry = fields[0].GetUInt16();
- uint8 effectId = fields[1].GetUInt8();
-
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
-
- if (!spellInfo)
- {
- sLog.outErrorDb("Spell %u listed in `spell_affect` does not exist", entry);
- continue;
- }
-
- if (effectId >= 3)
- {
- sLog.outErrorDb("Spell %u listed in `spell_affect` have invalid effect index (%u)", entry,effectId);
- continue;
- }
-
- if( spellInfo->Effect[effectId] != SPELL_EFFECT_APPLY_AURA ||
- spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_FLAT_MODIFIER &&
- spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_PCT_MODIFIER &&
- spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_TARGET_TRIGGER )
- {
- sLog.outErrorDb("Spell %u listed in `spell_affect` have not SPELL_AURA_ADD_FLAT_MODIFIER (%u) or SPELL_AURA_ADD_PCT_MODIFIER (%u) or SPELL_AURA_ADD_TARGET_TRIGGER (%u) for effect index (%u)", entry,SPELL_AURA_ADD_FLAT_MODIFIER,SPELL_AURA_ADD_PCT_MODIFIER,SPELL_AURA_ADD_TARGET_TRIGGER,effectId);
- continue;
- }
-
- uint64 spellAffectMask = fields[2].GetUInt64();
-
- // Spell.dbc have own data for low part of SpellFamilyMask
- if( spellInfo->EffectItemType[effectId])
- {
- if(spellInfo->EffectItemType[effectId] == spellAffectMask)
- {
- sLog.outErrorDb("Spell %u listed in `spell_affect` have redundant (same with EffectItemType%d) data for effect index (%u) and not needed, skipped.", entry,effectId+1,effectId);
- continue;
- }
-
- // 24429 have wrong data in EffectItemType and overwrites by DB, possible bug in client
- if(spellInfo->Id!=24429 && spellInfo->EffectItemType[effectId] != spellAffectMask)
- {
- sLog.outErrorDb("Spell %u listed in `spell_affect` have different low part from EffectItemType%d for effect index (%u) and not needed, skipped.", entry,effectId+1,effectId);
- continue;
- }
- }
-
- mSpellAffectMap.insert(SpellAffectMap::value_type((entry<<8) + effectId,spellAffectMask));
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell affect definitions", count );
-
- for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id)
- {
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
- if (!spellInfo)
- continue;
-
- for (int effectId = 0; effectId < 3; ++effectId)
- {
- if( spellInfo->Effect[effectId] != SPELL_EFFECT_APPLY_AURA ||
- (spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_FLAT_MODIFIER &&
- spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_PCT_MODIFIER &&
- spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_TARGET_TRIGGER) )
- continue;
-
- if(spellInfo->EffectItemType[effectId] != 0)
- continue;
-
- if(mSpellAffectMap.find((id<<8) + effectId) != mSpellAffectMap.end())
- continue;
-
- sLog.outErrorDb("Spell %u (%s) misses spell_affect for effect %u",id,spellInfo->SpellName[sWorld.GetDefaultDbcLocale()], effectId);
- }
- }
-}
-
-bool SpellMgr::IsAffectedBySpell(SpellEntry const *spellInfo, uint32 spellId, uint8 effectId, uint64 familyFlags) const
-{
- // false for spellInfo == NULL
- if (!spellInfo)
- return false;
-
- SpellEntry const *affect_spell = sSpellStore.LookupEntry(spellId);
- // false for affect_spell == NULL
- if (!affect_spell)
- return false;
-
- // False if spellFamily not equal
- if (affect_spell->SpellFamilyName != spellInfo->SpellFamilyName)
- return false;
-
- // If familyFlags == 0
- if (!familyFlags)
- {
- // Get it from spellAffect table
- familyFlags = GetSpellAffectMask(spellId,effectId);
- // false if familyFlags == 0
- if (!familyFlags)
- return false;
- }
-
- // true
- if (familyFlags & spellInfo->SpellFamilyFlags)
- return true;
-
- return false;
-}
-
-void SpellMgr::LoadSpellProcEvents()
-{
- mSpellProcEventMap.clear(); // need for reload case
-
- uint32 count = 0;
-
- // 0 1 2 3 4 5 6 7 8
- QueryResult *result = WorldDatabase.Query("SELECT entry, SchoolMask, Category, SkillID, SpellFamilyName, SpellFamilyMask, procFlags, ppmRate, cooldown FROM spell_proc_event");
- if( !result )
- {
-
- barGoLink bar( 1 );
-
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell proc event conditions", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- uint16 entry = fields[0].GetUInt16();
-
- if (!sSpellStore.LookupEntry(entry))
- {
- sLog.outErrorDb("Spell %u listed in `spell_proc_event` does not exist", entry);
- continue;
- }
-
- SpellProcEventEntry spe;
-
- spe.schoolMask = fields[1].GetUInt32();
- spe.category = fields[2].GetUInt32();
- spe.skillId = fields[3].GetUInt32();
- spe.spellFamilyName = fields[4].GetUInt32();
- spe.spellFamilyMask = fields[5].GetUInt64();
- spe.procFlags = fields[6].GetUInt32();
- spe.ppmRate = fields[7].GetFloat();
- spe.cooldown = fields[8].GetUInt32();
-
- mSpellProcEventMap[entry] = spe;
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell proc event conditions", count );
-
- /*
- // Commented for now, as it still produces many errors (still quite many spells miss spell_proc_event)
- for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id)
- {
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
- if (!spellInfo)
- continue;
-
- bool found = false;
- for (int effectId = 0; effectId < 3; ++effectId)
- {
- // at this moment check only SPELL_AURA_PROC_TRIGGER_SPELL
- if( spellInfo->EffectApplyAuraName[effectId] == SPELL_AURA_PROC_TRIGGER_SPELL )
- {
- found = true;
- break;
- }
- }
-
- if(!found)
- continue;
-
- if(GetSpellProcEvent(id))
- continue;
-
- sLog.outErrorDb("Spell %u (%s) misses spell_proc_event",id,spellInfo->SpellName[sWorld.GetDBClang()]);
- }
- */
-}
-
-bool SpellMgr::IsSpellProcEventCanTriggeredBy( SpellProcEventEntry const * spellProcEvent, SpellEntry const * procSpell, uint32 procFlags )
-{
- if((procFlags & spellProcEvent->procFlags) == 0)
- return false;
-
- // Additional checks in case spell cast/hit/crit is the event
- // Check (if set) school, category, skill line, spell talent mask
- if(spellProcEvent->schoolMask && (!procSpell || (GetSpellSchoolMask(procSpell) & spellProcEvent->schoolMask) == 0))
- return false;
- if(spellProcEvent->category && (!procSpell || procSpell->Category != spellProcEvent->category))
- return false;
- if(spellProcEvent->skillId)
- {
- if (!procSpell)
- return false;
-
- SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(procSpell->Id);
- SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(procSpell->Id);
-
- bool found = false;
- for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
- {
- if(_spell_idx->second->skillId == spellProcEvent->skillId)
- {
- found = true;
- break;
- }
- }
- if (!found)
- return false;
- }
- if(spellProcEvent->spellFamilyName && (!procSpell || spellProcEvent->spellFamilyName != procSpell->SpellFamilyName))
- return false;
- if(spellProcEvent->spellFamilyMask && (!procSpell || (spellProcEvent->spellFamilyMask & procSpell->SpellFamilyFlags) == 0))
- return false;
-
- return true;
-}
-
-void SpellMgr::LoadSpellElixirs()
-{
- mSpellElixirs.clear(); // need for reload case
-
- uint32 count = 0;
-
- // 0 1
- QueryResult *result = WorldDatabase.Query("SELECT entry, mask FROM spell_elixir");
- if( !result )
- {
-
- barGoLink bar( 1 );
-
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell elixir definitions", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- uint16 entry = fields[0].GetUInt16();
- uint8 mask = fields[1].GetUInt8();
-
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
-
- if (!spellInfo)
- {
- sLog.outErrorDb("Spell %u listed in `spell_elixir` does not exist", entry);
- continue;
- }
-
- mSpellElixirs[entry] = mask;
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell elixir definitions", count );
-}
-
-void SpellMgr::LoadSpellThreats()
-{
- sSpellThreatStore.Free(); // for reload
-
- sSpellThreatStore.Load();
-
- sLog.outString( ">> Loaded %u aggro generating spells", sSpellThreatStore.RecordCount );
- sLog.outString();
-}
-
-bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const
-{
- SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
- if(!spellInfo_1 || !spellInfo_2) return false;
- if(spellInfo_1->Id == spellId_2) return false;
-
- return GetFirstSpellInChain(spellInfo_1->Id)==GetFirstSpellInChain(spellId_2);
-}
-
-bool SpellMgr::canStackSpellRanks(SpellEntry const *spellInfo)
-{
- if(spellInfo->powerType != POWER_MANA && spellInfo->powerType != POWER_HEALTH)
- return false;
- if(IsProfessionSpell(spellInfo->Id))
- return false;
-
- // All stance spells. if any better way, change it.
- for (int i = 0; i < 3; i++)
- {
- // Paladin aura Spell
- if(spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN
- && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
- return false;
- // Druid form Spell
- if(spellInfo->SpellFamilyName == SPELLFAMILY_DRUID
- && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA
- && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
- return false;
- // Rogue Stealth
- if(spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE
- && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA
- && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
- return false;
- }
- return true;
-}
-
-bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) const
-{
- if(spellId_1 == spellId_2) // auras due to the same spell
- return false;
-
- SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
- SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
-
- if(!spellInfo_1 || !spellInfo_2)
- return false;
-
- if(spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName)
- return false;
-
- if(!spellInfo_1->SpellFamilyName) // generic spells
- {
- if(!spellInfo_1->SpellIconID
- || spellInfo_1->SpellIconID != spellInfo_2->SpellIconID)
- return false;
- }
- else if (spellInfo_1->SpellFamilyFlags != spellInfo_2->SpellFamilyFlags)
- return false;
-
- for(uint32 i = 0; i < 3; ++i)
- if(spellInfo_1->Effect[i] != spellInfo_2->Effect[i]
- || spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i])
- return false;
-
- return true;
-}
-
-bool SpellMgr::IsProfessionSpell(uint32 spellId)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if(!spellInfo)
- return false;
-
- if(spellInfo->Effect[1] != SPELL_EFFECT_SKILL)
- return false;
-
- uint32 skill = spellInfo->EffectMiscValue[1];
-
- return IsProfessionSkill(skill);
-}
-
-bool SpellMgr::IsPrimaryProfessionSpell(uint32 spellId)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if(!spellInfo)
- return false;
-
- if(spellInfo->Effect[1] != SPELL_EFFECT_SKILL)
- return false;
-
- uint32 skill = spellInfo->EffectMiscValue[1];
-
- return IsPrimaryProfessionSkill(skill);
-}
-
-bool SpellMgr::IsPrimaryProfessionFirstRankSpell(uint32 spellId) const
-{
- return IsPrimaryProfessionSpell(spellId) && GetSpellRank(spellId)==1;
-}
-
-SpellEntry const* SpellMgr::SelectAuraRankForPlayerLevel(SpellEntry const* spellInfo, uint32 playerLevel) const
-{
- // ignore passive spells
- if(IsPassiveSpell(spellInfo->Id))
- return spellInfo;
-
- bool needRankSelection = false;
- for(int i=0;i<3;i++)
- {
- if( IsPositiveEffect(spellInfo->Id, i) && (
- spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA ||
- spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY
- ) )
- {
- needRankSelection = true;
- break;
- }
- }
-
- // not required
- if(!needRankSelection)
- return spellInfo;
-
- for(uint32 nextSpellId = spellInfo->Id; nextSpellId != 0; nextSpellId = GetPrevSpellInChain(nextSpellId))
- {
- SpellEntry const *nextSpellInfo = sSpellStore.LookupEntry(nextSpellId);
- if(!nextSpellInfo)
- break;
-
- // if found appropriate level
- if(playerLevel + 10 >= nextSpellInfo->spellLevel)
- return nextSpellInfo;
-
- // one rank less then
- }
-
- // not found
- return NULL;
-}
-
-void SpellMgr::LoadSpellChains()
-{
- mSpellChains.clear(); // need for reload case
- mSpellChainsNext.clear(); // need for reload case
-
- QueryResult *result = WorldDatabase.Query("SELECT spell_id, prev_spell, first_spell, rank, req_spell FROM spell_chain");
- if(result == NULL)
- {
- barGoLink bar( 1 );
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded 0 spell chain records" );
- sLog.outErrorDb("`spell_chains` table is empty!");
- return;
- }
-
- uint32 count = 0;
-
- barGoLink bar( result->GetRowCount() );
- do
- {
- bar.step();
- Field *fields = result->Fetch();
-
- uint32 spell_id = fields[0].GetUInt32();
-
- SpellChainNode node;
- node.prev = fields[1].GetUInt32();
- node.first = fields[2].GetUInt32();
- node.rank = fields[3].GetUInt8();
- node.req = fields[4].GetUInt32();
-
- if(!sSpellStore.LookupEntry(spell_id))
- {
- sLog.outErrorDb("Spell %u listed in `spell_chain` does not exist",spell_id);
- continue;
- }
-
- if(node.prev!=0 && !sSpellStore.LookupEntry(node.prev))
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existed previous rank spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- if(!sSpellStore.LookupEntry(node.first))
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing first rank spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- // check basic spell chain data integrity (note: rank can be equal 0 or 1 for first/single spell)
- if( (spell_id == node.first) != (node.rank <= 1) ||
- (spell_id == node.first) != (node.prev == 0) ||
- (node.rank <= 1) != (node.prev == 0) )
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not compatible chain data.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- if(node.req!=0 && !sSpellStore.LookupEntry(node.req))
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing required spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- // talents not required data in spell chain for work, but must be checked if present for intergrity
- if(TalentSpellPos const* pos = GetTalentSpellPos(spell_id))
- {
- if(node.rank!=pos->rank+1)
- {
- sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong rank.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- if(TalentEntry const* talentEntry = sTalentStore.LookupEntry(pos->talent_id))
- {
- if(node.first!=talentEntry->RankID[0])
- {
- sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong first rank spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- if(node.rank > 1 && node.prev != talentEntry->RankID[node.rank-1-1])
- {
- sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong prev rank spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
-
- if(node.req!=talentEntry->DependsOnSpell)
- {
- sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong required spell.",
- spell_id,node.prev,node.first,node.rank,node.req);
- continue;
- }
- }
- }
-
- mSpellChains[spell_id] = node;
-
- if(node.prev)
- mSpellChainsNext.insert(SpellChainMapNext::value_type(node.prev,spell_id));
-
- if(node.req)
- mSpellChainsNext.insert(SpellChainMapNext::value_type(node.req,spell_id));
-
- ++count;
- } while( result->NextRow() );
-
- // additional integrity checks
- for(SpellChainMap::iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i)
- {
- if(i->second.prev)
- {
- SpellChainMap::iterator i_prev = mSpellChains.find(i->second.prev);
- if(i_prev == mSpellChains.end())
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found previous rank spell in table.",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
- }
- else if( i_prev->second.first != i->second.first )
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different first spell in chain compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
- i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
- }
- else if( i_prev->second.rank+1 != i->second.rank )
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different rank compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
- i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
- }
- }
-
- if(i->second.req)
- {
- SpellChainMap::iterator i_req = mSpellChains.find(i->second.req);
- if(i_req == mSpellChains.end())
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found required rank spell in table.",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
- }
- else if( i_req->second.first == i->second.first )
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell from same spell chain (prev: %u, first: %u, rank: %d, req: %u).",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
- i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
- }
- else if( i_req->second.req )
- {
- sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell with required spell (prev: %u, first: %u, rank: %d, req: %u).",
- i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
- i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
- }
- }
- }
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell chain records", count );
-}
-
-void SpellMgr::LoadSpellLearnSkills()
-{
- mSpellLearnSkills.clear(); // need for reload case
-
- // search auto-learned skills and add its to map also for use in unlearn spells/talents
- uint32 dbc_count = 0;
- for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
- {
- SpellEntry const* entry = sSpellStore.LookupEntry(spell);
-
- if(!entry)
- continue;
-
- for(int i = 0; i < 3; ++i)
- {
- if(entry->Effect[i]==SPELL_EFFECT_SKILL)
- {
- SpellLearnSkillNode dbc_node;
- dbc_node.skill = entry->EffectMiscValue[i];
- if ( dbc_node.skill != SKILL_RIDING )
- dbc_node.value = 1;
- else
- dbc_node.value = (entry->EffectBasePoints[i]+1)*75;
- dbc_node.maxvalue = (entry->EffectBasePoints[i]+1)*75;
-
- SpellLearnSkillNode const* db_node = GetSpellLearnSkill(spell);
-
- mSpellLearnSkills[spell] = dbc_node;
- ++dbc_count;
- break;
- }
- }
- }
-
- sLog.outString();
- sLog.outString( ">> Loaded %u Spell Learn Skills from DBC", dbc_count );
-}
-
-void SpellMgr::LoadSpellLearnSpells()
-{
- mSpellLearnSpells.clear(); // need for reload case
-
- QueryResult *result = WorldDatabase.Query("SELECT entry, SpellID FROM spell_learn_spell");
- if(!result)
- {
- barGoLink bar( 1 );
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded 0 spell learn spells" );
- sLog.outErrorDb("`spell_learn_spell` table is empty!");
- return;
- }
-
- uint32 count = 0;
-
- barGoLink bar( result->GetRowCount() );
- do
- {
- bar.step();
- Field *fields = result->Fetch();
-
- uint32 spell_id = fields[0].GetUInt32();
-
- SpellLearnSpellNode node;
- node.spell = fields[1].GetUInt32();
- node.autoLearned= false;
-
- if(!sSpellStore.LookupEntry(spell_id))
- {
- sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",spell_id);
- continue;
- }
-
- if(!sSpellStore.LookupEntry(node.spell))
- {
- sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",node.spell);
- continue;
- }
-
- mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell_id,node));
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- // search auto-learned spells and add its to map also for use in unlearn spells/talents
- uint32 dbc_count = 0;
- for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
- {
- SpellEntry const* entry = sSpellStore.LookupEntry(spell);
-
- if(!entry)
- continue;
-
- for(int i = 0; i < 3; ++i)
- {
- if(entry->Effect[i]==SPELL_EFFECT_LEARN_SPELL)
- {
- SpellLearnSpellNode dbc_node;
- dbc_node.spell = entry->EffectTriggerSpell[i];
- dbc_node.autoLearned = true;
-
- SpellLearnSpellMap::const_iterator db_node_begin = GetBeginSpellLearnSpell(spell);
- SpellLearnSpellMap::const_iterator db_node_end = GetEndSpellLearnSpell(spell);
-
- bool found = false;
- for(SpellLearnSpellMap::const_iterator itr = db_node_begin; itr != db_node_end; ++itr)
- {
- if(itr->second.spell == dbc_node.spell)
- {
- sLog.outErrorDb("Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.",
- spell,dbc_node.spell);
- found = true;
- break;
- }
- }
-
- if(!found) // add new spell-spell pair if not found
- {
- mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell,dbc_node));
- ++dbc_count;
- }
- }
- }
- }
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell learn spells + %u found in DBC", count, dbc_count );
-}
-
-void SpellMgr::LoadSpellScriptTarget()
-{
- mSpellScriptTarget.clear(); // need for reload case
-
- uint32 count = 0;
-
- QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM spell_script_target");
-
- if(!result)
- {
- barGoLink bar(1);
-
- bar.step();
-
- sLog.outString();
- sLog.outErrorDb(">> Loaded 0 SpellScriptTarget. DB table `spell_script_target` is empty.");
- return;
- }
-
- barGoLink bar(result->GetRowCount());
-
- do
- {
- Field *fields = result->Fetch();
- bar.step();
-
- uint32 spellId = fields[0].GetUInt32();
- uint32 type = fields[1].GetUInt32();
- uint32 targetEntry = fields[2].GetUInt32();
-
- SpellEntry const* spellProto = sSpellStore.LookupEntry(spellId);
-
- if(!spellProto)
- {
- sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not exist.",spellId,targetEntry);
- continue;
- }
-
- /*bool targetfound = false;
- for(int i = 0; i <3; ++i)
- {
- if( spellProto->EffectImplicitTargetA[i]==TARGET_SCRIPT ||
- spellProto->EffectImplicitTargetB[i]==TARGET_SCRIPT ||
- spellProto->EffectImplicitTargetA[i]==TARGET_SCRIPT_COORDINATES ||
- spellProto->EffectImplicitTargetB[i]==TARGET_SCRIPT_COORDINATES )
- {
- targetfound = true;
- break;
- }
- }
- if(!targetfound)
- {
- sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not have any implicit target TARGET_SCRIPT(38) or TARGET_SCRIPT_COORDINATES (46).",spellId,targetEntry);
- continue;
- }*/
-
- if( type >= MAX_SPELL_TARGET_TYPE )
- {
- sLog.outErrorDb("Table `spell_script_target`: target type %u for TargetEntry %u is incorrect.",type,targetEntry);
- continue;
- }
-
- switch(type)
- {
- case SPELL_TARGET_TYPE_GAMEOBJECT:
- {
- if( targetEntry==0 )
- break;
-
- if(!sGOStorage.LookupEntry(targetEntry))
- {
- sLog.outErrorDb("Table `spell_script_target`: gameobject template entry %u does not exist.",targetEntry);
- continue;
- }
- break;
- }
- default:
- {
- if( targetEntry==0 )
- {
- sLog.outErrorDb("Table `spell_script_target`: target entry == 0 for not GO target type (%u).",type);
- continue;
- }
- if(!sCreatureStorage.LookupEntry(targetEntry))
- {
- sLog.outErrorDb("Table `spell_script_target`: creature template entry %u does not exist.",targetEntry);
- continue;
- }
- const CreatureInfo* cInfo = sCreatureStorage.LookupEntry(targetEntry);
-
- if(spellId == 30427 && !cInfo->SkinLootId)
- {
- sLog.outErrorDb("Table `spell_script_target` has creature %u as a target of spellid 30427, but this creature has no skinlootid. Gas extraction will not work!", cInfo->Entry);
- continue;
- }
- break;
- }
- }
-
- mSpellScriptTarget.insert(SpellScriptTarget::value_type(spellId,SpellTargetEntry(SpellTargetType(type),targetEntry)));
-
- ++count;
- } while (result->NextRow());
-
- delete result;
-
- // Check all spells
- /* Disabled (lot errors at this moment)
- for(uint32 i = 1; i < sSpellStore.nCount; ++i)
- {
- SpellEntry const * spellInfo = sSpellStore.LookupEntry(i);
- if(!spellInfo)
- continue;
-
- bool found = false;
- for(int j=0; j<3; ++j)
- {
- if( spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT || spellInfo->EffectImplicitTargetA[j] != TARGET_SELF && spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT )
- {
- SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(spellInfo->Id);
- SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(spellInfo->Id);
- if(lower==upper)
- {
- sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = %u (TARGET_SCRIPT), but does not have record in `spell_script_target`",spellInfo->Id,TARGET_SCRIPT);
- break; // effects of spell
- }
- }
- }
- }
- */
-
- sLog.outString();
- sLog.outString(">> Loaded %u Spell Script Targets", count);
-}
-
-void SpellMgr::LoadSpellPetAuras()
-{
- mSpellPetAuraMap.clear(); // need for reload case
-
- uint32 count = 0;
-
- // 0 1 2
- QueryResult *result = WorldDatabase.Query("SELECT spell, pet, aura FROM spell_pet_auras");
- if( !result )
- {
-
- barGoLink bar( 1 );
-
- bar.step();
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell pet auras", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- uint16 spell = fields[0].GetUInt16();
- uint16 pet = fields[1].GetUInt16();
- uint16 aura = fields[2].GetUInt16();
-
- SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find(spell);
- if(itr != mSpellPetAuraMap.end())
- {
- itr->second.AddAura(pet, aura);
- }
- else
- {
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
- if (!spellInfo)
- {
- sLog.outErrorDb("Spell %u listed in `spell_pet_auras` does not exist", spell);
- continue;
- }
- int i = 0;
- for(; i < 3; ++i)
- if((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA &&
- spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DUMMY) ||
- spellInfo->Effect[i] == SPELL_EFFECT_DUMMY)
- break;
-
- if(i == 3)
- {
- sLog.outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell);
- continue;
- }
-
- SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(aura);
- if (!spellInfo2)
- {
- sLog.outErrorDb("Aura %u listed in `spell_pet_auras` does not exist", aura);
- continue;
- }
-
- PetAura pa(pet, aura, spellInfo->EffectImplicitTargetA[i] == TARGET_PET, spellInfo->EffectBasePoints[i] + spellInfo->EffectBaseDice[i]);
- mSpellPetAuraMap[spell] = pa;
- }
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u spell pet auras", count );
-}
-
-// set data in core for now
-void SpellMgr::LoadSpellCustomAttr()
-{
- SpellEntry *tempSpell;
- for(uint32 i = 0; i < GetSpellStore()->GetNumRows(); ++i)
- {
- tempSpell = (SpellEntry*)GetSpellStore()->LookupEntry(i);
- if(!tempSpell)
- continue;
-
- mSpellCustomAttrMap[tempSpell->Id] = 0;
-
- for(uint32 i = 0; i < 3; ++i)
- {
- switch(tempSpell->EffectApplyAuraName[i])
- {
- case SPELL_AURA_PERIODIC_DAMAGE:
- case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
- case SPELL_AURA_PERIODIC_LEECH:
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_EFFECT_DAMAGE;
- break;
- case SPELL_AURA_PERIODIC_HEAL:
- case SPELL_AURA_OBS_MOD_HEALTH:
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_EFFECT_HEAL;
- break;
- default:
- break;
- }
- }
-
- if(tempSpell->SpellVisual == 3879)
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_CONE_BACK;
-
- switch(tempSpell->Id)
- {
- case 26029: // dark glare
- case 37433: // spout
- case 43140: case 43215: // flame breath
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_CONE_LINE;
- break;
- case 24340: case 26558: case 28884: // Meteor
- case 36837: case 38903: case 41276: // Meteor
- case 26789: // Shard of the Fallen Star
- case 31436: // Malevolent Cleave
- case 35181: // Dive Bomb
- case 40810: case 43267: case 43268: // Saber Lash
- case 42384: // Brutal Swipe
- case 45150: // Meteor Slash
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_SHARE_DAMAGE;
- break;
- case 44978: case 45001: case 45002: // Wild Magic
- case 45004: case 45006: case 45010: // Wild Magic
- case 31347: // Doom
- case 41635: // Prayer of Mending
- case 44869: // Spectral Blast
- case 45027: // Revitalize
- case 45976: // Muru Portal Channel
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_PLAYERS_ONLY;
- tempSpell->MaxAffectedTargets = 1;
- break;
- case 41376: // Spite
- case 39992: // Needle Spine
- mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_PLAYERS_ONLY;
- tempSpell->MaxAffectedTargets = 3;
- break;
- case 8122: case 8124: case 10888: case 10890: // Psychic Scream
- tempSpell->Attributes |= SPELL_ATTR_BREAKABLE_BY_DAMAGE;
- break;
- default:
- break;
- }
- }
-}
-
-void SpellMgr::LoadSpellLinked()
-{
- mSpellLinkedMap.clear(); // need for reload case
- uint32 count = 0;
-
- // 0 1 2
- QueryResult *result = WorldDatabase.Query("SELECT spell_trigger, spell_effect, type FROM spell_linked_spell");
- if( !result )
- {
- barGoLink bar( 1 );
- bar.step();
- sLog.outString();
- sLog.outString( ">> Loaded %u linked spells", count );
- return;
- }
-
- barGoLink bar( result->GetRowCount() );
-
- do
- {
- Field *fields = result->Fetch();
-
- bar.step();
-
- int32 trigger = fields[0].GetInt32();
- int32 effect = fields[1].GetInt32();
- int32 type = fields[2].GetInt32();
-
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(trigger));
- if (!spellInfo)
- {
- sLog.outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(trigger));
- continue;
- }
- spellInfo = sSpellStore.LookupEntry(abs(effect));
- if (!spellInfo)
- {
- sLog.outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(effect));
- continue;
- }
-
- if(type) //we will find a better way when more types are needed
- trigger += 1000000;
- mSpellLinkedMap[trigger].push_back(effect);
-
- ++count;
- } while( result->NextRow() );
-
- delete result;
-
- sLog.outString();
- sLog.outString( ">> Loaded %u linked spells", count );
-}
-
-/// Some checks for spells, to prevent adding depricated/broken spells for trainers, spell book, etc
-bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg)
-{
- // not exist
- if(!spellInfo)
- return false;
-
- bool need_check_reagents = false;
-
- // check effects
- for(int i=0; i<3; ++i)
- {
- switch(spellInfo->Effect[i])
- {
- case 0:
- continue;
-
- // craft spell for crafting non-existed item (break client recipes list show)
- case SPELL_EFFECT_CREATE_ITEM:
- {
- if(!ObjectMgr::GetItemPrototype( spellInfo->EffectItemType[i] ))
- {
- if(msg)
- {
- if(pl)
- ChatHandler(pl).PSendSysMessage("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
- else
- sLog.outErrorDb("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
- }
- return false;
- }
-
- need_check_reagents = true;
- break;
- }
- case SPELL_EFFECT_LEARN_SPELL:
- {
- SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(spellInfo->EffectTriggerSpell[0]);
- if( !IsSpellValid(spellInfo2,pl,msg) )
- {
- if(msg)
- {
- if(pl)
- ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[0]);
- else
- sLog.outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[0]);
- }
- return false;
- }
- break;
- }
- }
- }
-
- if(need_check_reagents)
- {
- for(int j = 0; j < 8; ++j)
- {
- if(spellInfo->Reagent[j] > 0 && !ObjectMgr::GetItemPrototype( spellInfo->Reagent[j] ))
- {
- if(msg)
- {
- if(pl)
- ChatHandler(pl).PSendSysMessage("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
- else
- sLog.outErrorDb("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
- }
- return false;
- }
- }
- }
-
- return true;
-}
-
-bool IsSpellAllowedInLocation(SpellEntry const *spellInfo,uint32 map_id,uint32 zone_id,uint32 area_id)
-{
- // normal case
- if( spellInfo->AreaId && spellInfo->AreaId != zone_id && spellInfo->AreaId != area_id )
- return false;
-
- // elixirs (all area dependent elixirs have family SPELLFAMILY_POTION, use this for speedup)
- if(spellInfo->SpellFamilyName==SPELLFAMILY_POTION)
- {
- if(uint32 mask = spellmgr.GetSpellElixirMask(spellInfo->Id))
- {
- if(mask & ELIXIR_UNSTABLE_MASK)
- {
- // in the Blade's Edge Mountains Plateaus and Gruul's Lair.
- return zone_id ==3522 || map_id==565;
- }
- if(mask & ELIXIR_SHATTRATH_MASK)
- {
- // in Tempest Keep, Serpentshrine Cavern, Caverns of Time: Mount Hyjal, Black Temple
- // TODO: and the Sunwell Plateau
- if(zone_id ==3607 || map_id==534 || map_id==564)
- return true;
-
- MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
- if(!mapEntry)
- return false;
-
- return mapEntry->multimap_id==206;
- }
-
- // elixirs not have another limitations
- return true;
- }
- }
-
- // special cases zone check (maps checked by multimap common id)
- switch(spellInfo->Id)
- {
- case 41618:
- case 41620:
- {
- MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
- if(!mapEntry)
- return false;
-
- return mapEntry->multimap_id==206;
- }
-
- case 41617:
- case 41619:
- {
- MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
- if(!mapEntry)
- return false;
-
- return mapEntry->multimap_id==207;
- }
- // Dragonmaw Illusion
- case 40216:
- case 42016:
- {
- if ( area_id != 3759 && area_id != 3966 && area_id != 3939 )
- return false;
- break;
- }
- }
-
- return true;
-}
-
-void SpellMgr::LoadSkillLineAbilityMap()
-{
- mSkillLineAbilityMap.clear();
-
- uint32 count = 0;
-
- for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); i++)
- {
- SkillLineAbilityEntry const *SkillInfo = sSkillLineAbilityStore.LookupEntry(i);
- if(!SkillInfo)
- continue;
-
- mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId,SkillInfo));
- ++count;
- }
-
- sLog.outString();
- sLog.outString(">> Loaded %u SkillLineAbility MultiMap", count);
-}
-
-DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto, bool triggered)
-{
- // Explicit Diminishing Groups
- switch(spellproto->SpellFamilyName)
- {
- case SPELLFAMILY_MAGE:
- {
- // Polymorph
- if ((spellproto->SpellFamilyFlags & 0x00001000000LL) && spellproto->EffectApplyAuraName[0]==SPELL_AURA_MOD_CONFUSE)
- return DIMINISHING_POLYMORPH;
- break;
- }
- case SPELLFAMILY_ROGUE:
- {
- // Kidney Shot
- if (spellproto->SpellFamilyFlags & 0x00000200000LL)
- return DIMINISHING_KIDNEYSHOT;
- // Blind
- else if (spellproto->SpellFamilyFlags & 0x00001000000LL)
- return DIMINISHING_BLIND_CYCLONE;
- break;
- }
- case SPELLFAMILY_WARLOCK:
- {
- // Death Coil
- if (spellproto->SpellFamilyFlags & 0x00000080000LL)
- return DIMINISHING_DEATHCOIL;
- // Fear
- else if (spellproto->SpellFamilyFlags & 0x40840000000LL)
- return DIMINISHING_WARLOCK_FEAR;
- // Curses/etc
- else if (spellproto->SpellFamilyFlags & 0x00080000000LL)
- return DIMINISHING_LIMITONLY;
- break;
- }
- case SPELLFAMILY_DRUID:
- {
- // Cyclone
- if (spellproto->SpellFamilyFlags & 0x02000000000LL)
- return DIMINISHING_BLIND_CYCLONE;
- break;
- }
- case SPELLFAMILY_WARRIOR:
- {
- // Hamstring - limit duration to 10s in PvP
- if (spellproto->SpellFamilyFlags & 0x00000000002LL)
- return DIMINISHING_LIMITONLY;
- break;
- }
- default:
- break;
- }
-
- // Get by mechanic
- for (uint8 i=0;i<3;++i)
- {
- if (spellproto->Mechanic == MECHANIC_STUN || spellproto->EffectMechanic[i] == MECHANIC_STUN)
- return triggered ? DIMINISHING_TRIGGER_STUN : DIMINISHING_CONTROL_STUN;
- else if (spellproto->Mechanic == MECHANIC_SLEEP || spellproto->EffectMechanic[i] == MECHANIC_SLEEP)
- return DIMINISHING_SLEEP;
- else if (spellproto->Mechanic == MECHANIC_ROOT || spellproto->EffectMechanic[i] == MECHANIC_ROOT)
- return triggered ? DIMINISHING_TRIGGER_ROOT : DIMINISHING_CONTROL_ROOT;
- else if (spellproto->Mechanic == MECHANIC_FEAR || spellproto->EffectMechanic[i] == MECHANIC_FEAR)
- return DIMINISHING_FEAR;
- else if (spellproto->Mechanic == MECHANIC_CHARM || spellproto->EffectMechanic[i] == MECHANIC_CHARM)
- return DIMINISHING_CHARM;
- else if (spellproto->Mechanic == MECHANIC_SILENCE || spellproto->EffectMechanic[i] == MECHANIC_SILENCE)
- return DIMINISHING_SILENCE;
- else if (spellproto->Mechanic == MECHANIC_DISARM || spellproto->EffectMechanic[i] == MECHANIC_DISARM)
- return DIMINISHING_DISARM;
- else if (spellproto->Mechanic == MECHANIC_FREEZE || spellproto->EffectMechanic[i] == MECHANIC_FREEZE)
- return DIMINISHING_FREEZE;
- else if (spellproto->Mechanic == MECHANIC_KNOCKOUT|| spellproto->EffectMechanic[i] == MECHANIC_KNOCKOUT ||
- spellproto->Mechanic == MECHANIC_SAPPED || spellproto->EffectMechanic[i] == MECHANIC_SAPPED)
- return DIMINISHING_KNOCKOUT;
- else if (spellproto->Mechanic == MECHANIC_BANISH || spellproto->EffectMechanic[i] == MECHANIC_BANISH)
- return DIMINISHING_BANISH;
- }
-
- return DIMINISHING_NONE;
-}
-
-bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group)
-{
- switch(group)
- {
- case DIMINISHING_CONTROL_STUN:
- case DIMINISHING_TRIGGER_STUN:
- case DIMINISHING_KIDNEYSHOT:
- case DIMINISHING_SLEEP:
- case DIMINISHING_CONTROL_ROOT:
- case DIMINISHING_TRIGGER_ROOT:
- case DIMINISHING_FEAR:
- case DIMINISHING_WARLOCK_FEAR:
- case DIMINISHING_CHARM:
- case DIMINISHING_POLYMORPH:
- case DIMINISHING_FREEZE:
- case DIMINISHING_KNOCKOUT:
- case DIMINISHING_BLIND_CYCLONE:
- case DIMINISHING_BANISH:
- case DIMINISHING_LIMITONLY:
- return true;
- }
- return false;
-}
-
-DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group)
-{
- switch(group)
- {
- case DIMINISHING_BLIND_CYCLONE:
- case DIMINISHING_CONTROL_STUN:
- case DIMINISHING_TRIGGER_STUN:
- case DIMINISHING_KIDNEYSHOT:
- return DRTYPE_ALL;
- case DIMINISHING_SLEEP:
- case DIMINISHING_CONTROL_ROOT:
- case DIMINISHING_TRIGGER_ROOT:
- case DIMINISHING_FEAR:
- case DIMINISHING_CHARM:
- case DIMINISHING_POLYMORPH:
- case DIMINISHING_SILENCE:
- case DIMINISHING_DISARM:
- case DIMINISHING_DEATHCOIL:
- case DIMINISHING_FREEZE:
- case DIMINISHING_BANISH:
- case DIMINISHING_WARLOCK_FEAR:
- case DIMINISHING_KNOCKOUT:
- return DRTYPE_PLAYER;
- }
-
- return DRTYPE_NONE;
-}
+/*
+ * Copyright (C) 2005-2008 MaNGOS
+ *
+ * Copyright (C) 2008 Trinity
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "SpellMgr.h"
+#include "ObjectMgr.h"
+#include "SpellAuraDefines.h"
+#include "ProgressBar.h"
+#include "Database/DBCStores.h"
+#include "World.h"
+#include "Chat.h"
+#include "Spell.h"
+
+SpellMgr::SpellMgr()
+{
+}
+
+SpellMgr::~SpellMgr()
+{
+}
+
+SpellMgr& SpellMgr::Instance()
+{
+ static SpellMgr spellMgr;
+ return spellMgr;
+}
+
+int32 GetSpellDuration(SpellEntry const *spellInfo)
+{
+ if(!spellInfo)
+ return 0;
+ SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
+ if(!du)
+ return 0;
+ return (du->Duration[0] == -1) ? -1 : abs(du->Duration[0]);
+}
+
+int32 GetSpellMaxDuration(SpellEntry const *spellInfo)
+{
+ if(!spellInfo)
+ return 0;
+ SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
+ if(!du)
+ return 0;
+ return (du->Duration[2] == -1) ? -1 : abs(du->Duration[2]);
+}
+
+uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell)
+{
+ SpellCastTimesEntry const *spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->CastingTimeIndex);
+
+ // not all spells have cast time index and this is all is pasiive abilities
+ if(!spellCastTimeEntry)
+ return 0;
+
+ int32 castTime = spellCastTimeEntry->CastTime;
+
+ if (spell)
+ {
+ if(Player* modOwner = spell->GetCaster()->GetSpellModOwner())
+ modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell);
+
+ if( !(spellInfo->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_UNK5)) )
+ castTime = int32(castTime * spell->GetCaster()->GetFloatValue(UNIT_MOD_CAST_SPEED));
+ else
+ {
+ if (spell->IsRangedSpell() && !spell->IsAutoRepeat())
+ castTime = int32(castTime * spell->GetCaster()->m_modAttackSpeedPct[RANGED_ATTACK]);
+ }
+ }
+
+ if (spellInfo->Attributes & SPELL_ATTR_RANGED && (!spell || !(spell->IsAutoRepeat())))
+ castTime += 500;
+
+ return (castTime > 0) ? uint32(castTime) : 0;
+}
+
+bool IsPassiveSpell(uint32 spellId)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if (!spellInfo)
+ return false;
+ return (spellInfo->Attributes & SPELL_ATTR_PASSIVE) != 0;
+}
+/*not used for now so commented out
+bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
+{
+ SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
+ SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
+ if(!spellInfo_1 || !spellInfo_2) return false;
+ if(spellInfo_1->Id == spellId_2) return false;
+
+ if (spellInfo_1->Effect[effIndex_1] != spellInfo_2->Effect[effIndex_2] ||
+ spellInfo_1->EffectMiscValue[effIndex_1] != spellInfo_2->EffectMiscValue[effIndex_2] ||
+ spellInfo_1->EffectApplyAuraName[effIndex_1] != spellInfo_2->EffectApplyAuraName[effIndex_2])
+ return false;
+
+ return true;
+}*/
+
+int32 CompareAuraRanks(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
+{
+ SpellEntry const*spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
+ SpellEntry const*spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
+ if(!spellInfo_1 || !spellInfo_2) return 0;
+ if (spellId_1 == spellId_2) return 0;
+
+ int32 diff = spellInfo_1->EffectBasePoints[effIndex_1] - spellInfo_2->EffectBasePoints[effIndex_2];
+ if (spellInfo_1->EffectBasePoints[effIndex_1]+1 < 0 && spellInfo_2->EffectBasePoints[effIndex_2]+1 < 0) return -diff;
+ else return diff;
+}
+
+SpellSpecific GetSpellSpecific(uint32 spellId)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if(!spellInfo)
+ return SPELL_NORMAL;
+
+ switch(spellInfo->SpellFamilyName)
+ {
+ case SPELLFAMILY_MAGE:
+ {
+ // family flags 18(Molten), 25(Frost/Ice), 28(Mage)
+ if (spellInfo->SpellFamilyFlags & 0x12040000)
+ return SPELL_MAGE_ARMOR;
+
+ if ((spellInfo->SpellFamilyFlags & 0x1000000) && spellInfo->EffectApplyAuraName[0]==SPELL_AURA_MOD_CONFUSE)
+ return SPELL_MAGE_POLYMORPH;
+
+ break;
+ }
+ case SPELLFAMILY_WARRIOR:
+ {
+ if (spellInfo->SpellFamilyFlags & 0x00008000010000LL)
+ return SPELL_POSITIVE_SHOUT;
+
+ break;
+ }
+ case SPELLFAMILY_WARLOCK:
+ {
+ // only warlock curses have this
+ if (spellInfo->Dispel == DISPEL_CURSE)
+ return SPELL_CURSE;
+
+ // family flag 37 (only part spells have family name)
+ if (spellInfo->SpellFamilyFlags & 0x2000000000LL)
+ return SPELL_WARLOCK_ARMOR;
+
+ //seed of corruption and corruption
+ if (spellInfo->SpellFamilyFlags & 0x1000000002LL)
+ return SPELL_WARLOCK_CORRUPTION;
+ break;
+ }
+ case SPELLFAMILY_HUNTER:
+ {
+ // only hunter stings have this
+ if (spellInfo->Dispel == DISPEL_POISON)
+ return SPELL_STING;
+
+ break;
+ }
+ case SPELLFAMILY_PALADIN:
+ {
+ if (IsSealSpell(spellInfo))
+ return SPELL_SEAL;
+
+ if (spellInfo->SpellFamilyFlags & 0x10000100LL)
+ return SPELL_BLESSING;
+
+ if ((spellInfo->SpellFamilyFlags & 0x00000820180400LL) && (spellInfo->AttributesEx3 & 0x200))
+ return SPELL_JUDGEMENT;
+
+ for (int i = 0; i < 3; i++)
+ {
+ // only paladin auras have this
+ if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
+ return SPELL_AURA;
+ }
+ break;
+ }
+ case SPELLFAMILY_SHAMAN:
+ {
+ if (IsElementalShield(spellInfo))
+ return SPELL_ELEMENTAL_SHIELD;
+
+ break;
+ }
+
+ case SPELLFAMILY_POTION:
+ return spellmgr.GetSpellElixirSpecific(spellInfo->Id);
+ }
+
+ // only warlock armor/skin have this (in additional to family cases)
+ if( spellInfo->SpellVisual == 130 && spellInfo->SpellIconID == 89)
+ {
+ return SPELL_WARLOCK_ARMOR;
+ }
+
+ // only hunter aspects have this (but not all aspects in hunter family)
+ if( spellInfo->activeIconID == 122 && (GetSpellSchoolMask(spellInfo) & SPELL_SCHOOL_MASK_NATURE) &&
+ (spellInfo->Attributes & 0x50000) != 0 && (spellInfo->Attributes & 0x9000010) == 0)
+ {
+ return SPELL_ASPECT;
+ }
+
+ for(int i = 0; i < 3; i++)
+ if( spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA && (
+ spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_CREATURES ||
+ spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_RESOURCES ||
+ spellInfo->EffectApplyAuraName[i] == SPELL_AURA_TRACK_STEALTHED ) )
+ return SPELL_TRACKER;
+
+ // elixirs can have different families, but potion most ofc.
+ if(SpellSpecific sp = spellmgr.GetSpellElixirSpecific(spellInfo->Id))
+ return sp;
+
+ return SPELL_NORMAL;
+}
+
+bool IsSingleFromSpellSpecificPerCaster(uint32 spellSpec1,uint32 spellSpec2)
+{
+ switch(spellSpec1)
+ {
+ case SPELL_SEAL:
+ case SPELL_BLESSING:
+ case SPELL_AURA:
+ case SPELL_STING:
+ case SPELL_CURSE:
+ case SPELL_ASPECT:
+ case SPELL_POSITIVE_SHOUT:
+ case SPELL_JUDGEMENT:
+ case SPELL_WARLOCK_CORRUPTION:
+ return spellSpec1==spellSpec2;
+ default:
+ return false;
+ }
+}
+
+bool IsSingleFromSpellSpecificPerTarget(uint32 spellSpec1,uint32 spellSpec2)
+{
+ switch(spellSpec1)
+ {
+ case SPELL_TRACKER:
+ case SPELL_WARLOCK_ARMOR:
+ case SPELL_MAGE_ARMOR:
+ case SPELL_ELEMENTAL_SHIELD:
+ case SPELL_MAGE_POLYMORPH:
+ return spellSpec1==spellSpec2;
+ case SPELL_BATTLE_ELIXIR:
+ return spellSpec2==SPELL_BATTLE_ELIXIR
+ || spellSpec2==SPELL_FLASK_ELIXIR;
+ case SPELL_GUARDIAN_ELIXIR:
+ return spellSpec2==SPELL_GUARDIAN_ELIXIR
+ || spellSpec2==SPELL_FLASK_ELIXIR;
+ case SPELL_FLASK_ELIXIR:
+ return spellSpec2==SPELL_BATTLE_ELIXIR
+ || spellSpec2==SPELL_GUARDIAN_ELIXIR
+ || spellSpec2==SPELL_FLASK_ELIXIR;
+ default:
+ return false;
+ }
+}
+
+bool IsPositiveTarget(uint32 targetA, uint32 targetB)
+{
+ // non-positive targets
+ switch(targetA)
+ {
+ case TARGET_CHAIN_DAMAGE:
+ case TARGET_ALL_ENEMY_IN_AREA:
+ case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
+ case TARGET_IN_FRONT_OF_CASTER:
+ case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
+ case TARGET_CURRENT_ENEMY_COORDINATES:
+ case TARGET_SINGLE_ENEMY:
+ return false;
+ case TARGET_ALL_AROUND_CASTER:
+ return (targetB == TARGET_ALL_PARTY || targetB == TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER);
+ default:
+ break;
+ }
+ if (targetB)
+ return IsPositiveTarget(targetB, 0);
+ return true;
+}
+
+bool IsPositiveEffect(uint32 spellId, uint32 effIndex)
+{
+ SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
+ if (!spellproto) return false;
+
+ switch(spellId)
+ {
+ case 23333: // BG spell
+ case 23335: // BG spell
+ case 34976: // BG spell
+ return true;
+ case 28441: // not positive dummy spell
+ case 37675: // Chaos Blast
+ return false;
+ }
+
+ switch(spellproto->Effect[effIndex])
+ {
+ // always positive effects (check before target checks that provided non-positive result in some case for positive effects)
+ case SPELL_EFFECT_HEAL:
+ case SPELL_EFFECT_LEARN_SPELL:
+ case SPELL_EFFECT_SKILL_STEP:
+ case SPELL_EFFECT_HEAL_PCT:
+ case SPELL_EFFECT_ENERGIZE_PCT:
+ return true;
+
+ // non-positive aura use
+ case SPELL_EFFECT_APPLY_AURA:
+ case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
+ {
+ switch(spellproto->EffectApplyAuraName[effIndex])
+ {
+ case SPELL_AURA_DUMMY:
+ {
+ // dummy aura can be positive or negative dependent from casted spell
+ switch(spellproto->Id)
+ {
+ case 13139: // net-o-matic special effect
+ case 23445: // evil twin
+ case 38637: // Nether Exhaustion (red)
+ case 38638: // Nether Exhaustion (green)
+ case 38639: // Nether Exhaustion (blue)
+ return false;
+ default:
+ break;
+ }
+ } break;
+ case SPELL_AURA_MOD_STAT:
+ case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from bas point sign (negative -> negative)
+ case SPELL_AURA_MOD_HEALING_DONE:
+ {
+ if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
+ return false;
+ break;
+ }
+ case SPELL_AURA_ADD_TARGET_TRIGGER:
+ return true;
+ case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
+ if(spellId != spellproto->EffectTriggerSpell[effIndex])
+ {
+ uint32 spellTriggeredId = spellproto->EffectTriggerSpell[effIndex];
+ SpellEntry const *spellTriggeredProto = sSpellStore.LookupEntry(spellTriggeredId);
+
+ if(spellTriggeredProto)
+ {
+ // non-positive targets of main spell return early
+ for(int i = 0; i < 3; ++i)
+ {
+ // if non-positive trigger cast targeted to positive target this main cast is non-positive
+ // this will place this spell auras as debuffs
+ if(IsPositiveTarget(spellTriggeredProto->EffectImplicitTargetA[effIndex],spellTriggeredProto->EffectImplicitTargetB[effIndex]) && !IsPositiveEffect(spellTriggeredId,i))
+ return false;
+ }
+ }
+ }
+ break;
+ case SPELL_AURA_PROC_TRIGGER_SPELL:
+ // many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example)
+ break;
+ case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment.
+ if(effIndex==0 && spellproto->Effect[1]==0 && spellproto->Effect[2]==0)
+ return false; // but all single stun aura spells is negative
+
+ // Petrification
+ if(spellproto->Id == 17624)
+ return false;
+ break;
+ case SPELL_AURA_MOD_ROOT:
+ case SPELL_AURA_MOD_SILENCE:
+ case SPELL_AURA_GHOST:
+ case SPELL_AURA_PERIODIC_LEECH:
+ case SPELL_AURA_MOD_PACIFY_SILENCE:
+ case SPELL_AURA_MOD_STALKED:
+ case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
+ return false;
+ case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also.
+ // part of negative spell if casted at self (prevent cancel)
+ if(spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF)
+ return false;
+ break;
+ case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also
+ // part of positive spell if casted at self
+ if(spellproto->EffectImplicitTargetA[effIndex] != TARGET_SELF)
+ return false;
+ // but not this if this first effect (don't found batter check)
+ if(spellproto->Attributes & 0x4000000 && effIndex==0)
+ return false;
+ break;
+ case SPELL_AURA_TRANSFORM:
+ // some spells negative
+ switch(spellproto->Id)
+ {
+ case 36897: // Transporter Malfunction (race mutation to horde)
+ case 36899: // Transporter Malfunction (race mutation to alliance)
+ return false;
+ }
+ break;
+ case SPELL_AURA_MOD_SCALE:
+ // some spells negative
+ switch(spellproto->Id)
+ {
+ case 36900: // Soul Split: Evil!
+ case 36901: // Soul Split: Good
+ case 36893: // Transporter Malfunction (decrease size case)
+ case 36895: // Transporter Malfunction (increase size case)
+ return false;
+ }
+ break;
+ case SPELL_AURA_MECHANIC_IMMUNITY:
+ {
+ // non-positive immunities
+ switch(spellproto->EffectMiscValue[effIndex])
+ {
+ case MECHANIC_BANDAGE:
+ case MECHANIC_SHIELD:
+ case MECHANIC_MOUNT:
+ case MECHANIC_INVULNERABILITY:
+ return false;
+ default:
+ break;
+ }
+ } break;
+ case SPELL_AURA_ADD_FLAT_MODIFIER: // mods
+ case SPELL_AURA_ADD_PCT_MODIFIER:
+ {
+ // non-positive mods
+ switch(spellproto->EffectMiscValue[effIndex])
+ {
+ case SPELLMOD_COST: // dependent from bas point sign (negative -> positive)
+ if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) > 0)
+ return false;
+ break;
+ default:
+ break;
+ }
+ } break;
+ case SPELL_AURA_MOD_HEALING_PCT:
+ if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
+ return false;
+ break;
+ case SPELL_AURA_MOD_SKILL:
+ if(spellproto->EffectBasePoints[effIndex]+int32(spellproto->EffectBaseDice[effIndex]) < 0)
+ return false;
+ break;
+ case SPELL_AURA_FORCE_REACTION:
+ if(spellproto->Id==42792) // Recently Dropped Flag (prevent cancel)
+ return false;
+ break;
+ default:
+ break;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ // non-positive targets
+ if(!IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex]))
+ return false;
+
+ // AttributesEx check
+ if(spellproto->AttributesEx & (1<<7))
+ return false;
+
+ // ok, positive
+ return true;
+}
+
+bool IsPositiveSpell(uint32 spellId)
+{
+ SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
+ if (!spellproto) return false;
+
+ // spells with at least one negative effect are considered negative
+ // some self-applied spells have negative effects but in self casting case negative check ignored.
+ for (int i = 0; i < 3; i++)
+ if (!IsPositiveEffect(spellId, i))
+ return false;
+ return true;
+}
+
+bool IsSingleTargetSpell(SpellEntry const *spellInfo)
+{
+ // all other single target spells have if it has AttributesEx5
+ if ( spellInfo->AttributesEx5 & SPELL_ATTR_EX5_SINGLE_TARGET_SPELL )
+ return true;
+
+ // TODO - need found Judgements rule
+ switch(GetSpellSpecific(spellInfo->Id))
+ {
+ case SPELL_JUDGEMENT:
+ return true;
+ }
+
+ // single target triggered spell.
+ // Not real client side single target spell, but it' not triggered until prev. aura expired.
+ // This is allow store it in single target spells list for caster for spell proc checking
+ if(spellInfo->Id==38324) // Regeneration (triggered by 38299 (HoTs on Heals))
+ return true;
+
+ return false;
+}
+
+bool IsSingleTargetSpells(SpellEntry const *spellInfo1, SpellEntry const *spellInfo2)
+{
+ // TODO - need better check
+ // Equal icon and spellfamily
+ if( spellInfo1->SpellFamilyName == spellInfo2->SpellFamilyName &&
+ spellInfo1->SpellIconID == spellInfo2->SpellIconID )
+ return true;
+
+ // TODO - need found Judgements rule
+ SpellSpecific spec1 = GetSpellSpecific(spellInfo1->Id);
+ // spell with single target specific types
+ switch(spec1)
+ {
+ case SPELL_JUDGEMENT:
+ if(GetSpellSpecific(spellInfo2->Id) == spec1)
+ return true;
+ break;
+ }
+
+ return false;
+}
+
+uint8 GetErrorAtShapeshiftedCast (SpellEntry const *spellInfo, uint32 form)
+{
+ // talents that learn spells can have stance requirements that need ignore
+ // (this requirement only for client-side stance show in talent description)
+ if( GetTalentSpellCost(spellInfo->Id) > 0 &&
+ (spellInfo->Effect[0]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[1]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[2]==SPELL_EFFECT_LEARN_SPELL) )
+ return 0;
+
+ uint32 stanceMask = (form ? 1 << (form - 1) : 0);
+
+ if (stanceMask & spellInfo->StancesNot) // can explicitly not be casted in this stance
+ return SPELL_FAILED_NOT_SHAPESHIFT;
+
+ if (stanceMask & spellInfo->Stances) // can explicitly be casted in this stance
+ return 0;
+
+ bool actAsShifted = false;
+ if (form > 0)
+ {
+ SpellShapeshiftEntry const *shapeInfo = sSpellShapeshiftStore.LookupEntry(form);
+ if (!shapeInfo)
+ {
+ sLog.outError("GetErrorAtShapeshiftedCast: unknown shapeshift %u", form);
+ return 0;
+ }
+ actAsShifted = !(shapeInfo->flags1 & 1); // shapeshift acts as normal form for spells
+ }
+
+ if(actAsShifted)
+ {
+ if (spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT) // not while shapeshifted
+ return SPELL_FAILED_NOT_SHAPESHIFT;
+ else if (spellInfo->Stances != 0) // needs other shapeshift
+ return SPELL_FAILED_ONLY_SHAPESHIFT;
+ }
+ else
+ {
+ // needs shapeshift
+ if(!(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && spellInfo->Stances != 0)
+ return SPELL_FAILED_ONLY_SHAPESHIFT;
+ }
+
+ return 0;
+}
+
+void SpellMgr::LoadSpellTargetPositions()
+{
+ mSpellTargetPositions.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ // 0 1 2 3 4 5
+ QueryResult *result = WorldDatabase.Query("SELECT id, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM spell_target_position");
+ if( !result )
+ {
+
+ barGoLink bar( 1 );
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell target coordinates", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ ++count;
+
+ uint32 Spell_ID = fields[0].GetUInt32();
+
+ SpellTargetPosition st;
+
+ st.target_mapId = fields[1].GetUInt32();
+ st.target_X = fields[2].GetFloat();
+ st.target_Y = fields[3].GetFloat();
+ st.target_Z = fields[4].GetFloat();
+ st.target_Orientation = fields[5].GetFloat();
+
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(Spell_ID);
+ if(!spellInfo)
+ {
+ sLog.outErrorDb("Spell (ID:%u) listed in `spell_target_position` does not exist.",Spell_ID);
+ continue;
+ }
+
+ bool found = false;
+ for(int i = 0; i < 3; ++i)
+ {
+ if( spellInfo->EffectImplicitTargetA[i]==TARGET_TABLE_X_Y_Z_COORDINATES || spellInfo->EffectImplicitTargetB[i]==TARGET_TABLE_X_Y_Z_COORDINATES )
+ {
+ found = true;
+ break;
+ }
+ }
+ if(!found)
+ {
+ sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` does not have target TARGET_TABLE_X_Y_Z_COORDINATES (17).",Spell_ID);
+ continue;
+ }
+
+ MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId);
+ if(!mapEntry)
+ {
+ sLog.outErrorDb("Spell (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Spell_ID,st.target_mapId);
+ continue;
+ }
+
+ if(st.target_X==0 && st.target_Y==0 && st.target_Z==0)
+ {
+ sLog.outErrorDb("Spell (ID:%u) target coordinates not provided.",Spell_ID);
+ continue;
+ }
+
+ mSpellTargetPositions[Spell_ID] = st;
+
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell teleport coordinates", count );
+}
+
+void SpellMgr::LoadSpellAffects()
+{
+ mSpellAffectMap.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ // 0 1 2
+ QueryResult *result = WorldDatabase.Query("SELECT entry, effectId, SpellFamilyMask FROM spell_affect");
+ if( !result )
+ {
+
+ barGoLink bar( 1 );
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell affect definitions", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ uint16 entry = fields[0].GetUInt16();
+ uint8 effectId = fields[1].GetUInt8();
+
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
+
+ if (!spellInfo)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_affect` does not exist", entry);
+ continue;
+ }
+
+ if (effectId >= 3)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_affect` have invalid effect index (%u)", entry,effectId);
+ continue;
+ }
+
+ if( spellInfo->Effect[effectId] != SPELL_EFFECT_APPLY_AURA ||
+ spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_FLAT_MODIFIER &&
+ spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_PCT_MODIFIER &&
+ spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_TARGET_TRIGGER )
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_affect` have not SPELL_AURA_ADD_FLAT_MODIFIER (%u) or SPELL_AURA_ADD_PCT_MODIFIER (%u) or SPELL_AURA_ADD_TARGET_TRIGGER (%u) for effect index (%u)", entry,SPELL_AURA_ADD_FLAT_MODIFIER,SPELL_AURA_ADD_PCT_MODIFIER,SPELL_AURA_ADD_TARGET_TRIGGER,effectId);
+ continue;
+ }
+
+ uint64 spellAffectMask = fields[2].GetUInt64();
+
+ // Spell.dbc have own data for low part of SpellFamilyMask
+ if( spellInfo->EffectItemType[effectId])
+ {
+ if(spellInfo->EffectItemType[effectId] == spellAffectMask)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_affect` have redundant (same with EffectItemType%d) data for effect index (%u) and not needed, skipped.", entry,effectId+1,effectId);
+ continue;
+ }
+
+ // 24429 have wrong data in EffectItemType and overwrites by DB, possible bug in client
+ if(spellInfo->Id!=24429 && spellInfo->EffectItemType[effectId] != spellAffectMask)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_affect` have different low part from EffectItemType%d for effect index (%u) and not needed, skipped.", entry,effectId+1,effectId);
+ continue;
+ }
+ }
+
+ mSpellAffectMap.insert(SpellAffectMap::value_type((entry<<8) + effectId,spellAffectMask));
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell affect definitions", count );
+
+ for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id)
+ {
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
+ if (!spellInfo)
+ continue;
+
+ for (int effectId = 0; effectId < 3; ++effectId)
+ {
+ if( spellInfo->Effect[effectId] != SPELL_EFFECT_APPLY_AURA ||
+ (spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_FLAT_MODIFIER &&
+ spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_PCT_MODIFIER &&
+ spellInfo->EffectApplyAuraName[effectId] != SPELL_AURA_ADD_TARGET_TRIGGER) )
+ continue;
+
+ if(spellInfo->EffectItemType[effectId] != 0)
+ continue;
+
+ if(mSpellAffectMap.find((id<<8) + effectId) != mSpellAffectMap.end())
+ continue;
+
+ sLog.outErrorDb("Spell %u (%s) misses spell_affect for effect %u",id,spellInfo->SpellName[sWorld.GetDefaultDbcLocale()], effectId);
+ }
+ }
+}
+
+bool SpellMgr::IsAffectedBySpell(SpellEntry const *spellInfo, uint32 spellId, uint8 effectId, uint64 familyFlags) const
+{
+ // false for spellInfo == NULL
+ if (!spellInfo)
+ return false;
+
+ SpellEntry const *affect_spell = sSpellStore.LookupEntry(spellId);
+ // false for affect_spell == NULL
+ if (!affect_spell)
+ return false;
+
+ // False if spellFamily not equal
+ if (affect_spell->SpellFamilyName != spellInfo->SpellFamilyName)
+ return false;
+
+ // If familyFlags == 0
+ if (!familyFlags)
+ {
+ // Get it from spellAffect table
+ familyFlags = GetSpellAffectMask(spellId,effectId);
+ // false if familyFlags == 0
+ if (!familyFlags)
+ return false;
+ }
+
+ // true
+ if (familyFlags & spellInfo->SpellFamilyFlags)
+ return true;
+
+ return false;
+}
+
+void SpellMgr::LoadSpellProcEvents()
+{
+ mSpellProcEventMap.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ // 0 1 2 3 4 5 6 7 8
+ QueryResult *result = WorldDatabase.Query("SELECT entry, SchoolMask, Category, SkillID, SpellFamilyName, SpellFamilyMask, procFlags, ppmRate, cooldown FROM spell_proc_event");
+ if( !result )
+ {
+
+ barGoLink bar( 1 );
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell proc event conditions", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ uint16 entry = fields[0].GetUInt16();
+
+ if (!sSpellStore.LookupEntry(entry))
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_proc_event` does not exist", entry);
+ continue;
+ }
+
+ SpellProcEventEntry spe;
+
+ spe.schoolMask = fields[1].GetUInt32();
+ spe.category = fields[2].GetUInt32();
+ spe.skillId = fields[3].GetUInt32();
+ spe.spellFamilyName = fields[4].GetUInt32();
+ spe.spellFamilyMask = fields[5].GetUInt64();
+ spe.procFlags = fields[6].GetUInt32();
+ spe.ppmRate = fields[7].GetFloat();
+ spe.cooldown = fields[8].GetUInt32();
+
+ mSpellProcEventMap[entry] = spe;
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell proc event conditions", count );
+
+ /*
+ // Commented for now, as it still produces many errors (still quite many spells miss spell_proc_event)
+ for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id)
+ {
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
+ if (!spellInfo)
+ continue;
+
+ bool found = false;
+ for (int effectId = 0; effectId < 3; ++effectId)
+ {
+ // at this moment check only SPELL_AURA_PROC_TRIGGER_SPELL
+ if( spellInfo->EffectApplyAuraName[effectId] == SPELL_AURA_PROC_TRIGGER_SPELL )
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if(!found)
+ continue;
+
+ if(GetSpellProcEvent(id))
+ continue;
+
+ sLog.outErrorDb("Spell %u (%s) misses spell_proc_event",id,spellInfo->SpellName[sWorld.GetDBClang()]);
+ }
+ */
+}
+
+bool SpellMgr::IsSpellProcEventCanTriggeredBy( SpellProcEventEntry const * spellProcEvent, SpellEntry const * procSpell, uint32 procFlags )
+{
+ if((procFlags & spellProcEvent->procFlags) == 0)
+ return false;
+
+ // Additional checks in case spell cast/hit/crit is the event
+ // Check (if set) school, category, skill line, spell talent mask
+ if(spellProcEvent->schoolMask && (!procSpell || (GetSpellSchoolMask(procSpell) & spellProcEvent->schoolMask) == 0))
+ return false;
+ if(spellProcEvent->category && (!procSpell || procSpell->Category != spellProcEvent->category))
+ return false;
+ if(spellProcEvent->skillId)
+ {
+ if (!procSpell)
+ return false;
+
+ SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(procSpell->Id);
+ SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(procSpell->Id);
+
+ bool found = false;
+ for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
+ {
+ if(_spell_idx->second->skillId == spellProcEvent->skillId)
+ {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return false;
+ }
+ if(spellProcEvent->spellFamilyName && (!procSpell || spellProcEvent->spellFamilyName != procSpell->SpellFamilyName))
+ return false;
+ if(spellProcEvent->spellFamilyMask && (!procSpell || (spellProcEvent->spellFamilyMask & procSpell->SpellFamilyFlags) == 0))
+ return false;
+
+ return true;
+}
+
+void SpellMgr::LoadSpellElixirs()
+{
+ mSpellElixirs.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ // 0 1
+ QueryResult *result = WorldDatabase.Query("SELECT entry, mask FROM spell_elixir");
+ if( !result )
+ {
+
+ barGoLink bar( 1 );
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell elixir definitions", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ uint16 entry = fields[0].GetUInt16();
+ uint8 mask = fields[1].GetUInt8();
+
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry);
+
+ if (!spellInfo)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_elixir` does not exist", entry);
+ continue;
+ }
+
+ mSpellElixirs[entry] = mask;
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell elixir definitions", count );
+}
+
+void SpellMgr::LoadSpellThreats()
+{
+ sSpellThreatStore.Free(); // for reload
+
+ sSpellThreatStore.Load();
+
+ sLog.outString( ">> Loaded %u aggro generating spells", sSpellThreatStore.RecordCount );
+ sLog.outString();
+}
+
+bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const
+{
+ SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
+ if(!spellInfo_1 || !spellInfo_2) return false;
+ if(spellInfo_1->Id == spellId_2) return false;
+
+ return GetFirstSpellInChain(spellInfo_1->Id)==GetFirstSpellInChain(spellId_2);
+}
+
+bool SpellMgr::canStackSpellRanks(SpellEntry const *spellInfo)
+{
+ if(spellInfo->powerType != POWER_MANA && spellInfo->powerType != POWER_HEALTH)
+ return false;
+ if(IsProfessionSpell(spellInfo->Id))
+ return false;
+
+ // All stance spells. if any better way, change it.
+ for (int i = 0; i < 3; i++)
+ {
+ // Paladin aura Spell
+ if(spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN
+ && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
+ return false;
+ // Druid form Spell
+ if(spellInfo->SpellFamilyName == SPELLFAMILY_DRUID
+ && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA
+ && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
+ return false;
+ // Rogue Stealth
+ if(spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE
+ && spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA
+ && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
+ return false;
+ }
+ return true;
+}
+
+bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2, bool isFromTheSameCaster ) const
+{
+ SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
+ SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
+
+ if(!spellInfo_1 || !spellInfo_2)
+ return false;
+
+ SpellSpecific spellId_spec_1 = GetSpellSpecific(spellId_1);
+ SpellSpecific spellId_spec_2 = GetSpellSpecific(spellId_2);
+ if (spellId_spec_1 && spellId_spec_2)
+ if (IsSingleFromSpellSpecificPerTarget(spellId_spec_1,spellId_spec_2)
+ || (IsSingleFromSpellSpecificPerCaster(spellId_spec_1,spellId_spec_2) && isFromTheSameCaster))
+ return true;
+
+ if(spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName)
+ return false;
+
+ if(!spellInfo_1->SpellFamilyName) // generic spells
+ {
+ if(!spellInfo_1->SpellIconID
+ || spellInfo_1->SpellIconID != spellInfo_2->SpellIconID)
+ return false;
+ }
+
+ //if both elixirs are not battle/guardian/potions/flasks then always stack
+ else if ((spellInfo_1->SpellFamilyName == SPELLFAMILY_POTION)
+ &&(spellId_spec_1 || spellId_spec_2))
+ return false;
+
+ else if (spellInfo_1->SpellFamilyFlags != spellInfo_2->SpellFamilyFlags)
+ return false;
+
+ for(uint32 i = 0; i < 3; ++i)
+ {
+ if(spellInfo_1->Effect[i] != spellInfo_2->Effect[i])
+ return false;
+ if (spellInfo_1->EffectApplyAuraName[i] || spellInfo_2->EffectApplyAuraName[i])
+ {
+ if(spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i]
+ || spellInfo_1->EffectMiscValue[i] != spellInfo_2->EffectMiscValue[i])
+ // need itemtype check? need to find an example
+ return false;
+ else if (!isFromTheSameCaster)
+ switch(spellInfo_1->EffectApplyAuraName[i])
+ {
+ //spells with these auras from different casters will stack
+ case SPELL_AURA_PERIODIC_DAMAGE:
+ case SPELL_AURA_PERIODIC_HEAL:
+ case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
+ case SPELL_AURA_PERIODIC_ENERGIZE:
+ case SPELL_AURA_PERIODIC_MANA_LEECH:
+ case SPELL_AURA_PERIODIC_LEECH:
+ //exception for shaman positive totems with these auras
+ if ((spellInfo_1->SpellFamilyName != SPELLFAMILY_SHAMAN)
+ ||(spellInfo_1->Effect[i]!=SPELL_AURA_MOD_INCREASE_ENERGY))
+ return false;
+ default:
+ break;
+ }
+ }
+ }
+ return true;
+}
+
+bool SpellMgr::IsProfessionSpell(uint32 spellId)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if(!spellInfo)
+ return false;
+
+ if(spellInfo->Effect[1] != SPELL_EFFECT_SKILL)
+ return false;
+
+ uint32 skill = spellInfo->EffectMiscValue[1];
+
+ return IsProfessionSkill(skill);
+}
+
+bool SpellMgr::IsPrimaryProfessionSpell(uint32 spellId)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if(!spellInfo)
+ return false;
+
+ if(spellInfo->Effect[1] != SPELL_EFFECT_SKILL)
+ return false;
+
+ uint32 skill = spellInfo->EffectMiscValue[1];
+
+ return IsPrimaryProfessionSkill(skill);
+}
+
+bool SpellMgr::IsPrimaryProfessionFirstRankSpell(uint32 spellId) const
+{
+ return IsPrimaryProfessionSpell(spellId) && GetSpellRank(spellId)==1;
+}
+
+SpellEntry const* SpellMgr::SelectAuraRankForPlayerLevel(SpellEntry const* spellInfo, uint32 playerLevel) const
+{
+ // ignore passive spells
+ if(IsPassiveSpell(spellInfo->Id))
+ return spellInfo;
+
+ bool needRankSelection = false;
+ for(int i=0;i<3;i++)
+ {
+ if( IsPositiveEffect(spellInfo->Id, i) && (
+ spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA ||
+ spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY
+ ) )
+ {
+ needRankSelection = true;
+ break;
+ }
+ }
+
+ // not required
+ if(!needRankSelection)
+ return spellInfo;
+
+ for(uint32 nextSpellId = spellInfo->Id; nextSpellId != 0; nextSpellId = GetPrevSpellInChain(nextSpellId))
+ {
+ SpellEntry const *nextSpellInfo = sSpellStore.LookupEntry(nextSpellId);
+ if(!nextSpellInfo)
+ break;
+
+ // if found appropriate level
+ if(playerLevel + 10 >= nextSpellInfo->spellLevel)
+ return nextSpellInfo;
+
+ // one rank less then
+ }
+
+ // not found
+ return NULL;
+}
+
+void SpellMgr::LoadSpellChains()
+{
+ mSpellChains.clear(); // need for reload case
+ mSpellChainsNext.clear(); // need for reload case
+
+ QueryResult *result = WorldDatabase.Query("SELECT spell_id, prev_spell, first_spell, rank, req_spell FROM spell_chain");
+ if(result == NULL)
+ {
+ barGoLink bar( 1 );
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded 0 spell chain records" );
+ sLog.outErrorDb("`spell_chains` table is empty!");
+ return;
+ }
+
+ uint32 count = 0;
+
+ barGoLink bar( result->GetRowCount() );
+ do
+ {
+ bar.step();
+ Field *fields = result->Fetch();
+
+ uint32 spell_id = fields[0].GetUInt32();
+
+ SpellChainNode node;
+ node.prev = fields[1].GetUInt32();
+ node.first = fields[2].GetUInt32();
+ node.rank = fields[3].GetUInt8();
+ node.req = fields[4].GetUInt32();
+
+ if(!sSpellStore.LookupEntry(spell_id))
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_chain` does not exist",spell_id);
+ continue;
+ }
+
+ if(node.prev!=0 && !sSpellStore.LookupEntry(node.prev))
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existed previous rank spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ if(!sSpellStore.LookupEntry(node.first))
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing first rank spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ // check basic spell chain data integrity (note: rank can be equal 0 or 1 for first/single spell)
+ if( (spell_id == node.first) != (node.rank <= 1) ||
+ (spell_id == node.first) != (node.prev == 0) ||
+ (node.rank <= 1) != (node.prev == 0) )
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not compatible chain data.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ if(node.req!=0 && !sSpellStore.LookupEntry(node.req))
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing required spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ // talents not required data in spell chain for work, but must be checked if present for intergrity
+ if(TalentSpellPos const* pos = GetTalentSpellPos(spell_id))
+ {
+ if(node.rank!=pos->rank+1)
+ {
+ sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong rank.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ if(TalentEntry const* talentEntry = sTalentStore.LookupEntry(pos->talent_id))
+ {
+ if(node.first!=talentEntry->RankID[0])
+ {
+ sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong first rank spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ if(node.rank > 1 && node.prev != talentEntry->RankID[node.rank-1-1])
+ {
+ sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong prev rank spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+
+ if(node.req!=talentEntry->DependsOnSpell)
+ {
+ sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong required spell.",
+ spell_id,node.prev,node.first,node.rank,node.req);
+ continue;
+ }
+ }
+ }
+
+ mSpellChains[spell_id] = node;
+
+ if(node.prev)
+ mSpellChainsNext.insert(SpellChainMapNext::value_type(node.prev,spell_id));
+
+ if(node.req)
+ mSpellChainsNext.insert(SpellChainMapNext::value_type(node.req,spell_id));
+
+ ++count;
+ } while( result->NextRow() );
+
+ // additional integrity checks
+ for(SpellChainMap::iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i)
+ {
+ if(i->second.prev)
+ {
+ SpellChainMap::iterator i_prev = mSpellChains.find(i->second.prev);
+ if(i_prev == mSpellChains.end())
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found previous rank spell in table.",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
+ }
+ else if( i_prev->second.first != i->second.first )
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different first spell in chain compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
+ i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
+ }
+ else if( i_prev->second.rank+1 != i->second.rank )
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different rank compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
+ i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req);
+ }
+ }
+
+ if(i->second.req)
+ {
+ SpellChainMap::iterator i_req = mSpellChains.find(i->second.req);
+ if(i_req == mSpellChains.end())
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found required rank spell in table.",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req);
+ }
+ else if( i_req->second.first == i->second.first )
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell from same spell chain (prev: %u, first: %u, rank: %d, req: %u).",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
+ i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
+ }
+ else if( i_req->second.req )
+ {
+ sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell with required spell (prev: %u, first: %u, rank: %d, req: %u).",
+ i->first,i->second.prev,i->second.first,i->second.rank,i->second.req,
+ i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req);
+ }
+ }
+ }
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell chain records", count );
+}
+
+void SpellMgr::LoadSpellLearnSkills()
+{
+ mSpellLearnSkills.clear(); // need for reload case
+
+ // search auto-learned skills and add its to map also for use in unlearn spells/talents
+ uint32 dbc_count = 0;
+ for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
+ {
+ SpellEntry const* entry = sSpellStore.LookupEntry(spell);
+
+ if(!entry)
+ continue;
+
+ for(int i = 0; i < 3; ++i)
+ {
+ if(entry->Effect[i]==SPELL_EFFECT_SKILL)
+ {
+ SpellLearnSkillNode dbc_node;
+ dbc_node.skill = entry->EffectMiscValue[i];
+ if ( dbc_node.skill != SKILL_RIDING )
+ dbc_node.value = 1;
+ else
+ dbc_node.value = (entry->EffectBasePoints[i]+1)*75;
+ dbc_node.maxvalue = (entry->EffectBasePoints[i]+1)*75;
+
+ SpellLearnSkillNode const* db_node = GetSpellLearnSkill(spell);
+
+ mSpellLearnSkills[spell] = dbc_node;
+ ++dbc_count;
+ break;
+ }
+ }
+ }
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u Spell Learn Skills from DBC", dbc_count );
+}
+
+void SpellMgr::LoadSpellLearnSpells()
+{
+ mSpellLearnSpells.clear(); // need for reload case
+
+ QueryResult *result = WorldDatabase.Query("SELECT entry, SpellID FROM spell_learn_spell");
+ if(!result)
+ {
+ barGoLink bar( 1 );
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded 0 spell learn spells" );
+ sLog.outErrorDb("`spell_learn_spell` table is empty!");
+ return;
+ }
+
+ uint32 count = 0;
+
+ barGoLink bar( result->GetRowCount() );
+ do
+ {
+ bar.step();
+ Field *fields = result->Fetch();
+
+ uint32 spell_id = fields[0].GetUInt32();
+
+ SpellLearnSpellNode node;
+ node.spell = fields[1].GetUInt32();
+ node.autoLearned= false;
+
+ if(!sSpellStore.LookupEntry(spell_id))
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",spell_id);
+ continue;
+ }
+
+ if(!sSpellStore.LookupEntry(node.spell))
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",node.spell);
+ continue;
+ }
+
+ mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell_id,node));
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ // search auto-learned spells and add its to map also for use in unlearn spells/talents
+ uint32 dbc_count = 0;
+ for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
+ {
+ SpellEntry const* entry = sSpellStore.LookupEntry(spell);
+
+ if(!entry)
+ continue;
+
+ for(int i = 0; i < 3; ++i)
+ {
+ if(entry->Effect[i]==SPELL_EFFECT_LEARN_SPELL)
+ {
+ SpellLearnSpellNode dbc_node;
+ dbc_node.spell = entry->EffectTriggerSpell[i];
+ dbc_node.autoLearned = true;
+
+ SpellLearnSpellMap::const_iterator db_node_begin = GetBeginSpellLearnSpell(spell);
+ SpellLearnSpellMap::const_iterator db_node_end = GetEndSpellLearnSpell(spell);
+
+ bool found = false;
+ for(SpellLearnSpellMap::const_iterator itr = db_node_begin; itr != db_node_end; ++itr)
+ {
+ if(itr->second.spell == dbc_node.spell)
+ {
+ sLog.outErrorDb("Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.",
+ spell,dbc_node.spell);
+ found = true;
+ break;
+ }
+ }
+
+ if(!found) // add new spell-spell pair if not found
+ {
+ mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell,dbc_node));
+ ++dbc_count;
+ }
+ }
+ }
+ }
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell learn spells + %u found in DBC", count, dbc_count );
+}
+
+void SpellMgr::LoadSpellScriptTarget()
+{
+ mSpellScriptTarget.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM spell_script_target");
+
+ if(!result)
+ {
+ barGoLink bar(1);
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outErrorDb(">> Loaded 0 SpellScriptTarget. DB table `spell_script_target` is empty.");
+ return;
+ }
+
+ barGoLink bar(result->GetRowCount());
+
+ do
+ {
+ Field *fields = result->Fetch();
+ bar.step();
+
+ uint32 spellId = fields[0].GetUInt32();
+ uint32 type = fields[1].GetUInt32();
+ uint32 targetEntry = fields[2].GetUInt32();
+
+ SpellEntry const* spellProto = sSpellStore.LookupEntry(spellId);
+
+ if(!spellProto)
+ {
+ sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not exist.",spellId,targetEntry);
+ continue;
+ }
+
+ /*bool targetfound = false;
+ for(int i = 0; i <3; ++i)
+ {
+ if( spellProto->EffectImplicitTargetA[i]==TARGET_SCRIPT ||
+ spellProto->EffectImplicitTargetB[i]==TARGET_SCRIPT ||
+ spellProto->EffectImplicitTargetA[i]==TARGET_SCRIPT_COORDINATES ||
+ spellProto->EffectImplicitTargetB[i]==TARGET_SCRIPT_COORDINATES )
+ {
+ targetfound = true;
+ break;
+ }
+ }
+ if(!targetfound)
+ {
+ sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not have any implicit target TARGET_SCRIPT(38) or TARGET_SCRIPT_COORDINATES (46).",spellId,targetEntry);
+ continue;
+ }*/
+
+ if( type >= MAX_SPELL_TARGET_TYPE )
+ {
+ sLog.outErrorDb("Table `spell_script_target`: target type %u for TargetEntry %u is incorrect.",type,targetEntry);
+ continue;
+ }
+
+ switch(type)
+ {
+ case SPELL_TARGET_TYPE_GAMEOBJECT:
+ {
+ if( targetEntry==0 )
+ break;
+
+ if(!sGOStorage.LookupEntry(targetEntry))
+ {
+ sLog.outErrorDb("Table `spell_script_target`: gameobject template entry %u does not exist.",targetEntry);
+ continue;
+ }
+ break;
+ }
+ default:
+ {
+ if( targetEntry==0 )
+ {
+ sLog.outErrorDb("Table `spell_script_target`: target entry == 0 for not GO target type (%u).",type);
+ continue;
+ }
+ if(!sCreatureStorage.LookupEntry(targetEntry))
+ {
+ sLog.outErrorDb("Table `spell_script_target`: creature template entry %u does not exist.",targetEntry);
+ continue;
+ }
+ const CreatureInfo* cInfo = sCreatureStorage.LookupEntry(targetEntry);
+
+ if(spellId == 30427 && !cInfo->SkinLootId)
+ {
+ sLog.outErrorDb("Table `spell_script_target` has creature %u as a target of spellid 30427, but this creature has no skinlootid. Gas extraction will not work!", cInfo->Entry);
+ continue;
+ }
+ break;
+ }
+ }
+
+ mSpellScriptTarget.insert(SpellScriptTarget::value_type(spellId,SpellTargetEntry(SpellTargetType(type),targetEntry)));
+
+ ++count;
+ } while (result->NextRow());
+
+ delete result;
+
+ // Check all spells
+ /* Disabled (lot errors at this moment)
+ for(uint32 i = 1; i < sSpellStore.nCount; ++i)
+ {
+ SpellEntry const * spellInfo = sSpellStore.LookupEntry(i);
+ if(!spellInfo)
+ continue;
+
+ bool found = false;
+ for(int j=0; j<3; ++j)
+ {
+ if( spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT || spellInfo->EffectImplicitTargetA[j] != TARGET_SELF && spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT )
+ {
+ SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(spellInfo->Id);
+ SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(spellInfo->Id);
+ if(lower==upper)
+ {
+ sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = %u (TARGET_SCRIPT), but does not have record in `spell_script_target`",spellInfo->Id,TARGET_SCRIPT);
+ break; // effects of spell
+ }
+ }
+ }
+ }
+ */
+
+ sLog.outString();
+ sLog.outString(">> Loaded %u Spell Script Targets", count);
+}
+
+void SpellMgr::LoadSpellPetAuras()
+{
+ mSpellPetAuraMap.clear(); // need for reload case
+
+ uint32 count = 0;
+
+ // 0 1 2
+ QueryResult *result = WorldDatabase.Query("SELECT spell, pet, aura FROM spell_pet_auras");
+ if( !result )
+ {
+
+ barGoLink bar( 1 );
+
+ bar.step();
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell pet auras", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ uint16 spell = fields[0].GetUInt16();
+ uint16 pet = fields[1].GetUInt16();
+ uint16 aura = fields[2].GetUInt16();
+
+ SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find(spell);
+ if(itr != mSpellPetAuraMap.end())
+ {
+ itr->second.AddAura(pet, aura);
+ }
+ else
+ {
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
+ if (!spellInfo)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_pet_auras` does not exist", spell);
+ continue;
+ }
+ int i = 0;
+ for(; i < 3; ++i)
+ if((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA &&
+ spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DUMMY) ||
+ spellInfo->Effect[i] == SPELL_EFFECT_DUMMY)
+ break;
+
+ if(i == 3)
+ {
+ sLog.outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell);
+ continue;
+ }
+
+ SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(aura);
+ if (!spellInfo2)
+ {
+ sLog.outErrorDb("Aura %u listed in `spell_pet_auras` does not exist", aura);
+ continue;
+ }
+
+ PetAura pa(pet, aura, spellInfo->EffectImplicitTargetA[i] == TARGET_PET, spellInfo->EffectBasePoints[i] + spellInfo->EffectBaseDice[i]);
+ mSpellPetAuraMap[spell] = pa;
+ }
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u spell pet auras", count );
+}
+
+// set data in core for now
+void SpellMgr::LoadSpellCustomAttr()
+{
+ SpellEntry *tempSpell;
+ for(uint32 i = 0; i < GetSpellStore()->GetNumRows(); ++i)
+ {
+ tempSpell = (SpellEntry*)GetSpellStore()->LookupEntry(i);
+ if(!tempSpell)
+ continue;
+
+ mSpellCustomAttrMap[tempSpell->Id] = 0;
+
+ for(uint32 i = 0; i < 3; ++i)
+ {
+ switch(tempSpell->EffectApplyAuraName[i])
+ {
+ case SPELL_AURA_PERIODIC_DAMAGE:
+ case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
+ case SPELL_AURA_PERIODIC_LEECH:
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_EFFECT_DAMAGE;
+ break;
+ case SPELL_AURA_PERIODIC_HEAL:
+ case SPELL_AURA_OBS_MOD_HEALTH:
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_EFFECT_HEAL;
+ break;
+ default:
+ break;
+ }
+ }
+
+ if(tempSpell->SpellVisual == 3879)
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_CONE_BACK;
+
+ switch(tempSpell->Id)
+ {
+ case 26029: // dark glare
+ case 37433: // spout
+ case 43140: case 43215: // flame breath
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_CONE_LINE;
+ break;
+ case 24340: case 26558: case 28884: // Meteor
+ case 36837: case 38903: case 41276: // Meteor
+ case 26789: // Shard of the Fallen Star
+ case 31436: // Malevolent Cleave
+ case 35181: // Dive Bomb
+ case 40810: case 43267: case 43268: // Saber Lash
+ case 42384: // Brutal Swipe
+ case 45150: // Meteor Slash
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_SHARE_DAMAGE;
+ break;
+ case 44978: case 45001: case 45002: // Wild Magic
+ case 45004: case 45006: case 45010: // Wild Magic
+ case 31347: // Doom
+ case 41635: // Prayer of Mending
+ case 44869: // Spectral Blast
+ case 45027: // Revitalize
+ case 45976: // Muru Portal Channel
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_PLAYERS_ONLY;
+ tempSpell->MaxAffectedTargets = 1;
+ break;
+ case 41376: // Spite
+ case 39992: // Needle Spine
+ mSpellCustomAttrMap[tempSpell->Id] |= SPELL_ATTR_CU_PLAYERS_ONLY;
+ tempSpell->MaxAffectedTargets = 3;
+ break;
+ case 8122: case 8124: case 10888: case 10890: // Psychic Scream
+ tempSpell->Attributes |= SPELL_ATTR_BREAKABLE_BY_DAMAGE;
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+void SpellMgr::LoadSpellLinked()
+{
+ mSpellLinkedMap.clear(); // need for reload case
+ uint32 count = 0;
+
+ // 0 1 2
+ QueryResult *result = WorldDatabase.Query("SELECT spell_trigger, spell_effect, type FROM spell_linked_spell");
+ if( !result )
+ {
+ barGoLink bar( 1 );
+ bar.step();
+ sLog.outString();
+ sLog.outString( ">> Loaded %u linked spells", count );
+ return;
+ }
+
+ barGoLink bar( result->GetRowCount() );
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ bar.step();
+
+ int32 trigger = fields[0].GetInt32();
+ int32 effect = fields[1].GetInt32();
+ int32 type = fields[2].GetInt32();
+
+ SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(trigger));
+ if (!spellInfo)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(trigger));
+ continue;
+ }
+ spellInfo = sSpellStore.LookupEntry(abs(effect));
+ if (!spellInfo)
+ {
+ sLog.outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(effect));
+ continue;
+ }
+
+ if(type) //we will find a better way when more types are needed
+ trigger += 1000000;
+ mSpellLinkedMap[trigger].push_back(effect);
+
+ ++count;
+ } while( result->NextRow() );
+
+ delete result;
+
+ sLog.outString();
+ sLog.outString( ">> Loaded %u linked spells", count );
+}
+
+/// Some checks for spells, to prevent adding depricated/broken spells for trainers, spell book, etc
+bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg)
+{
+ // not exist
+ if(!spellInfo)
+ return false;
+
+ bool need_check_reagents = false;
+
+ // check effects
+ for(int i=0; i<3; ++i)
+ {
+ switch(spellInfo->Effect[i])
+ {
+ case 0:
+ continue;
+
+ // craft spell for crafting non-existed item (break client recipes list show)
+ case SPELL_EFFECT_CREATE_ITEM:
+ {
+ if(!ObjectMgr::GetItemPrototype( spellInfo->EffectItemType[i] ))
+ {
+ if(msg)
+ {
+ if(pl)
+ ChatHandler(pl).PSendSysMessage("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
+ else
+ sLog.outErrorDb("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
+ }
+ return false;
+ }
+
+ need_check_reagents = true;
+ break;
+ }
+ case SPELL_EFFECT_LEARN_SPELL:
+ {
+ SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(spellInfo->EffectTriggerSpell[0]);
+ if( !IsSpellValid(spellInfo2,pl,msg) )
+ {
+ if(msg)
+ {
+ if(pl)
+ ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[0]);
+ else
+ sLog.outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[0]);
+ }
+ return false;
+ }
+ break;
+ }
+ }
+ }
+
+ if(need_check_reagents)
+ {
+ for(int j = 0; j < 8; ++j)
+ {
+ if(spellInfo->Reagent[j] > 0 && !ObjectMgr::GetItemPrototype( spellInfo->Reagent[j] ))
+ {
+ if(msg)
+ {
+ if(pl)
+ ChatHandler(pl).PSendSysMessage("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
+ else
+ sLog.outErrorDb("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
+ }
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool IsSpellAllowedInLocation(SpellEntry const *spellInfo,uint32 map_id,uint32 zone_id,uint32 area_id)
+{
+ // normal case
+ if( spellInfo->AreaId && spellInfo->AreaId != zone_id && spellInfo->AreaId != area_id )
+ return false;
+
+ // elixirs (all area dependent elixirs have family SPELLFAMILY_POTION, use this for speedup)
+ if(spellInfo->SpellFamilyName==SPELLFAMILY_POTION)
+ {
+ if(uint32 mask = spellmgr.GetSpellElixirMask(spellInfo->Id))
+ {
+ if(mask & ELIXIR_UNSTABLE_MASK)
+ {
+ // in the Blade's Edge Mountains Plateaus and Gruul's Lair.
+ return zone_id ==3522 || map_id==565;
+ }
+ if(mask & ELIXIR_SHATTRATH_MASK)
+ {
+ // in Tempest Keep, Serpentshrine Cavern, Caverns of Time: Mount Hyjal, Black Temple
+ // TODO: and the Sunwell Plateau
+ if(zone_id ==3607 || map_id==534 || map_id==564)
+ return true;
+
+ MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
+ if(!mapEntry)
+ return false;
+
+ return mapEntry->multimap_id==206;
+ }
+
+ // elixirs not have another limitations
+ return true;
+ }
+ }
+
+ // special cases zone check (maps checked by multimap common id)
+ switch(spellInfo->Id)
+ {
+ case 41618:
+ case 41620:
+ {
+ MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
+ if(!mapEntry)
+ return false;
+
+ return mapEntry->multimap_id==206;
+ }
+
+ case 41617:
+ case 41619:
+ {
+ MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
+ if(!mapEntry)
+ return false;
+
+ return mapEntry->multimap_id==207;
+ }
+ // Dragonmaw Illusion
+ case 40216:
+ case 42016:
+ {
+ if ( area_id != 3759 && area_id != 3966 && area_id != 3939 )
+ return false;
+ break;
+ }
+ }
+
+ return true;
+}
+
+void SpellMgr::LoadSkillLineAbilityMap()
+{
+ mSkillLineAbilityMap.clear();
+
+ uint32 count = 0;
+
+ for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); i++)
+ {
+ SkillLineAbilityEntry const *SkillInfo = sSkillLineAbilityStore.LookupEntry(i);
+ if(!SkillInfo)
+ continue;
+
+ mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId,SkillInfo));
+ ++count;
+ }
+
+ sLog.outString();
+ sLog.outString(">> Loaded %u SkillLineAbility MultiMap", count);
+}
+
+DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto, bool triggered)
+{
+ // Explicit Diminishing Groups
+ switch(spellproto->SpellFamilyName)
+ {
+ case SPELLFAMILY_MAGE:
+ {
+ // Polymorph
+ if ((spellproto->SpellFamilyFlags & 0x00001000000LL) && spellproto->EffectApplyAuraName[0]==SPELL_AURA_MOD_CONFUSE)
+ return DIMINISHING_POLYMORPH;
+ break;
+ }
+ case SPELLFAMILY_ROGUE:
+ {
+ // Kidney Shot
+ if (spellproto->SpellFamilyFlags & 0x00000200000LL)
+ return DIMINISHING_KIDNEYSHOT;
+ // Blind
+ else if (spellproto->SpellFamilyFlags & 0x00001000000LL)
+ return DIMINISHING_BLIND_CYCLONE;
+ break;
+ }
+ case SPELLFAMILY_WARLOCK:
+ {
+ // Death Coil
+ if (spellproto->SpellFamilyFlags & 0x00000080000LL)
+ return DIMINISHING_DEATHCOIL;
+ // Fear
+ else if (spellproto->SpellFamilyFlags & 0x40840000000LL)
+ return DIMINISHING_WARLOCK_FEAR;
+ // Curses/etc
+ else if (spellproto->SpellFamilyFlags & 0x00080000000LL)
+ return DIMINISHING_LIMITONLY;
+ break;
+ }
+ case SPELLFAMILY_DRUID:
+ {
+ // Cyclone
+ if (spellproto->SpellFamilyFlags & 0x02000000000LL)
+ return DIMINISHING_BLIND_CYCLONE;
+ break;
+ }
+ case SPELLFAMILY_WARRIOR:
+ {
+ // Hamstring - limit duration to 10s in PvP
+ if (spellproto->SpellFamilyFlags & 0x00000000002LL)
+ return DIMINISHING_LIMITONLY;
+ break;
+ }
+ default:
+ break;
+ }
+
+ // Get by mechanic
+ for (uint8 i=0;i<3;++i)
+ {
+ if (spellproto->Mechanic == MECHANIC_STUN || spellproto->EffectMechanic[i] == MECHANIC_STUN)
+ return triggered ? DIMINISHING_TRIGGER_STUN : DIMINISHING_CONTROL_STUN;
+ else if (spellproto->Mechanic == MECHANIC_SLEEP || spellproto->EffectMechanic[i] == MECHANIC_SLEEP)
+ return DIMINISHING_SLEEP;
+ else if (spellproto->Mechanic == MECHANIC_ROOT || spellproto->EffectMechanic[i] == MECHANIC_ROOT)
+ return triggered ? DIMINISHING_TRIGGER_ROOT : DIMINISHING_CONTROL_ROOT;
+ else if (spellproto->Mechanic == MECHANIC_FEAR || spellproto->EffectMechanic[i] == MECHANIC_FEAR)
+ return DIMINISHING_FEAR;
+ else if (spellproto->Mechanic == MECHANIC_CHARM || spellproto->EffectMechanic[i] == MECHANIC_CHARM)
+ return DIMINISHING_CHARM;
+ else if (spellproto->Mechanic == MECHANIC_SILENCE || spellproto->EffectMechanic[i] == MECHANIC_SILENCE)
+ return DIMINISHING_SILENCE;
+ else if (spellproto->Mechanic == MECHANIC_DISARM || spellproto->EffectMechanic[i] == MECHANIC_DISARM)
+ return DIMINISHING_DISARM;
+ else if (spellproto->Mechanic == MECHANIC_FREEZE || spellproto->EffectMechanic[i] == MECHANIC_FREEZE)
+ return DIMINISHING_FREEZE;
+ else if (spellproto->Mechanic == MECHANIC_KNOCKOUT|| spellproto->EffectMechanic[i] == MECHANIC_KNOCKOUT ||
+ spellproto->Mechanic == MECHANIC_SAPPED || spellproto->EffectMechanic[i] == MECHANIC_SAPPED)
+ return DIMINISHING_KNOCKOUT;
+ else if (spellproto->Mechanic == MECHANIC_BANISH || spellproto->EffectMechanic[i] == MECHANIC_BANISH)
+ return DIMINISHING_BANISH;
+ }
+
+ return DIMINISHING_NONE;
+}
+
+bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group)
+{
+ switch(group)
+ {
+ case DIMINISHING_CONTROL_STUN:
+ case DIMINISHING_TRIGGER_STUN:
+ case DIMINISHING_KIDNEYSHOT:
+ case DIMINISHING_SLEEP:
+ case DIMINISHING_CONTROL_ROOT:
+ case DIMINISHING_TRIGGER_ROOT:
+ case DIMINISHING_FEAR:
+ case DIMINISHING_WARLOCK_FEAR:
+ case DIMINISHING_CHARM:
+ case DIMINISHING_POLYMORPH:
+ case DIMINISHING_FREEZE:
+ case DIMINISHING_KNOCKOUT:
+ case DIMINISHING_BLIND_CYCLONE:
+ case DIMINISHING_BANISH:
+ case DIMINISHING_LIMITONLY:
+ return true;
+ }
+ return false;
+}
+
+DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group)
+{
+ switch(group)
+ {
+ case DIMINISHING_BLIND_CYCLONE:
+ case DIMINISHING_CONTROL_STUN:
+ case DIMINISHING_TRIGGER_STUN:
+ case DIMINISHING_KIDNEYSHOT:
+ return DRTYPE_ALL;
+ case DIMINISHING_SLEEP:
+ case DIMINISHING_CONTROL_ROOT:
+ case DIMINISHING_TRIGGER_ROOT:
+ case DIMINISHING_FEAR:
+ case DIMINISHING_CHARM:
+ case DIMINISHING_POLYMORPH:
+ case DIMINISHING_SILENCE:
+ case DIMINISHING_DISARM:
+ case DIMINISHING_DEATHCOIL:
+ case DIMINISHING_FREEZE:
+ case DIMINISHING_BANISH:
+ case DIMINISHING_WARLOCK_FEAR:
+ case DIMINISHING_KNOCKOUT:
+ return DRTYPE_PLAYER;
+ }
+
+ return DRTYPE_NONE;
+}
diff --git a/src/game/SpellMgr.h b/src/game/SpellMgr.h
index 7de9c54c6cb..e86a394af9d 100644
--- a/src/game/SpellMgr.h
+++ b/src/game/SpellMgr.h
@@ -1,898 +1,899 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS
- *
- * Copyright (C) 2008 Trinity
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef _SPELLMGR_H
-#define _SPELLMGR_H
-
-// For static or at-server-startup loaded spell data
-// For more high level function for sSpellStore data
-
-#include "SharedDefines.h"
-#include "Database/DBCStructure.h"
-#include "Database/SQLStorage.h"
-
-#include "Utilities/UnorderedMap.h"
-#include