[9545] Rename ObjectDefines.h -> ObjectGuid.h
[getmangos.git] / src / game / Creature.cpp
blob9963129c9c082d93cd56d391eb8d5f62a7d460df
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 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
63 if((*i)->item == item_id)
65 m_items.erase(i);
66 return true;
69 return false;
72 size_t VendorItemData::FindItemSlot(uint32 item_id) const
74 for(size_t i = 0; i < m_items.size(); ++i )
75 if(m_items[i]->item == item_id)
76 return i;
77 return m_items.size();
80 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
82 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
83 if((*i)->item == item_id)
84 return *i;
85 return NULL;
88 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
90 if(Unit* victim = Unit::GetUnit(m_owner, m_victim))
92 while (!m_assistants.empty())
94 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
95 m_assistants.pop_front();
97 if (assistant && assistant->CanAssistTo(&m_owner, victim))
99 assistant->SetNoCallAssistance(true);
100 if(assistant->AI())
101 assistant->AI()->AttackStart(victim);
105 return true;
108 bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
110 m_owner.ForcedDespawn();
111 return true;
114 Creature::Creature(CreatureSubtype subtype) :
115 Unit(), i_AI(NULL),
116 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), m_groupLootId(0),
117 m_lootMoney(0), m_lootRecipient(0),
118 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
119 m_subtype(subtype), m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0),
120 m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
121 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_needNotify(false),
122 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
123 m_creatureInfo(NULL), m_isActiveObject(false), m_splineFlags(SPLINEFLAG_WALKMODE)
125 m_regenTimer = 200;
126 m_valuesCount = UNIT_END;
128 for(int i = 0; i < 4; ++i)
129 m_spells[i] = 0;
131 m_CreatureSpellCooldowns.clear();
132 m_CreatureCategoryCooldowns.clear();
133 m_GlobalCooldown = 0;
135 m_splineFlags = SPLINEFLAG_WALKMODE;
138 Creature::~Creature()
140 CleanupsBeforeDelete();
142 m_vendorItemCounts.clear();
144 delete i_AI;
145 i_AI = NULL;
148 void Creature::AddToWorld()
150 ///- Register the creature for guid lookup
151 if(!IsInWorld() && GetGUIDHigh() == HIGHGUID_UNIT)
152 GetMap()->GetObjectsStore().insert<Creature>(GetGUID(), (Creature*)this);
154 Unit::AddToWorld();
157 void Creature::RemoveFromWorld()
159 ///- Remove the creature from the accessor
160 if(IsInWorld() && GetGUIDHigh() == HIGHGUID_UNIT)
161 GetMap()->GetObjectsStore().erase<Creature>(GetGUID(), (Creature*)NULL);
163 Unit::RemoveFromWorld();
166 void Creature::RemoveCorpse()
168 if ((getDeathState() != CORPSE && !m_isDeadByDefault) || (getDeathState() != ALIVE && m_isDeadByDefault))
169 return;
171 m_deathTimer = 0;
172 setDeathState(DEAD);
173 UpdateObjectVisibility();
174 loot.clear();
175 uint32 respawnDelay = m_respawnDelay;
176 if (AI())
177 AI()->CorpseRemoved(respawnDelay);
179 m_respawnTime = time(NULL) + respawnDelay;
181 float x, y, z, o;
182 GetRespawnCoord(x, y, z, &o);
183 GetMap()->CreatureRelocation(this, x, y, z, o);
187 * change the entry of creature until respawn
189 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
191 CreatureInfo const *normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
192 if(!normalInfo)
194 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
195 return false;
198 // get difficulty 1 mode entry
199 uint32 actualEntry = Entry;
200 CreatureInfo const *cinfo = normalInfo;
201 // TODO correctly implement spawnmodes for non-bg maps
202 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
204 if (normalInfo->DifficultyEntry[diff])
206 // we already have valid Map pointer for current creature!
207 if (GetMap()->GetSpawnMode() > diff)
209 cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff]);
210 if (!cinfo)
212 // maybe check such things already at startup
213 sLog.outErrorDb("Creature::UpdateEntry creature difficulty %u entry %u does not exist.", diff + 1, actualEntry);
214 return false;
220 SetEntry(Entry); // normal entry always
221 m_creatureInfo = cinfo; // map mode related always
223 // equal to player Race field, but creature does not have race
224 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
226 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
227 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
229 uint32 display_id = sObjectMgr.ChooseDisplayId(team, GetCreatureInfo(), data);
230 if (!display_id) // Cancel load if no display id
232 sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load.", Entry);
233 return false;
236 CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
237 if (!minfo) // Cancel load if no model defined
239 sLog.outErrorDb("Creature (Entry: %u) has no model info defined in table `creature_model_info`, can't load.", Entry);
240 return false;
243 display_id = minfo->modelid; // it can be different (for another gender)
245 SetDisplayId(display_id);
246 SetNativeDisplayId(display_id);
247 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
249 // Load creature equipment
250 if(!data || data->equipmentId == 0)
251 { // use default from the template
252 LoadEquipment(cinfo->equipmentId);
254 else if(data && data->equipmentId != -1)
255 { // override, -1 means no equipment
256 LoadEquipment(data->equipmentId);
259 SetName(normalInfo->Name); // at normal entry always
261 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, minfo->bounding_radius);
262 SetFloatValue(UNIT_FIELD_COMBATREACH, minfo->combat_reach);
264 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
266 SetSpeedRate(MOVE_WALK, cinfo->speed);
267 SetSpeedRate(MOVE_RUN, cinfo->speed);
268 SetSpeedRate(MOVE_SWIM, cinfo->speed);
270 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
272 // checked at loading
273 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
274 if(!m_respawnradius && m_defaultMovementType == RANDOM_MOTION_TYPE)
275 m_defaultMovementType = IDLE_MOTION_TYPE;
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_LOG("Respawning...");
370 m_respawnTime = 0;
371 lootForPickPocketed = false;
372 lootForBody = false;
374 if(m_originalEntry != GetEntry())
375 UpdateEntry(m_originalEntry);
377 CreatureInfo const *cinfo = GetCreatureInfo();
379 SelectLevel(cinfo);
380 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
381 if (m_isDeadByDefault)
383 setDeathState(JUST_DIED);
384 SetHealth(0);
385 i_motionMaster.Clear();
386 clearUnitState(UNIT_STAT_ALL_STATE);
387 LoadCreaturesAddon(true);
389 else
390 setDeathState( JUST_ALIVED );
392 //Call AI respawn virtual function
393 i_AI->JustRespawned();
395 GetMap()->Add(this);
397 break;
399 case CORPSE:
401 if (m_isDeadByDefault)
402 break;
404 if( m_deathTimer <= diff )
406 // since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
407 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
408 if (poolid)
409 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
411 if (IsInWorld()) // can be despawned by update pool
413 RemoveCorpse();
414 DEBUG_LOG("Removing corpse... %u ", GetEntry());
417 else
419 m_deathTimer -= diff;
420 if (m_groupLootTimer && m_groupLootId)
422 if(diff <= m_groupLootTimer)
424 m_groupLootTimer -= diff;
426 else
428 if (Group* group = sObjectMgr.GetGroupById(m_groupLootId))
429 group->EndRoll();
430 m_groupLootTimer = 0;
431 m_groupLootId = 0;
436 break;
438 case ALIVE:
440 if (m_isDeadByDefault)
442 if( m_deathTimer <= diff )
444 // since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
445 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
447 if (poolid)
448 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
450 if (IsInWorld()) // can be despawned by update pool
452 RemoveCorpse();
453 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
455 else
456 return;
458 else
460 m_deathTimer -= diff;
464 Unit::Update( diff );
466 // creature can be dead after Unit::Update call
467 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
468 if(!isAlive())
469 break;
471 if(!IsInEvadeMode())
473 // do not allow the AI to be changed during update
474 m_AI_locked = true;
475 i_AI->UpdateAI(diff);
476 m_AI_locked = false;
479 // creature can be dead after UpdateAI call
480 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
481 if(!isAlive())
482 break;
483 if(m_regenTimer > 0)
485 if(diff >= m_regenTimer)
486 m_regenTimer = 0;
487 else
488 m_regenTimer -= diff;
490 if (m_regenTimer != 0)
491 break;
493 if (!isInCombat() || IsPolymorphed())
494 RegenerateHealth();
496 RegenerateMana();
498 m_regenTimer = REGEN_TIME_FULL;
499 break;
501 case DEAD_FALLING:
503 if (!FallGround())
504 setDeathState(JUST_DIED);
506 default:
507 break;
511 void Creature::RegenerateMana()
513 uint32 curValue = GetPower(POWER_MANA);
514 uint32 maxValue = GetMaxPower(POWER_MANA);
516 if (curValue >= maxValue)
517 return;
519 uint32 addvalue = 0;
521 // Combat and any controlled creature
522 if (isInCombat() || GetCharmerOrOwnerGUID())
524 if(!IsUnderLastManaUseEffect())
526 float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
527 float Spirit = GetStat(STAT_SPIRIT);
529 addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate);
532 else
533 addvalue = maxValue / 3;
535 ModifyPower(POWER_MANA, addvalue);
538 void Creature::RegenerateHealth()
540 if (!isRegeneratingHealth())
541 return;
543 uint32 curValue = GetHealth();
544 uint32 maxValue = GetMaxHealth();
546 if (curValue >= maxValue)
547 return;
549 uint32 addvalue = 0;
551 // Not only pet, but any controlled creature
552 if(GetCharmerOrOwnerGUID())
554 float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
555 float Spirit = GetStat(STAT_SPIRIT);
557 if( GetPower(POWER_MANA) > 0 )
558 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
559 else
560 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
562 else
563 addvalue = maxValue/3;
565 ModifyHealth(addvalue);
568 void Creature::DoFleeToGetAssistance()
570 if (!getVictim())
571 return;
573 float radius = sWorld.getConfig(CONFIG_FLOAT_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
574 if (radius >0)
576 Creature* pCreature = NULL;
578 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
579 Cell cell(p);
580 cell.data.Part.reserved = ALL_DISTRICT;
581 cell.SetNoCreate();
582 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
583 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
585 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
587 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
589 SetNoSearchAssistance(true);
590 UpdateSpeed(MOVE_RUN, false);
592 if(!pCreature)
593 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_UINT32_CREATURE_FAMILY_FLEE_DELAY));
594 else
595 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
599 bool Creature::AIM_Initialize()
601 // make sure nothing can change the AI during AI update
602 if(m_AI_locked)
604 sLog.outDebug("AIM_Initialize: failed to init, locked.");
605 return false;
608 CreatureAI * oldAI = i_AI;
609 i_motionMaster.Initialize();
610 i_AI = FactorySelector::selectAI(this);
611 if (oldAI)
612 delete oldAI;
613 return true;
616 bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
618 ASSERT(map);
619 SetMap(map);
620 SetPhaseMask(phaseMask,false);
622 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
623 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
625 if (bResult)
627 //Notify the map's instance data.
628 //Only works if you create the object in it, not if it is moves to that map.
629 //Normally non-players do not teleport to other maps.
630 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
631 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
633 switch (GetCreatureInfo()->rank)
635 case CREATURE_ELITE_RARE:
636 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RARE);
637 break;
638 case CREATURE_ELITE_ELITE:
639 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_ELITE);
640 break;
641 case CREATURE_ELITE_RAREELITE:
642 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RAREELITE);
643 break;
644 case CREATURE_ELITE_WORLDBOSS:
645 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_WORLDBOSS);
646 break;
647 default:
648 m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_NORMAL);
649 break;
651 LoadCreaturesAddon();
654 return bResult;
657 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
659 if(!isTrainer())
660 return false;
662 TrainerSpellData const* trainer_spells = GetTrainerSpells();
664 if(!trainer_spells || trainer_spells->spellList.empty())
666 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
667 GetGUIDLow(),GetEntry());
668 return false;
671 switch(GetCreatureInfo()->trainer_type)
673 case TRAINER_TYPE_CLASS:
674 if(pPlayer->getClass() != GetCreatureInfo()->trainer_class)
676 if(msg)
678 pPlayer->PlayerTalkClass->ClearMenus();
679 switch(GetCreatureInfo()->trainer_class)
681 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
682 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
683 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
684 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
685 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
686 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
687 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
688 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
689 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
692 return false;
694 break;
695 case TRAINER_TYPE_PETS:
696 if(pPlayer->getClass() != CLASS_HUNTER)
698 pPlayer->PlayerTalkClass->ClearMenus();
699 pPlayer->PlayerTalkClass->SendGossipMenu(3620, GetGUID());
700 return false;
702 break;
703 case TRAINER_TYPE_MOUNTS:
704 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
706 if(msg)
708 pPlayer->PlayerTalkClass->ClearMenus();
709 switch(GetCreatureInfo()->trainer_class)
711 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
712 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
713 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
714 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
715 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
716 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
717 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
718 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
719 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
720 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
723 return false;
725 break;
726 case TRAINER_TYPE_TRADESKILLS:
727 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
729 if(msg)
731 pPlayer->PlayerTalkClass->ClearMenus();
732 pPlayer->PlayerTalkClass->SendGossipMenu(11031, GetGUID());
734 return false;
736 break;
737 default:
738 return false; // checked and error output at creature_template loading
740 return true;
743 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
745 if(!isBattleMaster())
746 return false;
748 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
749 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
750 return false;
752 if(!msg)
753 return pPlayer->GetBGAccessByLevel(bgTypeId);
755 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
757 pPlayer->PlayerTalkClass->ClearMenus();
758 switch(bgTypeId)
760 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616, GetGUID()); break;
761 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599, GetGUID()); break;
762 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642, GetGUID()); break;
763 case BATTLEGROUND_EY:
764 case BATTLEGROUND_NA:
765 case BATTLEGROUND_BE:
766 case BATTLEGROUND_AA:
767 case BATTLEGROUND_RL:
768 case BATTLEGROUND_SA:
769 case BATTLEGROUND_DS:
770 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024, GetGUID()); break;
771 default: break;
773 return false;
775 return true;
778 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
780 return pPlayer->getLevel() >= 10
781 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
782 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
785 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, SplineFlags flags, SplineType type)
787 /* uint32 timeElap = getMSTime();
788 if ((timeElap - m_startMove) < m_moveTime)
790 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
791 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
793 else
795 oX = dX;
796 oY = dY;
799 dX = x;
800 dY = y;
801 m_orientation = atan2((oY - dY), (oX - dX));
803 m_startMove = getMSTime();
804 m_moveTime = time;*/
805 SendMonsterMove(x, y, z, type, flags, time);
808 Player *Creature::GetLootRecipient() const
810 if (!m_lootRecipient)
811 return NULL;
812 else return ObjectAccessor::FindPlayer(m_lootRecipient);
815 void Creature::SetLootRecipient(Unit *unit)
817 // set the player whose group should receive the right
818 // to loot the creature after it dies
819 // should be set to NULL after the loot disappears
821 if (!unit)
823 m_lootRecipient = 0;
824 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
825 return;
828 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
829 if(!player) // normal creature, no player involved
830 return;
832 m_lootRecipient = player->GetGUID();
833 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
836 void Creature::SaveToDB()
838 // this should only be used when the creature has already been loaded
839 // preferably after adding to map, because mapid may not be valid otherwise
840 CreatureData const *data = sObjectMgr.GetCreatureData(m_DBTableGuid);
841 if(!data)
843 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
844 return;
847 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
850 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
852 // update in loaded data
853 if (!m_DBTableGuid)
854 m_DBTableGuid = GetGUIDLow();
855 CreatureData& data = sObjectMgr.NewOrExistCreatureData(m_DBTableGuid);
857 uint32 displayId = GetNativeDisplayId();
859 // check if it's a custom model and if not, use 0 for displayId
860 CreatureInfo const *cinfo = GetCreatureInfo();
861 if (cinfo)
863 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
864 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
866 if (cinfo->DisplayID_A[0])
867 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
868 if(displayId == minfo->modelid_other_gender)
869 displayId = 0;
871 if (displayId && cinfo->DisplayID_A[1])
872 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
873 if(displayId == minfo->modelid_other_gender)
874 displayId = 0;
876 if (displayId && cinfo->DisplayID_H[0])
877 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
878 if(displayId == minfo->modelid_other_gender)
879 displayId = 0;
881 if (displayId && cinfo->DisplayID_H[1])
882 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
883 if(displayId == minfo->modelid_other_gender)
884 displayId = 0;
886 else
887 displayId = 0;
890 // data->guid = guid don't must be update at save
891 data.id = GetEntry();
892 data.mapid = mapid;
893 data.phaseMask = phaseMask;
894 data.displayid = displayId;
895 data.equipmentId = GetEquipmentId();
896 data.posX = GetPositionX();
897 data.posY = GetPositionY();
898 data.posZ = GetPositionZ();
899 data.orientation = GetOrientation();
900 data.spawntimesecs = m_respawnDelay;
901 // prevent add data integrity problems
902 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
903 data.currentwaypoint = 0;
904 data.curhealth = GetHealth();
905 data.curmana = GetPower(POWER_MANA);
906 data.is_dead = m_isDeadByDefault;
907 // prevent add data integrity problems
908 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
909 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
910 data.spawnMask = spawnMask;
912 // updated in DB
913 WorldDatabase.BeginTransaction();
915 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
917 std::ostringstream ss;
918 ss << "INSERT INTO creature VALUES ("
919 << m_DBTableGuid << ","
920 << GetEntry() << ","
921 << mapid <<","
922 << uint32(spawnMask) << "," // cast to prevent save as symbol
923 << uint16(GetPhaseMask()) << "," // prevent out of range error
924 << displayId <<","
925 << GetEquipmentId() <<","
926 << GetPositionX() << ","
927 << GetPositionY() << ","
928 << GetPositionZ() << ","
929 << GetOrientation() << ","
930 << m_respawnDelay << "," //respawn time
931 << (float) m_respawnradius << "," //spawn distance (float)
932 << (uint32) (0) << "," //currentwaypoint
933 << GetHealth() << "," //curhealth
934 << GetPower(POWER_MANA) << "," //curmana
935 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
936 << GetDefaultMovementType() << ")"; //default movement generator type
938 WorldDatabase.PExecuteLog("%s", ss.str().c_str());
940 WorldDatabase.CommitTransaction();
943 void Creature::SelectLevel(const CreatureInfo *cinfo, float percentHealth, float percentMana)
945 uint32 rank = isPet()? 0 : cinfo->rank;
947 // level
948 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
949 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
950 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
951 SetLevel(level);
953 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
955 // health
956 float healthmod = _GetHealthMod(rank);
958 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
959 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
960 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
962 SetCreateHealth(health);
963 SetMaxHealth(health);
965 if (percentHealth == 100.0f)
966 SetHealth(health);
967 else
968 SetHealthPercent(percentHealth);
970 // mana
971 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
972 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
973 uint32 mana = minmana + uint32(rellevel * (maxmana - minmana));
975 SetCreateMana(mana);
976 SetMaxPower(POWER_MANA, mana); //MAX Mana
977 SetPower(POWER_MANA, mana);
979 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
981 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, float(health));
982 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, float(mana));
984 // damage
985 float damagemod = _GetDamageMod(rank);
987 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
988 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
990 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
991 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
993 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
996 float Creature::_GetHealthMod(int32 Rank)
998 switch (Rank) // define rates for each elite rank
1000 case CREATURE_ELITE_NORMAL:
1001 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_HP);
1002 case CREATURE_ELITE_ELITE:
1003 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP);
1004 case CREATURE_ELITE_RAREELITE:
1005 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_HP);
1006 case CREATURE_ELITE_WORLDBOSS:
1007 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_HP);
1008 case CREATURE_ELITE_RARE:
1009 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_HP);
1010 default:
1011 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP);
1015 float Creature::_GetDamageMod(int32 Rank)
1017 switch (Rank) // define rates for each elite rank
1019 case CREATURE_ELITE_NORMAL:
1020 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_DAMAGE);
1021 case CREATURE_ELITE_ELITE:
1022 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE);
1023 case CREATURE_ELITE_RAREELITE:
1024 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1025 case CREATURE_ELITE_WORLDBOSS:
1026 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1027 case CREATURE_ELITE_RARE:
1028 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_DAMAGE);
1029 default:
1030 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE);
1034 float Creature::GetSpellDamageMod(int32 Rank)
1036 switch (Rank) // define rates for each elite rank
1038 case CREATURE_ELITE_NORMAL:
1039 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_NORMAL_SPELLDAMAGE);
1040 case CREATURE_ELITE_ELITE:
1041 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1042 case CREATURE_ELITE_RAREELITE:
1043 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1044 case CREATURE_ELITE_WORLDBOSS:
1045 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1046 case CREATURE_ELITE_RARE:
1047 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1048 default:
1049 return sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1053 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1055 CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
1056 if(!cinfo)
1058 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1059 return false;
1061 m_originalEntry = Entry;
1063 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1065 if (!UpdateEntry(Entry, team, data, false))
1066 return false;
1068 return true;
1071 bool Creature::LoadFromDB(uint32 guid, Map *map)
1073 CreatureData const* data = sObjectMgr.GetCreatureData(guid);
1075 if(!data)
1077 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1078 return false;
1081 m_DBTableGuid = guid;
1082 if (map->GetInstanceId() == 0)
1084 // Creature can be loaded already in map if grid has been unloaded while creature walk to another grid
1085 // FIXME: until creature guids is global and for instances used dynamic generated guids
1086 // in instance possible load creature duplicates with same DB guid but different in game guids
1087 // This will be until implementing per-map creature guids
1088 if (map->GetCreature(MAKE_NEW_GUID(guid, data->id, HIGHGUID_UNIT)))
1089 return false;
1091 else
1092 guid = sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT);
1094 uint16 team = 0;
1095 if(!Create(guid, map, data->phaseMask, data->id, team, data))
1096 return false;
1098 Relocate(data->posX, data->posY, data->posZ, data->orientation);
1100 if(!IsPositionValid())
1102 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)", GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
1103 return false;
1106 m_respawnradius = data->spawndist;
1108 m_respawnDelay = data->spawntimesecs;
1109 m_isDeadByDefault = data->is_dead;
1110 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1112 m_respawnTime = sObjectMgr.GetCreatureRespawnTime(m_DBTableGuid, GetInstanceId());
1113 if(m_respawnTime > time(NULL)) // not ready to respawn
1115 m_deathState = DEAD;
1116 if(canFly())
1118 float tz = GetMap()->GetHeight(data->posX, data->posY, data->posZ, false);
1119 if(data->posZ - tz > 0.1)
1120 Relocate(data->posX, data->posY, tz);
1123 else if(m_respawnTime) // respawn time set but expired
1125 m_respawnTime = 0;
1126 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1129 uint32 curhealth = data->curhealth;
1130 if(curhealth)
1132 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1133 if(curhealth < 1)
1134 curhealth = 1;
1137 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1138 SetPower(POWER_MANA, data->curmana);
1140 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1142 // checked at creature_template loading
1143 m_defaultMovementType = MovementGeneratorType(data->movementType);
1145 AIM_Initialize();
1146 return true;
1149 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1151 if(equip_entry == 0)
1153 if (force)
1155 for (uint8 i = 0; i < 3; ++i)
1156 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1157 m_equipmentId = 0;
1159 return;
1162 EquipmentInfo const *einfo = sObjectMgr.GetEquipmentInfo(equip_entry);
1163 if (!einfo)
1164 return;
1166 m_equipmentId = equip_entry;
1167 for (uint8 i = 0; i < 3; ++i)
1168 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1171 bool Creature::hasQuest(uint32 quest_id) const
1173 QuestRelations const& qr = sObjectMgr.mCreatureQuestRelations;
1174 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1176 if(itr->second==quest_id)
1177 return true;
1179 return false;
1182 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1184 QuestRelations const& qr = sObjectMgr.mCreatureQuestInvolvedRelations;
1185 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1187 if(itr->second == quest_id)
1188 return true;
1190 return false;
1193 void Creature::DeleteFromDB()
1195 if (!m_DBTableGuid)
1197 sLog.outDebug("Trying to delete not saved creature!");
1198 return;
1201 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1202 sObjectMgr.DeleteCreatureData(m_DBTableGuid);
1204 WorldDatabase.BeginTransaction();
1205 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1206 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1207 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1208 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1209 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1210 WorldDatabase.PExecuteLog("DELETE FROM creature_battleground WHERE guid = '%u'", m_DBTableGuid);
1211 WorldDatabase.CommitTransaction();
1214 float Creature::GetAttackDistance(Unit const* pl) const
1216 float aggroRate = sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
1217 if(aggroRate == 0)
1218 return 0.0f;
1220 uint32 playerlevel = pl->getLevelForTarget(this);
1221 uint32 creaturelevel = getLevelForTarget(pl);
1223 int32 leveldif = int32(playerlevel) - int32(creaturelevel);
1225 // "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."
1226 if ( leveldif < - 25)
1227 leveldif = -25;
1229 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1230 float RetDistance = 20;
1232 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1233 // radius grow if playlevel < creaturelevel
1234 RetDistance -= (float)leveldif;
1236 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
1238 // detect range auras
1239 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1241 // detected range auras
1242 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1245 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1246 if(RetDistance < 5)
1247 RetDistance = 5;
1249 return (RetDistance*aggroRate);
1252 void Creature::setDeathState(DeathState s)
1254 if ((s == JUST_DIED && !m_isDeadByDefault) || (s == JUST_ALIVED && m_isDeadByDefault))
1256 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1258 // always save boss respawn time at death to prevent crash cheating
1259 if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1260 SaveRespawnTime();
1262 if (canFly() && FallGround())
1263 return;
1265 if (!IsStopped())
1266 StopMoving();
1268 Unit::setDeathState(s);
1270 if (s == JUST_DIED)
1272 SetTargetGUID(0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1273 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1275 if (!isPet() && GetCreatureInfo()->SkinLootId)
1276 if (LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId))
1277 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1279 if (canFly() && FallGround())
1280 return;
1282 if (HasSearchedAssistance())
1284 SetNoSearchAssistance(false);
1285 UpdateSpeed(MOVE_RUN, false);
1288 Unit::setDeathState(CORPSE);
1290 if (s == JUST_ALIVED)
1292 SetHealth(GetMaxHealth());
1293 SetLootRecipient(NULL);
1294 CreatureInfo const *cinfo = GetCreatureInfo();
1295 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1296 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1297 AddSplineFlag(SPLINEFLAG_WALKMODE);
1298 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1299 Unit::setDeathState(ALIVE);
1300 clearUnitState(UNIT_STAT_ALL_STATE);
1301 i_motionMaster.Clear();
1302 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1303 LoadCreaturesAddon(true);
1307 bool Creature::FallGround()
1309 // Let's abort after we called this function one time
1310 if (getDeathState() == DEAD_FALLING)
1311 return false;
1313 // Let's do with no vmap because no way to get far distance with vmap high call
1314 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1316 // Abort too if the ground is very near
1317 if (fabs(GetPositionZ() - tz) < 0.1f)
1318 return false;
1320 Unit::setDeathState(DEAD_FALLING);
1321 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1322 Relocate(GetPositionX(), GetPositionY(), tz);
1323 return true;
1326 void Creature::Respawn()
1328 RemoveCorpse();
1330 // forced recreate creature object at clients
1331 UnitVisibility currentVis = GetVisibility();
1332 SetVisibility(VISIBILITY_RESPAWN);
1333 UpdateObjectVisibility();
1334 SetVisibility(currentVis); // restore visibility state
1335 UpdateObjectVisibility();
1337 if(getDeathState() == DEAD)
1339 if (m_DBTableGuid)
1340 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(), 0);
1341 m_respawnTime = time(NULL); // respawn at next tick
1345 void Creature::ForcedDespawn(uint32 timeMSToDespawn)
1347 if (timeMSToDespawn)
1349 ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
1351 m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
1352 return;
1355 if (isAlive())
1356 setDeathState(JUST_DIED);
1358 RemoveCorpse();
1359 SetHealth(0); // just for nice GM-mode view
1362 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1364 if (!spellInfo)
1365 return false;
1367 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1368 return true;
1370 return Unit::IsImmunedToSpell(spellInfo);
1373 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
1375 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1376 return true;
1378 // Taunt immunity special flag check
1379 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1381 // Taunt aura apply check
1382 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1384 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1385 return true;
1387 // Spell effect taunt check
1388 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1389 return true;
1392 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1395 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1397 if(!pVictim)
1398 return NULL;
1400 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1402 if(!m_spells[i])
1403 continue;
1404 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1405 if(!spellInfo)
1407 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1408 continue;
1411 bool bcontinue = true;
1412 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
1414 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1415 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1416 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1417 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1420 bcontinue = false;
1421 break;
1424 if(bcontinue) continue;
1426 if(spellInfo->manaCost > GetPower(POWER_MANA))
1427 continue;
1428 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1429 float range = GetSpellMaxRange(srange);
1430 float minrange = GetSpellMinRange(srange);
1432 float dist = GetCombatDistance(pVictim);
1434 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1435 // continue;
1436 if( dist > range || dist < minrange )
1437 continue;
1438 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1439 continue;
1440 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1441 continue;
1442 return spellInfo;
1444 return NULL;
1447 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1449 if(!pVictim)
1450 return NULL;
1452 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1454 if(!m_spells[i])
1455 continue;
1456 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1457 if(!spellInfo)
1459 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1460 continue;
1463 bool bcontinue = true;
1464 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
1466 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1468 bcontinue = false;
1469 break;
1472 if(bcontinue)
1473 continue;
1475 if(spellInfo->manaCost > GetPower(POWER_MANA))
1476 continue;
1477 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1478 float range = GetSpellMaxRange(srange);
1479 float minrange = GetSpellMinRange(srange);
1481 float dist = GetCombatDistance(pVictim);
1483 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1484 // continue;
1485 if( dist > range || dist < minrange )
1486 continue;
1487 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1488 continue;
1489 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1490 continue;
1491 return spellInfo;
1493 return NULL;
1496 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1498 // gamemaster in GM mode see all, including ghosts
1499 if(pl->isGameMaster())
1500 return true;
1502 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1503 return false;
1505 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1506 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1508 return (isAlive() || m_deathTimer > 0 || (m_isDeadByDefault && m_deathState == CORPSE));
1511 // Dead player see live creatures near own corpse
1512 if(isAlive())
1514 Corpse *corpse = pl->GetCorpse();
1515 if(corpse)
1517 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1518 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
1519 return true;
1523 // Dead player can see ghosts
1524 if (GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_GHOST_VISIBLE)
1525 return true;
1527 // and not see any other
1528 return false;
1531 void Creature::SendAIReaction(AiReaction reactionType)
1533 WorldPacket data(SMSG_AI_REACTION, 12);
1535 data << uint64(GetGUID());
1536 data << uint32(reactionType);
1538 ((WorldObject*)this)->SendMessageToSet(&data, true);
1540 sLog.outDebug("WORLD: Sent SMSG_AI_REACTION, type %u.", reactionType);
1543 void Creature::CallAssistance()
1545 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1547 SetNoCallAssistance(true);
1549 float radius = sWorld.getConfig(CONFIG_FLOAT_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1550 if(radius > 0)
1552 std::list<Creature*> assistList;
1555 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1556 Cell cell(p);
1557 cell.data.Part.reserved = ALL_DISTRICT;
1558 cell.SetNoCreate();
1560 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1561 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1563 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1565 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
1568 if (!assistList.empty())
1570 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1571 while (!assistList.empty())
1573 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1574 e->AddAssistant((*assistList.begin())->GetGUID());
1575 assistList.pop_front();
1577 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_UINT32_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1583 void Creature::CallForHelp(float fRadius)
1585 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1586 return;
1588 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1589 Cell cell(p);
1590 cell.data.Part.reserved = ALL_DISTRICT;
1591 cell.SetNoCreate();
1593 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1594 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1596 TypeContainerVisitor<MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo>, GridTypeMapContainer > grid_creature_searcher(worker);
1598 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, fRadius);
1601 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1603 // we don't need help from zombies :)
1604 if (!isAlive())
1605 return false;
1607 // we don't need help from non-combatant ;)
1608 if (isCivilian())
1609 return false;
1611 // skip fighting creature
1612 if (isInCombat())
1613 return false;
1615 // only free creature
1616 if (GetCharmerOrOwnerGUID())
1617 return false;
1619 // only from same creature faction
1620 if (checkfaction)
1622 if (getFaction() != u->getFaction())
1623 return false;
1625 else
1627 if (!IsFriendlyTo(u))
1628 return false;
1631 // skip non hostile to caster enemy creatures
1632 if (!IsHostileTo(enemy))
1633 return false;
1635 return true;
1638 void Creature::SaveRespawnTime()
1640 if(isPet() || !m_DBTableGuid)
1641 return;
1643 if(m_respawnTime > time(NULL)) // dead (no corpse)
1644 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), m_respawnTime);
1645 else if(m_deathTimer > 0) // dead (corpse)
1646 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), time(NULL) + m_respawnDelay + m_deathTimer / IN_MILISECONDS);
1649 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1651 if (!pVictim)
1652 return true;
1654 if (!pVictim->IsInMap(this))
1655 return true;
1657 if (!pVictim->isTargetableForAttack())
1658 return true;
1660 if (!pVictim->isInAccessablePlaceFor(this))
1661 return true;
1663 if (!pVictim->isVisibleForOrDetect(this,this,false))
1664 return true;
1666 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1667 return false;
1669 float AttackDist = GetAttackDistance(pVictim);
1670 float ThreatRadius = sWorld.getConfig(CONFIG_FLOAT_THREAT_RADIUS);
1672 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1673 return !pVictim->IsWithinDist3d(CombatStartX, CombatStartY, CombatStartZ,
1674 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1677 CreatureDataAddon const* Creature::GetCreatureAddon() const
1679 if (m_DBTableGuid)
1681 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1682 return addon;
1685 // dependent from difficulty mode entry
1686 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1689 //creature_addon table
1690 bool Creature::LoadCreaturesAddon(bool reload)
1692 CreatureDataAddon const *cainfo = GetCreatureAddon();
1693 if(!cainfo)
1694 return false;
1696 if (cainfo->mount != 0)
1697 Mount(cainfo->mount);
1699 if (cainfo->bytes1 != 0)
1701 // 0 StandState
1702 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1703 // 2 StandFlags
1704 // 3 StandMiscFlags
1706 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1707 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1708 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1709 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1710 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1713 if (cainfo->bytes2 != 0)
1715 // 0 SheathState
1716 // 1 UnitPVPStateFlags Set at Creature::UpdateEntry (SetPvp())
1717 // 2 UnitRename Pet only, so always 0 for default creature
1718 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1720 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1721 //SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1722 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1723 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1724 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1725 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1728 if (cainfo->emote != 0)
1729 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1731 if (cainfo->splineFlags != 0)
1732 SetSplineFlags(SplineFlags(cainfo->splineFlags));
1734 if(cainfo->auras)
1736 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1738 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1739 if (!AdditionalSpellInfo)
1741 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1742 continue;
1745 // skip already applied aura
1746 if(HasAura(cAura->spell_id,cAura->effect_idx))
1748 if(!reload)
1749 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);
1751 continue;
1754 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1755 AddAura(AdditionalAura);
1756 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[EFFECT_INDEX_0],GetGUIDLow(),GetEntry());
1759 return true;
1762 /// Send a message to LocalDefense channel for players opposition team in the zone
1763 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1765 uint32 enemy_team = attacker->GetTeam();
1767 WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4);
1768 data << uint32(GetZoneId());
1769 sWorld.SendGlobalMessage(&data, NULL, (enemy_team == ALLIANCE ? HORDE : ALLIANCE));
1772 void Creature::SetInCombatWithZone()
1774 if (!CanHaveThreatList())
1776 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1777 return;
1780 Map* pMap = GetMap();
1782 if (!pMap->IsDungeon())
1784 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1785 return;
1788 Map::PlayerList const &PlList = pMap->GetPlayers();
1790 if (PlList.isEmpty())
1791 return;
1793 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
1795 if (Player* pPlayer = i->getSource())
1797 if (pPlayer->isGameMaster())
1798 continue;
1800 if (pPlayer->isAlive())
1802 pPlayer->SetInCombatWith(this);
1803 AddThreat(pPlayer);
1809 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1811 m_CreatureSpellCooldowns[spell_id] = end_time;
1814 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1816 m_CreatureCategoryCooldowns[category] = apply_time;
1819 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1821 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1822 if(!spellInfo)
1823 return;
1825 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1826 if(cooldown)
1827 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1829 if(spellInfo->Category)
1830 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1832 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1835 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1837 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1838 if(!spellInfo)
1839 return false;
1841 // check global cooldown if spell affected by it
1842 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1843 return true;
1845 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1846 return (itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1849 bool Creature::HasSpellCooldown(uint32 spell_id) const
1851 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1852 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1855 bool Creature::IsInEvadeMode() const
1857 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1860 bool Creature::HasSpell(uint32 spellID) const
1862 uint8 i;
1863 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1864 if(spellID == m_spells[i])
1865 break;
1866 return i < CREATURE_MAX_SPELLS; // break before end of iteration of known spells
1869 time_t Creature::GetRespawnTimeEx() const
1871 time_t now = time(NULL);
1872 if(m_respawnTime > now) // dead (no corpse)
1873 return m_respawnTime;
1874 else if(m_deathTimer > 0) // dead (corpse)
1875 return now + m_respawnDelay + m_deathTimer / IN_MILISECONDS;
1876 else
1877 return now;
1880 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1882 if (m_DBTableGuid)
1884 if (CreatureData const* data = sObjectMgr.GetCreatureData(GetDBTableGUIDLow()))
1886 x = data->posX;
1887 y = data->posY;
1888 z = data->posZ;
1889 if (ori)
1890 *ori = data->orientation;
1891 if (dist)
1892 *dist = data->spawndist;
1894 return;
1898 float orient;
1900 GetSummonPoint(x, y, z, orient);
1902 if (ori)
1903 *ori = orient;
1904 if (dist)
1905 *dist = GetRespawnRadius();
1908 void Creature::AllLootRemovedFromCorpse()
1910 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1912 uint32 nDeathTimer;
1914 CreatureInfo const *cinfo = GetCreatureInfo();
1916 // corpse was not skinnable -> apply corpse looted timer
1917 if (!cinfo || !cinfo->SkinLootId)
1918 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getConfig(CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED));
1919 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1920 else
1921 nDeathTimer = 0;
1923 // update death timer only if looted timer is shorter
1924 if (m_deathTimer > nDeathTimer)
1925 m_deathTimer = nDeathTimer;
1929 uint32 Creature::getLevelForTarget( Unit const* target ) const
1931 if(!isWorldBoss())
1932 return Unit::getLevelForTarget(target);
1934 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_UINT32_WORLD_BOSS_LEVEL_DIFF);
1935 if(level < 1)
1936 return 1;
1937 if(level > 255)
1938 return 255;
1939 return level;
1942 std::string Creature::GetAIName() const
1944 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
1947 std::string Creature::GetScriptName() const
1949 return sObjectMgr.GetScriptName(GetScriptId());
1952 uint32 Creature::GetScriptId() const
1954 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
1957 VendorItemData const* Creature::GetVendorItems() const
1959 return sObjectMgr.GetNpcVendorItemList(GetEntry());
1962 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
1964 if(!vItem->maxcount)
1965 return vItem->maxcount;
1967 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1968 for(; itr != m_vendorItemCounts.end(); ++itr)
1969 if(itr->itemId==vItem->item)
1970 break;
1972 if(itr == m_vendorItemCounts.end())
1973 return vItem->maxcount;
1975 VendorItemCount* vCount = &*itr;
1977 time_t ptime = time(NULL);
1979 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1981 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1983 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1984 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
1986 m_vendorItemCounts.erase(itr);
1987 return vItem->maxcount;
1990 vCount->count += diff * pProto->BuyCount;
1991 vCount->lastIncrementTime = ptime;
1994 return vCount->count;
1997 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
1999 if(!vItem->maxcount)
2000 return 0;
2002 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2003 for(; itr != m_vendorItemCounts.end(); ++itr)
2004 if(itr->itemId==vItem->item)
2005 break;
2007 if(itr == m_vendorItemCounts.end())
2009 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2010 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2011 return new_count;
2014 VendorItemCount* vCount = &*itr;
2016 time_t ptime = time(NULL);
2018 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2020 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
2022 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2023 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2024 vCount->count += diff * pProto->BuyCount;
2025 else
2026 vCount->count = vItem->maxcount;
2029 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2030 vCount->lastIncrementTime = ptime;
2031 return vCount->count;
2034 TrainerSpellData const* Creature::GetTrainerSpells() const
2036 return sObjectMgr.GetNpcTrainerSpells(GetEntry());
2039 // overwrite WorldObject function for proper name localization
2040 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2042 if (loc_idx >= 0)
2044 CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(GetEntry());
2045 if (cl)
2047 if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
2048 return cl->Name[loc_idx].c_str();
2052 return GetName();
2055 void Creature::SetActiveObjectState( bool on )
2057 if(m_isActiveObject==on)
2058 return;
2060 bool world = IsInWorld();
2062 Map* map;
2063 if(world)
2065 map = GetMap();
2066 map->Remove(this,false);
2069 m_isActiveObject = on;
2071 if(world)
2072 map->Add(this);
2075 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2077 float x, y, z;
2078 if(GetMotionMaster()->GetDestination(x, y, z))
2079 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2082 void Creature::SendAreaSpiritHealerQueryOpcode(Player *pl)
2084 uint32 next_resurrect = 0;
2085 if (Spell* pcurSpell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
2086 next_resurrect = pcurSpell->GetCastedTime();
2087 WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 8 + 4);
2088 data << GetGUID() << next_resurrect;
2089 pl->SendDirectMessage(&data);
2092 void Creature::RelocationNotify()
2094 CellPair new_val = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
2095 Cell cell(new_val);
2096 CellPair cellpair = cell.cellPair();
2098 MaNGOS::CreatureRelocationNotifier relocationNotifier(*this);
2099 cell.data.Part.reserved = ALL_DISTRICT;
2100 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
2102 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
2103 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
2105 float radius = MAX_CREATURE_ATTACK_RADIUS * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
2107 cell.Visit(cellpair, c2world_relocation, *GetMap(), *this, radius);
2108 cell.Visit(cellpair, c2grid_relocation, *GetMap(), *this, radius);