[10041] Use for spell 49145 and ranks for decrease SPELL_DIRECT_DAMAGE damage.
[getmangos.git] / src / game / Creature.cpp
blob6e984a9901d832dea17471885c2756f1061f1038
1 /*
2 * Copyright (C) 2005-2010 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 "WorldPacket.h"
22 #include "World.h"
23 #include "ObjectMgr.h"
24 #include "ObjectGuid.h"
25 #include "SpellMgr.h"
26 #include "Creature.h"
27 #include "QuestDef.h"
28 #include "GossipDef.h"
29 #include "Player.h"
30 #include "PoolManager.h"
31 #include "Opcodes.h"
32 #include "Log.h"
33 #include "LootMgr.h"
34 #include "MapManager.h"
35 #include "CreatureAI.h"
36 #include "CreatureAISelector.h"
37 #include "Formulas.h"
38 #include "WaypointMovementGenerator.h"
39 #include "InstanceData.h"
40 #include "BattleGroundMgr.h"
41 #include "Spell.h"
42 #include "Util.h"
43 #include "GridNotifiers.h"
44 #include "GridNotifiersImpl.h"
45 #include "CellImpl.h"
47 // apply implementation of the singletons
48 #include "Policies/SingletonImp.h"
50 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
52 TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
53 if (itr != spellList.end())
54 return &itr->second;
56 return NULL;
59 bool VendorItemData::RemoveItem( uint32 item_id )
61 bool found = false;
62 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); )
64 // can have many examples
65 if((*i)->item == item_id)
67 i = m_items.erase(i);
68 found = true;
70 else
71 ++i;
74 return found;
77 VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, int32 extendedCost) const
79 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
80 if((*i)->item == item_id && (*i)->ExtendedCost == extendedCost)
81 return *i;
82 return NULL;
85 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
87 if(Unit* victim = Unit::GetUnit(m_owner, m_victim))
89 while (!m_assistants.empty())
91 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
92 m_assistants.pop_front();
94 if (assistant && assistant->CanAssistTo(&m_owner, victim))
96 assistant->SetNoCallAssistance(true);
97 if(assistant->AI())
98 assistant->AI()->AttackStart(victim);
102 return true;
105 bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
107 m_owner.ForcedDespawn();
108 return true;
111 Creature::Creature(CreatureSubtype subtype) :
112 Unit(), i_AI(NULL),
113 lootForPickPocketed(false), lootForBody(false), lootForSkin(false), m_groupLootTimer(0), m_groupLootId(0),
114 m_lootMoney(0), m_lootGroupRecipientId(0),
115 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(5.0f),
116 m_subtype(subtype), m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0),
117 m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
118 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_needNotify(false),
119 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
120 m_creatureInfo(NULL), m_isActiveObject(false), m_splineFlags(SPLINEFLAG_WALKMODE)
122 m_regenTimer = 200;
123 m_valuesCount = UNIT_END;
125 for(int i = 0; i < 4; ++i)
126 m_spells[i] = 0;
128 m_CreatureSpellCooldowns.clear();
129 m_CreatureCategoryCooldowns.clear();
130 m_GlobalCooldown = 0;
132 m_splineFlags = SPLINEFLAG_WALKMODE;
135 Creature::~Creature()
137 CleanupsBeforeDelete();
139 m_vendorItemCounts.clear();
141 delete i_AI;
142 i_AI = NULL;
145 void Creature::AddToWorld()
147 ///- Register the creature for guid lookup
148 if(!IsInWorld() && GetObjectGuid().GetHigh() == HIGHGUID_UNIT)
149 GetMap()->GetObjectsStore().insert<Creature>(GetGUID(), (Creature*)this);
151 Unit::AddToWorld();
154 void Creature::RemoveFromWorld()
156 ///- Remove the creature from the accessor
157 if(IsInWorld() && GetObjectGuid().GetHigh() == HIGHGUID_UNIT)
158 GetMap()->GetObjectsStore().erase<Creature>(GetGUID(), (Creature*)NULL);
160 Unit::RemoveFromWorld();
163 void Creature::RemoveCorpse()
165 if ((getDeathState() != CORPSE && !m_isDeadByDefault) || (getDeathState() != ALIVE && m_isDeadByDefault))
166 return;
168 m_deathTimer = 0;
169 setDeathState(DEAD);
170 UpdateObjectVisibility();
172 // stop loot rolling before loot clear and for close client dialogs
173 StopGroupLoot();
175 loot.clear();
176 uint32 respawnDelay = m_respawnDelay;
177 if (AI())
178 AI()->CorpseRemoved(respawnDelay);
180 m_respawnTime = time(NULL) + respawnDelay;
182 float x, y, z, o;
183 GetRespawnCoord(x, y, z, &o);
184 GetMap()->CreatureRelocation(this, x, y, z, o);
188 * change the entry of creature until respawn
190 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
192 CreatureInfo const *normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
193 if(!normalInfo)
195 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
196 return false;
199 // get difficulty 1 mode entry
200 uint32 actualEntry = Entry;
201 CreatureInfo const *cinfo = normalInfo;
202 // TODO correctly implement spawnmodes for non-bg maps
203 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
205 if (normalInfo->DifficultyEntry[diff])
207 // we already have valid Map pointer for current creature!
208 if (GetMap()->GetSpawnMode() > diff)
210 cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff]);
211 if (!cinfo)
213 // maybe check such things already at startup
214 sLog.outErrorDb("Creature::UpdateEntry creature difficulty %u entry %u does not exist.", diff + 1, actualEntry);
215 return false;
221 SetEntry(Entry); // normal entry always
222 m_creatureInfo = cinfo; // map mode related always
224 // equal to player Race field, but creature does not have race
225 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
227 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
228 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
230 uint32 display_id = sObjectMgr.ChooseDisplayId(team, GetCreatureInfo(), data);
231 if (!display_id) // Cancel load if no display id
233 sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load.", Entry);
234 return false;
237 CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
238 if (!minfo) // Cancel load if no model defined
240 sLog.outErrorDb("Creature (Entry: %u) has no model info defined in table `creature_model_info`, can't load.", Entry);
241 return false;
244 display_id = minfo->modelid; // it can be different (for another gender)
246 SetDisplayId(display_id);
247 SetNativeDisplayId(display_id);
248 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
250 // Load creature equipment
251 if(!data || data->equipmentId == 0)
252 { // use default from the template
253 LoadEquipment(cinfo->equipmentId);
255 else if(data && data->equipmentId != -1)
256 { // override, -1 means no equipment
257 LoadEquipment(data->equipmentId);
260 SetName(normalInfo->Name); // at normal entry always
262 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, minfo->bounding_radius);
263 SetFloatValue(UNIT_FIELD_COMBATREACH, minfo->combat_reach);
265 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
267 SetSpeedRate(MOVE_WALK, cinfo->speed_walk);
268 SetSpeedRate(MOVE_RUN, cinfo->speed_run);
269 SetSpeedRate(MOVE_SWIM, 1.0f); // using 1.0 rate
270 SetSpeedRate(MOVE_FLIGHT, 1.0f); // using 1.0 rate
272 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
274 // checked at loading
275 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
277 return true;
280 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data, bool preserveHPAndPower)
282 if (!InitEntry(Entry, team, data))
283 return false;
285 m_regenHealth = GetCreatureInfo()->RegenHealth;
287 // creatures always have melee weapon ready if any
288 SetSheath(SHEATH_STATE_MELEE);
290 SelectLevel(GetCreatureInfo(), preserveHPAndPower ? GetHealthPercent() : 100.0f, 100.0f);
292 if (team == HORDE)
293 setFaction(GetCreatureInfo()->faction_H);
294 else
295 setFaction(GetCreatureInfo()->faction_A);
297 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
299 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
300 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
301 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
303 uint32 unitFlags = GetCreatureInfo()->unit_flags;
305 // we may need to append or remove additional flags
306 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT))
307 unitFlags |= UNIT_FLAG_IN_COMBAT;
309 SetUInt32Value(UNIT_FIELD_FLAGS, unitFlags);
311 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
313 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
314 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
315 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
316 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
317 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
318 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
319 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
321 SetCanModifyStats(true);
322 UpdateAllStats();
324 // checked and error show at loading templates
325 if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A))
327 if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
328 SetPvP(true);
329 else
330 SetPvP(false);
333 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
334 m_spells[i] = GetCreatureInfo()->spells[i];
336 return true;
339 void Creature::Update(uint32 diff)
341 if(m_GlobalCooldown <= diff)
342 m_GlobalCooldown = 0;
343 else
344 m_GlobalCooldown -= diff;
346 if (m_needNotify)
348 m_needNotify = false;
349 RelocationNotify();
351 if (!IsInWorld())
352 return;
355 switch( m_deathState )
357 case JUST_ALIVED:
358 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
359 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
360 break;
361 case JUST_DIED:
362 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
363 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
364 break;
365 case DEAD:
367 if( m_respawnTime <= time(NULL) )
369 DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Respawning...");
370 m_respawnTime = 0;
371 lootForPickPocketed = false;
372 lootForBody = false;
373 lootForSkin = false;
375 if(m_originalEntry != GetEntry())
376 UpdateEntry(m_originalEntry);
378 CreatureInfo const *cinfo = GetCreatureInfo();
380 SelectLevel(cinfo);
381 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
382 if (m_isDeadByDefault)
384 setDeathState(JUST_DIED);
385 SetHealth(0);
386 i_motionMaster.Clear();
387 clearUnitState(UNIT_STAT_ALL_STATE);
388 LoadCreaturesAddon(true);
390 else
391 setDeathState( JUST_ALIVED );
393 //Call AI respawn virtual function
394 i_AI->JustRespawned();
396 GetMap()->Add(this);
398 break;
400 case CORPSE:
402 if (m_isDeadByDefault)
403 break;
405 if( m_deathTimer <= diff )
407 // since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
408 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
409 if (poolid)
410 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
412 if (IsInWorld()) // can be despawned by update pool
414 RemoveCorpse();
415 DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Removing corpse... %u ", GetEntry());
418 else
420 m_deathTimer -= diff;
421 if (m_groupLootId)
423 if(diff < m_groupLootTimer)
424 m_groupLootTimer -= diff;
425 else
426 StopGroupLoot();
430 break;
432 case ALIVE:
434 if (m_isDeadByDefault)
436 if( m_deathTimer <= diff )
438 // since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
439 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
441 if (poolid)
442 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
444 if (IsInWorld()) // can be despawned by update pool
446 RemoveCorpse();
447 DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Removing alive corpse... %u ", GetEntry());
449 else
450 return;
452 else
454 m_deathTimer -= diff;
458 Unit::Update( diff );
460 // creature can be dead after Unit::Update call
461 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
462 if(!isAlive())
463 break;
465 if(!IsInEvadeMode())
467 // do not allow the AI to be changed during update
468 m_AI_locked = true;
469 i_AI->UpdateAI(diff);
470 m_AI_locked = false;
473 // creature can be dead after UpdateAI call
474 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
475 if(!isAlive())
476 break;
477 if(m_regenTimer > 0)
479 if(diff >= m_regenTimer)
480 m_regenTimer = 0;
481 else
482 m_regenTimer -= diff;
484 if (m_regenTimer != 0)
485 break;
487 if (!isInCombat() || IsPolymorphed())
488 RegenerateHealth();
490 RegenerateMana();
492 m_regenTimer = REGEN_TIME_FULL;
493 break;
495 case DEAD_FALLING:
497 if (!FallGround())
498 setDeathState(JUST_DIED);
500 default:
501 break;
506 void Creature::StartGroupLoot( Group* group, uint32 timer )
508 m_groupLootId = group->GetId();
509 m_groupLootTimer = timer;
512 void Creature::StopGroupLoot()
514 if (!m_groupLootId)
515 return;
517 if (Group* group = sObjectMgr.GetGroupById(m_groupLootId))
518 group->EndRoll();
520 m_groupLootTimer = 0;
521 m_groupLootId = 0;
524 void Creature::RegenerateMana()
526 uint32 curValue = GetPower(POWER_MANA);
527 uint32 maxValue = GetMaxPower(POWER_MANA);
529 if (curValue >= maxValue)
530 return;
532 uint32 addvalue = 0;
534 // Combat and any controlled creature
535 if (isInCombat() || GetCharmerOrOwnerGUID())
537 if(!IsUnderLastManaUseEffect())
539 float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
540 float Spirit = GetStat(STAT_SPIRIT);
542 addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate);
545 else
546 addvalue = maxValue / 3;
548 ModifyPower(POWER_MANA, addvalue);
551 void Creature::RegenerateHealth()
553 if (!isRegeneratingHealth())
554 return;
556 uint32 curValue = GetHealth();
557 uint32 maxValue = GetMaxHealth();
559 if (curValue >= maxValue)
560 return;
562 uint32 addvalue = 0;
564 // Not only pet, but any controlled creature
565 if(GetCharmerOrOwnerGUID())
567 float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
568 float Spirit = GetStat(STAT_SPIRIT);
570 if( GetPower(POWER_MANA) > 0 )
571 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
572 else
573 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
575 else
576 addvalue = maxValue/3;
578 ModifyHealth(addvalue);
581 void Creature::DoFleeToGetAssistance()
583 if (!getVictim())
584 return;
586 float radius = sWorld.getConfig(CONFIG_FLOAT_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
587 if (radius >0)
589 Creature* pCreature = NULL;
591 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
592 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
593 Cell::VisitGridObjects(this, searcher, radius);
595 SetNoSearchAssistance(true);
596 UpdateSpeed(MOVE_RUN, false);
598 if(!pCreature)
599 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_UINT32_CREATURE_FAMILY_FLEE_DELAY));
600 else
601 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
605 bool Creature::AIM_Initialize()
607 // make sure nothing can change the AI during AI update
608 if(m_AI_locked)
610 DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "AIM_Initialize: failed to init, locked.");
611 return false;
614 CreatureAI * oldAI = i_AI;
615 i_motionMaster.Initialize();
616 i_AI = FactorySelector::selectAI(this);
617 if (oldAI)
618 delete oldAI;
619 return true;
622 bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
624 ASSERT(map);
625 SetMap(map);
626 SetPhaseMask(phaseMask,false);
628 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
629 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
631 if (bResult)
633 //Notify the map's instance data.
634 //Only works if you create the object in it, not if it is moves to that map.
635 //Normally non-players do not teleport to other maps.
636 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
637 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
639 switch (GetCreatureInfo()->rank)
641 case CREATURE_ELITE_RARE:
642 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RARE);
643 break;
644 case CREATURE_ELITE_ELITE:
645 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_ELITE);
646 break;
647 case CREATURE_ELITE_RAREELITE:
648 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RAREELITE);
649 break;
650 case CREATURE_ELITE_WORLDBOSS:
651 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_WORLDBOSS);
652 break;
653 default:
654 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_NORMAL);
655 break;
657 LoadCreaturesAddon();
660 return bResult;
663 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
665 if(!isTrainer())
666 return false;
668 TrainerSpellData const* trainer_spells = GetTrainerSpells();
670 if(!trainer_spells || trainer_spells->spellList.empty())
672 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
673 GetGUIDLow(),GetEntry());
674 return false;
677 switch(GetCreatureInfo()->trainer_type)
679 case TRAINER_TYPE_CLASS:
680 if(pPlayer->getClass() != GetCreatureInfo()->trainer_class)
682 if(msg)
684 pPlayer->PlayerTalkClass->ClearMenus();
685 switch(GetCreatureInfo()->trainer_class)
687 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
688 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
689 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
690 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
691 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
692 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
693 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
694 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
695 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
698 return false;
700 break;
701 case TRAINER_TYPE_PETS:
702 if(pPlayer->getClass() != CLASS_HUNTER)
704 pPlayer->PlayerTalkClass->ClearMenus();
705 pPlayer->PlayerTalkClass->SendGossipMenu(3620, GetGUID());
706 return false;
708 break;
709 case TRAINER_TYPE_MOUNTS:
710 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
712 if(msg)
714 pPlayer->PlayerTalkClass->ClearMenus();
715 switch(GetCreatureInfo()->trainer_class)
717 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
718 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
719 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
720 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
721 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
722 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
723 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
724 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
725 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
726 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
729 return false;
731 break;
732 case TRAINER_TYPE_TRADESKILLS:
733 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
735 if(msg)
737 pPlayer->PlayerTalkClass->ClearMenus();
738 pPlayer->PlayerTalkClass->SendGossipMenu(11031, GetGUID());
740 return false;
742 break;
743 default:
744 return false; // checked and error output at creature_template loading
746 return true;
749 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
751 if(!isBattleMaster())
752 return false;
754 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
755 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
756 return false;
758 if(!msg)
759 return pPlayer->GetBGAccessByLevel(bgTypeId);
761 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
763 pPlayer->PlayerTalkClass->ClearMenus();
764 switch(bgTypeId)
766 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616, GetGUID()); break;
767 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599, GetGUID()); break;
768 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642, GetGUID()); break;
769 case BATTLEGROUND_EY:
770 case BATTLEGROUND_NA:
771 case BATTLEGROUND_BE:
772 case BATTLEGROUND_AA:
773 case BATTLEGROUND_RL:
774 case BATTLEGROUND_SA:
775 case BATTLEGROUND_DS:
776 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024, GetGUID()); break;
777 default: break;
779 return false;
781 return true;
784 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
786 return pPlayer->getLevel() >= 10
787 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
788 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
791 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, SplineFlags flags, SplineType type)
793 /* uint32 timeElap = getMSTime();
794 if ((timeElap - m_startMove) < m_moveTime)
796 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
797 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
799 else
801 oX = dX;
802 oY = dY;
805 dX = x;
806 dY = y;
807 m_orientation = atan2((oY - dY), (oX - dX));
809 m_startMove = getMSTime();
810 m_moveTime = time;*/
811 SendMonsterMove(x, y, z, type, flags, time);
814 void Creature::PrepareBodyLootState()
816 loot.clear();
818 // if have normal loot then prepare it access
819 if (!isAlive() && !lootForBody)
821 // have normal loot
822 if (GetCreatureInfo()->maxgold > 0 || GetCreatureInfo()->lootid ||
823 // ... or can have skinning after
824 GetCreatureInfo()->SkinLootId && sWorld.getConfig(CONFIG_BOOL_CORPSE_EMPTY_LOOT_SHOW))
826 SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
827 return;
831 // if not have normal loot allow skinning if need
832 if (!isAlive() && !lootForSkin && GetCreatureInfo()->SkinLootId)
834 lootForBody = true; // pass this loot mode
836 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
837 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
838 return;
841 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
842 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
847 * Return original player who tap creature, it can be different from player/group allowed to loot so not use it for loot code
849 Player* Creature::GetOriginalLootRecipient() const
851 return !m_lootRecipientGuid.IsEmpty() ? ObjectAccessor::FindPlayer(m_lootRecipientGuid) : NULL;
855 * Return group if player tap creature as group member, independent is player after leave group or stil be group member
857 Group* Creature::GetGroupLootRecipient() const
859 // original recipient group if set and not disbanded
860 return m_lootGroupRecipientId ? sObjectMgr.GetGroupById(m_lootGroupRecipientId) : NULL;
864 * Return player who can loot tapped creature (member of group or single player)
866 * In case when original player tap creature as group member then group tap prefered.
867 * This is for example important if player after tap leave group.
868 * If group not exist or disbanded or player tap creature not as group member return player
870 Player* Creature::GetLootRecipient() const
872 // original recipient group if set and not disbanded
873 Group* group = GetGroupLootRecipient();
875 // original recipient player if online
876 Player* player = GetOriginalLootRecipient();
878 // if group not set or disbanded return original recipient player if any
879 if (!group)
880 return player;
882 // group case
884 // return player if it still be in original recipient group
885 if (player && player->GetGroup() == group)
886 return player;
888 // find any in group
889 for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
890 if (Player *p = itr->getSource())
891 return p;
893 return NULL;
897 * Set player and group (if player group member) who tap creature
899 void Creature::SetLootRecipient(Unit *unit)
901 // set the player whose group should receive the right
902 // to loot the creature after it dies
903 // should be set to NULL after the loot disappears
905 if (!unit)
907 m_lootRecipientGuid.Clear();
908 m_lootGroupRecipientId = 0;
909 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
910 return;
913 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
914 if(!player) // normal creature, no player involved
915 return;
917 // set player for non group case or if group will disbanded
918 m_lootRecipientGuid = player->GetObjectGuid();
920 // set group for group existed case including if player will leave group at loot time
921 if (Group* group = player->GetGroup())
922 m_lootGroupRecipientId = group->GetId();
924 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
927 void Creature::SaveToDB()
929 // this should only be used when the creature has already been loaded
930 // preferably after adding to map, because mapid may not be valid otherwise
931 CreatureData const *data = sObjectMgr.GetCreatureData(m_DBTableGuid);
932 if(!data)
934 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
935 return;
938 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
941 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
943 // update in loaded data
944 if (!m_DBTableGuid)
945 m_DBTableGuid = GetGUIDLow();
946 CreatureData& data = sObjectMgr.NewOrExistCreatureData(m_DBTableGuid);
948 uint32 displayId = GetNativeDisplayId();
950 // check if it's a custom model and if not, use 0 for displayId
951 CreatureInfo const *cinfo = GetCreatureInfo();
952 if (cinfo)
954 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
955 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
957 if (cinfo->DisplayID_A[0])
958 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
959 if(displayId == minfo->modelid_other_gender)
960 displayId = 0;
962 if (displayId && cinfo->DisplayID_A[1])
963 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
964 if(displayId == minfo->modelid_other_gender)
965 displayId = 0;
967 if (displayId && cinfo->DisplayID_H[0])
968 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
969 if(displayId == minfo->modelid_other_gender)
970 displayId = 0;
972 if (displayId && cinfo->DisplayID_H[1])
973 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
974 if(displayId == minfo->modelid_other_gender)
975 displayId = 0;
977 else
978 displayId = 0;
981 // data->guid = guid don't must be update at save
982 data.id = GetEntry();
983 data.mapid = mapid;
984 data.phaseMask = phaseMask;
985 data.displayid = displayId;
986 data.equipmentId = GetEquipmentId();
987 data.posX = GetPositionX();
988 data.posY = GetPositionY();
989 data.posZ = GetPositionZ();
990 data.orientation = GetOrientation();
991 data.spawntimesecs = m_respawnDelay;
992 // prevent add data integrity problems
993 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
994 data.currentwaypoint = 0;
995 data.curhealth = GetHealth();
996 data.curmana = GetPower(POWER_MANA);
997 data.is_dead = m_isDeadByDefault;
998 // prevent add data integrity problems
999 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1000 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1001 data.spawnMask = spawnMask;
1003 // updated in DB
1004 WorldDatabase.BeginTransaction();
1006 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1008 std::ostringstream ss;
1009 ss << "INSERT INTO creature VALUES ("
1010 << m_DBTableGuid << ","
1011 << GetEntry() << ","
1012 << mapid <<","
1013 << uint32(spawnMask) << "," // cast to prevent save as symbol
1014 << uint16(GetPhaseMask()) << "," // prevent out of range error
1015 << displayId <<","
1016 << GetEquipmentId() <<","
1017 << GetPositionX() << ","
1018 << GetPositionY() << ","
1019 << GetPositionZ() << ","
1020 << GetOrientation() << ","
1021 << m_respawnDelay << "," //respawn time
1022 << (float) m_respawnradius << "," //spawn distance (float)
1023 << (uint32) (0) << "," //currentwaypoint
1024 << GetHealth() << "," //curhealth
1025 << GetPower(POWER_MANA) << "," //curmana
1026 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1027 << GetDefaultMovementType() << ")"; //default movement generator type
1029 WorldDatabase.PExecuteLog("%s", ss.str().c_str());
1031 WorldDatabase.CommitTransaction();
1034 void Creature::SelectLevel(const CreatureInfo *cinfo, float percentHealth, float percentMana)
1036 uint32 rank = isPet()? 0 : cinfo->rank;
1038 // level
1039 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1040 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1041 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1042 SetLevel(level);
1044 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1046 // health
1047 float healthmod = _GetHealthMod(rank);
1049 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1050 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1051 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1053 SetCreateHealth(health);
1054 SetMaxHealth(health);
1056 if (percentHealth == 100.0f)
1057 SetHealth(health);
1058 else
1059 SetHealthPercent(percentHealth);
1061 // mana
1062 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1063 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1064 uint32 mana = minmana + uint32(rellevel * (maxmana - minmana));
1066 SetCreateMana(mana);
1067 SetMaxPower(POWER_MANA, mana); //MAX Mana
1068 SetPower(POWER_MANA, mana);
1070 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
1072 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, float(health));
1073 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, float(mana));
1075 // damage
1076 float damagemod = _GetDamageMod(rank);
1078 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1079 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1081 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1082 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1084 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1087 float Creature::_GetHealthMod(int32 Rank)
1089 switch (Rank) // define rates for each elite rank
1091 case CREATURE_ELITE_NORMAL:
1092 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_HP);
1093 case CREATURE_ELITE_ELITE:
1094 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP);
1095 case CREATURE_ELITE_RAREELITE:
1096 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_HP);
1097 case CREATURE_ELITE_WORLDBOSS:
1098 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_HP);
1099 case CREATURE_ELITE_RARE:
1100 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_HP);
1101 default:
1102 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP);
1106 float Creature::_GetDamageMod(int32 Rank)
1108 switch (Rank) // define rates for each elite rank
1110 case CREATURE_ELITE_NORMAL:
1111 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_DAMAGE);
1112 case CREATURE_ELITE_ELITE:
1113 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE);
1114 case CREATURE_ELITE_RAREELITE:
1115 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1116 case CREATURE_ELITE_WORLDBOSS:
1117 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1118 case CREATURE_ELITE_RARE:
1119 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_DAMAGE);
1120 default:
1121 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE);
1125 float Creature::GetSpellDamageMod(int32 Rank)
1127 switch (Rank) // define rates for each elite rank
1129 case CREATURE_ELITE_NORMAL:
1130 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_SPELLDAMAGE);
1131 case CREATURE_ELITE_ELITE:
1132 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1133 case CREATURE_ELITE_RAREELITE:
1134 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1135 case CREATURE_ELITE_WORLDBOSS:
1136 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1137 case CREATURE_ELITE_RARE:
1138 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1139 default:
1140 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1144 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1146 CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
1147 if(!cinfo)
1149 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1150 return false;
1152 m_originalEntry = Entry;
1154 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1156 if (!UpdateEntry(Entry, team, data, false))
1157 return false;
1159 return true;
1162 bool Creature::LoadFromDB(uint32 guid, Map *map)
1164 CreatureData const* data = sObjectMgr.GetCreatureData(guid);
1166 if(!data)
1168 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1169 return false;
1172 m_DBTableGuid = guid;
1173 if (map->GetInstanceId() == 0)
1175 // Creature can be loaded already in map if grid has been unloaded while creature walk to another grid
1176 // FIXME: until creature guids is global and for instances used dynamic generated guids
1177 // in instance possible load creature duplicates with same DB guid but different in game guids
1178 // This will be until implementing per-map creature guids
1179 if (map->GetCreature(MAKE_NEW_GUID(guid, data->id, HIGHGUID_UNIT)))
1180 return false;
1182 else
1183 guid = sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT);
1185 uint16 team = 0;
1186 if(!Create(guid, map, data->phaseMask, data->id, team, data))
1187 return false;
1189 Relocate(data->posX, data->posY, data->posZ, data->orientation);
1191 if(!IsPositionValid())
1193 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)", GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
1194 return false;
1197 m_respawnradius = data->spawndist;
1199 m_respawnDelay = data->spawntimesecs;
1200 m_isDeadByDefault = data->is_dead;
1201 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1203 m_respawnTime = sObjectMgr.GetCreatureRespawnTime(m_DBTableGuid, GetInstanceId());
1204 if(m_respawnTime > time(NULL)) // not ready to respawn
1206 m_deathState = DEAD;
1207 if(canFly())
1209 float tz = GetMap()->GetHeight(data->posX, data->posY, data->posZ, false);
1210 if(data->posZ - tz > 0.1)
1211 Relocate(data->posX, data->posY, tz);
1214 else if(m_respawnTime) // respawn time set but expired
1216 m_respawnTime = 0;
1217 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1220 uint32 curhealth = data->curhealth;
1221 if(curhealth)
1223 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1224 if(curhealth < 1)
1225 curhealth = 1;
1228 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1229 SetPower(POWER_MANA, data->curmana);
1231 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1233 // checked at creature_template loading
1234 m_defaultMovementType = MovementGeneratorType(data->movementType);
1236 AIM_Initialize();
1237 return true;
1240 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1242 if(equip_entry == 0)
1244 if (force)
1246 for (uint8 i = 0; i < 3; ++i)
1247 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1248 m_equipmentId = 0;
1250 return;
1253 EquipmentInfo const *einfo = sObjectMgr.GetEquipmentInfo(equip_entry);
1254 if (!einfo)
1255 return;
1257 m_equipmentId = equip_entry;
1258 for (uint8 i = 0; i < 3; ++i)
1259 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1262 bool Creature::hasQuest(uint32 quest_id) const
1264 QuestRelations const& qr = sObjectMgr.mCreatureQuestRelations;
1265 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1267 if(itr->second==quest_id)
1268 return true;
1270 return false;
1273 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1275 QuestRelations const& qr = sObjectMgr.mCreatureQuestInvolvedRelations;
1276 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1278 if(itr->second == quest_id)
1279 return true;
1281 return false;
1284 void Creature::DeleteFromDB()
1286 if (!m_DBTableGuid)
1288 DEBUG_LOG("Trying to delete not saved creature!");
1289 return;
1292 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1293 sObjectMgr.DeleteCreatureData(m_DBTableGuid);
1295 WorldDatabase.BeginTransaction();
1296 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1297 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1298 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1299 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1300 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1301 WorldDatabase.PExecuteLog("DELETE FROM creature_battleground WHERE guid = '%u'", m_DBTableGuid);
1302 WorldDatabase.CommitTransaction();
1305 float Creature::GetAttackDistance(Unit const* pl) const
1307 float aggroRate = sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
1308 if(aggroRate == 0)
1309 return 0.0f;
1311 uint32 playerlevel = pl->getLevelForTarget(this);
1312 uint32 creaturelevel = getLevelForTarget(pl);
1314 int32 leveldif = int32(playerlevel) - int32(creaturelevel);
1316 // "The maximum Aggro Radius has a cap of 25 levels under. Example: A level 30 char has the same Aggro Radius of a level 5 char on a level 60 mob."
1317 if ( leveldif < - 25)
1318 leveldif = -25;
1320 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1321 float RetDistance = 20;
1323 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1324 // radius grow if playlevel < creaturelevel
1325 RetDistance -= (float)leveldif;
1327 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
1329 // detect range auras
1330 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1332 // detected range auras
1333 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1336 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1337 if(RetDistance < 5)
1338 RetDistance = 5;
1340 return (RetDistance*aggroRate);
1343 void Creature::setDeathState(DeathState s)
1345 if ((s == JUST_DIED && !m_isDeadByDefault) || (s == JUST_ALIVED && m_isDeadByDefault))
1347 m_deathTimer = m_corpseDelay*IN_MILLISECONDS;
1349 // always save boss respawn time at death to prevent crash cheating
1350 if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1351 SaveRespawnTime();
1353 if (canFly() && FallGround())
1354 return;
1356 if (!IsStopped())
1357 StopMoving();
1359 Unit::setDeathState(s);
1361 if (s == JUST_DIED)
1363 SetTargetGUID(0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1364 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1366 if (canFly() && FallGround())
1367 return;
1369 if (HasSearchedAssistance())
1371 SetNoSearchAssistance(false);
1372 UpdateSpeed(MOVE_RUN, false);
1375 Unit::setDeathState(CORPSE);
1377 if (s == JUST_ALIVED)
1379 SetHealth(GetMaxHealth());
1380 SetLootRecipient(NULL);
1381 CreatureInfo const *cinfo = GetCreatureInfo();
1382 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1383 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1384 AddSplineFlag(SPLINEFLAG_WALKMODE);
1385 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1386 Unit::setDeathState(ALIVE);
1387 clearUnitState(UNIT_STAT_ALL_STATE);
1388 i_motionMaster.Clear();
1389 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1390 LoadCreaturesAddon(true);
1394 bool Creature::FallGround()
1396 // Let's abort after we called this function one time
1397 if (getDeathState() == DEAD_FALLING)
1398 return false;
1400 // Let's do with no vmap because no way to get far distance with vmap high call
1401 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1403 // Abort too if the ground is very near
1404 if (fabs(GetPositionZ() - tz) < 0.1f)
1405 return false;
1407 Unit::setDeathState(DEAD_FALLING);
1408 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1409 Relocate(GetPositionX(), GetPositionY(), tz);
1410 return true;
1413 void Creature::Respawn()
1415 RemoveCorpse();
1417 // forced recreate creature object at clients
1418 UnitVisibility currentVis = GetVisibility();
1419 SetVisibility(VISIBILITY_RESPAWN);
1420 UpdateObjectVisibility();
1421 SetVisibility(currentVis); // restore visibility state
1422 UpdateObjectVisibility();
1424 if(getDeathState() == DEAD)
1426 if (m_DBTableGuid)
1427 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(), 0);
1428 m_respawnTime = time(NULL); // respawn at next tick
1432 void Creature::ForcedDespawn(uint32 timeMSToDespawn)
1434 if (timeMSToDespawn)
1436 ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
1438 m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
1439 return;
1442 if (isAlive())
1443 setDeathState(JUST_DIED);
1445 RemoveCorpse();
1446 SetHealth(0); // just for nice GM-mode view
1449 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1451 if (!spellInfo)
1452 return false;
1454 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1455 return true;
1457 return Unit::IsImmunedToSpell(spellInfo);
1460 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
1462 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1463 return true;
1465 // Taunt immunity special flag check
1466 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1468 // Taunt aura apply check
1469 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1471 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1472 return true;
1474 // Spell effect taunt check
1475 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1476 return true;
1479 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1482 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1484 if(!pVictim)
1485 return NULL;
1487 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1489 if(!m_spells[i])
1490 continue;
1491 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1492 if(!spellInfo)
1494 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1495 continue;
1498 bool bcontinue = true;
1499 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
1501 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1502 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1503 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1504 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1507 bcontinue = false;
1508 break;
1511 if(bcontinue) continue;
1513 if(spellInfo->manaCost > GetPower(POWER_MANA))
1514 continue;
1515 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1516 float range = GetSpellMaxRange(srange);
1517 float minrange = GetSpellMinRange(srange);
1519 float dist = GetCombatDistance(pVictim);
1521 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1522 // continue;
1523 if( dist > range || dist < minrange )
1524 continue;
1525 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1526 continue;
1527 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1528 continue;
1529 return spellInfo;
1531 return NULL;
1534 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1536 if(!pVictim)
1537 return NULL;
1539 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1541 if(!m_spells[i])
1542 continue;
1543 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1544 if(!spellInfo)
1546 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1547 continue;
1550 bool bcontinue = true;
1551 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
1553 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1555 bcontinue = false;
1556 break;
1559 if(bcontinue)
1560 continue;
1562 if(spellInfo->manaCost > GetPower(POWER_MANA))
1563 continue;
1564 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1565 float range = GetSpellMaxRange(srange);
1566 float minrange = GetSpellMinRange(srange);
1568 float dist = GetCombatDistance(pVictim);
1570 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1571 // continue;
1572 if( dist > range || dist < minrange )
1573 continue;
1574 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1575 continue;
1576 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1577 continue;
1578 return spellInfo;
1580 return NULL;
1583 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1585 // gamemaster in GM mode see all, including ghosts
1586 if(pl->isGameMaster())
1587 return true;
1589 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1590 return false;
1592 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1593 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1595 return (isAlive() || m_deathTimer > 0 || (m_isDeadByDefault && m_deathState == CORPSE));
1598 // Dead player see live creatures near own corpse
1599 if(isAlive())
1601 Corpse *corpse = pl->GetCorpse();
1602 if(corpse)
1604 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1605 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
1606 return true;
1610 // Dead player can see ghosts
1611 if (GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_GHOST_VISIBLE)
1612 return true;
1614 // and not see any other
1615 return false;
1618 void Creature::SendAIReaction(AiReaction reactionType)
1620 WorldPacket data(SMSG_AI_REACTION, 12);
1622 data << uint64(GetGUID());
1623 data << uint32(reactionType);
1625 ((WorldObject*)this)->SendMessageToSet(&data, true);
1627 DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "WORLD: Sent SMSG_AI_REACTION, type %u.", reactionType);
1630 void Creature::CallAssistance()
1632 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1634 SetNoCallAssistance(true);
1636 float radius = sWorld.getConfig(CONFIG_FLOAT_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1637 if(radius > 0)
1639 std::list<Creature*> assistList;
1642 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1643 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1644 Cell::VisitGridObjects(this,searcher, radius);
1647 if (!assistList.empty())
1649 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1650 while (!assistList.empty())
1652 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1653 e->AddAssistant((*assistList.begin())->GetGUID());
1654 assistList.pop_front();
1656 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_UINT32_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1662 void Creature::CallForHelp(float fRadius)
1664 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1665 return;
1667 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1668 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1669 Cell::VisitGridObjects(this,worker, fRadius);
1672 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1674 // we don't need help from zombies :)
1675 if (!isAlive())
1676 return false;
1678 // we don't need help from non-combatant ;)
1679 if (isCivilian())
1680 return false;
1682 // skip fighting creature
1683 if (isInCombat())
1684 return false;
1686 // only free creature
1687 if (GetCharmerOrOwnerGUID())
1688 return false;
1690 // only from same creature faction
1691 if (checkfaction)
1693 if (getFaction() != u->getFaction())
1694 return false;
1696 else
1698 if (!IsFriendlyTo(u))
1699 return false;
1702 // skip non hostile to caster enemy creatures
1703 if (!IsHostileTo(enemy))
1704 return false;
1706 return true;
1709 bool Creature::CanInitiateAttack()
1711 if (hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED))
1712 return false;
1714 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
1715 return false;
1717 if (isPassiveToHostile())
1718 return false;
1720 return true;
1723 void Creature::SaveRespawnTime()
1725 if(isPet() || !m_DBTableGuid)
1726 return;
1728 if(m_respawnTime > time(NULL)) // dead (no corpse)
1729 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), m_respawnTime);
1730 else if(m_deathTimer > 0) // dead (corpse)
1731 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), time(NULL) + m_respawnDelay + m_deathTimer / IN_MILLISECONDS);
1734 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1736 if (!pVictim)
1737 return true;
1739 if (!pVictim->IsInMap(this))
1740 return true;
1742 if (!pVictim->isTargetableForAttack())
1743 return true;
1745 if (!pVictim->isInAccessablePlaceFor(this))
1746 return true;
1748 if (!pVictim->isVisibleForOrDetect(this,this,false))
1749 return true;
1751 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1752 return false;
1754 float AttackDist = GetAttackDistance(pVictim);
1755 float ThreatRadius = sWorld.getConfig(CONFIG_FLOAT_THREAT_RADIUS);
1757 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1758 return !pVictim->IsWithinDist3d(CombatStartX, CombatStartY, CombatStartZ,
1759 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1762 CreatureDataAddon const* Creature::GetCreatureAddon() const
1764 if (m_DBTableGuid)
1766 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1767 return addon;
1770 // dependent from difficulty mode entry
1771 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1774 //creature_addon table
1775 bool Creature::LoadCreaturesAddon(bool reload)
1777 CreatureDataAddon const *cainfo = GetCreatureAddon();
1778 if(!cainfo)
1779 return false;
1781 if (cainfo->mount != 0)
1782 Mount(cainfo->mount);
1784 if (cainfo->bytes1 != 0)
1786 // 0 StandState
1787 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1788 // 2 StandFlags
1789 // 3 StandMiscFlags
1791 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1792 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1793 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1794 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1795 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1798 if (cainfo->bytes2 != 0)
1800 // 0 SheathState
1801 // 1 UnitPVPStateFlags Set at Creature::UpdateEntry (SetPvp())
1802 // 2 UnitRename Pet only, so always 0 for default creature
1803 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1805 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1806 //SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1807 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1808 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1809 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1810 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1813 if (cainfo->emote != 0)
1814 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1816 if (cainfo->splineFlags != 0)
1817 SetSplineFlags(SplineFlags(cainfo->splineFlags));
1819 if(cainfo->auras)
1821 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1823 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1824 if (!AdditionalSpellInfo)
1826 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1827 continue;
1830 // skip already applied aura
1831 if(HasAura(cAura->spell_id,cAura->effect_idx))
1833 if(!reload)
1834 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has duplicate aura (spell %u effect %u) in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id,cAura->effect_idx);
1836 continue;
1839 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1840 AddAura(AdditionalAura);
1841 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[EFFECT_INDEX_0],GetGUIDLow(),GetEntry());
1844 return true;
1847 /// Send a message to LocalDefense channel for players opposition team in the zone
1848 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1850 uint32 enemy_team = attacker->GetTeam();
1852 WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4);
1853 data << uint32(GetZoneId());
1854 sWorld.SendGlobalMessage(&data, NULL, (enemy_team == ALLIANCE ? HORDE : ALLIANCE));
1857 void Creature::SetInCombatWithZone()
1859 if (!CanHaveThreatList())
1861 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1862 return;
1865 Map* pMap = GetMap();
1867 if (!pMap->IsDungeon())
1869 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1870 return;
1873 Map::PlayerList const &PlList = pMap->GetPlayers();
1875 if (PlList.isEmpty())
1876 return;
1878 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
1880 if (Player* pPlayer = i->getSource())
1882 if (pPlayer->isGameMaster())
1883 continue;
1885 if (pPlayer->isAlive())
1887 pPlayer->SetInCombatWith(this);
1888 AddThreat(pPlayer);
1894 Unit* Creature::SelectAttackingTarget(AttackingTarget target, uint32 position) const
1896 if (!CanHaveThreatList())
1897 return NULL;
1899 //ThreatList m_threatlist;
1900 ThreatList const& threatlist = getThreatManager().getThreatList();
1901 ThreatList::const_iterator i = threatlist.begin();
1902 ThreatList::const_reverse_iterator r = threatlist.rbegin();
1904 if (position >= threatlist.size() || !threatlist.size())
1905 return NULL;
1907 switch(target)
1909 case ATTACKING_TARGET_RANDOM:
1911 advance(i, position + (rand() % (threatlist.size() - position)));
1912 return Unit::GetUnit(*this, (*i)->getUnitGuid());
1914 case ATTACKING_TARGET_TOPAGGRO:
1916 advance(i, position);
1917 return Unit::GetUnit(*this, (*i)->getUnitGuid());
1919 case ATTACKING_TARGET_BOTTOMAGGRO:
1921 advance(r, position);
1922 return Unit::GetUnit(*this, (*r)->getUnitGuid());
1924 // TODO: implement these
1925 //case ATTACKING_TARGET_RANDOM_PLAYER:
1926 //case ATTACKING_TARGET_TOPAGGRO_PLAYER:
1927 //case ATTACKING_TARGET_BOTTOMAGGRO_PLAYER:
1930 return NULL;
1933 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1935 m_CreatureSpellCooldowns[spell_id] = end_time;
1938 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1940 m_CreatureCategoryCooldowns[category] = apply_time;
1943 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1945 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1946 if(!spellInfo)
1947 return;
1949 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1950 if(cooldown)
1951 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILLISECONDS);
1953 if(spellInfo->Category)
1954 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1956 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1959 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1961 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1962 if(!spellInfo)
1963 return false;
1965 // check global cooldown if spell affected by it
1966 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1967 return true;
1969 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1970 return (itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILLISECONDS)) > time(NULL));
1973 bool Creature::HasSpellCooldown(uint32 spell_id) const
1975 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1976 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1979 bool Creature::IsInEvadeMode() const
1981 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1984 bool Creature::HasSpell(uint32 spellID) const
1986 uint8 i;
1987 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1988 if(spellID == m_spells[i])
1989 break;
1990 return i < CREATURE_MAX_SPELLS; // break before end of iteration of known spells
1993 time_t Creature::GetRespawnTimeEx() const
1995 time_t now = time(NULL);
1996 if(m_respawnTime > now) // dead (no corpse)
1997 return m_respawnTime;
1998 else if(m_deathTimer > 0) // dead (corpse)
1999 return now + m_respawnDelay + m_deathTimer / IN_MILLISECONDS;
2000 else
2001 return now;
2004 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
2006 if (m_DBTableGuid)
2008 if (CreatureData const* data = sObjectMgr.GetCreatureData(GetDBTableGUIDLow()))
2010 x = data->posX;
2011 y = data->posY;
2012 z = data->posZ;
2013 if (ori)
2014 *ori = data->orientation;
2015 if (dist)
2016 *dist = GetRespawnRadius();
2018 return;
2022 float orient;
2024 GetSummonPoint(x, y, z, orient);
2026 if (ori)
2027 *ori = orient;
2028 if (dist)
2029 *dist = GetRespawnRadius();
2032 void Creature::AllLootRemovedFromCorpse()
2034 if (lootForBody && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
2036 uint32 nDeathTimer;
2038 CreatureInfo const *cinfo = GetCreatureInfo();
2040 // corpse was not skinned -> apply corpse looted timer
2041 if (!lootForSkin)
2042 nDeathTimer = (uint32)((m_corpseDelay * IN_MILLISECONDS) * sWorld.getConfig(CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED));
2043 // corpse was skinned, corpse will despawn next update
2044 else
2045 nDeathTimer = 0;
2047 // update death timer only if looted timer is shorter
2048 if (m_deathTimer > nDeathTimer)
2049 m_deathTimer = nDeathTimer;
2053 uint32 Creature::getLevelForTarget( Unit const* target ) const
2055 if(!isWorldBoss())
2056 return Unit::getLevelForTarget(target);
2058 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_UINT32_WORLD_BOSS_LEVEL_DIFF);
2059 if(level < 1)
2060 return 1;
2061 if(level > 255)
2062 return 255;
2063 return level;
2066 std::string Creature::GetAIName() const
2068 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
2071 std::string Creature::GetScriptName() const
2073 return sObjectMgr.GetScriptName(GetScriptId());
2076 uint32 Creature::GetScriptId() const
2078 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2081 VendorItemData const* Creature::GetVendorItems() const
2083 return sObjectMgr.GetNpcVendorItemList(GetEntry());
2086 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2088 if(!vItem->maxcount)
2089 return vItem->maxcount;
2091 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2092 for(; itr != m_vendorItemCounts.end(); ++itr)
2093 if(itr->itemId==vItem->item)
2094 break;
2096 if(itr == m_vendorItemCounts.end())
2097 return vItem->maxcount;
2099 VendorItemCount* vCount = &*itr;
2101 time_t ptime = time(NULL);
2103 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2105 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
2107 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2108 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2110 m_vendorItemCounts.erase(itr);
2111 return vItem->maxcount;
2114 vCount->count += diff * pProto->BuyCount;
2115 vCount->lastIncrementTime = ptime;
2118 return vCount->count;
2121 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2123 if(!vItem->maxcount)
2124 return 0;
2126 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2127 for(; itr != m_vendorItemCounts.end(); ++itr)
2128 if(itr->itemId==vItem->item)
2129 break;
2131 if(itr == m_vendorItemCounts.end())
2133 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2134 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2135 return new_count;
2138 VendorItemCount* vCount = &*itr;
2140 time_t ptime = time(NULL);
2142 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2144 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
2146 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2147 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2148 vCount->count += diff * pProto->BuyCount;
2149 else
2150 vCount->count = vItem->maxcount;
2153 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2154 vCount->lastIncrementTime = ptime;
2155 return vCount->count;
2158 TrainerSpellData const* Creature::GetTrainerSpells() const
2160 return sObjectMgr.GetNpcTrainerSpells(GetEntry());
2163 // overwrite WorldObject function for proper name localization
2164 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2166 if (loc_idx >= 0)
2168 CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(GetEntry());
2169 if (cl)
2171 if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
2172 return cl->Name[loc_idx].c_str();
2176 return GetName();
2179 void Creature::SetActiveObjectState( bool on )
2181 if(m_isActiveObject==on)
2182 return;
2184 bool world = IsInWorld();
2186 Map* map;
2187 if(world)
2189 map = GetMap();
2190 map->Remove(this,false);
2193 m_isActiveObject = on;
2195 if(world)
2196 map->Add(this);
2199 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2201 float x, y, z;
2202 if(GetMotionMaster()->GetDestination(x, y, z))
2203 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2206 void Creature::SendAreaSpiritHealerQueryOpcode(Player *pl)
2208 uint32 next_resurrect = 0;
2209 if (Spell* pcurSpell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
2210 next_resurrect = pcurSpell->GetCastedTime();
2211 WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 8 + 4);
2212 data << GetGUID() << next_resurrect;
2213 pl->SendDirectMessage(&data);
2216 void Creature::RelocationNotify()
2218 MaNGOS::CreatureRelocationNotifier relocationNotifier(*this);
2219 float radius = MAX_CREATURE_ATTACK_RADIUS * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
2220 Cell::VisitAllObjects(this, relocationNotifier, radius);