[9192] Fixed typo in error output for lock id gameobject template data check.
[getmangos.git] / src / game / Creature.cpp
blob4a51b6ada13ccf1c75e1c11431d770b2ea5fa6be
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() :
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_isPet(false), m_isVehicle(false), m_isTotem(false),
120 m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0),
121 m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
122 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
123 m_creatureInfo(NULL), m_isActiveObject(false), m_monsterMoveFlags(MONSTER_MOVE_WALK)
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_monsterMoveFlags = MONSTER_MOVE_WALK;
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 model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
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 defined in table `creature_template`, 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 SetSpeed(MOVE_WALK, cinfo->speed );
267 SetSpeed(MOVE_RUN, cinfo->speed );
268 SetSpeed(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 )
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());
291 if (team == HORDE)
292 setFaction(GetCreatureInfo()->faction_H);
293 else
294 setFaction(GetCreatureInfo()->faction_A);
296 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
298 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
299 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
300 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
302 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
303 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
305 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
306 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
307 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
308 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
309 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
310 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
311 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
313 SetCanModifyStats(true);
314 UpdateAllStats();
316 // checked and error show at loading templates
317 if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A))
319 if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
320 SetPvP(true);
321 else
322 SetPvP(false);
325 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
326 m_spells[i] = GetCreatureInfo()->spells[i];
328 return true;
331 void Creature::Update(uint32 diff)
333 if(m_GlobalCooldown <= diff)
334 m_GlobalCooldown = 0;
335 else
336 m_GlobalCooldown -= diff;
338 switch( m_deathState )
340 case JUST_ALIVED:
341 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
342 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
343 break;
344 case JUST_DIED:
345 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
346 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
347 break;
348 case DEAD:
350 if( m_respawnTime <= time(NULL) )
352 DEBUG_LOG("Respawning...");
353 m_respawnTime = 0;
354 lootForPickPocketed = false;
355 lootForBody = false;
357 if(m_originalEntry != GetEntry())
358 UpdateEntry(m_originalEntry);
360 CreatureInfo const *cinfo = GetCreatureInfo();
362 SelectLevel(cinfo);
363 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
364 if (m_isDeadByDefault)
366 setDeathState(JUST_DIED);
367 SetHealth(0);
368 i_motionMaster.Clear();
369 clearUnitState(UNIT_STAT_ALL_STATE);
370 LoadCreaturesAddon(true);
372 else
373 setDeathState( JUST_ALIVED );
375 //Call AI respawn virtual function
376 i_AI->JustRespawned();
378 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
379 if (poolid)
380 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
381 else
382 GetMap()->Add(this);
384 break;
386 case CORPSE:
388 if (m_isDeadByDefault)
389 break;
391 if( m_deathTimer <= diff )
393 RemoveCorpse();
394 DEBUG_LOG("Removing corpse... %u ", GetEntry());
396 else
398 m_deathTimer -= diff;
399 if (m_groupLootTimer && lootingGroupLeaderGUID)
401 if(diff <= m_groupLootTimer)
403 m_groupLootTimer -= diff;
405 else
407 Group* group = sObjectMgr.GetGroupByLeader(lootingGroupLeaderGUID);
408 if (group)
409 group->EndRoll();
410 m_groupLootTimer = 0;
411 lootingGroupLeaderGUID = 0;
416 break;
418 case ALIVE:
420 if (m_isDeadByDefault)
422 if( m_deathTimer <= diff )
424 RemoveCorpse();
425 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
427 else
429 m_deathTimer -= diff;
433 Unit::Update( diff );
435 // creature can be dead after Unit::Update call
436 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
437 if(!isAlive())
438 break;
440 if(!IsInEvadeMode())
442 // do not allow the AI to be changed during update
443 m_AI_locked = true;
444 i_AI->UpdateAI(diff);
445 m_AI_locked = false;
448 // creature can be dead after UpdateAI call
449 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
450 if(!isAlive())
451 break;
452 if(m_regenTimer > 0)
454 if(diff >= m_regenTimer)
455 m_regenTimer = 0;
456 else
457 m_regenTimer -= diff;
459 if (m_regenTimer != 0)
460 break;
462 if (!isInCombat() || IsPolymorphed())
463 RegenerateHealth();
465 RegenerateMana();
467 m_regenTimer = REGEN_TIME_FULL;
468 break;
470 case DEAD_FALLING:
472 if (!FallGround())
473 setDeathState(JUST_DIED);
475 default:
476 break;
480 void Creature::RegenerateMana()
482 uint32 curValue = GetPower(POWER_MANA);
483 uint32 maxValue = GetMaxPower(POWER_MANA);
485 if (curValue >= maxValue)
486 return;
488 uint32 addvalue = 0;
490 // Combat and any controlled creature
491 if (isInCombat() || GetCharmerOrOwnerGUID())
493 if(!IsUnderLastManaUseEffect())
495 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
496 float Spirit = GetStat(STAT_SPIRIT);
498 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
501 else
502 addvalue = maxValue/3;
504 ModifyPower(POWER_MANA, addvalue);
507 void Creature::RegenerateHealth()
509 if (!isRegeneratingHealth())
510 return;
512 uint32 curValue = GetHealth();
513 uint32 maxValue = GetMaxHealth();
515 if (curValue >= maxValue)
516 return;
518 uint32 addvalue = 0;
520 // Not only pet, but any controlled creature
521 if(GetCharmerOrOwnerGUID())
523 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
524 float Spirit = GetStat(STAT_SPIRIT);
526 if( GetPower(POWER_MANA) > 0 )
527 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
528 else
529 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
531 else
532 addvalue = maxValue/3;
534 ModifyHealth(addvalue);
537 void Creature::DoFleeToGetAssistance()
539 if (!getVictim())
540 return;
542 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
543 if (radius >0)
545 Creature* pCreature = NULL;
547 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
548 Cell cell(p);
549 cell.data.Part.reserved = ALL_DISTRICT;
550 cell.SetNoCreate();
551 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
552 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
554 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
556 CellLock<GridReadGuard> cell_lock(cell, p);
557 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap(), *this, radius);
559 SetNoSearchAssistance(true);
560 UpdateSpeed(MOVE_RUN, false);
562 if(!pCreature)
563 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
564 else
565 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
569 bool Creature::AIM_Initialize()
571 // make sure nothing can change the AI during AI update
572 if(m_AI_locked)
574 sLog.outDebug("AIM_Initialize: failed to init, locked.");
575 return false;
578 CreatureAI * oldAI = i_AI;
579 i_motionMaster.Initialize();
580 i_AI = FactorySelector::selectAI(this);
581 if (oldAI)
582 delete oldAI;
583 return true;
586 bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
588 ASSERT(map);
589 SetMap(map);
590 SetPhaseMask(phaseMask,false);
592 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
593 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
595 if (bResult)
597 //Notify the map's instance data.
598 //Only works if you create the object in it, not if it is moves to that map.
599 //Normally non-players do not teleport to other maps.
600 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
601 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
603 switch (GetCreatureInfo()->rank)
605 case CREATURE_ELITE_RARE:
606 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
607 break;
608 case CREATURE_ELITE_ELITE:
609 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
610 break;
611 case CREATURE_ELITE_RAREELITE:
612 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
613 break;
614 case CREATURE_ELITE_WORLDBOSS:
615 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
616 break;
617 default:
618 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
619 break;
621 LoadCreaturesAddon();
624 return bResult;
627 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
629 if(!isTrainer())
630 return false;
632 TrainerSpellData const* trainer_spells = GetTrainerSpells();
634 if(!trainer_spells || trainer_spells->spellList.empty())
636 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
637 GetGUIDLow(),GetEntry());
638 return false;
641 switch(GetCreatureInfo()->trainer_type)
643 case TRAINER_TYPE_CLASS:
644 if(pPlayer->getClass()!=GetCreatureInfo()->trainer_class)
646 if(msg)
648 pPlayer->PlayerTalkClass->ClearMenus();
649 switch(GetCreatureInfo()->trainer_class)
651 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
652 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
653 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
654 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
655 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
656 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
657 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
658 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
659 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
662 return false;
664 break;
665 case TRAINER_TYPE_PETS:
666 if(pPlayer->getClass()!=CLASS_HUNTER)
668 pPlayer->PlayerTalkClass->ClearMenus();
669 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
670 return false;
672 break;
673 case TRAINER_TYPE_MOUNTS:
674 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
676 if(msg)
678 pPlayer->PlayerTalkClass->ClearMenus();
679 switch(GetCreatureInfo()->trainer_class)
681 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
682 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
683 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
684 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
685 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
686 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
687 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
688 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
689 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
690 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
693 return false;
695 break;
696 case TRAINER_TYPE_TRADESKILLS:
697 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
699 if(msg)
701 pPlayer->PlayerTalkClass->ClearMenus();
702 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
704 return false;
706 break;
707 default:
708 return false; // checked and error output at creature_template loading
710 return true;
713 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
715 if(!isBattleMaster())
716 return false;
718 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
719 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
720 return false;
722 if(!msg)
723 return pPlayer->GetBGAccessByLevel(bgTypeId);
725 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
727 pPlayer->PlayerTalkClass->ClearMenus();
728 switch(bgTypeId)
730 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
731 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
732 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
733 case BATTLEGROUND_EY:
734 case BATTLEGROUND_NA:
735 case BATTLEGROUND_BE:
736 case BATTLEGROUND_AA:
737 case BATTLEGROUND_RL:
738 case BATTLEGROUND_SA:
739 case BATTLEGROUND_DS:
740 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
741 default: break;
743 return false;
745 return true;
748 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
750 return pPlayer->getLevel() >= 10
751 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
752 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
755 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, MonsterMovementFlags flags, uint8 type)
757 /* uint32 timeElap = getMSTime();
758 if ((timeElap - m_startMove) < m_moveTime)
760 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
761 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
763 else
765 oX = dX;
766 oY = dY;
769 dX = x;
770 dY = y;
771 m_orientation = atan2((oY - dY), (oX - dX));
773 m_startMove = getMSTime();
774 m_moveTime = time;*/
775 SendMonsterMove(x, y, z, type, flags, time);
778 Player *Creature::GetLootRecipient() const
780 if (!m_lootRecipient) return NULL;
781 else return ObjectAccessor::FindPlayer(m_lootRecipient);
784 void Creature::SetLootRecipient(Unit *unit)
786 // set the player whose group should receive the right
787 // to loot the creature after it dies
788 // should be set to NULL after the loot disappears
790 if (!unit)
792 m_lootRecipient = 0;
793 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
794 return;
797 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
798 if(!player) // normal creature, no player involved
799 return;
801 m_lootRecipient = player->GetGUID();
802 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
805 void Creature::SaveToDB()
807 // this should only be used when the creature has already been loaded
808 // preferably after adding to map, because mapid may not be valid otherwise
809 CreatureData const *data = sObjectMgr.GetCreatureData(m_DBTableGuid);
810 if(!data)
812 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
813 return;
816 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
819 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
821 // update in loaded data
822 if (!m_DBTableGuid)
823 m_DBTableGuid = GetGUIDLow();
824 CreatureData& data = sObjectMgr.NewOrExistCreatureData(m_DBTableGuid);
826 uint32 displayId = GetNativeDisplayId();
828 // check if it's a custom model and if not, use 0 for displayId
829 CreatureInfo const *cinfo = GetCreatureInfo();
830 if (cinfo)
832 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
833 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
835 if (cinfo->DisplayID_A[0])
836 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
837 if(displayId == minfo->modelid_other_gender)
838 displayId = 0;
840 if (displayId && cinfo->DisplayID_A[1])
841 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
842 if(displayId == minfo->modelid_other_gender)
843 displayId = 0;
845 if (displayId && cinfo->DisplayID_H[0])
846 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
847 if(displayId == minfo->modelid_other_gender)
848 displayId = 0;
850 if (displayId && cinfo->DisplayID_H[1])
851 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
852 if(displayId == minfo->modelid_other_gender)
853 displayId = 0;
855 else
856 displayId = 0;
859 // data->guid = guid don't must be update at save
860 data.id = GetEntry();
861 data.mapid = mapid;
862 data.phaseMask = phaseMask;
863 data.displayid = displayId;
864 data.equipmentId = GetEquipmentId();
865 data.posX = GetPositionX();
866 data.posY = GetPositionY();
867 data.posZ = GetPositionZ();
868 data.orientation = GetOrientation();
869 data.spawntimesecs = m_respawnDelay;
870 // prevent add data integrity problems
871 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
872 data.currentwaypoint = 0;
873 data.curhealth = GetHealth();
874 data.curmana = GetPower(POWER_MANA);
875 data.is_dead = m_isDeadByDefault;
876 // prevent add data integrity problems
877 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
878 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
879 data.spawnMask = spawnMask;
881 // updated in DB
882 WorldDatabase.BeginTransaction();
884 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
886 std::ostringstream ss;
887 ss << "INSERT INTO creature VALUES ("
888 << m_DBTableGuid << ","
889 << GetEntry() << ","
890 << mapid <<","
891 << uint32(spawnMask) << "," // cast to prevent save as symbol
892 << uint16(GetPhaseMask()) << "," // prevent out of range error
893 << displayId <<","
894 << GetEquipmentId() <<","
895 << GetPositionX() << ","
896 << GetPositionY() << ","
897 << GetPositionZ() << ","
898 << GetOrientation() << ","
899 << m_respawnDelay << "," //respawn time
900 << (float) m_respawnradius << "," //spawn distance (float)
901 << (uint32) (0) << "," //currentwaypoint
902 << GetHealth() << "," //curhealth
903 << GetPower(POWER_MANA) << "," //curmana
904 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
905 << GetDefaultMovementType() << ")"; //default movement generator type
907 WorldDatabase.PExecuteLog("%s", ss.str().c_str());
909 WorldDatabase.CommitTransaction();
912 void Creature::SelectLevel(const CreatureInfo *cinfo)
914 uint32 rank = isPet()? 0 : cinfo->rank;
916 // level
917 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
918 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
919 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
920 SetLevel(level);
922 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
924 // health
925 float healthmod = _GetHealthMod(rank);
927 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
928 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
929 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
931 SetCreateHealth(health);
932 SetMaxHealth(health);
933 SetHealth(health);
935 // mana
936 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
937 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
938 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
940 SetCreateMana(mana);
941 SetMaxPower(POWER_MANA, mana); //MAX Mana
942 SetPower(POWER_MANA, mana);
944 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
946 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
947 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
949 // damage
950 float damagemod = _GetDamageMod(rank);
952 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
953 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
955 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
956 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
958 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
961 float Creature::_GetHealthMod(int32 Rank)
963 switch (Rank) // define rates for each elite rank
965 case CREATURE_ELITE_NORMAL:
966 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
967 case CREATURE_ELITE_ELITE:
968 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
969 case CREATURE_ELITE_RAREELITE:
970 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
971 case CREATURE_ELITE_WORLDBOSS:
972 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
973 case CREATURE_ELITE_RARE:
974 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
975 default:
976 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
980 float Creature::_GetDamageMod(int32 Rank)
982 switch (Rank) // define rates for each elite rank
984 case CREATURE_ELITE_NORMAL:
985 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
986 case CREATURE_ELITE_ELITE:
987 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
988 case CREATURE_ELITE_RAREELITE:
989 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
990 case CREATURE_ELITE_WORLDBOSS:
991 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
992 case CREATURE_ELITE_RARE:
993 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
994 default:
995 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
999 float Creature::GetSpellDamageMod(int32 Rank)
1001 switch (Rank) // define rates for each elite rank
1003 case CREATURE_ELITE_NORMAL:
1004 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1005 case CREATURE_ELITE_ELITE:
1006 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1007 case CREATURE_ELITE_RAREELITE:
1008 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1009 case CREATURE_ELITE_WORLDBOSS:
1010 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1011 case CREATURE_ELITE_RARE:
1012 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1013 default:
1014 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1018 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1020 CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
1021 if(!cinfo)
1023 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1024 return false;
1026 m_originalEntry = Entry;
1028 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1030 if(!UpdateEntry(Entry, team, data))
1031 return false;
1033 return true;
1036 bool Creature::LoadFromDB(uint32 guid, Map *map)
1038 CreatureData const* data = sObjectMgr.GetCreatureData(guid);
1040 if(!data)
1042 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1043 return false;
1046 m_DBTableGuid = guid;
1047 if (map->GetInstanceId() == 0)
1049 // Creature can be loaded already in map if grid has been unloaded while creature walk to another grid
1050 // FIXME: until creature guids is global and for instances used dynamic generated guids
1051 // in instance possible load creature duplicates with same DB guid but different in game guids
1052 // This will be until implementing per-map creature guids
1053 if (map->GetCreature(MAKE_NEW_GUID(guid,data->id,HIGHGUID_UNIT)))
1054 return false;
1056 else
1057 guid = sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT);
1059 uint16 team = 0;
1060 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1061 return false;
1063 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1065 if(!IsPositionValid())
1067 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1068 return false;
1071 m_respawnradius = data->spawndist;
1073 m_respawnDelay = data->spawntimesecs;
1074 m_isDeadByDefault = data->is_dead;
1075 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1077 m_respawnTime = sObjectMgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1078 if(m_respawnTime > time(NULL)) // not ready to respawn
1080 m_deathState = DEAD;
1081 if(canFly())
1083 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1084 if(data->posZ - tz > 0.1)
1085 Relocate(data->posX,data->posY,tz);
1088 else if(m_respawnTime) // respawn time set but expired
1090 m_respawnTime = 0;
1091 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1094 uint32 curhealth = data->curhealth;
1095 if(curhealth)
1097 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1098 if(curhealth < 1)
1099 curhealth = 1;
1102 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1103 SetPower(POWER_MANA,data->curmana);
1105 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1107 // checked at creature_template loading
1108 m_defaultMovementType = MovementGeneratorType(data->movementType);
1110 AIM_Initialize();
1111 return true;
1114 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1116 if(equip_entry == 0)
1118 if (force)
1120 for (uint8 i = 0; i < 3; ++i)
1121 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1122 m_equipmentId = 0;
1124 return;
1127 EquipmentInfo const *einfo = sObjectMgr.GetEquipmentInfo(equip_entry);
1128 if (!einfo)
1129 return;
1131 m_equipmentId = equip_entry;
1132 for (uint8 i = 0; i < 3; ++i)
1133 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1136 bool Creature::hasQuest(uint32 quest_id) const
1138 QuestRelations const& qr = sObjectMgr.mCreatureQuestRelations;
1139 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1141 if(itr->second==quest_id)
1142 return true;
1144 return false;
1147 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1149 QuestRelations const& qr = sObjectMgr.mCreatureQuestInvolvedRelations;
1150 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1152 if(itr->second==quest_id)
1153 return true;
1155 return false;
1158 void Creature::DeleteFromDB()
1160 if (!m_DBTableGuid)
1162 sLog.outDebug("Trying to delete not saved creature!");
1163 return;
1166 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1167 sObjectMgr.DeleteCreatureData(m_DBTableGuid);
1169 WorldDatabase.BeginTransaction();
1170 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1171 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1172 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1173 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1174 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1175 WorldDatabase.PExecuteLog("DELETE FROM creature_battleground WHERE guid = '%u'", m_DBTableGuid);
1176 WorldDatabase.CommitTransaction();
1179 float Creature::GetAttackDistance(Unit const* pl) const
1181 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1182 if(aggroRate==0)
1183 return 0.0f;
1185 uint32 playerlevel = pl->getLevelForTarget(this);
1186 uint32 creaturelevel = getLevelForTarget(pl);
1188 int32 leveldif = int32(playerlevel) - int32(creaturelevel);
1190 // "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."
1191 if ( leveldif < - 25)
1192 leveldif = -25;
1194 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1195 float RetDistance = 20;
1197 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1198 // radius grow if playlevel < creaturelevel
1199 RetDistance -= (float)leveldif;
1201 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1203 // detect range auras
1204 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1206 // detected range auras
1207 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1210 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1211 if(RetDistance < 5)
1212 RetDistance = 5;
1214 return (RetDistance*aggroRate);
1217 void Creature::setDeathState(DeathState s)
1219 if ((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1221 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1223 // always save boss respawn time at death to prevent crash cheating
1224 if (sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1225 SaveRespawnTime();
1227 if (canFly() && FallGround())
1228 return;
1230 if (!IsStopped())
1231 StopMoving();
1233 Unit::setDeathState(s);
1235 if (s == JUST_DIED)
1237 SetTargetGUID(0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1238 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1240 if (!isPet() && GetCreatureInfo()->SkinLootId)
1241 if (LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId))
1242 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1244 if (canFly() && FallGround())
1245 return;
1247 if (HasSearchedAssistance())
1249 SetNoSearchAssistance(false);
1250 UpdateSpeed(MOVE_RUN, false);
1253 Unit::setDeathState(CORPSE);
1255 if (s == JUST_ALIVED)
1257 SetHealth(GetMaxHealth());
1258 SetLootRecipient(NULL);
1259 CreatureInfo const *cinfo = GetCreatureInfo();
1260 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1261 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1262 AddMonsterMoveFlag(MONSTER_MOVE_WALK);
1263 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1264 Unit::setDeathState(ALIVE);
1265 clearUnitState(UNIT_STAT_ALL_STATE);
1266 i_motionMaster.Clear();
1267 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1268 LoadCreaturesAddon(true);
1272 bool Creature::FallGround()
1274 // Let's abort after we called this function one time
1275 if (getDeathState() == DEAD_FALLING)
1276 return false;
1278 // Let's do with no vmap because no way to get far distance with vmap high call
1279 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1281 // Abort too if the ground is very near
1282 if (fabs(GetPositionZ() - tz) < 0.1f)
1283 return false;
1285 Unit::setDeathState(DEAD_FALLING);
1286 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1287 Relocate(GetPositionX(), GetPositionY(), tz);
1288 return true;
1291 void Creature::Respawn()
1293 RemoveCorpse();
1295 // forced recreate creature object at clients
1296 UnitVisibility currentVis = GetVisibility();
1297 SetVisibility(VISIBILITY_RESPAWN);
1298 UpdateObjectVisibility();
1299 SetVisibility(currentVis); // restore visibility state
1300 UpdateObjectVisibility();
1302 if(getDeathState()==DEAD)
1304 if (m_DBTableGuid)
1305 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1306 m_respawnTime = time(NULL); // respawn at next tick
1310 void Creature::ForcedDespawn(uint32 timeMSToDespawn)
1312 if (timeMSToDespawn)
1314 ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
1316 m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
1317 return;
1320 if (isAlive())
1321 setDeathState(JUST_DIED);
1323 RemoveCorpse();
1324 SetHealth(0); // just for nice GM-mode view
1327 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1329 if (!spellInfo)
1330 return false;
1332 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1333 return true;
1335 return Unit::IsImmunedToSpell(spellInfo);
1338 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1340 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1341 return true;
1343 // Taunt immunity special flag check
1344 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1346 // Taunt aura apply check
1347 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1349 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1350 return true;
1352 // Spell effect taunt check
1353 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1354 return true;
1357 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1360 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1362 if(!pVictim)
1363 return NULL;
1365 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1367 if(!m_spells[i])
1368 continue;
1369 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1370 if(!spellInfo)
1372 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1373 continue;
1376 bool bcontinue = true;
1377 for(uint32 j=0;j<3;j++)
1379 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1380 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1381 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1382 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1385 bcontinue = false;
1386 break;
1389 if(bcontinue) continue;
1391 if(spellInfo->manaCost > GetPower(POWER_MANA))
1392 continue;
1393 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1394 float range = GetSpellMaxRange(srange);
1395 float minrange = GetSpellMinRange(srange);
1397 float dist = GetCombatDistance(pVictim);
1399 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1400 // continue;
1401 if( dist > range || dist < minrange )
1402 continue;
1403 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1404 continue;
1405 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1406 continue;
1407 return spellInfo;
1409 return NULL;
1412 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1414 if(!pVictim)
1415 return NULL;
1417 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1419 if(!m_spells[i])
1420 continue;
1421 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1422 if(!spellInfo)
1424 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1425 continue;
1428 bool bcontinue = true;
1429 for(uint32 j=0;j<3;j++)
1431 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1433 bcontinue = false;
1434 break;
1437 if(bcontinue) continue;
1439 if(spellInfo->manaCost > GetPower(POWER_MANA))
1440 continue;
1441 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1442 float range = GetSpellMaxRange(srange);
1443 float minrange = GetSpellMinRange(srange);
1445 float dist = GetCombatDistance(pVictim);
1447 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1448 // continue;
1449 if( dist > range || dist < minrange )
1450 continue;
1451 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1452 continue;
1453 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1454 continue;
1455 return spellInfo;
1457 return NULL;
1460 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1462 // gamemaster in GM mode see all, including ghosts
1463 if(pl->isGameMaster())
1464 return true;
1466 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1467 return false;
1469 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1470 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1472 return (isAlive() || m_deathTimer > 0 || (m_isDeadByDefault && m_deathState == CORPSE));
1475 // Dead player see live creatures near own corpse
1476 if(isAlive())
1478 Corpse *corpse = pl->GetCorpse();
1479 if(corpse)
1481 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1482 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1483 return true;
1487 // Dead player can see ghosts
1488 if (GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_GHOST_VISIBLE)
1489 return true;
1491 // and not see any other
1492 return false;
1495 void Creature::SendAIReaction(AiReaction reactionType)
1497 WorldPacket data(SMSG_AI_REACTION, 12);
1499 data << uint64(GetGUID());
1500 data << uint32(reactionType);
1502 ((WorldObject*)this)->SendMessageToSet(&data, true);
1504 sLog.outDebug("WORLD: Sent SMSG_AI_REACTION, type %u.", reactionType);
1507 void Creature::CallAssistance()
1509 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1511 SetNoCallAssistance(true);
1513 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1514 if(radius > 0)
1516 std::list<Creature*> assistList;
1519 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1520 Cell cell(p);
1521 cell.data.Part.reserved = ALL_DISTRICT;
1522 cell.SetNoCreate();
1524 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1525 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1527 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1529 CellLock<GridReadGuard> cell_lock(cell, p);
1530 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap(), *this, radius);
1533 if (!assistList.empty())
1535 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1536 while (!assistList.empty())
1538 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1539 e->AddAssistant((*assistList.begin())->GetGUID());
1540 assistList.pop_front();
1542 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1548 void Creature::CallForHelp(float fRadius)
1550 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1551 return;
1553 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1554 Cell cell(p);
1555 cell.data.Part.reserved = ALL_DISTRICT;
1556 cell.SetNoCreate();
1558 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1559 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1561 TypeContainerVisitor<MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo>, GridTypeMapContainer > grid_creature_searcher(worker);
1563 CellLock<GridReadGuard> cell_lock(cell, p);
1564 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap(), *this, fRadius);
1567 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1569 // we don't need help from zombies :)
1570 if (!isAlive())
1571 return false;
1573 // we don't need help from non-combatant ;)
1574 if (isCivilian())
1575 return false;
1577 // skip fighting creature
1578 if (isInCombat())
1579 return false;
1581 // only free creature
1582 if (GetCharmerOrOwnerGUID())
1583 return false;
1585 // only from same creature faction
1586 if (checkfaction)
1588 if (getFaction() != u->getFaction())
1589 return false;
1591 else
1593 if (!IsFriendlyTo(u))
1594 return false;
1597 // skip non hostile to caster enemy creatures
1598 if (!IsHostileTo(enemy))
1599 return false;
1601 return true;
1604 void Creature::SaveRespawnTime()
1606 if(isPet() || !m_DBTableGuid)
1607 return;
1609 if(m_respawnTime > time(NULL)) // dead (no corpse)
1610 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1611 else if(m_deathTimer > 0) // dead (corpse)
1612 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1615 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1617 if (!pVictim)
1618 return true;
1620 if (!pVictim->IsInMap(this))
1621 return true;
1623 if (!pVictim->isTargetableForAttack())
1624 return true;
1626 if (!pVictim->isInAccessablePlaceFor(this))
1627 return true;
1629 if (!pVictim->isVisibleForOrDetect(this,this,false))
1630 return true;
1632 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1633 return false;
1635 float AttackDist = GetAttackDistance(pVictim);
1636 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1638 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1639 return !pVictim->IsWithinDist3d(CombatStartX,CombatStartY,CombatStartZ,
1640 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1643 CreatureDataAddon const* Creature::GetCreatureAddon() const
1645 if (m_DBTableGuid)
1647 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1648 return addon;
1651 // dependent from difficulty mode entry
1652 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1655 //creature_addon table
1656 bool Creature::LoadCreaturesAddon(bool reload)
1658 CreatureDataAddon const *cainfo = GetCreatureAddon();
1659 if(!cainfo)
1660 return false;
1662 if (cainfo->mount != 0)
1663 Mount(cainfo->mount);
1665 if (cainfo->bytes1 != 0)
1667 // 0 StandState
1668 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1669 // 2 StandFlags
1670 // 3 StandMiscFlags
1672 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1673 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1674 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1675 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1676 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1679 if (cainfo->bytes2 != 0)
1681 // 0 SheathState
1682 // 1 UnitPVPStateFlags Set at Creature::UpdateEntry (SetPvp())
1683 // 2 UnitRename Pet only, so always 0 for default creature
1684 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1686 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1687 //SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1688 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1689 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1690 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1691 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1694 if (cainfo->emote != 0)
1695 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1697 if (cainfo->move_flags != 0)
1698 SetMonsterMoveFlags(MonsterMovementFlags(cainfo->move_flags));
1700 if(cainfo->auras)
1702 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1704 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1705 if (!AdditionalSpellInfo)
1707 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1708 continue;
1711 // skip already applied aura
1712 if(HasAura(cAura->spell_id,cAura->effect_idx))
1714 if(!reload)
1715 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);
1717 continue;
1720 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1721 AddAura(AdditionalAura);
1722 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1725 return true;
1728 /// Send a message to LocalDefense channel for players opposition team in the zone
1729 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1731 uint32 enemy_team = attacker->GetTeam();
1733 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1734 data << (uint32)GetZoneId();
1735 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1738 void Creature::SetInCombatWithZone()
1740 if (!CanHaveThreatList())
1742 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1743 return;
1746 Map* pMap = GetMap();
1748 if (!pMap->IsDungeon())
1750 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1751 return;
1754 Map::PlayerList const &PlList = pMap->GetPlayers();
1756 if (PlList.isEmpty())
1757 return;
1759 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
1761 if (Player* pPlayer = i->getSource())
1763 if (pPlayer->isGameMaster())
1764 continue;
1766 if (pPlayer->isAlive())
1768 pPlayer->SetInCombatWith(this);
1769 AddThreat(pPlayer);
1775 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1777 m_CreatureSpellCooldowns[spell_id] = end_time;
1780 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1782 m_CreatureCategoryCooldowns[category] = apply_time;
1785 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1787 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1788 if(!spellInfo)
1789 return;
1791 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1792 if(cooldown)
1793 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1795 if(spellInfo->Category)
1796 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1798 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1801 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1803 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1804 if(!spellInfo)
1805 return false;
1807 // check global cooldown if spell affected by it
1808 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1809 return true;
1811 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1812 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1815 bool Creature::HasSpellCooldown(uint32 spell_id) const
1817 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1818 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1821 bool Creature::IsInEvadeMode() const
1823 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1826 bool Creature::HasSpell(uint32 spellID) const
1828 uint8 i;
1829 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1830 if(spellID == m_spells[i])
1831 break;
1832 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1835 time_t Creature::GetRespawnTimeEx() const
1837 time_t now = time(NULL);
1838 if(m_respawnTime > now) // dead (no corpse)
1839 return m_respawnTime;
1840 else if(m_deathTimer > 0) // dead (corpse)
1841 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
1842 else
1843 return now;
1846 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1848 if (m_DBTableGuid)
1850 if (CreatureData const* data = sObjectMgr.GetCreatureData(GetDBTableGUIDLow()))
1852 x = data->posX;
1853 y = data->posY;
1854 z = data->posZ;
1855 if (ori)
1856 *ori = data->orientation;
1857 if (dist)
1858 *dist = data->spawndist;
1860 return;
1864 float orient;
1866 GetSummonPoint(x, y, z, orient);
1868 if (ori)
1869 *ori = orient;
1870 if (dist)
1871 *dist = GetRespawnRadius();
1874 void Creature::AllLootRemovedFromCorpse()
1876 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1878 uint32 nDeathTimer;
1880 CreatureInfo const *cinfo = GetCreatureInfo();
1882 // corpse was not skinnable -> apply corpse looted timer
1883 if (!cinfo || !cinfo->SkinLootId)
1884 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1885 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1886 else
1887 nDeathTimer = 0;
1889 // update death timer only if looted timer is shorter
1890 if (m_deathTimer > nDeathTimer)
1891 m_deathTimer = nDeathTimer;
1895 uint32 Creature::getLevelForTarget( Unit const* target ) const
1897 if(!isWorldBoss())
1898 return Unit::getLevelForTarget(target);
1900 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1901 if(level < 1)
1902 return 1;
1903 if(level > 255)
1904 return 255;
1905 return level;
1908 std::string Creature::GetAIName() const
1910 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
1913 std::string Creature::GetScriptName() const
1915 return sObjectMgr.GetScriptName(GetScriptId());
1918 uint32 Creature::GetScriptId() const
1920 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
1923 VendorItemData const* Creature::GetVendorItems() const
1925 return sObjectMgr.GetNpcVendorItemList(GetEntry());
1928 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
1930 if(!vItem->maxcount)
1931 return vItem->maxcount;
1933 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1934 for(; itr != m_vendorItemCounts.end(); ++itr)
1935 if(itr->itemId==vItem->item)
1936 break;
1938 if(itr == m_vendorItemCounts.end())
1939 return vItem->maxcount;
1941 VendorItemCount* vCount = &*itr;
1943 time_t ptime = time(NULL);
1945 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1947 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1949 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1950 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
1952 m_vendorItemCounts.erase(itr);
1953 return vItem->maxcount;
1956 vCount->count += diff * pProto->BuyCount;
1957 vCount->lastIncrementTime = ptime;
1960 return vCount->count;
1963 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
1965 if(!vItem->maxcount)
1966 return 0;
1968 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1969 for(; itr != m_vendorItemCounts.end(); ++itr)
1970 if(itr->itemId==vItem->item)
1971 break;
1973 if(itr == m_vendorItemCounts.end())
1975 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
1976 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
1977 return new_count;
1980 VendorItemCount* vCount = &*itr;
1982 time_t ptime = time(NULL);
1984 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1986 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1988 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1989 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
1990 vCount->count += diff * pProto->BuyCount;
1991 else
1992 vCount->count = vItem->maxcount;
1995 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
1996 vCount->lastIncrementTime = ptime;
1997 return vCount->count;
2000 TrainerSpellData const* Creature::GetTrainerSpells() const
2002 return sObjectMgr.GetNpcTrainerSpells(GetEntry());
2005 // overwrite WorldObject function for proper name localization
2006 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2008 if (loc_idx >= 0)
2010 CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(GetEntry());
2011 if (cl)
2013 if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
2014 return cl->Name[loc_idx].c_str();
2018 return GetName();
2021 void Creature::SetActiveObjectState( bool on )
2023 if(m_isActiveObject==on)
2024 return;
2026 bool world = IsInWorld();
2028 Map* map;
2029 if(world)
2031 map = GetMap();
2032 map->Remove(this,false);
2035 m_isActiveObject = on;
2037 if(world)
2038 map->Add(this);
2041 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2043 float x, y, z;
2044 if(GetMotionMaster()->GetDestination(x, y, z))
2045 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2048 void Creature::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
2050 if (!transitTime)
2052 if(GetTypeId()==TYPEID_PLAYER)
2054 Traveller<Player> traveller(*(Player*)this);
2055 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2057 else
2059 Traveller<Creature> traveller(*(Creature*)this);
2060 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2063 //float orientation = (float)atan2((double)dy, (double)dx);
2064 SendMonsterMove(x, y, z, 0, GetMonsterMoveFlags(), transitTime, player);
2067 void Creature::SendAreaSpiritHealerQueryOpcode(Player *pl)
2069 uint32 next_resurrect = 0;
2070 if (Spell* pcurSpell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
2071 next_resurrect = pcurSpell->GetCastedTime();
2072 WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 8 + 4);
2073 data << GetGUID() << next_resurrect;
2074 pl->SendDirectMessage(&data);