[9290] Some cleanups in realmd, no functional changes
[getmangos.git] / src / game / Creature.cpp
blob6b5b99f434b44b093eb26daf8a3fef3b39c5709b
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 "ObjectDefines.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), lootingGroupLeaderGUID(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_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
122 m_creatureInfo(NULL), m_isActiveObject(false), m_monsterMoveFlags(MONSTER_MOVE_WALK)
124 m_regenTimer = 200;
125 m_valuesCount = UNIT_END;
127 for(int i =0; i<4; ++i)
128 m_spells[i] = 0;
130 m_CreatureSpellCooldowns.clear();
131 m_CreatureCategoryCooldowns.clear();
132 m_GlobalCooldown = 0;
134 m_monsterMoveFlags = MONSTER_MOVE_WALK;
137 Creature::~Creature()
139 CleanupsBeforeDelete();
141 m_vendorItemCounts.clear();
143 delete i_AI;
144 i_AI = NULL;
147 void Creature::AddToWorld()
149 ///- Register the creature for guid lookup
150 if(!IsInWorld() && GetGUIDHigh()==HIGHGUID_UNIT)
151 GetMap()->GetObjectsStore().insert<Creature>(GetGUID(), (Creature*)this);
153 Unit::AddToWorld();
156 void Creature::RemoveFromWorld()
158 ///- Remove the creature from the accessor
159 if(IsInWorld() && GetGUIDHigh()==HIGHGUID_UNIT)
160 GetMap()->GetObjectsStore().erase<Creature>(GetGUID(), (Creature*)NULL);
162 Unit::RemoveFromWorld();
165 void Creature::RemoveCorpse()
167 if ((getDeathState() != CORPSE && !m_isDeadByDefault) || (getDeathState() != ALIVE && m_isDeadByDefault))
168 return;
170 m_deathTimer = 0;
171 setDeathState(DEAD);
172 UpdateObjectVisibility();
173 loot.clear();
174 uint32 respawnDelay = m_respawnDelay;
175 if (AI())
176 AI()->CorpseRemoved(respawnDelay);
178 m_respawnTime = time(NULL) + respawnDelay;
180 float x,y,z,o;
181 GetRespawnCoord(x, y, z, &o);
182 GetMap()->CreatureRelocation(this,x,y,z,o);
186 * change the entry of creature until respawn
188 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
190 CreatureInfo const *normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
191 if(!normalInfo)
193 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
194 return false;
197 // get difficulty 1 mode entry
198 uint32 actualEntry = Entry;
199 CreatureInfo const *cinfo = normalInfo;
200 // TODO correctly implement spawnmodes for non-bg maps
201 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
203 if (normalInfo->DifficultyEntry[diff])
205 // we already have valid Map pointer for current creature!
206 if (GetMap()->GetSpawnMode() > diff)
208 cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff]);
209 if (!cinfo)
211 // maybe check such things already at startup
212 sLog.outErrorDb("Creature::UpdateEntry creature difficulty %u entry %u does not exist.", diff + 1, actualEntry);
213 return false;
219 SetEntry(Entry); // normal entry always
220 m_creatureInfo = cinfo; // map mode related always
222 // equal to player Race field, but creature does not have race
223 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
225 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
226 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
228 uint32 display_id = sObjectMgr.ChooseDisplayId(team, GetCreatureInfo(), data);
229 if (!display_id) // Cancel load if no display id
231 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
232 return false;
235 CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
236 if (!minfo) // Cancel load if no model defined
238 sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load. ",Entry);
239 return false;
242 display_id = minfo->modelid; // it can be different (for another gender)
244 SetDisplayId(display_id);
245 SetNativeDisplayId(display_id);
246 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
248 // Load creature equipment
249 if(!data || data->equipmentId == 0)
250 { // use default from the template
251 LoadEquipment(cinfo->equipmentId);
253 else if(data && data->equipmentId != -1)
254 { // override, -1 means no equipment
255 LoadEquipment(data->equipmentId);
258 SetName(normalInfo->Name); // at normal entry always
260 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
261 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
263 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
265 SetSpeedRate(MOVE_WALK, cinfo->speed );
266 SetSpeedRate(MOVE_RUN, cinfo->speed );
267 SetSpeedRate(MOVE_SWIM, cinfo->speed );
269 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
271 // checked at loading
272 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
273 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
274 m_defaultMovementType = IDLE_MOTION_TYPE;
276 return true;
279 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
281 if(!InitEntry(Entry,team,data))
282 return false;
284 m_regenHealth = GetCreatureInfo()->RegenHealth;
286 // creatures always have melee weapon ready if any
287 SetSheath(SHEATH_STATE_MELEE);
289 SelectLevel(GetCreatureInfo());
290 if (team == HORDE)
291 setFaction(GetCreatureInfo()->faction_H);
292 else
293 setFaction(GetCreatureInfo()->faction_A);
295 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
297 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
298 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
299 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
301 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
302 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
304 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
305 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
306 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
307 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
308 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
309 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
310 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
312 SetCanModifyStats(true);
313 UpdateAllStats();
315 // checked and error show at loading templates
316 if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A))
318 if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
319 SetPvP(true);
320 else
321 SetPvP(false);
324 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
325 m_spells[i] = GetCreatureInfo()->spells[i];
327 return true;
330 void Creature::Update(uint32 diff)
332 if(m_GlobalCooldown <= diff)
333 m_GlobalCooldown = 0;
334 else
335 m_GlobalCooldown -= diff;
337 switch( m_deathState )
339 case JUST_ALIVED:
340 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
341 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
342 break;
343 case JUST_DIED:
344 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
345 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
346 break;
347 case DEAD:
349 if( m_respawnTime <= time(NULL) )
351 DEBUG_LOG("Respawning...");
352 m_respawnTime = 0;
353 lootForPickPocketed = false;
354 lootForBody = false;
356 if(m_originalEntry != GetEntry())
357 UpdateEntry(m_originalEntry);
359 CreatureInfo const *cinfo = GetCreatureInfo();
361 SelectLevel(cinfo);
362 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
363 if (m_isDeadByDefault)
365 setDeathState(JUST_DIED);
366 SetHealth(0);
367 i_motionMaster.Clear();
368 clearUnitState(UNIT_STAT_ALL_STATE);
369 LoadCreaturesAddon(true);
371 else
372 setDeathState( JUST_ALIVED );
374 //Call AI respawn virtual function
375 i_AI->JustRespawned();
377 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
378 if (poolid)
379 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
380 else
381 GetMap()->Add(this);
383 break;
385 case CORPSE:
387 if (m_isDeadByDefault)
388 break;
390 if( m_deathTimer <= diff )
392 RemoveCorpse();
393 DEBUG_LOG("Removing corpse... %u ", GetEntry());
395 else
397 m_deathTimer -= diff;
398 if (m_groupLootTimer && lootingGroupLeaderGUID)
400 if(diff <= m_groupLootTimer)
402 m_groupLootTimer -= diff;
404 else
406 if (Group* group = sObjectMgr.GetGroupByLeaderLowGUID(GUID_LOPART(lootingGroupLeaderGUID)))
407 group->EndRoll();
408 m_groupLootTimer = 0;
409 lootingGroupLeaderGUID = 0;
414 break;
416 case ALIVE:
418 if (m_isDeadByDefault)
420 if( m_deathTimer <= diff )
422 RemoveCorpse();
423 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
425 else
427 m_deathTimer -= diff;
431 Unit::Update( diff );
433 // creature can be dead after Unit::Update call
434 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
435 if(!isAlive())
436 break;
438 if(!IsInEvadeMode())
440 // do not allow the AI to be changed during update
441 m_AI_locked = true;
442 i_AI->UpdateAI(diff);
443 m_AI_locked = false;
446 // creature can be dead after UpdateAI call
447 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
448 if(!isAlive())
449 break;
450 if(m_regenTimer > 0)
452 if(diff >= m_regenTimer)
453 m_regenTimer = 0;
454 else
455 m_regenTimer -= diff;
457 if (m_regenTimer != 0)
458 break;
460 if (!isInCombat() || IsPolymorphed())
461 RegenerateHealth();
463 RegenerateMana();
465 m_regenTimer = REGEN_TIME_FULL;
466 break;
468 case DEAD_FALLING:
470 if (!FallGround())
471 setDeathState(JUST_DIED);
473 default:
474 break;
478 void Creature::RegenerateMana()
480 uint32 curValue = GetPower(POWER_MANA);
481 uint32 maxValue = GetMaxPower(POWER_MANA);
483 if (curValue >= maxValue)
484 return;
486 uint32 addvalue = 0;
488 // Combat and any controlled creature
489 if (isInCombat() || GetCharmerOrOwnerGUID())
491 if(!IsUnderLastManaUseEffect())
493 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
494 float Spirit = GetStat(STAT_SPIRIT);
496 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
499 else
500 addvalue = maxValue/3;
502 ModifyPower(POWER_MANA, addvalue);
505 void Creature::RegenerateHealth()
507 if (!isRegeneratingHealth())
508 return;
510 uint32 curValue = GetHealth();
511 uint32 maxValue = GetMaxHealth();
513 if (curValue >= maxValue)
514 return;
516 uint32 addvalue = 0;
518 // Not only pet, but any controlled creature
519 if(GetCharmerOrOwnerGUID())
521 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
522 float Spirit = GetStat(STAT_SPIRIT);
524 if( GetPower(POWER_MANA) > 0 )
525 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
526 else
527 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
529 else
530 addvalue = maxValue/3;
532 ModifyHealth(addvalue);
535 void Creature::DoFleeToGetAssistance()
537 if (!getVictim())
538 return;
540 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
541 if (radius >0)
543 Creature* pCreature = NULL;
545 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
546 Cell cell(p);
547 cell.data.Part.reserved = ALL_DISTRICT;
548 cell.SetNoCreate();
549 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
550 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
552 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
554 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
556 SetNoSearchAssistance(true);
557 UpdateSpeed(MOVE_RUN, false);
559 if(!pCreature)
560 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
561 else
562 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
566 bool Creature::AIM_Initialize()
568 // make sure nothing can change the AI during AI update
569 if(m_AI_locked)
571 sLog.outDebug("AIM_Initialize: failed to init, locked.");
572 return false;
575 CreatureAI * oldAI = i_AI;
576 i_motionMaster.Initialize();
577 i_AI = FactorySelector::selectAI(this);
578 if (oldAI)
579 delete oldAI;
580 return true;
583 bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
585 ASSERT(map);
586 SetMap(map);
587 SetPhaseMask(phaseMask,false);
589 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
590 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
592 if (bResult)
594 //Notify the map's instance data.
595 //Only works if you create the object in it, not if it is moves to that map.
596 //Normally non-players do not teleport to other maps.
597 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
598 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
600 switch (GetCreatureInfo()->rank)
602 case CREATURE_ELITE_RARE:
603 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
604 break;
605 case CREATURE_ELITE_ELITE:
606 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
607 break;
608 case CREATURE_ELITE_RAREELITE:
609 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
610 break;
611 case CREATURE_ELITE_WORLDBOSS:
612 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
613 break;
614 default:
615 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
616 break;
618 LoadCreaturesAddon();
621 return bResult;
624 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
626 if(!isTrainer())
627 return false;
629 TrainerSpellData const* trainer_spells = GetTrainerSpells();
631 if(!trainer_spells || trainer_spells->spellList.empty())
633 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
634 GetGUIDLow(),GetEntry());
635 return false;
638 switch(GetCreatureInfo()->trainer_type)
640 case TRAINER_TYPE_CLASS:
641 if(pPlayer->getClass()!=GetCreatureInfo()->trainer_class)
643 if(msg)
645 pPlayer->PlayerTalkClass->ClearMenus();
646 switch(GetCreatureInfo()->trainer_class)
648 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
649 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
650 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
651 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
652 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
653 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
654 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
655 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
656 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
659 return false;
661 break;
662 case TRAINER_TYPE_PETS:
663 if(pPlayer->getClass()!=CLASS_HUNTER)
665 pPlayer->PlayerTalkClass->ClearMenus();
666 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
667 return false;
669 break;
670 case TRAINER_TYPE_MOUNTS:
671 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
673 if(msg)
675 pPlayer->PlayerTalkClass->ClearMenus();
676 switch(GetCreatureInfo()->trainer_class)
678 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
679 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
680 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
681 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
682 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
683 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
684 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
685 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
686 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
687 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
690 return false;
692 break;
693 case TRAINER_TYPE_TRADESKILLS:
694 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
696 if(msg)
698 pPlayer->PlayerTalkClass->ClearMenus();
699 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
701 return false;
703 break;
704 default:
705 return false; // checked and error output at creature_template loading
707 return true;
710 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
712 if(!isBattleMaster())
713 return false;
715 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
716 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
717 return false;
719 if(!msg)
720 return pPlayer->GetBGAccessByLevel(bgTypeId);
722 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
724 pPlayer->PlayerTalkClass->ClearMenus();
725 switch(bgTypeId)
727 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
728 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
729 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
730 case BATTLEGROUND_EY:
731 case BATTLEGROUND_NA:
732 case BATTLEGROUND_BE:
733 case BATTLEGROUND_AA:
734 case BATTLEGROUND_RL:
735 case BATTLEGROUND_SA:
736 case BATTLEGROUND_DS:
737 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
738 default: break;
740 return false;
742 return true;
745 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
747 return pPlayer->getLevel() >= 10
748 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
749 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
752 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, MonsterMovementFlags flags, uint8 type)
754 /* uint32 timeElap = getMSTime();
755 if ((timeElap - m_startMove) < m_moveTime)
757 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
758 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
760 else
762 oX = dX;
763 oY = dY;
766 dX = x;
767 dY = y;
768 m_orientation = atan2((oY - dY), (oX - dX));
770 m_startMove = getMSTime();
771 m_moveTime = time;*/
772 SendMonsterMove(x, y, z, type, flags, time);
775 Player *Creature::GetLootRecipient() const
777 if (!m_lootRecipient) return NULL;
778 else return ObjectAccessor::FindPlayer(m_lootRecipient);
781 void Creature::SetLootRecipient(Unit *unit)
783 // set the player whose group should receive the right
784 // to loot the creature after it dies
785 // should be set to NULL after the loot disappears
787 if (!unit)
789 m_lootRecipient = 0;
790 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
791 return;
794 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
795 if(!player) // normal creature, no player involved
796 return;
798 m_lootRecipient = player->GetGUID();
799 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
802 void Creature::SaveToDB()
804 // this should only be used when the creature has already been loaded
805 // preferably after adding to map, because mapid may not be valid otherwise
806 CreatureData const *data = sObjectMgr.GetCreatureData(m_DBTableGuid);
807 if(!data)
809 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
810 return;
813 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
816 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
818 // update in loaded data
819 if (!m_DBTableGuid)
820 m_DBTableGuid = GetGUIDLow();
821 CreatureData& data = sObjectMgr.NewOrExistCreatureData(m_DBTableGuid);
823 uint32 displayId = GetNativeDisplayId();
825 // check if it's a custom model and if not, use 0 for displayId
826 CreatureInfo const *cinfo = GetCreatureInfo();
827 if (cinfo)
829 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
830 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
832 if (cinfo->DisplayID_A[0])
833 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
834 if(displayId == minfo->modelid_other_gender)
835 displayId = 0;
837 if (displayId && cinfo->DisplayID_A[1])
838 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
839 if(displayId == minfo->modelid_other_gender)
840 displayId = 0;
842 if (displayId && cinfo->DisplayID_H[0])
843 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
844 if(displayId == minfo->modelid_other_gender)
845 displayId = 0;
847 if (displayId && cinfo->DisplayID_H[1])
848 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
849 if(displayId == minfo->modelid_other_gender)
850 displayId = 0;
852 else
853 displayId = 0;
856 // data->guid = guid don't must be update at save
857 data.id = GetEntry();
858 data.mapid = mapid;
859 data.phaseMask = phaseMask;
860 data.displayid = displayId;
861 data.equipmentId = GetEquipmentId();
862 data.posX = GetPositionX();
863 data.posY = GetPositionY();
864 data.posZ = GetPositionZ();
865 data.orientation = GetOrientation();
866 data.spawntimesecs = m_respawnDelay;
867 // prevent add data integrity problems
868 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
869 data.currentwaypoint = 0;
870 data.curhealth = GetHealth();
871 data.curmana = GetPower(POWER_MANA);
872 data.is_dead = m_isDeadByDefault;
873 // prevent add data integrity problems
874 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
875 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
876 data.spawnMask = spawnMask;
878 // updated in DB
879 WorldDatabase.BeginTransaction();
881 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
883 std::ostringstream ss;
884 ss << "INSERT INTO creature VALUES ("
885 << m_DBTableGuid << ","
886 << GetEntry() << ","
887 << mapid <<","
888 << uint32(spawnMask) << "," // cast to prevent save as symbol
889 << uint16(GetPhaseMask()) << "," // prevent out of range error
890 << displayId <<","
891 << GetEquipmentId() <<","
892 << GetPositionX() << ","
893 << GetPositionY() << ","
894 << GetPositionZ() << ","
895 << GetOrientation() << ","
896 << m_respawnDelay << "," //respawn time
897 << (float) m_respawnradius << "," //spawn distance (float)
898 << (uint32) (0) << "," //currentwaypoint
899 << GetHealth() << "," //curhealth
900 << GetPower(POWER_MANA) << "," //curmana
901 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
902 << GetDefaultMovementType() << ")"; //default movement generator type
904 WorldDatabase.PExecuteLog("%s", ss.str().c_str());
906 WorldDatabase.CommitTransaction();
909 void Creature::SelectLevel(const CreatureInfo *cinfo)
911 uint32 rank = isPet()? 0 : cinfo->rank;
913 // level
914 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
915 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
916 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
917 SetLevel(level);
919 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
921 // health
922 float healthmod = _GetHealthMod(rank);
924 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
925 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
926 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
928 SetCreateHealth(health);
929 SetMaxHealth(health);
930 SetHealth(health);
932 // mana
933 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
934 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
935 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
937 SetCreateMana(mana);
938 SetMaxPower(POWER_MANA, mana); //MAX Mana
939 SetPower(POWER_MANA, mana);
941 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
943 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
944 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
946 // damage
947 float damagemod = _GetDamageMod(rank);
949 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
950 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
952 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
953 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
955 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
958 float Creature::_GetHealthMod(int32 Rank)
960 switch (Rank) // define rates for each elite rank
962 case CREATURE_ELITE_NORMAL:
963 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
964 case CREATURE_ELITE_ELITE:
965 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
966 case CREATURE_ELITE_RAREELITE:
967 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
968 case CREATURE_ELITE_WORLDBOSS:
969 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
970 case CREATURE_ELITE_RARE:
971 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
972 default:
973 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
977 float Creature::_GetDamageMod(int32 Rank)
979 switch (Rank) // define rates for each elite rank
981 case CREATURE_ELITE_NORMAL:
982 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
983 case CREATURE_ELITE_ELITE:
984 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
985 case CREATURE_ELITE_RAREELITE:
986 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
987 case CREATURE_ELITE_WORLDBOSS:
988 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
989 case CREATURE_ELITE_RARE:
990 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
991 default:
992 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
996 float Creature::GetSpellDamageMod(int32 Rank)
998 switch (Rank) // define rates for each elite rank
1000 case CREATURE_ELITE_NORMAL:
1001 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1002 case CREATURE_ELITE_ELITE:
1003 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1004 case CREATURE_ELITE_RAREELITE:
1005 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1006 case CREATURE_ELITE_WORLDBOSS:
1007 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1008 case CREATURE_ELITE_RARE:
1009 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1010 default:
1011 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1015 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1017 CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
1018 if(!cinfo)
1020 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1021 return false;
1023 m_originalEntry = Entry;
1025 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1027 if(!UpdateEntry(Entry, team, data))
1028 return false;
1030 return true;
1033 bool Creature::LoadFromDB(uint32 guid, Map *map)
1035 CreatureData const* data = sObjectMgr.GetCreatureData(guid);
1037 if(!data)
1039 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1040 return false;
1043 m_DBTableGuid = guid;
1044 if (map->GetInstanceId() == 0)
1046 // Creature can be loaded already in map if grid has been unloaded while creature walk to another grid
1047 // FIXME: until creature guids is global and for instances used dynamic generated guids
1048 // in instance possible load creature duplicates with same DB guid but different in game guids
1049 // This will be until implementing per-map creature guids
1050 if (map->GetCreature(MAKE_NEW_GUID(guid,data->id,HIGHGUID_UNIT)))
1051 return false;
1053 else
1054 guid = sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT);
1056 uint16 team = 0;
1057 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1058 return false;
1060 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1062 if(!IsPositionValid())
1064 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1065 return false;
1068 m_respawnradius = data->spawndist;
1070 m_respawnDelay = data->spawntimesecs;
1071 m_isDeadByDefault = data->is_dead;
1072 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1074 m_respawnTime = sObjectMgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1075 if(m_respawnTime > time(NULL)) // not ready to respawn
1077 m_deathState = DEAD;
1078 if(canFly())
1080 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1081 if(data->posZ - tz > 0.1)
1082 Relocate(data->posX,data->posY,tz);
1085 else if(m_respawnTime) // respawn time set but expired
1087 m_respawnTime = 0;
1088 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1091 uint32 curhealth = data->curhealth;
1092 if(curhealth)
1094 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1095 if(curhealth < 1)
1096 curhealth = 1;
1099 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1100 SetPower(POWER_MANA,data->curmana);
1102 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1104 // checked at creature_template loading
1105 m_defaultMovementType = MovementGeneratorType(data->movementType);
1107 AIM_Initialize();
1108 return true;
1111 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1113 if(equip_entry == 0)
1115 if (force)
1117 for (uint8 i = 0; i < 3; ++i)
1118 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1119 m_equipmentId = 0;
1121 return;
1124 EquipmentInfo const *einfo = sObjectMgr.GetEquipmentInfo(equip_entry);
1125 if (!einfo)
1126 return;
1128 m_equipmentId = equip_entry;
1129 for (uint8 i = 0; i < 3; ++i)
1130 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1133 bool Creature::hasQuest(uint32 quest_id) const
1135 QuestRelations const& qr = sObjectMgr.mCreatureQuestRelations;
1136 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1138 if(itr->second==quest_id)
1139 return true;
1141 return false;
1144 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1146 QuestRelations const& qr = sObjectMgr.mCreatureQuestInvolvedRelations;
1147 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1149 if(itr->second==quest_id)
1150 return true;
1152 return false;
1155 void Creature::DeleteFromDB()
1157 if (!m_DBTableGuid)
1159 sLog.outDebug("Trying to delete not saved creature!");
1160 return;
1163 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1164 sObjectMgr.DeleteCreatureData(m_DBTableGuid);
1166 WorldDatabase.BeginTransaction();
1167 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1168 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1169 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1170 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1171 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1172 WorldDatabase.PExecuteLog("DELETE FROM creature_battleground WHERE guid = '%u'", m_DBTableGuid);
1173 WorldDatabase.CommitTransaction();
1176 float Creature::GetAttackDistance(Unit const* pl) const
1178 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1179 if(aggroRate==0)
1180 return 0.0f;
1182 uint32 playerlevel = pl->getLevelForTarget(this);
1183 uint32 creaturelevel = getLevelForTarget(pl);
1185 int32 leveldif = int32(playerlevel) - int32(creaturelevel);
1187 // "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."
1188 if ( leveldif < - 25)
1189 leveldif = -25;
1191 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1192 float RetDistance = 20;
1194 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1195 // radius grow if playlevel < creaturelevel
1196 RetDistance -= (float)leveldif;
1198 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1200 // detect range auras
1201 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1203 // detected range auras
1204 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1207 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1208 if(RetDistance < 5)
1209 RetDistance = 5;
1211 return (RetDistance*aggroRate);
1214 void Creature::setDeathState(DeathState s)
1216 if ((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1218 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1220 // always save boss respawn time at death to prevent crash cheating
1221 if (sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1222 SaveRespawnTime();
1224 if (canFly() && FallGround())
1225 return;
1227 if (!IsStopped())
1228 StopMoving();
1230 Unit::setDeathState(s);
1232 if (s == JUST_DIED)
1234 SetTargetGUID(0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1235 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1237 if (!isPet() && GetCreatureInfo()->SkinLootId)
1238 if (LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId))
1239 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1241 if (canFly() && FallGround())
1242 return;
1244 if (HasSearchedAssistance())
1246 SetNoSearchAssistance(false);
1247 UpdateSpeed(MOVE_RUN, false);
1250 Unit::setDeathState(CORPSE);
1252 if (s == JUST_ALIVED)
1254 SetHealth(GetMaxHealth());
1255 SetLootRecipient(NULL);
1256 CreatureInfo const *cinfo = GetCreatureInfo();
1257 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1258 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1259 AddMonsterMoveFlag(MONSTER_MOVE_WALK);
1260 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1261 Unit::setDeathState(ALIVE);
1262 clearUnitState(UNIT_STAT_ALL_STATE);
1263 i_motionMaster.Clear();
1264 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1265 LoadCreaturesAddon(true);
1269 bool Creature::FallGround()
1271 // Let's abort after we called this function one time
1272 if (getDeathState() == DEAD_FALLING)
1273 return false;
1275 // Let's do with no vmap because no way to get far distance with vmap high call
1276 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1278 // Abort too if the ground is very near
1279 if (fabs(GetPositionZ() - tz) < 0.1f)
1280 return false;
1282 Unit::setDeathState(DEAD_FALLING);
1283 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1284 Relocate(GetPositionX(), GetPositionY(), tz);
1285 return true;
1288 void Creature::Respawn()
1290 RemoveCorpse();
1292 // forced recreate creature object at clients
1293 UnitVisibility currentVis = GetVisibility();
1294 SetVisibility(VISIBILITY_RESPAWN);
1295 UpdateObjectVisibility();
1296 SetVisibility(currentVis); // restore visibility state
1297 UpdateObjectVisibility();
1299 if(getDeathState()==DEAD)
1301 if (m_DBTableGuid)
1302 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1303 m_respawnTime = time(NULL); // respawn at next tick
1307 void Creature::ForcedDespawn(uint32 timeMSToDespawn)
1309 if (timeMSToDespawn)
1311 ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
1313 m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
1314 return;
1317 if (isAlive())
1318 setDeathState(JUST_DIED);
1320 RemoveCorpse();
1321 SetHealth(0); // just for nice GM-mode view
1324 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1326 if (!spellInfo)
1327 return false;
1329 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1330 return true;
1332 return Unit::IsImmunedToSpell(spellInfo);
1335 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1337 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1338 return true;
1340 // Taunt immunity special flag check
1341 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1343 // Taunt aura apply check
1344 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1346 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1347 return true;
1349 // Spell effect taunt check
1350 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1351 return true;
1354 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1357 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1359 if(!pVictim)
1360 return NULL;
1362 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1364 if(!m_spells[i])
1365 continue;
1366 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1367 if(!spellInfo)
1369 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1370 continue;
1373 bool bcontinue = true;
1374 for(uint32 j=0;j<3;j++)
1376 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1377 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1378 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1379 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1382 bcontinue = false;
1383 break;
1386 if(bcontinue) continue;
1388 if(spellInfo->manaCost > GetPower(POWER_MANA))
1389 continue;
1390 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1391 float range = GetSpellMaxRange(srange);
1392 float minrange = GetSpellMinRange(srange);
1394 float dist = GetCombatDistance(pVictim);
1396 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1397 // continue;
1398 if( dist > range || dist < minrange )
1399 continue;
1400 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1401 continue;
1402 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1403 continue;
1404 return spellInfo;
1406 return NULL;
1409 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1411 if(!pVictim)
1412 return NULL;
1414 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1416 if(!m_spells[i])
1417 continue;
1418 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1419 if(!spellInfo)
1421 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1422 continue;
1425 bool bcontinue = true;
1426 for(uint32 j=0;j<3;j++)
1428 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1430 bcontinue = false;
1431 break;
1434 if(bcontinue) continue;
1436 if(spellInfo->manaCost > GetPower(POWER_MANA))
1437 continue;
1438 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1439 float range = GetSpellMaxRange(srange);
1440 float minrange = GetSpellMinRange(srange);
1442 float dist = GetCombatDistance(pVictim);
1444 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1445 // continue;
1446 if( dist > range || dist < minrange )
1447 continue;
1448 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1449 continue;
1450 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1451 continue;
1452 return spellInfo;
1454 return NULL;
1457 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1459 // gamemaster in GM mode see all, including ghosts
1460 if(pl->isGameMaster())
1461 return true;
1463 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1464 return false;
1466 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1467 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1469 return (isAlive() || m_deathTimer > 0 || (m_isDeadByDefault && m_deathState == CORPSE));
1472 // Dead player see live creatures near own corpse
1473 if(isAlive())
1475 Corpse *corpse = pl->GetCorpse();
1476 if(corpse)
1478 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1479 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1480 return true;
1484 // Dead player can see ghosts
1485 if (GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_GHOST_VISIBLE)
1486 return true;
1488 // and not see any other
1489 return false;
1492 void Creature::SendAIReaction(AiReaction reactionType)
1494 WorldPacket data(SMSG_AI_REACTION, 12);
1496 data << uint64(GetGUID());
1497 data << uint32(reactionType);
1499 ((WorldObject*)this)->SendMessageToSet(&data, true);
1501 sLog.outDebug("WORLD: Sent SMSG_AI_REACTION, type %u.", reactionType);
1504 void Creature::CallAssistance()
1506 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1508 SetNoCallAssistance(true);
1510 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1511 if(radius > 0)
1513 std::list<Creature*> assistList;
1516 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1517 Cell cell(p);
1518 cell.data.Part.reserved = ALL_DISTRICT;
1519 cell.SetNoCreate();
1521 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1522 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1524 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1526 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
1529 if (!assistList.empty())
1531 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1532 while (!assistList.empty())
1534 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1535 e->AddAssistant((*assistList.begin())->GetGUID());
1536 assistList.pop_front();
1538 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1544 void Creature::CallForHelp(float fRadius)
1546 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1547 return;
1549 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1550 Cell cell(p);
1551 cell.data.Part.reserved = ALL_DISTRICT;
1552 cell.SetNoCreate();
1554 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1555 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1557 TypeContainerVisitor<MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo>, GridTypeMapContainer > grid_creature_searcher(worker);
1559 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, fRadius);
1562 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1564 // we don't need help from zombies :)
1565 if (!isAlive())
1566 return false;
1568 // we don't need help from non-combatant ;)
1569 if (isCivilian())
1570 return false;
1572 // skip fighting creature
1573 if (isInCombat())
1574 return false;
1576 // only free creature
1577 if (GetCharmerOrOwnerGUID())
1578 return false;
1580 // only from same creature faction
1581 if (checkfaction)
1583 if (getFaction() != u->getFaction())
1584 return false;
1586 else
1588 if (!IsFriendlyTo(u))
1589 return false;
1592 // skip non hostile to caster enemy creatures
1593 if (!IsHostileTo(enemy))
1594 return false;
1596 return true;
1599 void Creature::SaveRespawnTime()
1601 if(isPet() || !m_DBTableGuid)
1602 return;
1604 if(m_respawnTime > time(NULL)) // dead (no corpse)
1605 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1606 else if(m_deathTimer > 0) // dead (corpse)
1607 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1610 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1612 if (!pVictim)
1613 return true;
1615 if (!pVictim->IsInMap(this))
1616 return true;
1618 if (!pVictim->isTargetableForAttack())
1619 return true;
1621 if (!pVictim->isInAccessablePlaceFor(this))
1622 return true;
1624 if (!pVictim->isVisibleForOrDetect(this,this,false))
1625 return true;
1627 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1628 return false;
1630 float AttackDist = GetAttackDistance(pVictim);
1631 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1633 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1634 return !pVictim->IsWithinDist3d(CombatStartX,CombatStartY,CombatStartZ,
1635 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1638 CreatureDataAddon const* Creature::GetCreatureAddon() const
1640 if (m_DBTableGuid)
1642 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1643 return addon;
1646 // dependent from difficulty mode entry
1647 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1650 //creature_addon table
1651 bool Creature::LoadCreaturesAddon(bool reload)
1653 CreatureDataAddon const *cainfo = GetCreatureAddon();
1654 if(!cainfo)
1655 return false;
1657 if (cainfo->mount != 0)
1658 Mount(cainfo->mount);
1660 if (cainfo->bytes1 != 0)
1662 // 0 StandState
1663 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1664 // 2 StandFlags
1665 // 3 StandMiscFlags
1667 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1668 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1669 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1670 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1671 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1674 if (cainfo->bytes2 != 0)
1676 // 0 SheathState
1677 // 1 UnitPVPStateFlags Set at Creature::UpdateEntry (SetPvp())
1678 // 2 UnitRename Pet only, so always 0 for default creature
1679 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1681 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1682 //SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1683 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1684 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1685 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1686 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1689 if (cainfo->emote != 0)
1690 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1692 if (cainfo->move_flags != 0)
1693 SetMonsterMoveFlags(MonsterMovementFlags(cainfo->move_flags));
1695 if(cainfo->auras)
1697 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1699 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1700 if (!AdditionalSpellInfo)
1702 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1703 continue;
1706 // skip already applied aura
1707 if(HasAura(cAura->spell_id,cAura->effect_idx))
1709 if(!reload)
1710 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);
1712 continue;
1715 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1716 AddAura(AdditionalAura);
1717 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1720 return true;
1723 /// Send a message to LocalDefense channel for players opposition team in the zone
1724 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1726 uint32 enemy_team = attacker->GetTeam();
1728 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1729 data << (uint32)GetZoneId();
1730 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1733 void Creature::SetInCombatWithZone()
1735 if (!CanHaveThreatList())
1737 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1738 return;
1741 Map* pMap = GetMap();
1743 if (!pMap->IsDungeon())
1745 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1746 return;
1749 Map::PlayerList const &PlList = pMap->GetPlayers();
1751 if (PlList.isEmpty())
1752 return;
1754 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
1756 if (Player* pPlayer = i->getSource())
1758 if (pPlayer->isGameMaster())
1759 continue;
1761 if (pPlayer->isAlive())
1763 pPlayer->SetInCombatWith(this);
1764 AddThreat(pPlayer);
1770 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1772 m_CreatureSpellCooldowns[spell_id] = end_time;
1775 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1777 m_CreatureCategoryCooldowns[category] = apply_time;
1780 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1782 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1783 if(!spellInfo)
1784 return;
1786 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1787 if(cooldown)
1788 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1790 if(spellInfo->Category)
1791 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1793 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1796 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1798 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1799 if(!spellInfo)
1800 return false;
1802 // check global cooldown if spell affected by it
1803 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1804 return true;
1806 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1807 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1810 bool Creature::HasSpellCooldown(uint32 spell_id) const
1812 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1813 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1816 bool Creature::IsInEvadeMode() const
1818 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1821 bool Creature::HasSpell(uint32 spellID) const
1823 uint8 i;
1824 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1825 if(spellID == m_spells[i])
1826 break;
1827 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1830 time_t Creature::GetRespawnTimeEx() const
1832 time_t now = time(NULL);
1833 if(m_respawnTime > now) // dead (no corpse)
1834 return m_respawnTime;
1835 else if(m_deathTimer > 0) // dead (corpse)
1836 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
1837 else
1838 return now;
1841 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1843 if (m_DBTableGuid)
1845 if (CreatureData const* data = sObjectMgr.GetCreatureData(GetDBTableGUIDLow()))
1847 x = data->posX;
1848 y = data->posY;
1849 z = data->posZ;
1850 if (ori)
1851 *ori = data->orientation;
1852 if (dist)
1853 *dist = data->spawndist;
1855 return;
1859 float orient;
1861 GetSummonPoint(x, y, z, orient);
1863 if (ori)
1864 *ori = orient;
1865 if (dist)
1866 *dist = GetRespawnRadius();
1869 void Creature::AllLootRemovedFromCorpse()
1871 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1873 uint32 nDeathTimer;
1875 CreatureInfo const *cinfo = GetCreatureInfo();
1877 // corpse was not skinnable -> apply corpse looted timer
1878 if (!cinfo || !cinfo->SkinLootId)
1879 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1880 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1881 else
1882 nDeathTimer = 0;
1884 // update death timer only if looted timer is shorter
1885 if (m_deathTimer > nDeathTimer)
1886 m_deathTimer = nDeathTimer;
1890 uint32 Creature::getLevelForTarget( Unit const* target ) const
1892 if(!isWorldBoss())
1893 return Unit::getLevelForTarget(target);
1895 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1896 if(level < 1)
1897 return 1;
1898 if(level > 255)
1899 return 255;
1900 return level;
1903 std::string Creature::GetAIName() const
1905 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
1908 std::string Creature::GetScriptName() const
1910 return sObjectMgr.GetScriptName(GetScriptId());
1913 uint32 Creature::GetScriptId() const
1915 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
1918 VendorItemData const* Creature::GetVendorItems() const
1920 return sObjectMgr.GetNpcVendorItemList(GetEntry());
1923 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
1925 if(!vItem->maxcount)
1926 return vItem->maxcount;
1928 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1929 for(; itr != m_vendorItemCounts.end(); ++itr)
1930 if(itr->itemId==vItem->item)
1931 break;
1933 if(itr == m_vendorItemCounts.end())
1934 return vItem->maxcount;
1936 VendorItemCount* vCount = &*itr;
1938 time_t ptime = time(NULL);
1940 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1942 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1944 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1945 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
1947 m_vendorItemCounts.erase(itr);
1948 return vItem->maxcount;
1951 vCount->count += diff * pProto->BuyCount;
1952 vCount->lastIncrementTime = ptime;
1955 return vCount->count;
1958 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
1960 if(!vItem->maxcount)
1961 return 0;
1963 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1964 for(; itr != m_vendorItemCounts.end(); ++itr)
1965 if(itr->itemId==vItem->item)
1966 break;
1968 if(itr == m_vendorItemCounts.end())
1970 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
1971 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
1972 return new_count;
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 )
1985 vCount->count += diff * pProto->BuyCount;
1986 else
1987 vCount->count = vItem->maxcount;
1990 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
1991 vCount->lastIncrementTime = ptime;
1992 return vCount->count;
1995 TrainerSpellData const* Creature::GetTrainerSpells() const
1997 return sObjectMgr.GetNpcTrainerSpells(GetEntry());
2000 // overwrite WorldObject function for proper name localization
2001 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2003 if (loc_idx >= 0)
2005 CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(GetEntry());
2006 if (cl)
2008 if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
2009 return cl->Name[loc_idx].c_str();
2013 return GetName();
2016 void Creature::SetActiveObjectState( bool on )
2018 if(m_isActiveObject==on)
2019 return;
2021 bool world = IsInWorld();
2023 Map* map;
2024 if(world)
2026 map = GetMap();
2027 map->Remove(this,false);
2030 m_isActiveObject = on;
2032 if(world)
2033 map->Add(this);
2036 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2038 float x, y, z;
2039 if(GetMotionMaster()->GetDestination(x, y, z))
2040 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2043 void Creature::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
2045 if (!transitTime)
2047 if(GetTypeId()==TYPEID_PLAYER)
2049 Traveller<Player> traveller(*(Player*)this);
2050 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2052 else
2054 Traveller<Creature> traveller(*(Creature*)this);
2055 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2058 //float orientation = (float)atan2((double)dy, (double)dx);
2059 SendMonsterMove(x, y, z, 0, GetMonsterMoveFlags(), transitTime, player);
2062 void Creature::SendAreaSpiritHealerQueryOpcode(Player *pl)
2064 uint32 next_resurrect = 0;
2065 if (Spell* pcurSpell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
2066 next_resurrect = pcurSpell->GetCastedTime();
2067 WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 8 + 4);
2068 data << GetGUID() << next_resurrect;
2069 pl->SendDirectMessage(&data);