Removed direct use of some updatefields
[getmangos.git] / src / game / Pet.cpp
blob4838ac098cf0defbca3ea3bde597d40975b34b2c
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Log.h"
22 #include "WorldSession.h"
23 #include "WorldPacket.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "Pet.h"
27 #include "MapManager.h"
28 #include "Formulas.h"
29 #include "SpellAuras.h"
30 #include "CreatureAI.h"
31 #include "Unit.h"
32 #include "Util.h"
34 char const* petTypeSuffix[MAX_PET_TYPE] =
36 "'s Minion", // SUMMON_PET
37 "'s Pet", // HUNTER_PET
38 "'s Guardian", // GUARDIAN_PET
39 "'s Companion" // MINI_PET
42 Pet::Pet(PetType type) : Creature()
44 m_isPet = true;
45 m_name = "Pet";
46 m_petType = type;
48 m_removed = false;
49 m_regenTimer = 4000;
50 m_happinessTimer = 7500;
51 m_duration = 0;
52 m_bonusdamage = 0;
54 m_resetTalentsCost = 0;
55 m_resetTalentsTime = 0;
57 m_auraUpdateMask = 0;
59 m_loading = false;
61 // pets always have a charminfo, even if they are not actually charmed
62 CharmInfo* charmInfo = InitCharmInfo(this);
64 if(type == MINI_PET) // always passive
65 charmInfo->SetReactState(REACT_PASSIVE);
66 else if(type == GUARDIAN_PET) // always aggressive
67 charmInfo->SetReactState(REACT_AGGRESSIVE);
69 m_spells.clear();
70 m_Auras.clear();
71 m_CreatureSpellCooldowns.clear();
72 m_CreatureCategoryCooldowns.clear();
73 m_autospells.clear();
74 m_declinedname = NULL;
77 Pet::~Pet()
79 if(m_uint32Values) // only for fully created Object
81 for (PetSpellMap::iterator i = m_spells.begin(); i != m_spells.end(); ++i)
82 delete i->second;
83 ObjectAccessor::Instance().RemoveObject(this);
86 delete m_declinedname;
89 void Pet::AddToWorld()
91 ///- Register the pet for guid lookup
92 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
93 Unit::AddToWorld();
96 void Pet::RemoveFromWorld()
98 ///- Remove the pet from the accessor
99 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
100 ///- Don't call the function for Creature, normal mobs + totems go in a different storage
101 Unit::RemoveFromWorld();
104 bool Pet::LoadPetFromDB( Unit* owner, uint32 petentry, uint32 petnumber, bool current )
106 m_loading = true;
108 uint32 ownerid = owner->GetGUIDLow();
110 QueryResult *result;
112 if(petnumber)
113 // known petnumber entry 0 1 2(?) 3 4 5 6 7 8(?) 9 10 11 12 13 14 15 16 17 18 19 20
114 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, 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);
115 else if(current)
116 // 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
117 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, 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 );
118 else if(petentry)
119 // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
120 // 0 1 2(?) 3 4 5 6 7 8(?) 9 10 11 12 13 14 15 16 17 18 19 20
121 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, 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 );
122 else
123 // any current or other non-stabled pet (for hunter "call pet")
124 // 0 1 2(?) 3 4 5 6 7 8(?) 9 10 11 12 13 14 15 16 17 18 19 20
125 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, 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);
127 if(!result)
128 return false;
130 Field *fields = result->Fetch();
132 // update for case of current pet "slot = 0"
133 petentry = fields[1].GetUInt32();
134 if(!petentry)
136 delete result;
137 return false;
140 uint32 summon_spell_id = fields[19].GetUInt32();
141 SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
143 bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
145 // check temporary summoned pets like mage water elemental
146 if(current && is_temporary_summoned)
148 delete result;
149 return false;
152 Map *map = owner->GetMap();
153 uint32 guid = objmgr.GenerateLowGuid(HIGHGUID_PET);
154 uint32 pet_number = fields[0].GetUInt32();
155 if(!Create(guid, map, petentry, pet_number))
157 delete result;
158 return false;
161 float px, py, pz;
162 owner->GetClosePoint(px, py, pz, GetObjectSize(), PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
164 Relocate(px, py, pz, owner->GetOrientation());
166 if(!IsPositionValid())
168 sLog.outError("ERROR: Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
169 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
170 delete result;
171 return false;
174 setPetType(PetType(fields[20].GetUInt8()));
175 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, owner->getFaction());
176 SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
178 CreatureInfo const *cinfo = GetCreatureInfo();
179 if(cinfo->type == CREATURE_TYPE_CRITTER)
181 AIM_Initialize();
182 map->Add((Creature*)this);
183 delete result;
184 return true;
187 if(getPetType() == HUNTER_PET || (getPetType() == SUMMON_PET && cinfo->type == CREATURE_TYPE_DEMON && owner->getClass() == CLASS_WARLOCK))
188 m_charmInfo->SetPetNumber(pet_number, true);
189 else
190 m_charmInfo->SetPetNumber(pet_number, false);
192 SetOwnerGUID(owner->GetGUID());
193 SetDisplayId(fields[3].GetUInt32());
194 SetNativeDisplayId(fields[3].GetUInt32());
195 uint32 petlevel = fields[4].GetUInt32();
196 SetUInt32Value(UNIT_NPC_FLAGS, 0);
197 SetName(fields[9].GetString());
199 switch(getPetType())
201 case SUMMON_PET:
202 petlevel=owner->getLevel();
204 SetUInt32Value(UNIT_FIELD_BYTES_0, 2048);
205 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
206 // this enables popup window (pet dismiss, cancel)
207 break;
208 case HUNTER_PET:
209 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
210 SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[7].GetUInt32());
211 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
212 SetByteValue(UNIT_FIELD_BYTES_2, 2, fields[10].GetBool() ? UNIT_RENAME_NOT_ALLOWED : UNIT_RENAME_ALLOWED);
214 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
215 // this enables popup window (pet abandon, cancel)
216 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
217 SetPower(POWER_HAPPINESS, fields[13].GetUInt32());
218 setPowerType(POWER_FOCUS);
219 break;
220 default:
221 sLog.outError("Pet have incorrect type (%u) for pet loading.", getPetType());
224 InitStatsForLevel(petlevel);
225 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
226 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
227 SetCreatorGUID(owner->GetGUID());
229 m_charmInfo->SetReactState(ReactStates(fields[6].GetUInt8()));
231 uint32 savedhealth = fields[11].GetUInt32();
232 uint32 savedmana = fields[12].GetUInt32();
234 // set current pet as current
235 if(fields[8].GetUInt32() != 0)
237 CharacterDatabase.BeginTransaction();
238 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '3' WHERE owner = '%u' AND slot = '0' AND id <> '%u'", ownerid, m_charmInfo->GetPetNumber());
239 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '0' WHERE owner = '%u' AND id = '%u'", ownerid, m_charmInfo->GetPetNumber());
240 CharacterDatabase.CommitTransaction();
243 if(!is_temporary_summoned)
245 // permanent controlled pets store state in DB
246 Tokens tokens = StrSplit(fields[14].GetString(), " ");
248 if(tokens.size() != 20)
250 delete result;
251 return false;
254 int index;
255 Tokens::iterator iter;
256 for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
258 m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
259 ++iter;
260 m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
263 //init teach spells
264 tokens = StrSplit(fields[15].GetString(), " ");
265 for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
267 uint32 tmp = atol((*iter).c_str());
269 ++iter;
271 if(tmp)
272 AddTeachSpell(tmp, atol((*iter).c_str()));
273 else
274 break;
278 // since last save (in seconds)
279 uint32 timediff = (time(NULL) - fields[16].GetUInt32());
281 m_resetTalentsCost = fields[17].GetUInt32();
282 m_resetTalentsTime = fields[18].GetUInt64();
284 delete result;
286 //load spells/cooldowns/auras
287 SetCanModifyStats(true);
288 _LoadAuras(timediff);
290 //init AB
291 if(is_temporary_summoned)
293 // Temporary summoned pets always have initial spell list at load
294 InitPetCreateSpells();
296 else
298 LearnPetPassives();
299 CastPetAuras(current);
302 if(getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
304 SetHealth(GetMaxHealth());
305 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
307 else
309 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
310 SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
313 AIM_Initialize();
314 map->Add((Creature*)this);
316 // Spells should be loaded after pet is added to map, because in CanCast is check on it
317 _LoadSpells();
318 _LoadSpellCooldowns();
320 owner->SetPet(this); // in DB stored only full controlled creature
321 sLog.outDebug("New Pet has guid %u", GetGUIDLow());
323 if(owner->GetTypeId() == TYPEID_PLAYER)
325 ((Player*)owner)->PetSpellInitialize();
326 if(((Player*)owner)->GetGroup())
327 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
330 if(owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
332 result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner->GetGUIDLow(), GetCharmInfo()->GetPetNumber());
334 if(result)
336 if(m_declinedname)
337 delete m_declinedname;
339 m_declinedname = new DeclinedName;
340 Field *fields = result->Fetch();
341 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
343 m_declinedname->name[i] = fields[i].GetCppString();
348 m_loading = false;
349 return true;
352 void Pet::SavePetToDB(PetSaveMode mode)
354 if(!GetEntry())
355 return;
357 // save only fully controlled creature
358 if(!isControlled())
359 return;
361 uint32 curhealth = GetHealth();
362 uint32 curmana = GetPower(POWER_MANA);
364 switch(mode)
366 case PET_SAVE_IN_STABLE_SLOT_1:
367 case PET_SAVE_IN_STABLE_SLOT_2:
368 case PET_SAVE_NOT_IN_SLOT:
370 RemoveAllAuras();
372 //only alive hunter pets get auras saved, the others don't
373 if(!(getPetType() == HUNTER_PET && isAlive()))
374 m_Auras.clear();
376 default:
377 break;
380 _SaveSpells();
381 _SaveSpellCooldowns();
382 _SaveAuras();
384 switch(mode)
386 case PET_SAVE_AS_CURRENT:
387 case PET_SAVE_IN_STABLE_SLOT_1:
388 case PET_SAVE_IN_STABLE_SLOT_2:
389 case PET_SAVE_NOT_IN_SLOT:
391 uint32 owner = GUID_LOPART(GetOwnerGUID());
392 std::string name = m_name;
393 CharacterDatabase.escape_string(name);
394 CharacterDatabase.BeginTransaction();
395 // remove current data
396 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner,m_charmInfo->GetPetNumber() );
398 // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
399 if(mode!=PET_SAVE_NOT_IN_SLOT)
400 CharacterDatabase.PExecute("UPDATE character_pet SET slot = 3 WHERE owner = '%u' AND slot = '%u'", owner, uint32(mode) );
402 // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
403 if(getPetType()==HUNTER_PET && (mode==PET_SAVE_AS_CURRENT||mode==PET_SAVE_NOT_IN_SLOT))
404 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3')", owner );
405 // save pet
406 std::ostringstream ss;
407 ss << "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType) "
408 << "VALUES ("
409 << m_charmInfo->GetPetNumber() << ", "
410 << GetEntry() << ", "
411 << owner << ", "
412 << GetNativeDisplayId() << ", "
413 << getLevel() << ", "
414 << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE) << ", "
415 << uint32(m_charmInfo->GetReactState()) << ", "
416 << uint32(GetFreeTalentPoints()) << ", "
417 << uint32(mode) << ", '"
418 << name.c_str() << "', "
419 << uint32((GetByteValue(UNIT_FIELD_BYTES_2, 2) == UNIT_RENAME_ALLOWED)?0:1) << ", "
420 << (curhealth<1?1:curhealth) << ", "
421 << curmana << ", "
422 << GetPower(POWER_HAPPINESS) << ", '";
424 for(uint32 i = 0; i < 10; i++)
425 ss << uint32(m_charmInfo->GetActionBarEntry(i)->Type) << " " << uint32(m_charmInfo->GetActionBarEntry(i)->SpellOrAction) << " ";
426 ss << "', '";
428 //save spells the pet can teach to it's Master
430 int i = 0;
431 for(TeachSpellMap::iterator itr = m_teachspells.begin(); i < 4 && itr != m_teachspells.end(); ++i, ++itr)
432 ss << itr->first << " " << itr->second << " ";
433 for(; i < 4; ++i)
434 ss << uint32(0) << " " << uint32(0) << " ";
437 ss << "', "
438 << time(NULL) << ", "
439 << uint32(m_resetTalentsCost) << ", "
440 << uint64(m_resetTalentsTime) << ", "
441 << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ", "
442 << uint32(getPetType()) << ")";
444 CharacterDatabase.Execute( ss.str().c_str() );
446 CharacterDatabase.CommitTransaction();
447 break;
449 case PET_SAVE_AS_DELETED:
451 RemoveAllAuras();
452 DeleteFromDB(m_charmInfo->GetPetNumber());
453 break;
455 default:
456 sLog.outError("Unknown pet save/remove mode: %d",mode);
460 void Pet::DeleteFromDB(uint32 guidlow)
462 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow);
463 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow);
464 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow);
465 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow);
466 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow);
469 void Pet::setDeathState(DeathState s) // overwrite virtual Creature::setDeathState and Unit::setDeathState
471 Creature::setDeathState(s);
472 if(getDeathState()==CORPSE)
474 //remove summoned pet (no corpse)
475 if(getPetType()==SUMMON_PET)
476 Remove(PET_SAVE_NOT_IN_SLOT);
477 // other will despawn at corpse desppawning (Pet::Update code)
478 else
480 // pet corpse non lootable and non skinnable
481 SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
482 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
484 //lose happiness when died and not in BG/Arena
485 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
486 if(!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND))
487 ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE);
489 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
492 else if(getDeathState()==ALIVE)
494 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
495 CastPetAuras(true);
499 void Pet::Update(uint32 diff)
501 if(m_removed) // pet already removed, just wait in remove queue, no updates
502 return;
504 switch( m_deathState )
506 case CORPSE:
508 if( m_deathTimer <= diff )
510 assert(getPetType()!=SUMMON_PET && "Must be already removed.");
511 Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER!
512 return;
514 break;
516 case ALIVE:
518 // unsummon pet that lost owner
519 Unit* owner = GetOwner();
520 if(!owner || !IsWithinDistInMap(owner, OWNER_MAX_DISTANCE) || isControlled() && !owner->GetPetGUID())
522 Remove(PET_SAVE_NOT_IN_SLOT, true);
523 return;
526 if(isControlled())
528 if( owner->GetPetGUID() != GetGUID() )
530 Remove(getPetType()==HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
531 return;
535 if(m_duration > 0)
537 if(m_duration > diff)
538 m_duration -= diff;
539 else
541 Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
542 return;
546 if(getPetType() != HUNTER_PET)
547 break;
549 //regenerate Focus
550 if(m_regenTimer <= diff)
552 RegenerateFocus();
553 m_regenTimer = 4000;
555 else
556 m_regenTimer -= diff;
558 if(m_happinessTimer <= diff)
560 LooseHappiness();
561 m_happinessTimer = 7500;
563 else
564 m_happinessTimer -= diff;
566 break;
568 default:
569 break;
571 Creature::Update(diff);
574 void Pet::RegenerateFocus()
576 uint32 curValue = GetPower(POWER_FOCUS);
577 uint32 maxValue = GetMaxPower(POWER_FOCUS);
579 if (curValue >= maxValue)
580 return;
582 float addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
584 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
585 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
586 if ((*i)->GetModifier()->m_miscvalue == POWER_FOCUS)
587 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
589 ModifyPower(POWER_FOCUS, (int32)addvalue);
592 void Pet::LooseHappiness()
594 uint32 curValue = GetPower(POWER_HAPPINESS);
595 if (curValue <= 0)
596 return;
597 int32 addvalue = 670; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
598 if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
599 addvalue = int32(addvalue * 1.5);
600 ModifyPower(POWER_HAPPINESS, -addvalue);
603 HappinessState Pet::GetHappinessState()
605 if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
606 return UNHAPPY;
607 else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
608 return HAPPY;
609 else
610 return CONTENT;
613 bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
615 uint8 activecount = 1;
616 uint32 chainstartstore[ACTIVE_SPELLS_MAX];
618 if(IsPassiveSpell(spellid))
619 return true;
621 chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
623 for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
625 if(IsPassiveSpell(itr->first))
626 continue;
628 uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
630 uint8 x;
632 for(x = 0; x < activecount; x++)
634 if(chainstart == chainstartstore[x])
635 break;
638 if(x == activecount) //spellchain not yet saved -> add active count
640 ++activecount;
641 if(activecount > ACTIVE_SPELLS_MAX)
642 return false;
643 chainstartstore[x] = chainstart;
646 return true;
649 void Pet::Remove(PetSaveMode mode, bool returnreagent)
651 Unit* owner = GetOwner();
653 if(owner)
655 if(owner->GetTypeId()==TYPEID_PLAYER)
657 ((Player*)owner)->RemovePet(this,mode,returnreagent);
658 return;
661 // only if current pet in slot
662 if(owner->GetPetGUID()==GetGUID())
663 owner->SetPet(0);
666 CleanupsBeforeDelete();
667 AddObjectToRemoveList();
668 m_removed = true;
671 void Pet::GivePetXP(uint32 xp)
673 if(getPetType() != HUNTER_PET)
674 return;
676 if ( xp < 1 )
677 return;
679 if(!isAlive())
680 return;
682 uint32 level = getLevel();
684 // XP to money conversion processed in Player::RewardQuest
685 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
686 return;
688 uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
689 uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
690 uint32 newXP = curXP + xp;
692 if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
694 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
695 return;
698 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
700 newXP -= nextLvlXP;
702 SetLevel( level + 1 );
703 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(level+1))/4));
705 level = getLevel();
706 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
707 GivePetLevel(level);
710 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
713 void Pet::GivePetLevel(uint32 level)
715 if(!level)
716 return;
718 InitStatsForLevel(level);
721 bool Pet::CreateBaseAtCreature(Creature* creature)
723 if(!creature)
725 sLog.outError("CRITICAL ERROR: NULL pointer parsed into CreateBaseAtCreature()");
726 return false;
728 uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
730 sLog.outBasic("SetInstanceID()");
731 SetInstanceId(creature->GetInstanceId());
733 sLog.outBasic("Create pet");
734 uint32 pet_number = objmgr.GeneratePetNumber();
735 if(!Create(guid, creature->GetMap(), creature->GetEntry(), pet_number))
736 return false;
738 Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
740 if(!IsPositionValid())
742 sLog.outError("ERROR: Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
743 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
744 return false;
747 CreatureInfo const *cinfo = GetCreatureInfo();
748 if(!cinfo)
750 sLog.outError("ERROR: CreateBaseAtCreature() failed, creatureInfo is missing!");
751 return false;
754 if(cinfo->type == CREATURE_TYPE_CRITTER)
756 setPetType(MINI_PET);
757 return true;
759 SetDisplayId(creature->GetDisplayId());
760 SetNativeDisplayId(creature->GetNativeDisplayId());
761 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
762 SetPower(POWER_HAPPINESS, 166500);
763 setPowerType(POWER_FOCUS);
764 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, 0);
765 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
766 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(creature->getLevel()))/4));
767 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
768 SetUInt32Value(UNIT_NPC_FLAGS, 0);
770 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(creature->GetCreatureInfo()->family);
771 if( char* familyname = cFamily->Name[sWorld.GetDefaultDbcLocale()] )
772 SetName(familyname);
773 else
774 SetName(creature->GetName());
776 if(cinfo->type == CREATURE_TYPE_BEAST)
778 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
779 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
780 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
781 SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED));
783 return true;
786 bool Pet::InitStatsForLevel(uint32 petlevel)
788 CreatureInfo const *cinfo = GetCreatureInfo();
789 assert(cinfo);
791 Unit* owner = GetOwner();
792 if(!owner)
794 sLog.outError("ERROR: attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
795 return false;
798 uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
800 SetLevel(petlevel);
802 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
804 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
806 SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
807 SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
808 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
810 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
812 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
813 if(cFamily && cFamily->minScale > 0.0f)
815 float scale;
816 if (getLevel() >= cFamily->maxScaleLevel)
817 scale = cFamily->maxScale;
818 else if (getLevel() <= cFamily->minScaleLevel)
819 scale = cFamily->minScale;
820 else
821 scale = cFamily->minScale + (getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
823 SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
825 m_bonusdamage = 0;
827 int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
829 if(cinfo && getPetType() != HUNTER_PET)
831 createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
832 createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
833 createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
834 createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
835 createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
836 createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
839 switch(getPetType())
841 case SUMMON_PET:
843 if(owner->GetTypeId() == TYPEID_PLAYER)
845 switch(owner->getClass())
847 case CLASS_WARLOCK:
850 //the damage bonus used for pets is either fire or shadow damage, whatever is higher
851 uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
852 uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
853 uint32 val = (fire > shadow) ? fire : shadow;
855 SetBonusDamage(int32 (val * 0.15f));
856 //bonusAP += val * 0.57;
857 break;
859 case CLASS_MAGE:
861 //40% damage bonus of mage's frost damage
862 float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
863 if(val < 0)
864 val = 0;
865 SetBonusDamage( int32(val));
866 break;
868 default:
869 break;
873 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
874 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
876 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
878 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
879 if(pInfo) // exist in DB
881 SetCreateHealth(pInfo->health);
882 SetCreateMana(pInfo->mana);
884 if(pInfo->armor > 0)
885 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
887 for(int stat = 0; stat < MAX_STATS; ++stat)
889 SetCreateStat(Stats(stat), float(pInfo->stats[stat]));
892 else // not exist in DB, use some default fake data
894 sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
896 // remove elite bonuses included in DB values
897 SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
898 SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
900 SetCreateStat(STAT_STRENGTH, 22);
901 SetCreateStat(STAT_AGILITY, 22);
902 SetCreateStat(STAT_STAMINA, 25);
903 SetCreateStat(STAT_INTELLECT, 28);
904 SetCreateStat(STAT_SPIRIT, 27);
906 break;
908 case HUNTER_PET:
910 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(petlevel))/4));
911 learnLevelupSpells();
912 //these formula may not be correct; however, it is designed to be close to what it should be
913 //this makes dps 0.5 of pets level
914 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
915 //damage range is then petlevel / 2
916 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
917 //damage is increased afterwards as strength and pet scaling modify attack power
919 //stored standard pet stats are entry 1 in pet_levelinfo
920 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
921 if(pInfo) // exist in DB
923 SetCreateHealth(pInfo->health);
924 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
925 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
927 for( int i = STAT_STRENGTH; i < MAX_STATS; i++)
929 SetCreateStat(Stats(i), float(pInfo->stats[i]));
932 else // not exist in DB, use some default fake data
934 sLog.outErrorDb("Hunter pet levelstats missing in DB");
936 // remove elite bonuses included in DB values
937 SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
939 SetCreateStat(STAT_STRENGTH, 22);
940 SetCreateStat(STAT_AGILITY, 22);
941 SetCreateStat(STAT_STAMINA, 25);
942 SetCreateStat(STAT_INTELLECT, 28);
943 SetCreateStat(STAT_SPIRIT, 27);
945 break;
947 case GUARDIAN_PET:
948 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
949 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000);
951 SetCreateMana(28 + 10*petlevel);
952 SetCreateHealth(28 + 30*petlevel);
954 // FIXME: this is wrong formula, possible each guardian pet have own damage formula
955 //these formula may not be correct; however, it is designed to be close to what it should be
956 //this makes dps 0.5 of pets level
957 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)));
958 //damage range is then petlevel / 2
959 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)));
960 break;
961 default:
962 sLog.outError("Pet have incorrect type (%u) for levelup.", getPetType());
963 break;
966 for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
967 SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]));
969 UpdateAllStats();
971 SetHealth(GetMaxHealth());
972 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
974 return true;
977 bool Pet::HaveInDiet(ItemPrototype const* item) const
979 if (!item->FoodType)
980 return false;
982 CreatureInfo const* cInfo = GetCreatureInfo();
983 if(!cInfo)
984 return false;
986 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
987 if(!cFamily)
988 return false;
990 uint32 diet = cFamily->petFoodMask;
991 uint32 FoodMask = 1 << (item->FoodType-1);
992 return diet & FoodMask;
995 uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
997 // -5 or greater food level
998 if(getLevel() <= itemlevel + 5) //possible to feed level 60 pet with level 55 level food for full effect
999 return 35000;
1000 // -10..-6
1001 else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
1002 return 17000;
1003 // -14..-11
1004 else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
1005 return 8000;
1006 // -15 or less
1007 else
1008 return 0; //food too low level
1011 void Pet::_LoadSpellCooldowns()
1013 m_CreatureSpellCooldowns.clear();
1014 m_CreatureCategoryCooldowns.clear();
1016 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1018 if(result)
1020 time_t curTime = time(NULL);
1022 WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
1023 data << GetGUID();
1024 data << uint8(0x0); // flags (0x1, 0x2)
1028 Field *fields = result->Fetch();
1030 uint32 spell_id = fields[0].GetUInt32();
1031 time_t db_time = (time_t)fields[1].GetUInt64();
1033 if(!sSpellStore.LookupEntry(spell_id))
1035 sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
1036 continue;
1039 // skip outdated cooldown
1040 if(db_time <= curTime)
1041 continue;
1043 data << uint32(spell_id);
1044 data << uint32(uint32(db_time-curTime)*1000); // in m.secs
1046 _AddCreatureSpellCooldown(spell_id,db_time);
1048 sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo->GetPetNumber(), spell_id, uint32(db_time-curTime));
1050 while( result->NextRow() );
1052 delete result;
1054 if(!m_CreatureSpellCooldowns.empty() && GetOwner())
1056 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1061 void Pet::_SaveSpellCooldowns()
1063 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1065 time_t curTime = time(NULL);
1067 // remove oudated and save active
1068 for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
1070 if(itr->second <= curTime)
1071 m_CreatureSpellCooldowns.erase(itr++);
1072 else
1074 CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
1075 ++itr;
1080 void Pet::_LoadSpells()
1082 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1084 if(result)
1088 Field *fields = result->Fetch();
1090 addSpell(fields[0].GetUInt16(), fields[2].GetUInt16(), PETSPELL_UNCHANGED, fields[1].GetUInt16());
1092 while( result->NextRow() );
1094 delete result;
1098 void Pet::_SaveSpells()
1100 for (PetSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
1102 ++next;
1103 if (itr->second->type == PETSPELL_FAMILY) continue; // prevent saving family passives to DB
1104 if (itr->second->state == PETSPELL_REMOVED || itr->second->state == PETSPELL_CHANGED)
1105 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
1106 if (itr->second->state == PETSPELL_NEW || itr->second->state == PETSPELL_CHANGED)
1107 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);
1109 if (itr->second->state == PETSPELL_REMOVED)
1110 _removeSpell(itr->first);
1111 else
1112 itr->second->state = PETSPELL_UNCHANGED;
1116 void Pet::_LoadAuras(uint32 timediff)
1118 m_Auras.clear();
1119 for (int i = 0; i < TOTAL_AURAS; i++)
1120 m_modAuras[i].clear();
1122 QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1124 if(result)
1128 Field *fields = result->Fetch();
1129 uint64 caster_guid = fields[0].GetUInt64();
1130 uint32 spellid = fields[1].GetUInt32();
1131 uint32 effindex = fields[2].GetUInt32();
1132 uint32 stackcount= fields[3].GetUInt32();
1133 int32 damage = (int32)fields[4].GetUInt32();
1134 int32 maxduration = (int32)fields[5].GetUInt32();
1135 int32 remaintime = (int32)fields[6].GetUInt32();
1136 int32 remaincharges = (int32)fields[7].GetUInt32();
1138 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
1139 if(!spellproto)
1141 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
1142 continue;
1145 if(effindex >= 3)
1147 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
1148 continue;
1151 // negative effects should continue counting down after logout
1152 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
1154 if(remaintime <= int32(timediff))
1155 continue;
1157 remaintime -= timediff;
1160 // prevent wrong values of remaincharges
1161 if(spellproto->procCharges)
1163 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
1164 remaincharges = spellproto->procCharges;
1166 else
1167 remaincharges = -1;
1169 /// do not load single target auras (unless they were cast by the player)
1170 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
1171 continue;
1173 for(uint32 i=0; i<stackcount; i++)
1175 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
1177 if(!damage)
1178 damage = aura->GetModifier()->m_amount;
1179 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
1180 AddAura(aura);
1183 while( result->NextRow() );
1185 delete result;
1189 void Pet::_SaveAuras()
1191 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1193 AuraMap const& auras = GetAuras();
1194 if (auras.empty())
1195 return;
1197 spellEffectPair lastEffectPair = auras.begin()->first;
1198 uint32 stackCounter = 1;
1200 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
1202 if(itr == auras.end() || lastEffectPair != itr->first)
1204 AuraMap::const_iterator itr2 = itr;
1205 // save previous spellEffectPair to db
1206 itr2--;
1207 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
1208 /// do not save single target auras (unless they were cast by the player)
1209 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
1211 if(!itr2->second->IsPassive())
1213 // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
1214 uint8 i;
1215 for (i = 0; i < 3; i++)
1216 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
1217 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
1218 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
1219 break;
1221 if (i == 3)
1223 CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
1224 "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%u', '%d', '%d', '%d', '%d')",
1225 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->m_procCharges));
1229 if(itr == auras.end())
1230 break;
1233 if (lastEffectPair == itr->first)
1234 stackCounter++;
1235 else
1237 lastEffectPair = itr->first;
1238 stackCounter = 1;
1243 bool Pet::addSpell(uint16 spell_id, uint16 active, PetSpellState state, uint16 slot_id, PetSpellType type)
1245 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1246 if (!spellInfo)
1248 // do pet spell book cleanup
1249 if(state == PETSPELL_UNCHANGED) // spell load case
1251 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
1252 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
1254 else
1255 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
1257 return false;
1260 PetSpellMap::iterator itr = m_spells.find(spell_id);
1261 if (itr != m_spells.end())
1263 if (itr->second->state == PETSPELL_REMOVED)
1265 delete itr->second;
1266 m_spells.erase(itr);
1267 state = PETSPELL_CHANGED;
1269 else if (state == PETSPELL_UNCHANGED && itr->second->state != PETSPELL_UNCHANGED)
1271 // can be in case spell loading but learned at some previous spell loading
1272 itr->second->state = PETSPELL_UNCHANGED;
1273 return false;
1275 else
1276 return false;
1279 uint32 oldspell_id = 0;
1281 PetSpell *newspell = new PetSpell;
1282 newspell->state = state;
1283 newspell->type = type;
1285 if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
1287 if(IsPassiveSpell(spell_id))
1288 newspell->active = ACT_PASSIVE;
1289 else
1290 newspell->active = ACT_DISABLED;
1292 else
1293 newspell->active = active;
1295 uint32 chainstart = spellmgr.GetFirstSpellInChain(spell_id);
1297 for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
1299 if(itr->second->state == PETSPELL_REMOVED) continue;
1301 if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
1303 slot_id = itr->second->slotId;
1304 newspell->active = itr->second->active;
1306 if(newspell->active == ACT_ENABLED)
1307 ToggleAutocast(itr->first, false);
1309 oldspell_id = itr->first;
1310 unlearnSpell(itr->first);
1311 break;
1315 uint16 tmpslot = slot_id;
1317 if (tmpslot == 0xffff)
1319 uint16 maxid = 0;
1320 PetSpellMap::iterator itr;
1321 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
1323 if(itr->second->state == PETSPELL_REMOVED) continue;
1324 if (itr->second->slotId > maxid) maxid = itr->second->slotId;
1326 tmpslot = maxid + 1;
1329 newspell->slotId = tmpslot;
1330 m_spells[spell_id] = newspell;
1332 if (IsPassiveSpell(spell_id))
1333 CastSpell(this, spell_id, true);
1334 else if(state == PETSPELL_NEW)
1335 m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
1337 if(newspell->active == ACT_ENABLED)
1338 ToggleAutocast(spell_id, true);
1340 return true;
1343 bool Pet::learnSpell(uint16 spell_id)
1345 // prevent duplicated entires in spell book
1346 if (!addSpell(spell_id))
1347 return false;
1349 if(GetOwner()->GetTypeId() == TYPEID_PLAYER)
1351 if(!m_loading)
1353 WorldPacket data(SMSG_PET_LEARNED_SPELL, 2);
1354 data << uint16(spell_id);
1355 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1359 Unit* owner = GetOwner();
1360 if(owner->GetTypeId() == TYPEID_PLAYER)
1361 ((Player*)owner)->PetSpellInitialize();
1362 return true;
1365 void Pet::learnLevelupSpells()
1367 PetLevelupSpellSet const *levelupSpells = spellmgr.GetPetLevelupSpellList(GetCreatureInfo()->family);
1368 if(!levelupSpells)
1369 return;
1371 uint32 level = getLevel();
1373 for(PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr)
1375 if(itr->first <= level)
1376 learnSpell(itr->second);
1377 else
1378 unlearnSpell(itr->second);
1382 bool Pet::unlearnSpell(uint16 spell_id)
1384 if(removeSpell(spell_id))
1386 if(GetOwner()->GetTypeId() == TYPEID_PLAYER)
1388 if(!m_loading)
1390 WorldPacket data(SMSG_PET_UNLEARNED_SPELL, 2);
1391 data << uint16(spell_id);
1392 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1395 return true;
1397 return false;
1400 bool Pet::removeSpell(uint16 spell_id)
1402 PetSpellMap::iterator itr = m_spells.find(spell_id);
1403 if (itr == m_spells.end())
1404 return false;
1406 if(itr->second->state == PETSPELL_REMOVED)
1407 return false;
1409 if(itr->second->state == PETSPELL_NEW)
1411 delete itr->second;
1412 m_spells.erase(itr);
1414 else
1415 itr->second->state = PETSPELL_REMOVED;
1417 RemoveAurasDueToSpell(spell_id);
1419 return true;
1422 bool Pet::_removeSpell(uint16 spell_id)
1424 PetSpellMap::iterator itr = m_spells.find(spell_id);
1425 if (itr != m_spells.end())
1427 delete itr->second;
1428 m_spells.erase(itr);
1429 return true;
1431 return false;
1434 void Pet::InitPetCreateSpells()
1436 m_charmInfo->InitPetActionBar();
1438 m_spells.clear();
1439 int32 petspellid;
1440 PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
1441 if(CreateSpells)
1443 for(uint8 i = 0; i < 4; i++)
1445 if(!CreateSpells->spellid[i])
1446 break;
1448 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
1449 if(!learn_spellproto)
1450 continue;
1452 if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
1454 petspellid = learn_spellproto->EffectTriggerSpell[0];
1455 Unit* owner = GetOwner();
1456 if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
1458 if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
1459 ((Player*)owner)->learnSpell(learn_spellproto->Id);
1460 else
1461 AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
1464 else
1465 petspellid = learn_spellproto->Id;
1467 addSpell(petspellid);
1471 LearnPetPassives();
1473 CastPetAuras(false);
1476 void Pet::CheckLearning(uint32 spellid)
1478 //charmed case -> prevent crash
1479 if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
1480 return;
1482 Unit* owner = GetOwner();
1484 if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
1485 return;
1487 TeachSpellMap::iterator itr = m_teachspells.find(spellid);
1488 if(itr == m_teachspells.end())
1489 return;
1491 if(urand(0, 100) < 10)
1493 ((Player*)owner)->learnSpell(itr->second);
1494 m_teachspells.erase(itr);
1498 uint32 Pet::resetTalentsCost() const
1500 uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
1502 // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
1503 if(m_resetTalentsCost < 10*SILVER || days > 0)
1504 return 10*SILVER;
1505 // then 50 silver
1506 else if(m_resetTalentsCost < 50*SILVER)
1507 return 50*SILVER;
1508 // then 1 gold
1509 else if(m_resetTalentsCost < 1*GOLD)
1510 return 1*GOLD;
1511 // then increasing at a rate of 1 gold; cap 10 gold
1512 else
1513 return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
1516 void Pet::ToggleAutocast(uint32 spellid, bool apply)
1518 if(IsPassiveSpell(spellid))
1519 return;
1521 PetSpellMap::const_iterator itr = m_spells.find((uint16)spellid);
1523 int i;
1525 if(apply)
1527 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++);
1528 if (i == m_autospells.size())
1530 m_autospells.push_back(spellid);
1531 itr->second->active = ACT_ENABLED;
1532 itr->second->state = PETSPELL_CHANGED;
1535 else
1537 AutoSpellList::iterator itr2 = m_autospells.begin();
1538 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++, itr2++);
1539 if (i < m_autospells.size())
1541 m_autospells.erase(itr2);
1542 itr->second->active = ACT_DISABLED;
1543 itr->second->state = PETSPELL_CHANGED;
1548 bool Pet::Create(uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number)
1550 SetMapId(map->GetId());
1551 SetInstanceId(map->GetInstanceId());
1553 Object::_Create(guidlow, pet_number, HIGHGUID_PET);
1555 m_DBTableGuid = guidlow;
1556 m_originalEntry = Entry;
1558 if(!InitEntry(Entry))
1559 return false;
1561 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
1563 if(getPetType() == MINI_PET) // always non-attackable
1564 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
1566 return true;
1569 bool Pet::HasSpell(uint32 spell) const
1571 return (m_spells.find(spell) != m_spells.end());
1574 // Get all passive spells in our skill line
1575 void Pet::LearnPetPassives()
1577 CreatureInfo const* cInfo = GetCreatureInfo();
1578 if(!cInfo)
1579 return;
1581 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1582 if(!cFamily)
1583 return;
1585 PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
1586 if(petStore != sPetFamilySpellsStore.end())
1588 for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
1589 addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, 0xffff, PETSPELL_FAMILY);
1593 void Pet::CastPetAuras(bool current)
1595 Unit* owner = GetOwner();
1596 if(!owner)
1597 return;
1599 if(getPetType() != HUNTER_PET && (getPetType() != SUMMON_PET || owner->getClass() != CLASS_WARLOCK))
1600 return;
1602 for(PetAuraSet::iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end();)
1604 PetAura const* pa = *itr;
1605 ++itr;
1607 if(!current && pa->IsRemovedOnChangePet())
1608 owner->RemovePetAura(pa);
1609 else
1610 CastPetAura(pa);
1614 void Pet::CastPetAura(PetAura const* aura)
1616 uint16 auraId = aura->GetAura(GetEntry());
1617 if(!auraId)
1618 return;
1620 if(auraId == 35696) // Demonic Knowledge
1622 int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
1623 CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true);
1625 else
1626 CastSpell(this, auraId, true);