More fixes for wrong format arg/value pairs.
[auctionmangos.git] / src / game / Pet.cpp
blob7c40ff32a2cb10968951a2301e2a3c01f45e055c
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 //numbers represent minutes * 100 while happy (you get 100 loyalty points per min while happy)
43 uint32 const LevelUpLoyalty[6] =
45 5500,
46 11500,
47 17000,
48 23500,
49 31000,
50 39500,
53 uint32 const LevelStartLoyalty[6] =
55 2000,
56 4500,
57 7000,
58 10000,
59 13500,
60 17500,
63 Pet::Pet(PetType type) : Creature()
65 m_isPet = true;
66 m_name = "Pet";
67 m_petType = type;
69 m_removed = false;
70 m_regenTimer = 4000;
71 m_happinessTimer = 7500;
72 m_loyaltyTimer = 12000;
73 m_duration = 0;
74 m_bonusdamage = 0;
76 m_loyaltyPoints = 0;
77 m_TrainingPoints = 0;
78 m_resetTalentsCost = 0;
79 m_resetTalentsTime = 0;
81 m_auraUpdateMask = 0;
83 // pets always have a charminfo, even if they are not actually charmed
84 CharmInfo* charmInfo = InitCharmInfo(this);
86 if(type == MINI_PET) // always passive
87 charmInfo->SetReactState(REACT_PASSIVE);
88 else if(type == GUARDIAN_PET) // always aggressive
89 charmInfo->SetReactState(REACT_AGGRESSIVE);
91 m_spells.clear();
92 m_Auras.clear();
93 m_CreatureSpellCooldowns.clear();
94 m_CreatureCategoryCooldowns.clear();
95 m_autospells.clear();
96 m_declinedname = NULL;
99 Pet::~Pet()
101 if(m_uint32Values) // only for fully created Object
103 for (PetSpellMap::iterator i = m_spells.begin(); i != m_spells.end(); ++i)
104 delete i->second;
105 ObjectAccessor::Instance().RemoveObject(this);
108 delete m_declinedname;
111 void Pet::AddToWorld()
113 ///- Register the pet for guid lookup
114 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
115 Unit::AddToWorld();
118 void Pet::RemoveFromWorld()
120 ///- Remove the pet from the accessor
121 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
122 ///- Don't call the function for Creature, normal mobs + totems go in a different storage
123 Unit::RemoveFromWorld();
126 bool Pet::LoadPetFromDB( Unit* owner, uint32 petentry, uint32 petnumber, bool current )
128 uint32 ownerid = owner->GetGUIDLow();
130 QueryResult *result;
132 if(petnumber)
133 // known petnumber entry 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
134 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND id = '%u'",ownerid, petnumber);
135 else if(current)
136 // current pet (slot 0) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
137 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND slot = '0'",ownerid );
138 else if(petentry)
139 // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
140 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
141 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '0' OR slot = '3') ",ownerid, petentry );
142 else
143 // any current or other non-stabled pet (for hunter "call pet")
144 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
145 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3') ",ownerid);
147 if(!result)
148 return false;
150 Field *fields = result->Fetch();
152 // update for case of current pet "slot = 0"
153 petentry = fields[1].GetUInt32();
154 if(!petentry)
156 delete result;
157 return false;
160 uint32 summon_spell_id = fields[21].GetUInt32();
161 SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
163 bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
165 // check temporary summoned pets like mage water elemental
166 if(current && is_temporary_summoned)
168 delete result;
169 return false;
172 Map *map = owner->GetMap();
173 uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
174 uint32 pet_number = fields[0].GetUInt32();
175 if(!Create(guid, map, petentry, pet_number))
177 delete result;
178 return false;
181 float px, py, pz;
182 owner->GetClosePoint(px, py, pz,GetObjectSize(),PET_FOLLOW_DIST,PET_FOLLOW_ANGLE);
184 Relocate(px, py, pz, owner->GetOrientation());
186 if(!IsPositionValid())
188 sLog.outError("ERROR: Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
189 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
190 delete result;
191 return false;
194 setPetType(PetType(fields[22].GetUInt8()));
195 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,owner->getFaction());
196 SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
198 CreatureInfo const *cinfo = GetCreatureInfo();
199 if(cinfo->type == CREATURE_TYPE_CRITTER)
201 AIM_Initialize();
202 map->Add((Creature*)this);
203 delete result;
204 return true;
206 if(getPetType()==HUNTER_PET || (getPetType()==SUMMON_PET && cinfo->type == CREATURE_TYPE_DEMON && owner->getClass() == CLASS_WARLOCK))
207 m_charmInfo->SetPetNumber(pet_number, true);
208 else
209 m_charmInfo->SetPetNumber(pet_number, false);
210 SetUInt64Value(UNIT_FIELD_SUMMONEDBY, owner->GetGUID());
211 SetDisplayId(fields[3].GetUInt32());
212 SetNativeDisplayId(fields[3].GetUInt32());
213 uint32 petlevel=fields[4].GetUInt32();
214 SetUInt32Value(UNIT_NPC_FLAGS , 0);
215 SetName(fields[11].GetString());
217 switch(getPetType())
220 case SUMMON_PET:
221 petlevel=owner->getLevel();
223 SetUInt32Value(UNIT_FIELD_BYTES_0,2048);
224 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
225 // this enables popup window (pet dismiss, cancel)
226 break;
227 case HUNTER_PET:
228 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
229 SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[8].GetUInt32());
230 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
231 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
233 if(fields[12].GetBool())
234 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_NOT_ALLOWED);
235 else
236 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
238 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
239 // this enables popup window (pet abandon, cancel)
240 SetTP(fields[9].GetInt32());
241 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
242 SetPower( POWER_HAPPINESS,fields[15].GetUInt32());
243 setPowerType(POWER_FOCUS);
244 break;
245 default:
246 sLog.outError("Pet have incorrect type (%u) for pet loading.",getPetType());
248 InitStatsForLevel( petlevel);
249 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
250 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
251 SetUInt64Value(UNIT_FIELD_CREATEDBY, owner->GetGUID());
253 m_charmInfo->SetReactState( ReactStates( fields[6].GetUInt8() ));
254 m_loyaltyPoints = fields[7].GetInt32();
256 uint32 savedhealth = fields[13].GetUInt32();
257 uint32 savedmana = fields[14].GetUInt32();
259 // set current pet as current
260 if(fields[10].GetUInt32() != 0)
262 CharacterDatabase.BeginTransaction();
263 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '3' WHERE owner = '%u' AND slot = '0' AND id <> '%u'",ownerid, m_charmInfo->GetPetNumber());
264 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '0' WHERE owner = '%u' AND id = '%u'",ownerid, m_charmInfo->GetPetNumber());
265 CharacterDatabase.CommitTransaction();
268 if(!is_temporary_summoned)
270 // permanent controlled pets store state in DB
271 Tokens tokens = StrSplit(fields[16].GetString(), " ");
273 if(tokens.size() != 20)
275 delete result;
276 return false;
279 int index;
280 Tokens::iterator iter;
281 for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
283 m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
284 ++iter;
285 m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
288 //init teach spells
289 tokens = StrSplit(fields[17].GetString(), " ");
290 for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
292 uint32 tmp = atol((*iter).c_str());
294 ++iter;
296 if(tmp)
297 AddTeachSpell(tmp, atol((*iter).c_str()));
298 else
299 break;
303 // since last save (in seconds)
304 uint32 timediff = (time(NULL) - fields[18].GetUInt32());
306 delete result;
308 //load spells/cooldowns/auras
309 SetCanModifyStats(true);
310 _LoadAuras(timediff);
312 //init AB
313 if(is_temporary_summoned)
315 // Temporary summoned pets always have initial spell list at load
316 InitPetCreateSpells();
318 else
320 LearnPetPassives();
321 CastPetAuras(current);
324 if(getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
326 SetHealth(GetMaxHealth());
327 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
329 else
331 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
332 SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
335 AIM_Initialize();
336 map->Add((Creature*)this);
338 // Spells should be loaded after pet is added to map, because in CanCast is check on it
339 _LoadSpells();
340 _LoadSpellCooldowns();
342 owner->SetPet(this); // in DB stored only full controlled creature
343 sLog.outDebug("New Pet has guid %u", GetGUIDLow());
345 if(owner->GetTypeId() == TYPEID_PLAYER)
347 ((Player*)owner)->PetSpellInitialize();
348 if(((Player*)owner)->GetGroup())
349 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
352 if(owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
354 result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'",owner->GetGUIDLow(),GetCharmInfo()->GetPetNumber());
356 if(result)
358 if(m_declinedname)
359 delete m_declinedname;
361 m_declinedname = new DeclinedName;
362 Field *fields = result->Fetch();
363 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
365 m_declinedname->name[i] = fields[i].GetCppString();
370 return true;
373 void Pet::SavePetToDB(PetSaveMode mode)
375 if(!GetEntry())
376 return;
378 // save only fully controlled creature
379 if(!isControlled())
380 return;
382 uint32 curhealth = GetHealth();
383 uint32 curmana = GetPower(POWER_MANA);
385 switch(mode)
387 case PET_SAVE_IN_STABLE_SLOT_1:
388 case PET_SAVE_IN_STABLE_SLOT_2:
389 case PET_SAVE_NOT_IN_SLOT:
391 RemoveAllAuras();
393 //only alive hunter pets get auras saved, the others don't
394 if(!(getPetType() == HUNTER_PET && isAlive()))
395 m_Auras.clear();
397 default:
398 break;
401 _SaveSpells();
402 _SaveSpellCooldowns();
403 _SaveAuras();
405 switch(mode)
407 case PET_SAVE_AS_CURRENT:
408 case PET_SAVE_IN_STABLE_SLOT_1:
409 case PET_SAVE_IN_STABLE_SLOT_2:
410 case PET_SAVE_NOT_IN_SLOT:
412 uint32 loyalty =1;
413 if(getPetType()!=HUNTER_PET)
414 loyalty = GetLoyaltyLevel();
416 uint32 owner = GUID_LOPART(GetOwnerGUID());
417 std::string name = m_name;
418 CharacterDatabase.escape_string(name);
419 CharacterDatabase.BeginTransaction();
420 // remove current data
421 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner,m_charmInfo->GetPetNumber() );
423 // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
424 if(mode!=PET_SAVE_NOT_IN_SLOT)
425 CharacterDatabase.PExecute("UPDATE character_pet SET slot = 3 WHERE owner = '%u' AND slot = '%u'", owner, uint32(mode) );
427 // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
428 if(getPetType()==HUNTER_PET && (mode==PET_SAVE_AS_CURRENT||mode==PET_SAVE_NOT_IN_SLOT))
429 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '0' OR slot = '3')", owner );
430 // save pet
431 std::ostringstream ss;
432 ss << "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, loyaltypoints, loyalty, trainpoint, slot, name, renamed, curhealth, curmana, curhappiness, abdata,TeachSpelldata,savetime,resettalents_cost,resettalents_time,CreatedBySpell,PetType) "
433 << "VALUES ("
434 << m_charmInfo->GetPetNumber() << ", "
435 << GetEntry() << ", "
436 << owner << ", "
437 << GetNativeDisplayId() << ", "
438 << getLevel() << ", "
439 << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE) << ", "
440 << uint32(m_charmInfo->GetReactState()) << ", "
441 << m_loyaltyPoints << ", "
442 << GetLoyaltyLevel() << ", "
443 << m_TrainingPoints << ", "
444 << uint32(mode) << ", '"
445 << name.c_str() << "', "
446 << uint32((GetByteValue(UNIT_FIELD_BYTES_2, 2) == UNIT_RENAME_ALLOWED)?0:1) << ", "
447 << (curhealth<1?1:curhealth) << ", "
448 << curmana << ", "
449 << GetPower(POWER_HAPPINESS) << ", '";
451 for(uint32 i = 0; i < 10; i++)
452 ss << uint32(m_charmInfo->GetActionBarEntry(i)->Type) << " " << uint32(m_charmInfo->GetActionBarEntry(i)->SpellOrAction) << " ";
453 ss << "', '";
455 //save spells the pet can teach to it's Master
457 int i = 0;
458 for(TeachSpellMap::iterator itr = m_teachspells.begin(); i < 4 && itr != m_teachspells.end(); ++i, ++itr)
459 ss << itr->first << " " << itr->second << " ";
460 for(; i < 4; ++i)
461 ss << uint32(0) << " " << uint32(0) << " ";
464 ss << "', "
465 << time(NULL) << ", "
466 << uint32(m_resetTalentsCost) << ", "
467 << uint64(m_resetTalentsTime) << ", "
468 << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ", "
469 << uint32(getPetType()) << ")";
471 CharacterDatabase.Execute( ss.str().c_str() );
473 CharacterDatabase.CommitTransaction();
474 break;
476 case PET_SAVE_AS_DELETED:
478 RemoveAllAuras();
479 uint32 owner = GUID_LOPART(GetOwnerGUID());
480 DeleteFromDB(m_charmInfo->GetPetNumber());
481 break;
483 default:
484 sLog.outError("Unknown pet save/remove mode: %d",mode);
488 void Pet::DeleteFromDB(uint32 guidlow)
490 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow);
491 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow);
492 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow);
493 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow);
494 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow);
497 void Pet::setDeathState(DeathState s) // overwrite virtual Creature::setDeathState and Unit::setDeathState
499 Creature::setDeathState(s);
500 if(getDeathState()==CORPSE)
502 //remove summoned pet (no corpse)
503 if(getPetType()==SUMMON_PET)
504 Remove(PET_SAVE_NOT_IN_SLOT);
505 // other will despawn at corpse desppawning (Pet::Update code)
506 else
508 // pet corpse non lootable and non skinnable
509 SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
510 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
512 //lose happiness when died and not in BG/Arena
513 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
514 if(!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND))
515 ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE);
517 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
520 else if(getDeathState()==ALIVE)
522 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
523 CastPetAuras(true);
527 void Pet::Update(uint32 diff)
529 if(m_removed) // pet already removed, just wait in remove queue, no updates
530 return;
532 switch( m_deathState )
534 case CORPSE:
536 if( m_deathTimer <= diff )
538 assert(getPetType()!=SUMMON_PET && "Must be already removed.");
539 Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER!
540 return;
542 break;
544 case ALIVE:
546 // unsummon pet that lost owner
547 Unit* owner = GetOwner();
548 if(!owner || !IsWithinDistInMap(owner, OWNER_MAX_DISTANCE) || isControlled() && !owner->GetPetGUID())
550 Remove(PET_SAVE_NOT_IN_SLOT, true);
551 return;
554 if(isControlled())
556 if( owner->GetPetGUID() != GetGUID() )
558 Remove(getPetType()==HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
559 return;
563 if(m_duration > 0)
565 if(m_duration > diff)
566 m_duration -= diff;
567 else
569 Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
570 return;
574 if(getPetType() != HUNTER_PET)
575 break;
577 //regenerate Focus
578 if(m_regenTimer <= diff)
580 RegenerateFocus();
581 m_regenTimer = 4000;
583 else
584 m_regenTimer -= diff;
586 if(m_happinessTimer <= diff)
588 LooseHappiness();
589 m_happinessTimer = 7500;
591 else
592 m_happinessTimer -= diff;
594 if(m_loyaltyTimer <= diff)
596 TickLoyaltyChange();
597 m_loyaltyTimer = 12000;
599 else
600 m_loyaltyTimer -= diff;
602 break;
604 default:
605 break;
607 Creature::Update(diff);
610 void Pet::RegenerateFocus()
612 uint32 curValue = GetPower(POWER_FOCUS);
613 uint32 maxValue = GetMaxPower(POWER_FOCUS);
615 if (curValue >= maxValue)
616 return;
618 float addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
620 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
621 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
622 if ((*i)->GetModifier()->m_miscvalue == POWER_FOCUS)
623 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
625 ModifyPower(POWER_FOCUS, (int32)addvalue);
628 void Pet::LooseHappiness()
630 uint32 curValue = GetPower(POWER_HAPPINESS);
631 if (curValue <= 0)
632 return;
633 int32 addvalue = (140 >> GetLoyaltyLevel()) * 125; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
634 if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
635 addvalue = int32(addvalue * 1.5);
636 ModifyPower(POWER_HAPPINESS, -addvalue);
639 void Pet::ModifyLoyalty(int32 addvalue)
641 uint32 loyaltylevel = GetLoyaltyLevel();
643 if(addvalue > 0) //only gain influenced, not loss
644 addvalue = int32((float)addvalue * sWorld.getRate(RATE_LOYALTY));
646 if(loyaltylevel >= BEST_FRIEND && (addvalue + m_loyaltyPoints) > int32(GetMaxLoyaltyPoints(loyaltylevel)))
647 return;
649 m_loyaltyPoints += addvalue;
651 if(m_loyaltyPoints < 0)
653 if(loyaltylevel > REBELLIOUS)
655 //level down
656 --loyaltylevel;
657 SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
658 m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
659 SetTP(m_TrainingPoints - int32(getLevel()));
661 else
663 m_loyaltyPoints = 0;
664 Unit* owner = GetOwner();
665 if(owner && owner->GetTypeId() == TYPEID_PLAYER)
667 WorldPacket data(SMSG_PET_BROKEN, 0);
668 ((Player*)owner)->GetSession()->SendPacket(&data);
670 //run away
671 ((Player*)owner)->RemovePet(this,PET_SAVE_AS_DELETED);
675 //level up
676 else if(m_loyaltyPoints > int32(GetMaxLoyaltyPoints(loyaltylevel)))
678 ++loyaltylevel;
679 SetLoyaltyLevel(LoyaltyLevel(loyaltylevel));
680 m_loyaltyPoints = GetStartLoyaltyPoints(loyaltylevel);
681 SetTP(m_TrainingPoints + getLevel());
685 void Pet::TickLoyaltyChange()
687 int32 addvalue;
689 switch(GetHappinessState())
691 case HAPPY: addvalue = 20; break;
692 case CONTENT: addvalue = 10; break;
693 case UNHAPPY: addvalue = -20; break;
694 default:
695 return;
697 ModifyLoyalty(addvalue);
700 void Pet::KillLoyaltyBonus(uint32 level)
702 if(level > 100)
703 return;
705 //at lower levels gain is faster | the lower loyalty the more loyalty is gained
706 uint32 bonus = uint32(((100 - level) / 10) + (6 - GetLoyaltyLevel()));
707 ModifyLoyalty(bonus);
710 HappinessState Pet::GetHappinessState()
712 if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
713 return UNHAPPY;
714 else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
715 return HAPPY;
716 else
717 return CONTENT;
720 void Pet::SetLoyaltyLevel(LoyaltyLevel level)
722 SetByteValue(UNIT_FIELD_BYTES_1, 1, level);
725 bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
727 uint8 activecount = 1;
728 uint32 chainstartstore[ACTIVE_SPELLS_MAX];
730 if(IsPassiveSpell(spellid))
731 return true;
733 chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
735 for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
737 if(IsPassiveSpell(itr->first))
738 continue;
740 uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
742 uint8 x;
744 for(x = 0; x < activecount; x++)
746 if(chainstart == chainstartstore[x])
747 break;
750 if(x == activecount) //spellchain not yet saved -> add active count
752 ++activecount;
753 if(activecount > ACTIVE_SPELLS_MAX)
754 return false;
755 chainstartstore[x] = chainstart;
758 return true;
761 bool Pet::HasTPForSpell(uint32 spellid)
763 int32 neededtrainp = GetTPForSpell(spellid);
764 if((m_TrainingPoints - neededtrainp < 0 || neededtrainp < 0) && neededtrainp != 0)
765 return false;
766 return true;
769 int32 Pet::GetTPForSpell(uint32 spellid)
771 uint32 basetrainp = 0;
773 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
774 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
775 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
777 if(!_spell_idx->second->reqtrainpoints)
778 return 0;
780 basetrainp = _spell_idx->second->reqtrainpoints;
781 break;
784 uint32 spenttrainp = 0;
785 uint32 chainstart = spellmgr.GetFirstSpellInChain(spellid);
787 for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
789 if(itr->second->state == PETSPELL_REMOVED)
790 continue;
792 if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
794 SkillLineAbilityMap::const_iterator _lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
795 SkillLineAbilityMap::const_iterator _upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
797 for(SkillLineAbilityMap::const_iterator _spell_idx2 = _lower; _spell_idx2 != _upper; ++_spell_idx2)
799 if(_spell_idx2->second->reqtrainpoints > spenttrainp)
801 spenttrainp = _spell_idx2->second->reqtrainpoints;
802 break;
808 return int32(basetrainp) - int32(spenttrainp);
811 uint32 Pet::GetMaxLoyaltyPoints(uint32 level)
813 return LevelUpLoyalty[level - 1];
816 uint32 Pet::GetStartLoyaltyPoints(uint32 level)
818 return LevelStartLoyalty[level - 1];
821 void Pet::SetTP(int32 TP)
823 m_TrainingPoints = TP;
824 SetUInt32Value(UNIT_TRAINING_POINTS, (uint32)GetDispTP());
827 int32 Pet::GetDispTP()
829 if(getPetType()!= HUNTER_PET)
830 return(0);
831 if(m_TrainingPoints < 0)
832 return -m_TrainingPoints;
833 else
834 return -(m_TrainingPoints + 1);
837 void Pet::Remove(PetSaveMode mode, bool returnreagent)
839 Unit* owner = GetOwner();
841 if(owner)
843 if(owner->GetTypeId()==TYPEID_PLAYER)
845 ((Player*)owner)->RemovePet(this,mode,returnreagent);
846 return;
849 // only if current pet in slot
850 if(owner->GetPetGUID()==GetGUID())
851 owner->SetPet(0);
854 CleanupsBeforeDelete();
855 AddObjectToRemoveList();
856 m_removed = true;
859 void Pet::GivePetXP(uint32 xp)
861 if(getPetType() != HUNTER_PET)
862 return;
864 if ( xp < 1 )
865 return;
867 if(!isAlive())
868 return;
870 uint32 level = getLevel();
872 // XP to money conversion processed in Player::RewardQuest
873 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
874 return;
876 uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
877 uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
878 uint32 newXP = curXP + xp;
880 if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
882 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
883 return;
886 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
888 newXP -= nextLvlXP;
890 SetLevel( level + 1 );
891 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(level+1))/4));
893 level = getLevel();
894 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
895 GivePetLevel(level);
898 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
900 if(getPetType() == HUNTER_PET)
901 KillLoyaltyBonus(level);
904 void Pet::GivePetLevel(uint32 level)
906 if(!level)
907 return;
909 InitStatsForLevel( level);
911 SetTP(m_TrainingPoints + (GetLoyaltyLevel() - 1));
914 bool Pet::CreateBaseAtCreature(Creature* creature)
916 if(!creature)
918 sLog.outError("CRITICAL ERROR: NULL pointer parsed into CreateBaseAtCreature()");
919 return false;
921 uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
923 sLog.outBasic("SetInstanceID()");
924 SetInstanceId(creature->GetInstanceId());
926 sLog.outBasic("Create pet");
927 uint32 pet_number = objmgr.GeneratePetNumber();
928 if(!Create(guid, creature->GetMap(), creature->GetEntry(), pet_number))
929 return false;
931 Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
933 if(!IsPositionValid())
935 sLog.outError("ERROR: Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
936 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
937 return false;
940 CreatureInfo const *cinfo = GetCreatureInfo();
941 if(!cinfo)
943 sLog.outError("ERROR: CreateBaseAtCreature() failed, creatureInfo is missing!");
944 return false;
947 if(cinfo->type == CREATURE_TYPE_CRITTER)
949 setPetType(MINI_PET);
950 return true;
952 SetDisplayId(creature->GetDisplayId());
953 SetNativeDisplayId(creature->GetNativeDisplayId());
954 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
955 SetPower( POWER_HAPPINESS,166500);
956 setPowerType(POWER_FOCUS);
957 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP,0);
958 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
959 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(creature->getLevel()))/4));
960 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
961 SetUInt32Value(UNIT_NPC_FLAGS , 0);
963 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(creature->GetCreatureInfo()->family);
964 if( char* familyname = cFamily->Name[sWorld.GetDefaultDbcLocale()] )
965 SetName(familyname);
966 else
967 SetName(creature->GetName());
969 m_loyaltyPoints = 1000;
970 if(cinfo->type == CREATURE_TYPE_BEAST)
972 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
973 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
974 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
975 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
977 SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED) );
978 SetLoyaltyLevel(REBELLIOUS);
980 return true;
983 bool Pet::InitStatsForLevel(uint32 petlevel)
985 CreatureInfo const *cinfo = GetCreatureInfo();
986 assert(cinfo);
988 Unit* owner = GetOwner();
989 if(!owner)
991 sLog.outError("ERROR: attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
992 return false;
995 uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
997 SetLevel( petlevel);
999 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1001 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
1003 SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
1004 SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
1005 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
1007 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
1009 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
1010 if(cFamily && cFamily->minScale > 0.0f)
1012 float scale;
1013 if (getLevel() >= cFamily->maxScaleLevel)
1014 scale = cFamily->maxScale;
1015 else if (getLevel() <= cFamily->minScaleLevel)
1016 scale = cFamily->minScale;
1017 else
1018 scale = cFamily->minScale + (getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
1020 SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
1022 m_bonusdamage = 0;
1024 int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
1026 if(cinfo && getPetType() != HUNTER_PET)
1028 createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
1029 createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
1030 createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
1031 createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
1032 createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
1033 createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
1036 switch(getPetType())
1038 case SUMMON_PET:
1040 if(owner->GetTypeId() == TYPEID_PLAYER)
1042 switch(owner->getClass())
1044 case CLASS_WARLOCK:
1047 //the damage bonus used for pets is either fire or shadow damage, whatever is higher
1048 uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
1049 uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
1050 uint32 val = (fire > shadow) ? fire : shadow;
1052 SetBonusDamage(int32 (val * 0.15f));
1053 //bonusAP += val * 0.57;
1054 break;
1056 case CLASS_MAGE:
1058 //40% damage bonus of mage's frost damage
1059 float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
1060 if(val < 0)
1061 val = 0;
1062 SetBonusDamage( int32(val));
1063 break;
1065 default:
1066 break;
1070 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
1071 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
1073 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
1075 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
1076 if(pInfo) // exist in DB
1078 SetCreateHealth(pInfo->health);
1079 SetCreateMana(pInfo->mana);
1081 if(pInfo->armor > 0)
1082 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
1084 for(int stat = 0; stat < MAX_STATS; ++stat)
1086 SetCreateStat(Stats(stat),float(pInfo->stats[stat]));
1089 else // not exist in DB, use some default fake data
1091 sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
1093 // remove elite bonuses included in DB values
1094 SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
1095 SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
1097 SetCreateStat(STAT_STRENGTH,22);
1098 SetCreateStat(STAT_AGILITY,22);
1099 SetCreateStat(STAT_STAMINA,25);
1100 SetCreateStat(STAT_INTELLECT,28);
1101 SetCreateStat(STAT_SPIRIT,27);
1103 break;
1105 case HUNTER_PET:
1107 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32((MaNGOS::XP::xp_to_level(petlevel))/4));
1109 //these formula may not be correct; however, it is designed to be close to what it should be
1110 //this makes dps 0.5 of pets level
1111 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
1112 //damage range is then petlevel / 2
1113 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
1114 //damage is increased afterwards as strength and pet scaling modify attack power
1116 //stored standard pet stats are entry 1 in pet_levelinfo
1117 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
1118 if(pInfo) // exist in DB
1120 SetCreateHealth(pInfo->health);
1121 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
1122 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
1124 for( int i = STAT_STRENGTH; i < MAX_STATS; i++)
1126 SetCreateStat(Stats(i), float(pInfo->stats[i]));
1129 else // not exist in DB, use some default fake data
1131 sLog.outErrorDb("Hunter pet levelstats missing in DB");
1133 // remove elite bonuses included in DB values
1134 SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
1136 SetCreateStat(STAT_STRENGTH,22);
1137 SetCreateStat(STAT_AGILITY,22);
1138 SetCreateStat(STAT_STAMINA,25);
1139 SetCreateStat(STAT_INTELLECT,28);
1140 SetCreateStat(STAT_SPIRIT,27);
1142 break;
1144 case GUARDIAN_PET:
1145 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE,0);
1146 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP,1000);
1148 SetCreateMana( 28 + 10*petlevel );
1149 SetCreateHealth( 28 + 30*petlevel );
1151 // FIXME: this is wrong formula, possible each guardian pet have own damage formula
1152 //these formula may not be correct; however, it is designed to be close to what it should be
1153 //this makes dps 0.5 of pets level
1154 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
1155 //damage range is then petlevel / 2
1156 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
1157 break;
1158 default:
1159 sLog.outError("Pet have incorrect type (%u) for levelup.",getPetType()); break;
1162 for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
1163 SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]) );
1165 UpdateAllStats();
1167 SetHealth(GetMaxHealth());
1168 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
1170 return true;
1173 bool Pet::HaveInDiet(ItemPrototype const* item) const
1175 if (!item->FoodType)
1176 return false;
1178 CreatureInfo const* cInfo = GetCreatureInfo();
1179 if(!cInfo)
1180 return false;
1182 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1183 if(!cFamily)
1184 return false;
1186 uint32 diet = cFamily->petFoodMask;
1187 uint32 FoodMask = 1 << (item->FoodType-1);
1188 return diet & FoodMask;
1191 uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
1193 // -5 or greater food level
1194 if(getLevel() <= itemlevel +5) //possible to feed level 60 pet with level 55 level food for full effect
1195 return 35000;
1196 // -10..-6
1197 else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
1198 return 17000;
1199 // -14..-11
1200 else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
1201 return 8000;
1202 // -15 or less
1203 else
1204 return 0; //food too low level
1207 void Pet::_LoadSpellCooldowns()
1209 m_CreatureSpellCooldowns.clear();
1210 m_CreatureCategoryCooldowns.clear();
1212 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1214 if(result)
1216 time_t curTime = time(NULL);
1218 WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
1219 data << GetGUID();
1220 data << uint8(0x0); // flags (0x1, 0x2)
1224 Field *fields = result->Fetch();
1226 uint32 spell_id = fields[0].GetUInt32();
1227 time_t db_time = (time_t)fields[1].GetUInt64();
1229 if(!sSpellStore.LookupEntry(spell_id))
1231 sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
1232 continue;
1235 // skip outdated cooldown
1236 if(db_time <= curTime)
1237 continue;
1239 data << uint32(spell_id);
1240 data << uint32(uint32(db_time-curTime)*1000); // in m.secs
1242 _AddCreatureSpellCooldown(spell_id,db_time);
1244 sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).",m_charmInfo->GetPetNumber(),spell_id,uint32(db_time-curTime));
1246 while( result->NextRow() );
1248 delete result;
1250 if(!m_CreatureSpellCooldowns.empty() && GetOwner())
1252 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1257 void Pet::_SaveSpellCooldowns()
1259 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1261 time_t curTime = time(NULL);
1263 // remove oudated and save active
1264 for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
1266 if(itr->second <= curTime)
1267 m_CreatureSpellCooldowns.erase(itr++);
1268 else
1270 CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
1271 ++itr;
1276 void Pet::_LoadSpells()
1278 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1280 if(result)
1284 Field *fields = result->Fetch();
1286 addSpell(fields[0].GetUInt16(), fields[2].GetUInt16(), PETSPELL_UNCHANGED, fields[1].GetUInt16());
1288 while( result->NextRow() );
1290 delete result;
1294 void Pet::_SaveSpells()
1296 for (PetSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
1298 ++next;
1299 if (itr->second->type == PETSPELL_FAMILY) continue; // prevent saving family passives to DB
1300 if (itr->second->state == PETSPELL_REMOVED || itr->second->state == PETSPELL_CHANGED)
1301 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
1302 if (itr->second->state == PETSPELL_NEW || itr->second->state == PETSPELL_CHANGED)
1303 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);
1305 if (itr->second->state == PETSPELL_REMOVED)
1306 _removeSpell(itr->first);
1307 else
1308 itr->second->state = PETSPELL_UNCHANGED;
1312 void Pet::_LoadAuras(uint32 timediff)
1314 m_Auras.clear();
1315 for (int i = 0; i < TOTAL_AURAS; i++)
1316 m_modAuras[i].clear();
1318 // all aura related fields
1319 for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
1320 SetUInt32Value(i, 0);
1322 QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1324 if(result)
1328 Field *fields = result->Fetch();
1329 uint64 caster_guid = fields[0].GetUInt64();
1330 uint32 spellid = fields[1].GetUInt32();
1331 uint32 effindex = fields[2].GetUInt32();
1332 int32 damage = (int32)fields[3].GetUInt32();
1333 int32 maxduration = (int32)fields[4].GetUInt32();
1334 int32 remaintime = (int32)fields[5].GetUInt32();
1335 int32 remaincharges = (int32)fields[6].GetUInt32();
1337 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
1338 if(!spellproto)
1340 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
1341 continue;
1344 if(effindex >= 3)
1346 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
1347 continue;
1350 // negative effects should continue counting down after logout
1351 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
1353 if(remaintime <= int32(timediff))
1354 continue;
1356 remaintime -= timediff;
1359 // prevent wrong values of remaincharges
1360 if(spellproto->procCharges)
1362 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
1363 remaincharges = spellproto->procCharges;
1365 else
1366 remaincharges = -1;
1368 /// do not load single target auras (unless they were cast by the player)
1369 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
1370 continue;
1372 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
1374 if(!damage)
1375 damage = aura->GetModifier()->m_amount;
1376 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
1377 AddAura(aura);
1379 while( result->NextRow() );
1381 delete result;
1385 void Pet::_SaveAuras()
1387 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1389 AuraMap const& auras = GetAuras();
1390 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
1392 // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
1393 SpellEntry const *spellInfo = itr->second->GetSpellProto();
1394 uint8 i;
1395 for (i = 0; i < 3; i++)
1396 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
1397 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
1398 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
1399 break;
1401 if (i != 3)
1402 continue;
1404 if(itr->second->IsPassive())
1405 continue;
1407 /// do not save single target auras (unless they were cast by the player)
1408 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
1409 continue;
1411 CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
1412 "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%d', '%d', '%d', '%d')",
1413 m_charmInfo->GetPetNumber(), itr->second->GetCasterGUID(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(),(*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
1417 bool Pet::addSpell(uint16 spell_id, uint16 active, PetSpellState state, uint16 slot_id, PetSpellType type)
1419 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1420 if (!spellInfo)
1422 // do pet spell book cleanup
1423 if(state == PETSPELL_UNCHANGED) // spell load case
1425 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
1426 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
1428 else
1429 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
1431 return false;
1434 PetSpellMap::iterator itr = m_spells.find(spell_id);
1435 if (itr != m_spells.end())
1437 if (itr->second->state == PETSPELL_REMOVED)
1439 delete itr->second;
1440 m_spells.erase(itr);
1441 state = PETSPELL_CHANGED;
1443 else if (state == PETSPELL_UNCHANGED && itr->second->state != PETSPELL_UNCHANGED)
1445 // can be in case spell loading but learned at some previous spell loading
1446 itr->second->state = PETSPELL_UNCHANGED;
1447 return false;
1449 else
1450 return false;
1453 uint32 oldspell_id = 0;
1455 PetSpell *newspell = new PetSpell;
1456 newspell->state = state;
1457 newspell->type = type;
1459 if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
1461 if(IsPassiveSpell(spell_id))
1462 newspell->active = ACT_PASSIVE;
1463 else
1464 newspell->active = ACT_DISABLED;
1466 else
1467 newspell->active = active;
1469 uint32 chainstart = spellmgr.GetFirstSpellInChain(spell_id);
1471 for (PetSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); itr++)
1473 if(itr->second->state == PETSPELL_REMOVED) continue;
1475 if(spellmgr.GetFirstSpellInChain(itr->first) == chainstart)
1477 slot_id = itr->second->slotId;
1478 newspell->active = itr->second->active;
1480 if(newspell->active == ACT_ENABLED)
1481 ToggleAutocast(itr->first, false);
1483 oldspell_id = itr->first;
1484 removeSpell(itr->first);
1488 uint16 tmpslot=slot_id;
1490 if (tmpslot == 0xffff)
1492 uint16 maxid = 0;
1493 PetSpellMap::iterator itr;
1494 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
1496 if(itr->second->state == PETSPELL_REMOVED) continue;
1497 if (itr->second->slotId > maxid) maxid = itr->second->slotId;
1499 tmpslot = maxid + 1;
1502 newspell->slotId = tmpslot;
1503 m_spells[spell_id] = newspell;
1505 if (IsPassiveSpell(spell_id))
1506 CastSpell(this, spell_id, true);
1507 else if(state == PETSPELL_NEW)
1508 m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
1510 if(newspell->active == ACT_ENABLED)
1511 ToggleAutocast(spell_id, true);
1513 return true;
1516 bool Pet::learnSpell(uint16 spell_id)
1518 // prevent duplicated entires in spell book
1519 if (!addSpell(spell_id))
1520 return false;
1522 Unit* owner = GetOwner();
1523 if(owner->GetTypeId()==TYPEID_PLAYER)
1524 ((Player*)owner)->PetSpellInitialize();
1525 return true;
1528 void Pet::removeSpell(uint16 spell_id)
1530 PetSpellMap::iterator itr = m_spells.find(spell_id);
1531 if (itr == m_spells.end())
1532 return;
1534 if(itr->second->state == PETSPELL_REMOVED)
1535 return;
1537 if(itr->second->state == PETSPELL_NEW)
1539 delete itr->second;
1540 m_spells.erase(itr);
1542 else
1543 itr->second->state = PETSPELL_REMOVED;
1545 RemoveAurasDueToSpell(spell_id);
1548 bool Pet::_removeSpell(uint16 spell_id)
1550 PetSpellMap::iterator itr = m_spells.find(spell_id);
1551 if (itr != m_spells.end())
1553 delete itr->second;
1554 m_spells.erase(itr);
1555 return true;
1557 return false;
1560 void Pet::InitPetCreateSpells()
1562 m_charmInfo->InitPetActionBar();
1564 m_spells.clear();
1565 int32 usedtrainpoints = 0, petspellid;
1566 PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
1567 if(CreateSpells)
1569 for(uint8 i = 0; i < 4; i++)
1571 if(!CreateSpells->spellid[i])
1572 break;
1574 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
1575 if(!learn_spellproto)
1576 continue;
1578 if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
1580 petspellid = learn_spellproto->EffectTriggerSpell[0];
1581 Unit* owner = GetOwner();
1582 if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
1584 if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
1585 ((Player*)owner)->learnSpell(learn_spellproto->Id);
1586 else
1587 AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
1590 else
1591 petspellid = learn_spellproto->Id;
1593 addSpell(petspellid);
1595 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
1596 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(learn_spellproto->EffectTriggerSpell[0]);
1598 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
1600 usedtrainpoints += _spell_idx->second->reqtrainpoints;
1601 break;
1606 LearnPetPassives();
1608 CastPetAuras(false);
1610 SetTP(-usedtrainpoints);
1613 void Pet::CheckLearning(uint32 spellid)
1615 //charmed case -> prevent crash
1616 if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
1617 return;
1619 Unit* owner = GetOwner();
1621 if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
1622 return;
1624 TeachSpellMap::iterator itr = m_teachspells.find(spellid);
1625 if(itr == m_teachspells.end())
1626 return;
1628 if(urand(0, 100) < 10)
1630 ((Player*)owner)->learnSpell(itr->second);
1631 m_teachspells.erase(itr);
1635 uint32 Pet::resetTalentsCost() const
1637 uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
1639 // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
1640 if(m_resetTalentsCost < 10*SILVER || days > 0)
1641 return 10*SILVER;
1642 // then 50 silver
1643 else if(m_resetTalentsCost < 50*SILVER)
1644 return 50*SILVER;
1645 // then 1 gold
1646 else if(m_resetTalentsCost < 1*GOLD)
1647 return 1*GOLD;
1648 // then increasing at a rate of 1 gold; cap 10 gold
1649 else
1650 return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
1653 void Pet::ToggleAutocast(uint32 spellid, bool apply)
1655 if(IsPassiveSpell(spellid))
1656 return;
1658 PetSpellMap::const_iterator itr = m_spells.find((uint16)spellid);
1660 int i;
1662 if(apply)
1664 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++);
1665 if (i == m_autospells.size())
1667 m_autospells.push_back(spellid);
1668 itr->second->active = ACT_ENABLED;
1669 itr->second->state = PETSPELL_CHANGED;
1672 else
1674 AutoSpellList::iterator itr2 = m_autospells.begin();
1675 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; i++, itr2++);
1676 if (i < m_autospells.size())
1678 m_autospells.erase(itr2);
1679 itr->second->active = ACT_DISABLED;
1680 itr->second->state = PETSPELL_CHANGED;
1685 bool Pet::Create(uint32 guidlow, Map *map, uint32 Entry, uint32 pet_number)
1687 SetMapId(map->GetId());
1688 SetInstanceId(map->GetInstanceId());
1690 Object::_Create(guidlow, pet_number, HIGHGUID_PET);
1692 m_DBTableGuid = guidlow;
1693 m_originalEntry = Entry;
1695 if(!InitEntry(Entry))
1696 return false;
1698 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
1699 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_AURAS | UNIT_BYTE2_FLAG_UNK5 );
1701 if(getPetType() == MINI_PET) // always non-attackable
1702 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
1704 return true;
1707 bool Pet::HasSpell(uint32 spell) const
1709 return (m_spells.find(spell) != m_spells.end());
1712 // Get all passive spells in our skill line
1713 void Pet::LearnPetPassives()
1715 CreatureInfo const* cInfo = GetCreatureInfo();
1716 if(!cInfo)
1717 return;
1719 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1720 if(!cFamily)
1721 return;
1723 PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
1724 if(petStore != sPetFamilySpellsStore.end())
1726 for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
1727 addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, 0xffff, PETSPELL_FAMILY);
1731 void Pet::CastPetAuras(bool current)
1733 Unit* owner = GetOwner();
1734 if(!owner)
1735 return;
1737 if(getPetType() != HUNTER_PET && (getPetType() != SUMMON_PET || owner->getClass() != CLASS_WARLOCK))
1738 return;
1740 for(PetAuraSet::iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end(); )
1742 PetAura const* pa = *itr;
1743 ++itr;
1745 if(!current && pa->IsRemovedOnChangePet())
1746 owner->RemovePetAura(pa);
1747 else
1748 CastPetAura(pa);
1752 void Pet::CastPetAura(PetAura const* aura)
1754 uint16 auraId = aura->GetAura(GetEntry());
1755 if(!auraId)
1756 return;
1758 if(auraId == 35696) // Demonic Knowledge
1760 int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
1761 CastCustomSpell(this,auraId,&basePoints, NULL, NULL, true );
1763 else
1764 CastSpell(this, auraId, true);