2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include "Database/DatabaseEnv.h"
22 #include "WorldPacket.h"
23 #include "ObjectMgr.h"
27 #include "SpellAuras.h"
28 #include "CreatureAI.h"
32 char const* petTypeSuffix
[MAX_PET_TYPE
] =
34 "'s Minion", // SUMMON_PET
35 "'s Pet", // HUNTER_PET
36 "'s Guardian", // GUARDIAN_PET
37 "'s Companion" // MINI_PET
40 Pet::Pet(PetType type
) :
41 Creature(), m_removed(false), m_petType(type
), m_happinessTimer(7500), m_duration(0), m_resetTalentsCost(0),
42 m_bonusdamage(0), m_resetTalentsTime(0), m_usedTalentCount(0), m_auraUpdateMask(0), m_loading(false),
49 // pets always have a charminfo, even if they are not actually charmed
50 CharmInfo
* charmInfo
= InitCharmInfo(this);
52 if(type
== MINI_PET
) // always passive
53 charmInfo
->SetReactState(REACT_PASSIVE
);
54 else if(type
== GUARDIAN_PET
) // always aggressive
55 charmInfo
->SetReactState(REACT_AGGRESSIVE
);
60 delete m_declinedname
;
63 void Pet::AddToWorld()
65 ///- Register the pet for guid lookup
67 GetMap()->GetObjectsStore().insert
<Pet
>(GetGUID(), (Pet
*)this);
72 void Pet::RemoveFromWorld()
74 ///- Remove the pet from the accessor
76 GetMap()->GetObjectsStore().erase
<Pet
>(GetGUID(), (Pet
*)NULL
);
78 ///- Don't call the function for Creature, normal mobs + totems go in a different storage
79 Unit::RemoveFromWorld();
82 bool Pet::LoadPetFromDB( Player
* owner
, uint32 petentry
, uint32 petnumber
, bool current
)
86 uint32 ownerid
= owner
->GetGUIDLow();
91 // known petnumber entry 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
92 result
= CharacterDatabase
.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
93 "FROM character_pet WHERE owner = '%u' AND id = '%u'",
96 // current pet (slot 0) 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
97 result
= CharacterDatabase
.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
98 "FROM character_pet WHERE owner = '%u' AND slot = '%u'",
99 ownerid
, PET_SAVE_AS_CURRENT
);
101 // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
102 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
103 result
= CharacterDatabase
.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
104 "FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '%u' OR slot > '%u') ",
105 ownerid
, petentry
,PET_SAVE_AS_CURRENT
,PET_SAVE_LAST_STABLE_SLOT
);
107 // any current or other non-stabled pet (for hunter "call pet")
108 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
109 result
= CharacterDatabase
.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
110 "FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u') ",
111 ownerid
,PET_SAVE_AS_CURRENT
,PET_SAVE_LAST_STABLE_SLOT
);
116 Field
*fields
= result
->Fetch();
118 // update for case of current pet "slot = 0"
119 petentry
= fields
[1].GetUInt32();
126 uint32 summon_spell_id
= fields
[17].GetUInt32();
127 SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(summon_spell_id
);
129 bool is_temporary_summoned
= spellInfo
&& GetSpellDuration(spellInfo
) > 0;
131 // check temporary summoned pets like mage water elemental
132 if (current
&& is_temporary_summoned
)
138 PetType pet_type
= PetType(fields
[18].GetUInt8());
139 if(pet_type
==HUNTER_PET
)
141 CreatureInfo
const* creatureInfo
= ObjectMgr::GetCreatureTemplate(petentry
);
142 if(!creatureInfo
|| !creatureInfo
->isTameable(owner
->CanTameExoticPets()))
149 uint32 pet_number
= fields
[0].GetUInt32();
151 if (current
&& owner
->IsPetNeedBeTemporaryUnsummoned())
153 owner
->SetTemporaryUnsummonedPetNumber(pet_number
);
158 Map
*map
= owner
->GetMap();
159 uint32 guid
= map
->GenerateLocalLowGuid(HIGHGUID_PET
);
160 if (!Create(guid
, map
, owner
->GetPhaseMask(), petentry
, pet_number
))
167 owner
->GetClosePoint(px
, py
, pz
, GetObjectSize(), PET_FOLLOW_DIST
, PET_FOLLOW_ANGLE
);
169 Relocate(px
, py
, pz
, owner
->GetOrientation());
171 if (!IsPositionValid())
173 sLog
.outError("Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
174 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
179 setPetType(pet_type
);
180 setFaction(owner
->getFaction());
181 SetUInt32Value(UNIT_CREATED_BY_SPELL
, summon_spell_id
);
183 CreatureInfo
const *cinfo
= GetCreatureInfo();
184 if (cinfo
->type
== CREATURE_TYPE_CRITTER
)
187 map
->Add((Creature
*)this);
192 m_charmInfo
->SetPetNumber(pet_number
, IsPermanentPetFor(owner
));
194 SetOwnerGUID(owner
->GetGUID());
195 SetDisplayId(fields
[3].GetUInt32());
196 SetNativeDisplayId(fields
[3].GetUInt32());
197 uint32 petlevel
= fields
[4].GetUInt32();
198 SetUInt32Value(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_NONE
);
199 SetName(fields
[8].GetString());
201 switch (getPetType())
204 petlevel
=owner
->getLevel();
206 SetUInt32Value(UNIT_FIELD_BYTES_0
, 2048);
207 SetUInt32Value(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
208 // this enables popup window (pet dismiss, cancel)
211 SetUInt32Value(UNIT_FIELD_BYTES_0
, 0x02020100);
212 SetSheath(SHEATH_STATE_MELEE
);
213 SetByteValue(UNIT_FIELD_BYTES_2
, 2, fields
[9].GetBool() ? UNIT_RENAME_NOT_ALLOWED
: UNIT_RENAME_ALLOWED
);
215 SetUInt32Value(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
216 // this enables popup window (pet abandon, cancel)
217 SetMaxPower(POWER_HAPPINESS
, GetCreatePowers(POWER_HAPPINESS
));
218 SetPower(POWER_HAPPINESS
, fields
[12].GetUInt32());
219 setPowerType(POWER_FOCUS
);
222 sLog
.outError("Pet have incorrect type (%u) for pet loading.", getPetType());
228 SetCanModifyStats(true);
229 InitStatsForLevel(petlevel
);
230 InitTalentForLevel(); // set original talents points before spell loading
232 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP
, time(NULL
));
233 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, fields
[5].GetUInt32());
234 SetCreatorGUID(owner
->GetGUID());
236 m_charmInfo
->SetReactState(ReactStates(fields
[6].GetUInt8()));
238 uint32 savedhealth
= fields
[10].GetUInt32();
239 uint32 savedmana
= fields
[11].GetUInt32();
241 // set current pet as current
243 // 1..MAX_PET_STABLES in stable slot
244 // PET_SAVE_NOT_IN_SLOT(100) = not stable slot (summoning))
245 if (fields
[7].GetUInt32() != 0)
247 CharacterDatabase
.BeginTransaction();
248 CharacterDatabase
.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND slot = '%u' AND id <> '%u'",
249 PET_SAVE_NOT_IN_SLOT
, ownerid
, PET_SAVE_AS_CURRENT
, m_charmInfo
->GetPetNumber());
250 CharacterDatabase
.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND id = '%u'",
251 PET_SAVE_AS_CURRENT
, ownerid
, m_charmInfo
->GetPetNumber());
252 CharacterDatabase
.CommitTransaction();
255 // load action bar, if data broken will fill later by default spells.
256 if (!is_temporary_summoned
)
257 m_charmInfo
->LoadPetActionBar(fields
[13].GetCppString());
259 // since last save (in seconds)
260 uint32 timediff
= (time(NULL
) - fields
[14].GetUInt32());
262 m_resetTalentsCost
= fields
[15].GetUInt32();
263 m_resetTalentsTime
= fields
[16].GetUInt64();
267 //load spells/cooldowns/auras
268 _LoadAuras(timediff
);
271 if (is_temporary_summoned
)
273 // Temporary summoned pets always have initial spell list at load
274 InitPetCreateSpells();
279 CastPetAuras(current
);
282 if (getPetType() == SUMMON_PET
&& !current
) //all (?) summon pets come with full health when called, but not when they are current
284 SetHealth(GetMaxHealth());
285 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
289 SetHealth(savedhealth
> GetMaxHealth() ? GetMaxHealth() : savedhealth
);
290 SetPower(POWER_MANA
, savedmana
> GetMaxPower(POWER_MANA
) ? GetMaxPower(POWER_MANA
) : savedmana
);
294 map
->Add((Creature
*)this);
296 // Spells should be loaded after pet is added to map, because in CheckCast is check on it
298 InitLevelupSpellsForLevel();
300 CleanupActionBar(); // remove unknown spells from action bar after load
302 _LoadSpellCooldowns();
304 owner
->SetPet(this); // in DB stored only full controlled creature
305 sLog
.outDebug("New Pet has guid %u", GetGUIDLow());
307 if (owner
->GetTypeId() == TYPEID_PLAYER
)
309 ((Player
*)owner
)->PetSpellInitialize();
310 if(((Player
*)owner
)->GetGroup())
311 ((Player
*)owner
)->SetGroupUpdateFlag(GROUP_UPDATE_PET
);
313 ((Player
*)owner
)->SendTalentsInfoData(true);
316 if (owner
->GetTypeId() == TYPEID_PLAYER
&& getPetType() == HUNTER_PET
)
318 result
= CharacterDatabase
.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner
->GetGUIDLow(), GetCharmInfo()->GetPetNumber());
323 delete m_declinedname
;
325 m_declinedname
= new DeclinedName
;
326 Field
*fields2
= result
->Fetch();
327 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
329 m_declinedname
->name
[i
] = fields2
[i
].GetCppString();
336 SynchronizeLevelWithOwner();
340 void Pet::SavePetToDB(PetSaveMode mode
)
345 // save only fully controlled creature
349 // not save not player pets
350 if(!IS_PLAYER_GUID(GetOwnerGUID()))
353 Player
* pOwner
= (Player
*)GetOwner();
357 // current/stable/not_in_slot
358 if (mode
>= PET_SAVE_AS_CURRENT
)
360 // not save pet as current if another pet temporary unsummoned
361 if (mode
== PET_SAVE_AS_CURRENT
&& pOwner
->GetTemporaryUnsummonedPetNumber() &&
362 pOwner
->GetTemporaryUnsummonedPetNumber() != m_charmInfo
->GetPetNumber())
364 // pet will lost anyway at restore temporary unsummoned
365 if(getPetType()==HUNTER_PET
)
369 mode
= PET_SAVE_NOT_IN_SLOT
;
372 uint32 curhealth
= GetHealth();
373 uint32 curmana
= GetPower(POWER_MANA
);
375 // stable and not in slot saves
376 if (mode
!= PET_SAVE_AS_CURRENT
)
380 _SaveSpellCooldowns();
383 uint32 owner
= GUID_LOPART(GetOwnerGUID());
384 std::string name
= m_name
;
385 CharacterDatabase
.escape_string(name
);
386 CharacterDatabase
.BeginTransaction();
387 // remove current data
388 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner
,m_charmInfo
->GetPetNumber() );
390 // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
391 if(mode
<= PET_SAVE_LAST_STABLE_SLOT
)
392 CharacterDatabase
.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND slot = '%u'",
393 PET_SAVE_NOT_IN_SLOT
, owner
, uint32(mode
) );
395 // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
396 if(getPetType()==HUNTER_PET
&& (mode
==PET_SAVE_AS_CURRENT
||mode
> PET_SAVE_LAST_STABLE_SLOT
))
397 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u')",
398 owner
,PET_SAVE_AS_CURRENT
,PET_SAVE_LAST_STABLE_SLOT
);
400 std::ostringstream ss
;
401 ss
<< "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType) "
403 << m_charmInfo
->GetPetNumber() << ", "
404 << GetEntry() << ", "
406 << GetNativeDisplayId() << ", "
407 << getLevel() << ", "
408 << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE
) << ", "
409 << uint32(m_charmInfo
->GetReactState()) << ", "
410 << uint32(mode
) << ", '"
411 << name
.c_str() << "', "
412 << uint32((GetByteValue(UNIT_FIELD_BYTES_2
, 2) == UNIT_RENAME_ALLOWED
)?0:1) << ", "
413 << (curhealth
<1?1:curhealth
) << ", "
415 << GetPower(POWER_HAPPINESS
) << ", '";
417 // save only spell slots from action bar
418 for(uint32 i
= ACTION_BAR_INDEX_PET_SPELL_START
; i
< ACTION_BAR_INDEX_PET_SPELL_END
; ++i
)
420 ss
<< uint32(m_charmInfo
->GetActionBarEntry(i
)->GetType()) << " "
421 << uint32(m_charmInfo
->GetActionBarEntry(i
)->GetAction()) << " ";
425 << time(NULL
) << ", "
426 << uint32(m_resetTalentsCost
) << ", "
427 << uint64(m_resetTalentsTime
) << ", "
428 << GetUInt32Value(UNIT_CREATED_BY_SPELL
) << ", "
429 << uint32(getPetType()) << ")";
431 CharacterDatabase
.Execute( ss
.str().c_str() );
432 CharacterDatabase
.CommitTransaction();
437 RemoveAllAuras(AURA_REMOVE_BY_DELETE
);
438 DeleteFromDB(m_charmInfo
->GetPetNumber());
442 void Pet::DeleteFromDB(uint32 guidlow
)
444 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow
);
445 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow
);
446 CharacterDatabase
.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow
);
447 CharacterDatabase
.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow
);
448 CharacterDatabase
.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow
);
451 void Pet::setDeathState(DeathState s
) // overwrite virtual Creature::setDeathState and Unit::setDeathState
453 Creature::setDeathState(s
);
454 if(getDeathState()==CORPSE
)
456 //remove summoned pet (no corpse)
457 if(getPetType()==SUMMON_PET
)
458 Remove(PET_SAVE_NOT_IN_SLOT
);
459 // other will despawn at corpse desppawning (Pet::Update code)
462 // pet corpse non lootable and non skinnable
463 SetUInt32Value( UNIT_DYNAMIC_FLAGS
, 0x00 );
464 RemoveFlag (UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
466 //lose happiness when died and not in BG/Arena
467 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
468 if(!mapEntry
|| (mapEntry
->map_type
!= MAP_ARENA
&& mapEntry
->map_type
!= MAP_BATTLEGROUND
))
469 ModifyPower(POWER_HAPPINESS
, -HAPPINESS_LEVEL_SIZE
);
471 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
474 else if(getDeathState()==ALIVE
)
476 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
481 void Pet::Update(uint32 diff
)
483 if(m_removed
) // pet already removed, just wait in remove queue, no updates
486 switch( m_deathState
)
490 if( m_deathTimer
<= diff
)
492 assert(getPetType()!=SUMMON_PET
&& "Must be already removed.");
493 Remove(PET_SAVE_NOT_IN_SLOT
); //hunters' pets never get removed because of death, NEVER!
500 // unsummon pet that lost owner
501 Unit
* owner
= GetOwner();
502 if(!owner
|| (!IsWithinDistInMap(owner
, OWNER_MAX_DISTANCE
) && (owner
->GetCharmGUID() && (owner
->GetCharmGUID() != GetGUID()))) || (isControlled() && !owner
->GetPetGUID()))
504 Remove(PET_SAVE_NOT_IN_SLOT
, true);
510 if( owner
->GetPetGUID() != GetGUID() )
512 Remove(getPetType()==HUNTER_PET
?PET_SAVE_AS_DELETED
:PET_SAVE_NOT_IN_SLOT
);
519 if(m_duration
> diff
)
523 Remove(getPetType() != SUMMON_PET
? PET_SAVE_AS_DELETED
:PET_SAVE_NOT_IN_SLOT
);
528 //regenerate focus for hunter pets or energy for deathknight's ghoul
529 if(m_regenTimer
<= diff
)
531 switch (getPowerType())
535 Regenerate(getPowerType());
543 m_regenTimer
-= diff
;
545 if(getPetType() != HUNTER_PET
)
548 if(m_happinessTimer
<= diff
)
551 m_happinessTimer
= 7500;
554 m_happinessTimer
-= diff
;
561 Creature::Update(diff
);
564 void Pet::Regenerate(Powers power
)
566 uint32 curValue
= GetPower(power
);
567 uint32 maxValue
= GetMaxPower(power
);
569 if (curValue
>= maxValue
)
572 float addvalue
= 0.0f
;
579 addvalue
= 24 * sWorld
.getRate(RATE_POWER_FOCUS
);
584 // For deathknight's ghoul.
592 // Apply modifiers (if any).
593 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
594 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
595 if ((*i
)->GetModifier()->m_miscvalue
== power
)
596 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
598 ModifyPower(power
, (int32
)addvalue
);
601 void Pet::LooseHappiness()
603 uint32 curValue
= GetPower(POWER_HAPPINESS
);
606 int32 addvalue
= 670; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
607 if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
608 addvalue
= int32(addvalue
* 1.5);
609 ModifyPower(POWER_HAPPINESS
, -addvalue
);
612 HappinessState
Pet::GetHappinessState()
614 if(GetPower(POWER_HAPPINESS
) < HAPPINESS_LEVEL_SIZE
)
616 else if(GetPower(POWER_HAPPINESS
) >= HAPPINESS_LEVEL_SIZE
* 2)
622 bool Pet::CanTakeMoreActiveSpells(uint32 spellid
)
624 uint8 activecount
= 1;
625 uint32 chainstartstore
[ACTIVE_SPELLS_MAX
];
627 if(IsPassiveSpell(spellid
))
630 chainstartstore
[0] = spellmgr
.GetFirstSpellInChain(spellid
);
632 for (PetSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
634 if(itr
->second
.state
== PETSPELL_REMOVED
)
637 if(IsPassiveSpell(itr
->first
))
640 uint32 chainstart
= spellmgr
.GetFirstSpellInChain(itr
->first
);
644 for(x
= 0; x
< activecount
; x
++)
646 if(chainstart
== chainstartstore
[x
])
650 if(x
== activecount
) //spellchain not yet saved -> add active count
653 if(activecount
> ACTIVE_SPELLS_MAX
)
655 chainstartstore
[x
] = chainstart
;
661 void Pet::Remove(PetSaveMode mode
, bool returnreagent
)
663 Unit
* owner
= GetOwner();
667 if(owner
->GetTypeId()==TYPEID_PLAYER
)
669 ((Player
*)owner
)->RemovePet(this,mode
,returnreagent
);
673 // only if current pet in slot
674 if(owner
->GetPetGUID()==GetGUID())
678 AddObjectToRemoveList();
682 void Pet::GivePetXP(uint32 xp
)
684 if(getPetType() != HUNTER_PET
)
693 uint32 level
= getLevel();
695 // XP to money conversion processed in Player::RewardQuest
696 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
699 uint32 curXP
= GetUInt32Value(UNIT_FIELD_PETEXPERIENCE
);
700 uint32 nextLvlXP
= GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
);
701 uint32 newXP
= curXP
+ xp
;
703 if(newXP
>= nextLvlXP
&& level
+1 > GetOwner()->getLevel())
705 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, nextLvlXP
-1);
709 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
713 GivePetLevel(level
+1);
714 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
, objmgr
.GetXPForLevel(level
+1)/4);
717 nextLvlXP
= GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
);
720 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, newXP
);
723 void Pet::GivePetLevel(uint32 level
)
728 InitStatsForLevel(level
);
729 InitLevelupSpellsForLevel();
730 InitTalentForLevel();
733 bool Pet::CreateBaseAtCreature(Creature
* creature
)
737 sLog
.outError("CRITICAL: NULL pointer parsed into CreateBaseAtCreature()");
741 uint32 guid
= creature
->GetMap()->GenerateLocalLowGuid(HIGHGUID_PET
);
743 sLog
.outBasic("Create pet");
744 uint32 pet_number
= objmgr
.GeneratePetNumber();
745 if(!Create(guid
, creature
->GetMap(), creature
->GetPhaseMask(), creature
->GetEntry(), pet_number
))
748 Relocate(creature
->GetPositionX(), creature
->GetPositionY(), creature
->GetPositionZ(), creature
->GetOrientation());
750 if(!IsPositionValid())
752 sLog
.outError("Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
753 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
757 CreatureInfo
const *cinfo
= GetCreatureInfo();
760 sLog
.outError("CreateBaseAtCreature() failed, creatureInfo is missing!");
764 if(cinfo
->type
== CREATURE_TYPE_CRITTER
)
766 setPetType(MINI_PET
);
769 SetDisplayId(creature
->GetDisplayId());
770 SetNativeDisplayId(creature
->GetNativeDisplayId());
771 SetMaxPower(POWER_HAPPINESS
, GetCreatePowers(POWER_HAPPINESS
));
772 SetPower(POWER_HAPPINESS
, 166500);
773 setPowerType(POWER_FOCUS
);
774 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP
, 0);
775 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, 0);
776 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
, objmgr
.GetXPForLevel(creature
->getLevel())/4);
777 SetUInt32Value(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_NONE
);
779 if(CreatureFamilyEntry
const* cFamily
= sCreatureFamilyStore
.LookupEntry(cinfo
->family
))
780 SetName(cFamily
->Name
[sWorld
.GetDefaultDbcLocale()]);
782 SetName(creature
->GetNameForLocaleIdx(objmgr
.GetDBCLocaleIndex()));
784 if(cinfo
->type
== CREATURE_TYPE_BEAST
)
786 SetUInt32Value(UNIT_FIELD_BYTES_0
, 0x02020100);
787 SetSheath(SHEATH_STATE_MELEE
);
788 SetByteValue(UNIT_FIELD_BYTES_2
, 2, UNIT_RENAME_ALLOWED
);
789 SetUInt32Value(UNIT_MOD_CAST_SPEED
, creature
->GetUInt32Value(UNIT_MOD_CAST_SPEED
));
794 bool Pet::InitStatsForLevel(uint32 petlevel
, Unit
* owner
)
796 CreatureInfo
const *cinfo
= GetCreatureInfo();
804 sLog
.outError("attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo
->Entry
);
809 uint32 creature_ID
= (getPetType() == HUNTER_PET
) ? 1 : cinfo
->Entry
;
813 SetMeleeDamageSchool(SpellSchools(cinfo
->dmgschool
));
815 SetModifierValue(UNIT_MOD_ARMOR
, BASE_VALUE
, float(petlevel
*50));
817 SetAttackTime(BASE_ATTACK
, BASE_ATTACK_TIME
);
818 SetAttackTime(OFF_ATTACK
, BASE_ATTACK_TIME
);
819 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
821 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0);
823 CreatureFamilyEntry
const* cFamily
= sCreatureFamilyStore
.LookupEntry(cinfo
->family
);
824 if(cFamily
&& cFamily
->minScale
> 0.0f
&& getPetType()==HUNTER_PET
)
827 if (getLevel() >= cFamily
->maxScaleLevel
)
828 scale
= cFamily
->maxScale
;
829 else if (getLevel() <= cFamily
->minScaleLevel
)
830 scale
= cFamily
->minScale
;
832 scale
= cFamily
->minScale
+ float(getLevel() - cFamily
->minScaleLevel
) / cFamily
->maxScaleLevel
* (cFamily
->maxScale
- cFamily
->minScale
);
834 SetFloatValue(OBJECT_FIELD_SCALE_X
, scale
);
838 int32 createResistance
[MAX_SPELL_SCHOOL
] = {0,0,0,0,0,0,0};
840 if(cinfo
&& getPetType() != HUNTER_PET
)
842 createResistance
[SPELL_SCHOOL_HOLY
] = cinfo
->resistance1
;
843 createResistance
[SPELL_SCHOOL_FIRE
] = cinfo
->resistance2
;
844 createResistance
[SPELL_SCHOOL_NATURE
] = cinfo
->resistance3
;
845 createResistance
[SPELL_SCHOOL_FROST
] = cinfo
->resistance4
;
846 createResistance
[SPELL_SCHOOL_SHADOW
] = cinfo
->resistance5
;
847 createResistance
[SPELL_SCHOOL_ARCANE
] = cinfo
->resistance6
;
854 if(owner
->GetTypeId() == TYPEID_PLAYER
)
856 switch(owner
->getClass())
861 //the damage bonus used for pets is either fire or shadow damage, whatever is higher
862 uint32 fire
= owner
->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+ SPELL_SCHOOL_FIRE
);
863 uint32 shadow
= owner
->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+ SPELL_SCHOOL_SHADOW
);
864 uint32 val
= (fire
> shadow
) ? fire
: shadow
;
866 SetBonusDamage(int32 (val
* 0.15f
));
867 //bonusAP += val * 0.57;
872 //40% damage bonus of mage's frost damage
873 float val
= owner
->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+ SPELL_SCHOOL_FROST
) * 0.4;
876 SetBonusDamage( int32(val
));
884 SetBaseWeaponDamage(BASE_ATTACK
, MINDAMAGE
, float(petlevel
- (petlevel
/ 4)) );
885 SetBaseWeaponDamage(BASE_ATTACK
, MAXDAMAGE
, float(petlevel
+ (petlevel
/ 4)) );
887 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
889 PetLevelInfo
const* pInfo
= objmgr
.GetPetLevelInfo(creature_ID
, petlevel
);
890 if(pInfo
) // exist in DB
892 SetCreateHealth(pInfo
->health
);
893 SetCreateMana(pInfo
->mana
);
896 SetModifierValue(UNIT_MOD_ARMOR
, BASE_VALUE
, float(pInfo
->armor
));
898 for(int stat
= 0; stat
< MAX_STATS
; ++stat
)
900 SetCreateStat(Stats(stat
), float(pInfo
->stats
[stat
]));
903 else // not exist in DB, use some default fake data
905 sLog
.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo
->Entry
);
907 // remove elite bonuses included in DB values
908 SetCreateHealth(uint32(((float(cinfo
->maxhealth
) / cinfo
->maxlevel
) / (1 + 2 * cinfo
->rank
)) * petlevel
) );
909 SetCreateMana( uint32(((float(cinfo
->maxmana
) / cinfo
->maxlevel
) / (1 + 2 * cinfo
->rank
)) * petlevel
) );
911 SetCreateStat(STAT_STRENGTH
, 22);
912 SetCreateStat(STAT_AGILITY
, 22);
913 SetCreateStat(STAT_STAMINA
, 25);
914 SetCreateStat(STAT_INTELLECT
, 28);
915 SetCreateStat(STAT_SPIRIT
, 27);
921 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
, objmgr
.GetXPForLevel(petlevel
)/4);
922 //these formula may not be correct; however, it is designed to be close to what it should be
923 //this makes dps 0.5 of pets level
924 SetBaseWeaponDamage(BASE_ATTACK
, MINDAMAGE
, float(petlevel
- (petlevel
/ 4)) );
925 //damage range is then petlevel / 2
926 SetBaseWeaponDamage(BASE_ATTACK
, MAXDAMAGE
, float(petlevel
+ (petlevel
/ 4)) );
927 //damage is increased afterwards as strength and pet scaling modify attack power
929 //stored standard pet stats are entry 1 in pet_levelinfo
930 PetLevelInfo
const* pInfo
= objmgr
.GetPetLevelInfo(creature_ID
, petlevel
);
931 if(pInfo
) // exist in DB
933 SetCreateHealth(pInfo
->health
);
934 SetModifierValue(UNIT_MOD_ARMOR
, BASE_VALUE
, float(pInfo
->armor
));
935 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
937 for( int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
939 SetCreateStat(Stats(i
), float(pInfo
->stats
[i
]));
942 else // not exist in DB, use some default fake data
944 sLog
.outErrorDb("Hunter pet levelstats missing in DB");
946 // remove elite bonuses included in DB values
947 SetCreateHealth( uint32(((float(cinfo
->maxhealth
) / cinfo
->maxlevel
) / (1 + 2 * cinfo
->rank
)) * petlevel
) );
949 SetCreateStat(STAT_STRENGTH
, 22);
950 SetCreateStat(STAT_AGILITY
, 22);
951 SetCreateStat(STAT_STAMINA
, 25);
952 SetCreateStat(STAT_INTELLECT
, 28);
953 SetCreateStat(STAT_SPIRIT
, 27);
958 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, 0);
959 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
, 1000);
961 SetCreateMana(28 + 10*petlevel
);
962 SetCreateHealth(28 + 30*petlevel
);
964 // FIXME: this is wrong formula, possible each guardian pet have own damage formula
965 //these formula may not be correct; however, it is designed to be close to what it should be
966 //this makes dps 0.5 of pets level
967 SetBaseWeaponDamage(BASE_ATTACK
, MINDAMAGE
, float(petlevel
- (petlevel
/ 4)));
968 //damage range is then petlevel / 2
969 SetBaseWeaponDamage(BASE_ATTACK
, MAXDAMAGE
, float(petlevel
+ (petlevel
/ 4)));
972 sLog
.outError("Pet have incorrect type (%u) for levelup.", getPetType());
976 for (int i
= SPELL_SCHOOL_HOLY
; i
< MAX_SPELL_SCHOOL
; ++i
)
977 SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START
+ i
), BASE_VALUE
, float(createResistance
[i
]));
981 SetHealth(GetMaxHealth());
982 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
987 bool Pet::HaveInDiet(ItemPrototype
const* item
) const
992 CreatureInfo
const* cInfo
= GetCreatureInfo();
996 CreatureFamilyEntry
const* cFamily
= sCreatureFamilyStore
.LookupEntry(cInfo
->family
);
1000 uint32 diet
= cFamily
->petFoodMask
;
1001 uint32 FoodMask
= 1 << (item
->FoodType
-1);
1002 return diet
& FoodMask
;
1005 uint32
Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel
)
1007 // -5 or greater food level
1008 if(getLevel() <= itemlevel
+ 5) //possible to feed level 60 pet with level 55 level food for full effect
1011 else if(getLevel() <= itemlevel
+ 10) //pure guess, but sounds good
1014 else if(getLevel() <= itemlevel
+ 14) //level 55 food gets green on 70, makes sense to me
1018 return 0; //food too low level
1021 void Pet::_LoadSpellCooldowns()
1023 m_CreatureSpellCooldowns
.clear();
1024 m_CreatureCategoryCooldowns
.clear();
1026 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo
->GetPetNumber());
1030 time_t curTime
= time(NULL
);
1032 WorldPacket
data(SMSG_SPELL_COOLDOWN
, (8+1+result
->GetRowCount()*8));
1034 data
<< uint8(0x0); // flags (0x1, 0x2)
1038 Field
*fields
= result
->Fetch();
1040 uint32 spell_id
= fields
[0].GetUInt32();
1041 time_t db_time
= (time_t)fields
[1].GetUInt64();
1043 if(!sSpellStore
.LookupEntry(spell_id
))
1045 sLog
.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo
->GetPetNumber(),spell_id
);
1049 // skip outdated cooldown
1050 if(db_time
<= curTime
)
1053 data
<< uint32(spell_id
);
1054 data
<< uint32(uint32(db_time
-curTime
)*IN_MILISECONDS
);
1056 _AddCreatureSpellCooldown(spell_id
,db_time
);
1058 sLog
.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo
->GetPetNumber(), spell_id
, uint32(db_time
-curTime
));
1060 while( result
->NextRow() );
1064 if(!m_CreatureSpellCooldowns
.empty() && GetOwner())
1066 ((Player
*)GetOwner())->GetSession()->SendPacket(&data
);
1071 void Pet::_SaveSpellCooldowns()
1073 CharacterDatabase
.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo
->GetPetNumber());
1075 time_t curTime
= time(NULL
);
1077 // remove oudated and save active
1078 for(CreatureSpellCooldowns::iterator itr
= m_CreatureSpellCooldowns
.begin();itr
!= m_CreatureSpellCooldowns
.end();)
1080 if(itr
->second
<= curTime
)
1081 m_CreatureSpellCooldowns
.erase(itr
++);
1084 CharacterDatabase
.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" UI64FMTD
"')", m_charmInfo
->GetPetNumber(), itr
->first
, uint64(itr
->second
));
1090 void Pet::_LoadSpells()
1092 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT spell,active FROM pet_spell WHERE guid = '%u'",m_charmInfo
->GetPetNumber());
1098 Field
*fields
= result
->Fetch();
1100 addSpell(fields
[0].GetUInt32(), ActiveStates(fields
[1].GetUInt8()), PETSPELL_UNCHANGED
);
1102 while( result
->NextRow() );
1108 void Pet::_SaveSpells()
1110 for (PetSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
1114 // prevent saving family passives to DB
1115 if (itr
->second
.type
== PETSPELL_FAMILY
)
1118 switch(itr
->second
.state
)
1120 case PETSPELL_REMOVED
:
1121 CharacterDatabase
.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo
->GetPetNumber(), itr
->first
);
1122 m_spells
.erase(itr
);
1124 case PETSPELL_CHANGED
:
1125 CharacterDatabase
.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo
->GetPetNumber(), itr
->first
);
1126 CharacterDatabase
.PExecute("INSERT INTO pet_spell (guid,spell,active) VALUES ('%u', '%u', '%u')", m_charmInfo
->GetPetNumber(), itr
->first
, itr
->second
.active
);
1129 CharacterDatabase
.PExecute("INSERT INTO pet_spell (guid,spell,active) VALUES ('%u', '%u', '%u')", m_charmInfo
->GetPetNumber(), itr
->first
, itr
->second
.active
);
1131 case PETSPELL_UNCHANGED
:
1135 itr
->second
.state
= PETSPELL_UNCHANGED
;
1139 void Pet::_LoadAuras(uint32 timediff
)
1143 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo
->GetPetNumber());
1149 Field
*fields
= result
->Fetch();
1150 uint64 caster_guid
= fields
[0].GetUInt64();
1151 uint32 spellid
= fields
[1].GetUInt32();
1152 uint32 effindex
= fields
[2].GetUInt32();
1153 uint32 stackcount
= fields
[3].GetUInt32();
1154 int32 damage
= (int32
)fields
[4].GetUInt32();
1155 int32 maxduration
= (int32
)fields
[5].GetUInt32();
1156 int32 remaintime
= (int32
)fields
[6].GetUInt32();
1157 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
1159 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
1162 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
1168 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
1172 // negative effects should continue counting down after logout
1173 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
1175 if (remaintime
/IN_MILISECONDS
<= int32(timediff
))
1178 remaintime
-= timediff
*IN_MILISECONDS
;
1181 // prevent wrong values of remaincharges
1182 if(spellproto
->procCharges
)
1184 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
1185 remaincharges
= spellproto
->procCharges
;
1190 /// do not load single target auras (unless they were cast by the player)
1191 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
1194 for(uint32 i
=0; i
<stackcount
; ++i
)
1196 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
1199 damage
= aura
->GetModifier()->m_amount
;
1200 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
1204 while( result
->NextRow() );
1210 void Pet::_SaveAuras()
1212 CharacterDatabase
.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", m_charmInfo
->GetPetNumber());
1214 AuraMap
const& auras
= GetAuras();
1218 spellEffectPair lastEffectPair
= auras
.begin()->first
;
1219 uint32 stackCounter
= 1;
1221 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
1223 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
1225 AuraMap::const_iterator itr2
= itr
;
1226 // save previous spellEffectPair to db
1228 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
1229 /// do not save single target auras (unless they were cast by the player)
1230 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
1232 if(!itr2
->second
->IsPassive())
1234 // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
1236 for (i
= 0; i
< 3; ++i
)
1237 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
||
1238 spellInfo
->Effect
[i
] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER
||
1239 spellInfo
->Effect
[i
] == SPELL_EFFECT_APPLY_AREA_AURA_PET
)
1244 CharacterDatabase
.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
1245 "VALUES ('%u', '" UI64FMTD
"', '%u', '%u', '%u', '%d', '%d', '%d', '%d')",
1246 m_charmInfo
->GetPetNumber(), itr2
->second
->GetCasterGUID(),(uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->GetAuraCharges()));
1250 if(itr
== auras
.end())
1254 if (lastEffectPair
== itr
->first
)
1258 lastEffectPair
= itr
->first
;
1264 bool Pet::addSpell(uint32 spell_id
,ActiveStates active
/*= ACT_DECIDE*/, PetSpellState state
/*= PETSPELL_NEW*/, PetSpellType type
/*= PETSPELL_NORMAL*/)
1266 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
1269 // do pet spell book cleanup
1270 if(state
== PETSPELL_UNCHANGED
) // spell load case
1272 sLog
.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id
);
1273 CharacterDatabase
.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id
);
1276 sLog
.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
1281 PetSpellMap::iterator itr
= m_spells
.find(spell_id
);
1282 if (itr
!= m_spells
.end())
1284 if (itr
->second
.state
== PETSPELL_REMOVED
)
1286 m_spells
.erase(itr
);
1287 state
= PETSPELL_CHANGED
;
1289 else if (state
== PETSPELL_UNCHANGED
&& itr
->second
.state
!= PETSPELL_UNCHANGED
)
1291 // can be in case spell loading but learned at some previous spell loading
1292 itr
->second
.state
= PETSPELL_UNCHANGED
;
1294 if(active
== ACT_ENABLED
)
1295 ToggleAutocast(spell_id
, true);
1296 else if(active
== ACT_DISABLED
)
1297 ToggleAutocast(spell_id
, false);
1305 uint32 oldspell_id
= 0;
1308 newspell
.state
= state
;
1309 newspell
.type
= type
;
1311 if(active
== ACT_DECIDE
) //active was not used before, so we save it's autocast/passive state here
1313 if(IsPassiveSpell(spell_id
))
1314 newspell
.active
= ACT_PASSIVE
;
1316 newspell
.active
= ACT_DISABLED
;
1319 newspell
.active
= active
;
1321 // talent: unlearn all other talent ranks (high and low)
1322 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
1324 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
1326 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
1328 // skip learning spell and no rank spell case
1329 uint32 rankSpellId
= talentInfo
->RankID
[i
];
1330 if(!rankSpellId
|| rankSpellId
==spell_id
)
1333 // skip unknown ranks
1334 if(!HasSpell(rankSpellId
))
1336 removeSpell(rankSpellId
,false,false);
1340 else if(spellmgr
.GetSpellRank(spell_id
)!=0)
1342 for (PetSpellMap::const_iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
1344 if(itr2
->second
.state
== PETSPELL_REMOVED
) continue;
1346 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
1348 // replace by new high rank
1349 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
1351 newspell
.active
= itr2
->second
.active
;
1353 if(newspell
.active
== ACT_ENABLED
)
1354 ToggleAutocast(itr2
->first
, false);
1356 oldspell_id
= itr2
->first
;
1357 unlearnSpell(itr2
->first
,false,false);
1360 // ignore new lesser rank
1361 else if(spellmgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
1367 m_spells
[spell_id
] = newspell
;
1369 if (IsPassiveSpell(spell_id
))
1370 CastSpell(this, spell_id
, true);
1372 m_charmInfo
->AddSpellToActionBar(spell_id
);
1374 if(newspell
.active
== ACT_ENABLED
)
1375 ToggleAutocast(spell_id
, true);
1377 uint32 talentCost
= GetTalentSpellCost(spell_id
);
1380 int32 free_points
= GetMaxTalentPointsForLevel(getLevel());
1381 m_usedTalentCount
+=talentCost
;
1382 // update free talent points
1383 free_points
-=m_usedTalentCount
;
1384 SetFreeTalentPoints(free_points
> 0 ? free_points
: 0);
1389 bool Pet::learnSpell(uint32 spell_id
)
1391 // prevent duplicated entires in spell book
1392 if (!addSpell(spell_id
))
1397 Unit
* owner
= GetOwner();
1398 if(owner
&& owner
->GetTypeId() == TYPEID_PLAYER
)
1400 WorldPacket
data(SMSG_PET_LEARNED_SPELL
, 4);
1401 data
<< uint32(spell_id
);
1402 ((Player
*)owner
)->GetSession()->SendPacket(&data
);
1404 ((Player
*)owner
)->PetSpellInitialize();
1410 void Pet::InitLevelupSpellsForLevel()
1412 uint32 level
= getLevel();
1414 if(PetLevelupSpellSet
const *levelupSpells
= GetCreatureInfo()->family
? spellmgr
.GetPetLevelupSpellList(GetCreatureInfo()->family
) : NULL
)
1416 // PetLevelupSpellSet ordered by levels, process in reversed order
1417 for(PetLevelupSpellSet::const_reverse_iterator itr
= levelupSpells
->rbegin(); itr
!= levelupSpells
->rend(); ++itr
)
1419 // will called first if level down
1420 if(itr
->first
> level
)
1421 unlearnSpell(itr
->second
,true); // will learn prev rank if any
1422 // will called if level up
1424 learnSpell(itr
->second
); // will unlearn prev rank if any
1428 int32 petSpellsId
= GetCreatureInfo()->PetSpellDataId
? -(int32
)GetCreatureInfo()->PetSpellDataId
: GetEntry();
1430 // default spells (can be not learned if pet level (as owner level decrease result for example) less first possible in normal game)
1431 if(PetDefaultSpellsEntry
const *defSpells
= spellmgr
.GetPetDefaultSpellsEntry(petSpellsId
))
1433 for(int i
= 0; i
< MAX_CREATURE_SPELL_DATA_SLOT
; ++i
)
1435 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(defSpells
->spellid
[i
]);
1439 // will called first if level down
1440 if(spellEntry
->spellLevel
> level
)
1441 unlearnSpell(spellEntry
->Id
,true);
1442 // will called if level up
1444 learnSpell(spellEntry
->Id
);
1449 bool Pet::unlearnSpell(uint32 spell_id
, bool learn_prev
, bool clear_ab
)
1451 if(removeSpell(spell_id
,learn_prev
,clear_ab
))
1455 if (Unit
* owner
= GetOwner())
1457 if(owner
->GetTypeId() == TYPEID_PLAYER
)
1459 WorldPacket
data(SMSG_PET_REMOVED_SPELL
, 4);
1460 data
<< uint32(spell_id
);
1461 ((Player
*)owner
)->GetSession()->SendPacket(&data
);
1470 bool Pet::removeSpell(uint32 spell_id
, bool learn_prev
, bool clear_ab
)
1472 PetSpellMap::iterator itr
= m_spells
.find(spell_id
);
1473 if (itr
== m_spells
.end())
1476 if(itr
->second
.state
== PETSPELL_REMOVED
)
1479 if(itr
->second
.state
== PETSPELL_NEW
)
1480 m_spells
.erase(itr
);
1482 itr
->second
.state
= PETSPELL_REMOVED
;
1484 RemoveAurasDueToSpell(spell_id
);
1486 uint32 talentCost
= GetTalentSpellCost(spell_id
);
1489 if (m_usedTalentCount
> talentCost
)
1490 m_usedTalentCount
-=talentCost
;
1492 m_usedTalentCount
= 0;
1493 // update free talent points
1494 int32 free_points
= GetMaxTalentPointsForLevel(getLevel()) - m_usedTalentCount
;
1495 SetFreeTalentPoints(free_points
> 0 ? free_points
: 0);
1500 if (uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
1501 learnSpell(prev_id
);
1506 // if remove last rank or non-ranked then update action bar at server and client if need
1507 if (clear_ab
&& !learn_prev
&& m_charmInfo
->RemoveSpellFromActionBar(spell_id
))
1511 // need update action bar for last removed rank
1512 if (Unit
* owner
= GetOwner())
1513 if (owner
->GetTypeId() == TYPEID_PLAYER
)
1514 ((Player
*)owner
)->PetSpellInitialize();
1522 void Pet::CleanupActionBar()
1524 for(int i
= 0; i
< MAX_UNIT_ACTION_BAR_INDEX
; ++i
)
1525 if(UnitActionBarEntry
const* ab
= m_charmInfo
->GetActionBarEntry(i
))
1526 if(uint32 action
= ab
->GetAction())
1527 if(ab
->IsActionBarForSpell() && !HasSpell(action
))
1528 m_charmInfo
->SetActionBar(i
,0,ACT_DISABLED
);
1531 void Pet::InitPetCreateSpells()
1533 m_charmInfo
->InitPetActionBar();
1538 CastPetAuras(false);
1541 bool Pet::resetTalents(bool no_cost
)
1543 Unit
*owner
= GetOwner();
1544 if (!owner
|| owner
->GetTypeId()!=TYPEID_PLAYER
)
1547 // not need after this call
1548 if(((Player
*)owner
)->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS
))
1549 ((Player
*)owner
)->RemoveAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS
,true);
1551 CreatureInfo
const * ci
= GetCreatureInfo();
1554 // Check pet talent type
1555 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
1556 if(!pet_family
|| pet_family
->petTalentType
< 0)
1559 Player
*player
= (Player
*)owner
;
1561 uint32 level
= getLevel();
1562 uint32 talentPointsForLevel
= GetMaxTalentPointsForLevel(level
);
1564 if (m_usedTalentCount
== 0)
1566 SetFreeTalentPoints(talentPointsForLevel
);
1574 cost
= resetTalentsCost();
1576 if (player
->GetMoney() < cost
)
1578 player
->SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
1583 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
1585 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
1587 if (!talentInfo
) continue;
1589 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
1594 // unlearn only talents for pets family talent type
1595 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
1598 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
1600 for(PetSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end();)
1602 if(itr
->second
.state
== PETSPELL_REMOVED
)
1607 // remove learned spells (all ranks)
1608 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
1610 // unlearn if first rank is talent or learned by talent
1611 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
1613 removeSpell(itr
->first
,false);
1614 itr
= m_spells
.begin();
1623 SetFreeTalentPoints(talentPointsForLevel
);
1627 player
->ModifyMoney(-(int32
)cost
);
1629 m_resetTalentsCost
= cost
;
1630 m_resetTalentsTime
= time(NULL
);
1632 player
->PetSpellInitialize();
1636 void Pet::resetTalentsForAllPetsOf(Player
* owner
, Pet
* online_pet
/*= NULL*/)
1638 // not need after this call
1639 if(((Player
*)owner
)->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS
))
1640 ((Player
*)owner
)->RemoveAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS
,true);
1644 online_pet
->resetTalents(true);
1646 // now need only reset for offline pets (all pets except online case)
1647 uint32 except_petnumber
= online_pet
? online_pet
->GetCharmInfo()->GetPetNumber() : 0;
1649 QueryResult
*resultPets
= CharacterDatabase
.PQuery(
1650 "SELECT id FROM character_pet WHERE owner = '%u' AND id <> '%u'",
1651 owner
->GetGUIDLow(),except_petnumber
);
1657 QueryResult
*result
= CharacterDatabase
.PQuery(
1658 "SELECT DISTINCT pet_spell.spell FROM pet_spell, character_pet "
1659 "WHERE character_pet.owner = '%u' AND character_pet.id = pet_spell.guid AND character_pet.id <> %u",
1660 owner
->GetGUIDLow(),except_petnumber
);
1668 bool need_comma
= false;
1669 std::ostringstream ss
;
1670 ss
<< "DELETE FROM pet_spell WHERE guid IN (";
1674 Field
*fields
= resultPets
->Fetch();
1676 uint32 id
= fields
[0].GetUInt32();
1685 while( resultPets
->NextRow() );
1689 ss
<< ") AND spell IN (";
1691 bool need_execute
= false;
1694 Field
*fields
= result
->Fetch();
1696 uint32 spell
= fields
[0].GetUInt32();
1698 if(!GetTalentSpellCost(spell
))
1706 need_execute
= true;
1708 while( result
->NextRow() );
1717 CharacterDatabase
.Execute(ss
.str().c_str());
1720 void Pet::InitTalentForLevel()
1722 uint32 level
= getLevel();
1723 uint32 talentPointsForLevel
= GetMaxTalentPointsForLevel(level
);
1724 // Reset talents in case low level (on level down) or wrong points for level (hunter can unlearn TP increase talent)
1725 if(talentPointsForLevel
== 0 || m_usedTalentCount
> talentPointsForLevel
)
1727 // Remove all talent points
1730 SetFreeTalentPoints(talentPointsForLevel
- m_usedTalentCount
);
1732 Unit
*owner
= GetOwner();
1733 if (!owner
|| owner
->GetTypeId() != TYPEID_PLAYER
)
1737 ((Player
*)owner
)->SendTalentsInfoData(true);
1740 uint32
Pet::resetTalentsCost() const
1742 uint32 days
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/DAY
;
1744 // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
1745 if(m_resetTalentsCost
< 10*SILVER
|| days
> 0)
1748 else if(m_resetTalentsCost
< 50*SILVER
)
1751 else if(m_resetTalentsCost
< 1*GOLD
)
1753 // then increasing at a rate of 1 gold; cap 10 gold
1755 return (m_resetTalentsCost
+ 1*GOLD
> 10*GOLD
? 10*GOLD
: m_resetTalentsCost
+ 1*GOLD
);
1758 uint8
Pet::GetMaxTalentPointsForLevel(uint32 level
)
1760 uint8 points
= (level
>= 20) ? ((level
- 16) / 4) : 0;
1761 // Mod points from owner SPELL_AURA_MOD_PET_TALENT_POINTS
1762 if (Unit
*owner
= GetOwner())
1763 points
+=owner
->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS
);
1767 void Pet::ToggleAutocast(uint32 spellid
, bool apply
)
1769 if(IsPassiveSpell(spellid
))
1772 PetSpellMap::iterator itr
= m_spells
.find(spellid
);
1778 for (i
= 0; i
< m_autospells
.size() && m_autospells
[i
] != spellid
; ++i
)
1781 if (i
== m_autospells
.size())
1783 m_autospells
.push_back(spellid
);
1785 if(itr
->second
.active
!= ACT_ENABLED
)
1787 itr
->second
.active
= ACT_ENABLED
;
1788 if(itr
->second
.state
!= PETSPELL_NEW
)
1789 itr
->second
.state
= PETSPELL_CHANGED
;
1795 AutoSpellList::iterator itr2
= m_autospells
.begin();
1796 for (i
= 0; i
< m_autospells
.size() && m_autospells
[i
] != spellid
; ++i
, itr2
++)
1799 if (i
< m_autospells
.size())
1801 m_autospells
.erase(itr2
);
1802 if(itr
->second
.active
!= ACT_DISABLED
)
1804 itr
->second
.active
= ACT_DISABLED
;
1805 if(itr
->second
.state
!= PETSPELL_NEW
)
1806 itr
->second
.state
= PETSPELL_CHANGED
;
1812 bool Pet::IsPermanentPetFor(Player
* owner
)
1814 switch(getPetType())
1817 switch(owner
->getClass())
1820 return GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
;
1821 case CLASS_DEATH_KNIGHT
:
1822 return GetCreatureInfo()->type
== CREATURE_TYPE_UNDEAD
;
1833 bool Pet::Create(uint32 guidlow
, Map
*map
, uint32 phaseMask
, uint32 Entry
, uint32 pet_number
)
1836 SetPhaseMask(phaseMask
,false);
1838 Object::_Create(guidlow
, pet_number
, HIGHGUID_PET
);
1840 m_DBTableGuid
= guidlow
;
1841 m_originalEntry
= Entry
;
1843 if(!InitEntry(Entry
))
1846 SetSheath(SHEATH_STATE_MELEE
);
1848 if(getPetType() == MINI_PET
) // always non-attackable
1849 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_NON_ATTACKABLE
);
1854 bool Pet::HasSpell(uint32 spell
) const
1856 PetSpellMap::const_iterator itr
= m_spells
.find(spell
);
1857 return (itr
!= m_spells
.end() && itr
->second
.state
!= PETSPELL_REMOVED
);
1860 // Get all passive spells in our skill line
1861 void Pet::LearnPetPassives()
1863 CreatureInfo
const* cInfo
= GetCreatureInfo();
1867 CreatureFamilyEntry
const* cFamily
= sCreatureFamilyStore
.LookupEntry(cInfo
->family
);
1871 PetFamilySpellsStore::const_iterator petStore
= sPetFamilySpellsStore
.find(cFamily
->ID
);
1872 if(petStore
!= sPetFamilySpellsStore
.end())
1874 for(PetFamilySpellsSet::const_iterator petSet
= petStore
->second
.begin(); petSet
!= petStore
->second
.end(); ++petSet
)
1875 addSpell(*petSet
, ACT_DECIDE
, PETSPELL_NEW
, PETSPELL_FAMILY
);
1879 void Pet::CastPetAuras(bool current
)
1881 Unit
* owner
= GetOwner();
1882 if(!owner
|| owner
->GetTypeId()!=TYPEID_PLAYER
)
1885 if(!IsPermanentPetFor((Player
*)owner
))
1888 for(PetAuraSet::const_iterator itr
= owner
->m_petAuras
.begin(); itr
!= owner
->m_petAuras
.end();)
1890 PetAura
const* pa
= *itr
;
1893 if(!current
&& pa
->IsRemovedOnChangePet())
1894 owner
->RemovePetAura(pa
);
1900 void Pet::CastPetAura(PetAura
const* aura
)
1902 uint32 auraId
= aura
->GetAura(GetEntry());
1906 if(auraId
== 35696) // Demonic Knowledge
1908 int32 basePoints
= int32(aura
->GetDamage() * (GetStat(STAT_STAMINA
) + GetStat(STAT_INTELLECT
)) / 100);
1909 CastCustomSpell(this, auraId
, &basePoints
, NULL
, NULL
, true);
1912 CastSpell(this, auraId
, true);
1915 struct DoPetLearnSpell
1917 DoPetLearnSpell(Pet
& _pet
) : pet(_pet
) {}
1918 void operator() (uint32 spell_id
) { pet
.learnSpell(spell_id
); }
1922 void Pet::learnSpellHighRank(uint32 spellid
)
1924 learnSpell(spellid
);
1926 DoPetLearnSpell
worker(*this);
1927 spellmgr
.doForHighRanks(spellid
,worker
);
1930 void Pet::SynchronizeLevelWithOwner()
1932 Unit
* owner
= GetOwner();
1933 if (!owner
|| owner
->GetTypeId() != TYPEID_PLAYER
)
1936 switch(getPetType())
1938 // always same level
1940 GivePetLevel(owner
->getLevel());
1942 // can't be greater owner level
1944 if(getLevel() > owner
->getLevel())
1946 GivePetLevel(owner
->getLevel());
1947 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
, objmgr
.GetXPForLevel(owner
->getLevel())/4);
1948 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE
, GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP
)-1);