[7023] Remove not used useCharges for IsImmunedToSpell/IsImmunedToDamage
[getmangos.git] / src / game / Creature.cpp
blobd278e7a3527ae39a636e51fdea7fb218f2b8a375
1 /*
2 * Copyright (C) 2005-2009 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 "WorldSession.h"
23 #include "World.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "Creature.h"
27 #include "QuestDef.h"
28 #include "GossipDef.h"
29 #include "Player.h"
30 #include "Opcodes.h"
31 #include "Log.h"
32 #include "LootMgr.h"
33 #include "MapManager.h"
34 #include "CreatureAI.h"
35 #include "CreatureAISelector.h"
36 #include "Formulas.h"
37 #include "SpellAuras.h"
38 #include "WaypointMovementGenerator.h"
39 #include "InstanceData.h"
40 #include "BattleGround.h"
41 #include "Util.h"
42 #include "GridNotifiers.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
46 // apply implementation of the singletons
47 #include "Policies/SingletonImp.h"
49 void TrainerSpellData::Clear()
51 for (TrainerSpellList::iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
52 delete (*itr);
53 spellList.empty();
56 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
58 for(TrainerSpellList::const_iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
59 if((*itr)->spell == spell_id)
60 return *itr;
62 return NULL;
65 bool VendorItemData::RemoveItem( uint32 item_id )
67 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
69 if((*i)->item==item_id)
71 m_items.erase(i);
72 return true;
75 return false;
78 size_t VendorItemData::FindItemSlot(uint32 item_id) const
80 for(size_t i = 0; i < m_items.size(); ++i )
81 if(m_items[i]->item==item_id)
82 return i;
83 return m_items.size();
86 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
88 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
89 if((*i)->item==item_id)
90 return *i;
91 return NULL;
94 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
96 Unit* victim = Unit::GetUnit(m_owner, m_victim);
97 if (victim)
99 while (!m_assistants.empty())
101 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
102 m_assistants.pop_front();
104 if (assistant && assistant->CanAssistTo(&m_owner, victim))
106 assistant->SetNoCallAssistance(true);
107 if(assistant->AI())
108 assistant->AI()->AttackStart(victim);
112 return true;
115 Creature::Creature() :
116 Unit(), i_AI(NULL),
117 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
118 m_lootMoney(0), m_lootRecipient(0),
119 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
120 m_gossipOptionLoaded(false), m_emoteState(0), m_isPet(false), m_isTotem(false), m_isVehicle(false),
121 m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
122 m_AlreadyCallAssistance(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
123 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
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;
134 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
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()) ObjectAccessor::Instance().AddObject(this);
151 Unit::AddToWorld();
154 void Creature::RemoveFromWorld()
156 ///- Remove the creature from the accessor
157 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
158 Unit::RemoveFromWorld();
161 void Creature::RemoveCorpse()
163 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
164 return;
166 m_deathTimer = 0;
167 setDeathState(DEAD);
168 ObjectAccessor::UpdateObjectVisibility(this);
169 loot.clear();
170 m_respawnTime = time(NULL) + m_respawnDelay;
172 float x,y,z,o;
173 GetRespawnCoord(x, y, z, &o);
174 GetMap()->CreatureRelocation(this,x,y,z,o);
178 * change the entry of creature until respawn
180 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
182 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
183 if(!normalInfo)
185 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
186 return false;
189 // get heroic mode entry
190 uint32 actualEntry = Entry;
191 CreatureInfo const *cinfo = normalInfo;
192 if(normalInfo->HeroicEntry)
194 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
195 if(map && map->IsHeroic())
197 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
198 if(!cinfo)
200 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
201 return false;
206 SetEntry(Entry); // normal entry always
207 m_creatureInfo = cinfo; // map mode related always
209 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
211 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
212 return false;
215 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
216 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
217 if (!minfo)
219 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
220 return false;
222 else
223 display_id = minfo->modelid; // it can be different (for another gender)
225 SetDisplayId(display_id);
226 SetNativeDisplayId(display_id);
227 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
229 // Load creature equipment
230 if(!data || data->equipmentId == 0)
231 { // use default from the template
232 LoadEquipment(cinfo->equipmentId);
234 else if(data && data->equipmentId != -1)
235 { // override, -1 means no equipment
236 LoadEquipment(data->equipmentId);
239 SetName(normalInfo->Name); // at normal entry always
241 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
242 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
244 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
246 SetSpeed(MOVE_WALK, cinfo->speed );
247 SetSpeed(MOVE_RUN, cinfo->speed );
248 SetSpeed(MOVE_SWIM, cinfo->speed );
250 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
252 // checked at loading
253 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
254 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
255 m_defaultMovementType = IDLE_MOTION_TYPE;
257 return true;
260 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
262 if(!InitEntry(Entry,team,data))
263 return false;
265 m_regenHealth = GetCreatureInfo()->RegenHealth;
267 // creatures always have melee weapon ready if any
268 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
270 SelectLevel(GetCreatureInfo());
271 if (team == HORDE)
272 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
273 else
274 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
276 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
278 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
279 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
280 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
282 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
283 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
285 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
286 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
287 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
288 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
289 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
290 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
291 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
293 SetCanModifyStats(true);
294 UpdateAllStats();
296 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
297 if (factionTemplate) // check and error show at loading templates
299 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
300 if (factionEntry)
301 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
302 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
303 SetPvP(true);
306 m_spells[0] = GetCreatureInfo()->spell1;
307 m_spells[1] = GetCreatureInfo()->spell2;
308 m_spells[2] = GetCreatureInfo()->spell3;
309 m_spells[3] = GetCreatureInfo()->spell4;
311 return true;
314 void Creature::Update(uint32 diff)
316 if(m_GlobalCooldown <= diff)
317 m_GlobalCooldown = 0;
318 else
319 m_GlobalCooldown -= diff;
321 switch( m_deathState )
323 case JUST_ALIVED:
324 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
325 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
326 break;
327 case JUST_DIED:
328 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
329 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
330 break;
331 case DEAD:
333 if( m_respawnTime <= time(NULL) )
335 DEBUG_LOG("Respawning...");
336 m_respawnTime = 0;
337 lootForPickPocketed = false;
338 lootForBody = false;
340 if(m_originalEntry != GetEntry())
341 UpdateEntry(m_originalEntry);
343 CreatureInfo const *cinfo = GetCreatureInfo();
345 SelectLevel(cinfo);
346 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
347 if (m_isDeadByDefault)
349 setDeathState(JUST_DIED);
350 SetHealth(0);
351 i_motionMaster.Clear();
352 clearUnitState(UNIT_STAT_ALL_STATE);
353 LoadCreaturesAddon(true);
355 else
356 setDeathState( JUST_ALIVED );
358 //Call AI respawn virtual function
359 i_AI->JustRespawned();
361 GetMap()->Add(this);
363 break;
365 case CORPSE:
367 if (m_isDeadByDefault)
368 break;
370 if( m_deathTimer <= diff )
372 RemoveCorpse();
373 DEBUG_LOG("Removing corpse... %u ", GetEntry());
375 else
377 m_deathTimer -= diff;
378 if (m_groupLootTimer && lootingGroupLeaderGUID)
380 if(diff <= m_groupLootTimer)
382 m_groupLootTimer -= diff;
384 else
386 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
387 if (group)
388 group->EndRoll();
389 m_groupLootTimer = 0;
390 lootingGroupLeaderGUID = 0;
395 break;
397 case ALIVE:
399 if (m_isDeadByDefault)
401 if( m_deathTimer <= diff )
403 RemoveCorpse();
404 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
406 else
408 m_deathTimer -= diff;
412 Unit::Update( diff );
414 // creature can be dead after Unit::Update call
415 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
416 if(!isAlive())
417 break;
419 if(!IsInEvadeMode())
421 // do not allow the AI to be changed during update
422 m_AI_locked = true;
423 i_AI->UpdateAI(diff);
424 m_AI_locked = false;
427 // creature can be dead after UpdateAI call
428 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
429 if(!isAlive())
430 break;
431 if(m_regenTimer > 0)
433 if(diff >= m_regenTimer)
434 m_regenTimer = 0;
435 else
436 m_regenTimer -= diff;
438 if (m_regenTimer != 0)
439 break;
441 if (!isInCombat() || IsPolymorphed())
442 RegenerateHealth();
444 RegenerateMana();
446 m_regenTimer = 2000;
447 break;
449 case DEAD_FALLING:
451 if (!FallGround())
452 setDeathState(JUST_DIED);
454 default:
455 break;
459 void Creature::RegenerateMana()
461 uint32 curValue = GetPower(POWER_MANA);
462 uint32 maxValue = GetMaxPower(POWER_MANA);
464 if (curValue >= maxValue)
465 return;
467 uint32 addvalue = 0;
469 // Combat and any controlled creature
470 if (isInCombat() || GetCharmerOrOwnerGUID())
472 if(!IsUnderLastManaUseEffect())
474 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
475 float Spirit = GetStat(STAT_SPIRIT);
477 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
480 else
481 addvalue = maxValue/3;
483 ModifyPower(POWER_MANA, addvalue);
486 void Creature::RegenerateHealth()
488 if (!isRegeneratingHealth())
489 return;
491 uint32 curValue = GetHealth();
492 uint32 maxValue = GetMaxHealth();
494 if (curValue >= maxValue)
495 return;
497 uint32 addvalue = 0;
499 // Not only pet, but any controlled creature
500 if(GetCharmerOrOwnerGUID())
502 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
503 float Spirit = GetStat(STAT_SPIRIT);
505 if( GetPower(POWER_MANA) > 0 )
506 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
507 else
508 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
510 else
511 addvalue = maxValue/3;
513 ModifyHealth(addvalue);
516 bool Creature::AIM_Initialize()
518 // make sure nothing can change the AI during AI update
519 if(m_AI_locked)
521 sLog.outDebug("AIM_Initialize: failed to init, locked.");
522 return false;
525 CreatureAI * oldAI = i_AI;
526 i_motionMaster.Initialize();
527 i_AI = FactorySelector::selectAI(this);
528 if (oldAI)
529 delete oldAI;
530 return true;
533 bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
535 SetMapId(map->GetId());
536 SetInstanceId(map->GetInstanceId());
538 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
539 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
541 if (bResult)
543 switch (GetCreatureInfo()->rank)
545 case CREATURE_ELITE_RARE:
546 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
547 break;
548 case CREATURE_ELITE_ELITE:
549 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
550 break;
551 case CREATURE_ELITE_RAREELITE:
552 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
553 break;
554 case CREATURE_ELITE_WORLDBOSS:
555 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
556 break;
557 default:
558 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
559 break;
561 LoadCreaturesAddon();
564 return bResult;
567 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
569 if(!isTrainer())
570 return false;
572 TrainerSpellData const* trainer_spells = GetTrainerSpells();
574 if(!trainer_spells || trainer_spells->spellList.empty())
576 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
577 GetGUIDLow(),GetEntry());
578 return false;
581 switch(GetCreatureInfo()->trainer_type)
583 case TRAINER_TYPE_CLASS:
584 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
586 if(msg)
588 pPlayer->PlayerTalkClass->ClearMenus();
589 switch(GetCreatureInfo()->classNum)
591 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
592 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
593 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
594 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
595 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
596 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
597 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
598 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
599 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
602 return false;
604 break;
605 case TRAINER_TYPE_PETS:
606 if(pPlayer->getClass()!=CLASS_HUNTER)
608 pPlayer->PlayerTalkClass->ClearMenus();
609 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
610 return false;
612 break;
613 case TRAINER_TYPE_MOUNTS:
614 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
616 if(msg)
618 pPlayer->PlayerTalkClass->ClearMenus();
619 switch(GetCreatureInfo()->classNum)
621 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
622 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
623 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
624 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
625 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
626 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
627 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
628 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
629 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
630 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
633 return false;
635 break;
636 case TRAINER_TYPE_TRADESKILLS:
637 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
639 if(msg)
641 pPlayer->PlayerTalkClass->ClearMenus();
642 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
644 return false;
646 break;
647 default:
648 return false; // checked and error output at creature_template loading
650 return true;
653 bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
655 if(!isBattleMaster())
656 return false;
658 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
659 if(!msg)
660 return pPlayer->GetBGAccessByLevel(bgTypeId);
662 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
664 pPlayer->PlayerTalkClass->ClearMenus();
665 switch(bgTypeId)
667 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
668 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
669 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
670 case BATTLEGROUND_EY:
671 case BATTLEGROUND_NA:
672 case BATTLEGROUND_BE:
673 case BATTLEGROUND_AA:
674 case BATTLEGROUND_RL:
675 case BATTLEGROUND_SA:
676 case BATTLEGROUND_DS:
677 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
678 default: break;
680 return false;
682 return true;
685 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
687 return pPlayer->getLevel() >= 10
688 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
689 && pPlayer->getClass() == GetCreatureInfo()->classNum;
692 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
694 PlayerMenu* pm=pPlayer->PlayerTalkClass;
695 pm->ClearMenus();
697 // lazy loading single time at use
698 LoadGossipOptions();
700 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
702 GossipOption* gso=&*i;
703 if(gso->GossipId == gossipid)
705 bool cantalking=true;
706 if(gso->Id==1)
708 uint32 textid=GetNpcTextId();
709 GossipText * gossiptext=objmgr.GetGossipText(textid);
710 if(!gossiptext)
711 cantalking=false;
713 else
715 switch (gso->Action)
717 case GOSSIP_OPTION_QUESTGIVER:
718 pPlayer->PrepareQuestMenu(GetGUID());
719 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
720 cantalking=false;
721 //pm->GetQuestMenu()->ClearMenu();
722 break;
723 case GOSSIP_OPTION_ARMORER:
724 cantalking=false; // added in special mode
725 break;
726 case GOSSIP_OPTION_SPIRITHEALER:
727 if( !pPlayer->isDead() )
728 cantalking=false;
729 break;
730 case GOSSIP_OPTION_VENDOR:
732 VendorItemData const* vItems = GetVendorItems();
733 if(!vItems || vItems->Empty())
735 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
736 GetGUIDLow(),GetEntry());
737 cantalking=false;
739 break;
741 case GOSSIP_OPTION_TRAINER:
742 if(!isCanTrainingOf(pPlayer,false))
743 cantalking=false;
744 break;
745 case GOSSIP_OPTION_UNLEARNTALENTS:
746 if(!isCanTrainingAndResetTalentsOf(pPlayer))
747 cantalking=false;
748 break;
749 case GOSSIP_OPTION_UNLEARNPETSKILLS:
750 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
751 cantalking=false;
752 break;
753 case GOSSIP_OPTION_TAXIVENDOR:
754 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
755 return;
756 break;
757 case GOSSIP_OPTION_BATTLEFIELD:
758 if(!isCanIneractWithBattleMaster(pPlayer,false))
759 cantalking=false;
760 break;
761 case GOSSIP_OPTION_SPIRITGUIDE:
762 case GOSSIP_OPTION_INNKEEPER:
763 case GOSSIP_OPTION_BANKER:
764 case GOSSIP_OPTION_PETITIONER:
765 case GOSSIP_OPTION_STABLEPET:
766 case GOSSIP_OPTION_TABARDDESIGNER:
767 case GOSSIP_OPTION_AUCTIONEER:
768 break; // no checks
769 default:
770 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
771 break;
775 //note for future dev: should have database fields for BoxMessage & BoxMoney
776 if(!gso->OptionText.empty() && cantalking)
778 std::string OptionText = gso->OptionText;
779 std::string BoxText = gso->BoxText;
780 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
781 if (loc_idx >= 0)
783 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
784 if (no)
786 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
787 OptionText=no->OptionText[loc_idx];
788 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
789 BoxText=no->BoxText[loc_idx];
792 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
797 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
798 if(pm->Empty())
800 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
802 isCanTrainingOf(pPlayer,true); // output error message if need
804 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
806 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
811 void Creature::sendPreparedGossip(Player* player)
813 if(!player)
814 return;
816 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
818 // in case empty gossip menu open quest menu if any
819 if (gossipmenu.Empty() && GetNpcTextId() == 0)
821 player->SendPreparedQuest(GetGUID());
822 return;
825 // in case non empty gossip menu (that not included quests list size) show it
826 // (quest entries from quest menu will be included in list)
827 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
830 void Creature::OnGossipSelect(Player* player, uint32 option)
832 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
834 if(option >= gossipmenu.MenuItemCount())
835 return;
837 uint32 action=gossipmenu.GetItem(option).m_gAction;
838 uint32 zoneid=GetZoneId();
839 uint64 guid=GetGUID();
841 GossipOption const *gossip=GetGossipOption( action );
842 if(!gossip)
844 zoneid=0;
845 gossip=GetGossipOption( action );
846 if(!gossip)
847 return;
850 switch (gossip->Action)
852 case GOSSIP_OPTION_GOSSIP:
854 uint32 textid = GetGossipTextId(action, zoneid);
855 if (textid == 0)
856 textid=GetNpcTextId();
858 player->PlayerTalkClass->CloseGossip();
859 player->PlayerTalkClass->SendTalking(textid);
860 break;
862 case GOSSIP_OPTION_SPIRITHEALER:
863 if (player->isDead())
864 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
865 break;
866 case GOSSIP_OPTION_QUESTGIVER:
867 player->PrepareQuestMenu( guid );
868 player->SendPreparedQuest( guid );
869 break;
870 case GOSSIP_OPTION_VENDOR:
871 case GOSSIP_OPTION_ARMORER:
872 player->GetSession()->SendListInventory(guid);
873 break;
874 case GOSSIP_OPTION_STABLEPET:
875 player->GetSession()->SendStablePet(guid);
876 break;
877 case GOSSIP_OPTION_TRAINER:
878 player->GetSession()->SendTrainerList(guid);
879 break;
880 case GOSSIP_OPTION_UNLEARNTALENTS:
881 player->PlayerTalkClass->CloseGossip();
882 player->SendTalentWipeConfirm(guid);
883 break;
884 case GOSSIP_OPTION_UNLEARNPETSKILLS:
885 player->PlayerTalkClass->CloseGossip();
886 player->SendPetSkillWipeConfirm();
887 break;
888 case GOSSIP_OPTION_TAXIVENDOR:
889 player->GetSession()->SendTaxiMenu(this);
890 break;
891 case GOSSIP_OPTION_INNKEEPER:
892 player->PlayerTalkClass->CloseGossip();
893 player->SetBindPoint( guid );
894 break;
895 case GOSSIP_OPTION_BANKER:
896 player->GetSession()->SendShowBank( guid );
897 break;
898 case GOSSIP_OPTION_PETITIONER:
899 player->PlayerTalkClass->CloseGossip();
900 player->GetSession()->SendPetitionShowList( guid );
901 break;
902 case GOSSIP_OPTION_TABARDDESIGNER:
903 player->PlayerTalkClass->CloseGossip();
904 player->GetSession()->SendTabardVendorActivate( guid );
905 break;
906 case GOSSIP_OPTION_AUCTIONEER:
907 player->GetSession()->SendAuctionHello( guid, this );
908 break;
909 case GOSSIP_OPTION_SPIRITGUIDE:
910 case GOSSIP_GUARD_SPELLTRAINER:
911 case GOSSIP_GUARD_SKILLTRAINER:
912 prepareGossipMenu( player,gossip->Id );
913 sendPreparedGossip( player );
914 break;
915 case GOSSIP_OPTION_BATTLEFIELD:
917 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
918 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
919 break;
921 default:
922 OnPoiSelect( player, gossip );
923 break;
928 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
930 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
932 Poi_Icon icon = ICON_POI_0;
933 //need add more case.
934 switch(gossip->Action)
936 case GOSSIP_GUARD_BANK:
937 icon=ICON_POI_HOUSE;
938 break;
939 case GOSSIP_GUARD_RIDE:
940 icon=ICON_POI_RWHORSE;
941 break;
942 case GOSSIP_GUARD_GUILD:
943 icon=ICON_POI_BLUETOWER;
944 break;
945 default:
946 icon=ICON_POI_TOWER;
947 break;
949 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
950 player->PlayerTalkClass->SendTalking(textid);
951 // std::string areaname= gossip->OptionText;
952 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
956 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
958 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
960 if(!result)
961 return 0;
963 Field *fields = result->Fetch();
964 uint32 id = fields[0].GetUInt32();
966 delete result;
968 return id;
971 uint32 Creature::GetNpcTextId()
973 if (!m_DBTableGuid)
974 return DEFAULT_GOSSIP_MESSAGE;
976 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
977 return pos;
979 return DEFAULT_GOSSIP_MESSAGE;
982 GossipOption const* Creature::GetGossipOption( uint32 id ) const
984 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
986 if(i->Action==id )
987 return &*i;
989 return NULL;
992 void Creature::LoadGossipOptions()
994 if(m_gossipOptionLoaded)
995 return;
997 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
999 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1000 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1001 if(i->NpcFlag & npcflags)
1002 addGossipOption(*i);
1004 m_gossipOptionLoaded = true;
1007 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1009 /* uint32 timeElap = getMSTime();
1010 if ((timeElap - m_startMove) < m_moveTime)
1012 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1013 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1015 else
1017 oX = dX;
1018 oY = dY;
1021 dX = x;
1022 dY = y;
1023 m_orientation = atan2((oY - dY), (oX - dX));
1025 m_startMove = getMSTime();
1026 m_moveTime = time;*/
1027 SendMonsterMove(x, y, z, type, MovementFlags, time);
1030 Player *Creature::GetLootRecipient() const
1032 if (!m_lootRecipient) return NULL;
1033 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1036 void Creature::SetLootRecipient(Unit *unit)
1038 // set the player whose group should receive the right
1039 // to loot the creature after it dies
1040 // should be set to NULL after the loot disappears
1042 if (!unit)
1044 m_lootRecipient = 0;
1045 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1046 return;
1049 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1050 if(!player) // normal creature, no player involved
1051 return;
1053 m_lootRecipient = player->GetGUID();
1054 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1057 void Creature::SaveToDB()
1059 // this should only be used when the creature has already been loaded
1060 // preferably after adding to map, because mapid may not be valid otherwise
1061 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1062 if(!data)
1064 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1065 return;
1068 SaveToDB(GetMapId(), data->spawnMask);
1071 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1073 // update in loaded data
1074 if (!m_DBTableGuid)
1075 m_DBTableGuid = GetGUIDLow();
1076 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1078 uint32 displayId = GetNativeDisplayId();
1080 // check if it's a custom model and if not, use 0 for displayId
1081 CreatureInfo const *cinfo = GetCreatureInfo();
1082 if(cinfo)
1084 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1086 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1087 if(!minfo || displayId != minfo->modelid_other_gender)
1089 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1090 if(minfo && displayId == minfo->modelid_other_gender)
1091 displayId = 0;
1093 else
1094 displayId = 0;
1096 else
1097 displayId = 0;
1100 // data->guid = guid don't must be update at save
1101 data.id = GetEntry();
1102 data.mapid = mapid;
1103 data.displayid = displayId;
1104 data.equipmentId = GetEquipmentId();
1105 data.posX = GetPositionX();
1106 data.posY = GetPositionY();
1107 data.posZ = GetPositionZ();
1108 data.orientation = GetOrientation();
1109 data.spawntimesecs = m_respawnDelay;
1110 // prevent add data integrity problems
1111 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1112 data.currentwaypoint = 0;
1113 data.curhealth = GetHealth();
1114 data.curmana = GetPower(POWER_MANA);
1115 data.is_dead = m_isDeadByDefault;
1116 // prevent add data integrity problems
1117 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1118 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1119 data.spawnMask = spawnMask;
1121 // updated in DB
1122 WorldDatabase.BeginTransaction();
1124 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1126 std::ostringstream ss;
1127 ss << "INSERT INTO creature VALUES ("
1128 << m_DBTableGuid << ","
1129 << GetEntry() << ","
1130 << mapid <<","
1131 << (uint32)spawnMask << ","
1132 << displayId <<","
1133 << GetEquipmentId() <<","
1134 << GetPositionX() << ","
1135 << GetPositionY() << ","
1136 << GetPositionZ() << ","
1137 << GetOrientation() << ","
1138 << m_respawnDelay << "," //respawn time
1139 << (float) m_respawnradius << "," //spawn distance (float)
1140 << (uint32) (0) << "," //currentwaypoint
1141 << GetHealth() << "," //curhealth
1142 << GetPower(POWER_MANA) << "," //curmana
1143 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1144 << GetDefaultMovementType() << ")"; //default movement generator type
1146 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1148 WorldDatabase.CommitTransaction();
1151 void Creature::SelectLevel(const CreatureInfo *cinfo)
1153 uint32 rank = isPet()? 0 : cinfo->rank;
1155 // level
1156 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1157 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1158 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1159 SetLevel(level);
1161 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1163 // health
1164 float healthmod = _GetHealthMod(rank);
1166 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1167 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1168 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1170 SetCreateHealth(health);
1171 SetMaxHealth(health);
1172 SetHealth(health);
1174 // mana
1175 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1176 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1177 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1179 SetCreateMana(mana);
1180 SetMaxPower(POWER_MANA, mana); //MAX Mana
1181 SetPower(POWER_MANA, mana);
1183 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1184 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1186 // damage
1187 float damagemod = _GetDamageMod(rank);
1189 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1190 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1192 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1193 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1195 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1198 float Creature::_GetHealthMod(int32 Rank)
1200 switch (Rank) // define rates for each elite rank
1202 case CREATURE_ELITE_NORMAL:
1203 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1204 case CREATURE_ELITE_ELITE:
1205 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1206 case CREATURE_ELITE_RAREELITE:
1207 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1208 case CREATURE_ELITE_WORLDBOSS:
1209 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1210 case CREATURE_ELITE_RARE:
1211 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1212 default:
1213 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1217 float Creature::_GetDamageMod(int32 Rank)
1219 switch (Rank) // define rates for each elite rank
1221 case CREATURE_ELITE_NORMAL:
1222 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1223 case CREATURE_ELITE_ELITE:
1224 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1225 case CREATURE_ELITE_RAREELITE:
1226 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1227 case CREATURE_ELITE_WORLDBOSS:
1228 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1229 case CREATURE_ELITE_RARE:
1230 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1231 default:
1232 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1236 float Creature::GetSpellDamageMod(int32 Rank)
1238 switch (Rank) // define rates for each elite rank
1240 case CREATURE_ELITE_NORMAL:
1241 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1242 case CREATURE_ELITE_ELITE:
1243 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1244 case CREATURE_ELITE_RAREELITE:
1245 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1246 case CREATURE_ELITE_WORLDBOSS:
1247 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1248 case CREATURE_ELITE_RARE:
1249 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1250 default:
1251 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1255 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1257 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1258 if(!cinfo)
1260 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1261 return false;
1263 m_originalEntry = Entry;
1265 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1267 if(!UpdateEntry(Entry, team, data))
1268 return false;
1270 //Notify the map's instance data.
1271 //Only works if you create the object in it, not if it is moves to that map.
1272 //Normally non-players do not teleport to other maps.
1273 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1274 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1276 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1279 return true;
1282 bool Creature::LoadFromDB(uint32 guid, Map *map)
1284 CreatureData const* data = objmgr.GetCreatureData(guid);
1286 if(!data)
1288 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1289 return false;
1292 m_DBTableGuid = guid;
1293 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1295 uint16 team = 0;
1296 if(!Create(guid,map,data->id,team,data))
1297 return false;
1299 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1301 if(!IsPositionValid())
1303 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1304 return false;
1307 m_respawnradius = data->spawndist;
1309 m_respawnDelay = data->spawntimesecs;
1310 m_isDeadByDefault = data->is_dead;
1311 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1313 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1314 if(m_respawnTime > time(NULL)) // not ready to respawn
1316 m_deathState = DEAD;
1317 if(canFly())
1319 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1320 if(data->posZ - tz > 0.1)
1321 Relocate(data->posX,data->posY,tz);
1324 else if(m_respawnTime) // respawn time set but expired
1326 m_respawnTime = 0;
1327 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1330 uint32 curhealth = data->curhealth;
1331 if(curhealth)
1333 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1334 if(curhealth < 1)
1335 curhealth = 1;
1338 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1339 SetPower(POWER_MANA,data->curmana);
1341 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1343 // checked at creature_template loading
1344 m_defaultMovementType = MovementGeneratorType(data->movementType);
1346 AIM_Initialize();
1347 return true;
1350 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1352 if(equip_entry == 0)
1354 if (force)
1356 for (uint8 i = 0; i < 3; i++)
1357 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1358 m_equipmentId = 0;
1360 return;
1363 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1364 if (!einfo)
1365 return;
1367 m_equipmentId = equip_entry;
1368 for (uint8 i = 0; i < 3; i++)
1369 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1372 bool Creature::hasQuest(uint32 quest_id) const
1374 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1375 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1377 if(itr->second==quest_id)
1378 return true;
1380 return false;
1383 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1385 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1386 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1388 if(itr->second==quest_id)
1389 return true;
1391 return false;
1394 void Creature::DeleteFromDB()
1396 if (!m_DBTableGuid)
1398 sLog.outDebug("Trying to delete not saved creature!");
1399 return;
1402 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1403 objmgr.DeleteCreatureData(m_DBTableGuid);
1405 WorldDatabase.BeginTransaction();
1406 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1407 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1408 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1409 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1410 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1411 WorldDatabase.CommitTransaction();
1414 float Creature::GetAttackDistance(Unit const* pl) const
1416 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1417 if(aggroRate==0)
1418 return 0.0f;
1420 int32 playerlevel = pl->getLevelForTarget(this);
1421 int32 creaturelevel = getLevelForTarget(pl);
1423 int32 leveldif = playerlevel - creaturelevel;
1425 // "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."
1426 if ( leveldif < - 25)
1427 leveldif = -25;
1429 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1430 float RetDistance = 20;
1432 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1433 // radius grow if playlevel < creaturelevel
1434 RetDistance -= (float)leveldif;
1436 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1438 // detect range auras
1439 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1441 // detected range auras
1442 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1445 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1446 if(RetDistance < 5)
1447 RetDistance = 5;
1449 return (RetDistance*aggroRate);
1452 void Creature::setDeathState(DeathState s)
1454 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1456 m_deathTimer = m_corpseDelay*1000;
1458 // always save boss respawn time at death to prevent crash cheating
1459 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1460 SaveRespawnTime();
1462 if (canFly() && FallGround())
1463 return;
1465 if(!IsStopped())
1466 StopMoving();
1468 Unit::setDeathState(s);
1470 if(s == JUST_DIED)
1472 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1473 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1475 if(!isPet() && GetCreatureInfo()->SkinLootId)
1476 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1477 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1479 if (canFly() && FallGround())
1480 return;
1482 Unit::setDeathState(CORPSE);
1484 if(s == JUST_ALIVED)
1486 SetHealth(GetMaxHealth());
1487 SetLootRecipient(NULL);
1488 Unit::setDeathState(ALIVE);
1489 CreatureInfo const *cinfo = GetCreatureInfo();
1490 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1491 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1492 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1493 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1494 clearUnitState(UNIT_STAT_ALL_STATE);
1495 i_motionMaster.Clear();
1496 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1497 LoadCreaturesAddon(true);
1501 bool Creature::FallGround()
1503 // Let's abort after we called this function one time
1504 if (getDeathState() == DEAD_FALLING)
1505 return false;
1507 // Let's do with no vmap because no way to get far distance with vmap high call
1508 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1510 // Abort too if the ground is very near
1511 if (fabs(GetPositionZ() - tz) < 0.1f)
1512 return false;
1514 Unit::setDeathState(DEAD_FALLING);
1515 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1516 Relocate(GetPositionX(), GetPositionY(), tz);
1517 return true;
1520 void Creature::Respawn()
1522 RemoveCorpse();
1524 // forced recreate creature object at clients
1525 UnitVisibility currentVis = GetVisibility();
1526 SetVisibility(VISIBILITY_RESPAWN);
1527 ObjectAccessor::UpdateObjectVisibility(this);
1528 SetVisibility(currentVis); // restore visibility state
1529 ObjectAccessor::UpdateObjectVisibility(this);
1531 if(getDeathState()==DEAD)
1533 if (m_DBTableGuid)
1534 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1535 m_respawnTime = time(NULL); // respawn at next tick
1539 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1541 if (!spellInfo)
1542 return false;
1544 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1545 return true;
1547 return Unit::IsImmunedToSpell(spellInfo);
1550 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1552 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1553 return true;
1555 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1558 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1560 if(!pVictim)
1561 return NULL;
1563 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1565 if(!m_spells[i])
1566 continue;
1567 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1568 if(!spellInfo)
1570 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1571 continue;
1574 bool bcontinue = true;
1575 for(uint32 j=0;j<3;j++)
1577 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1578 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1579 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1580 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1583 bcontinue = false;
1584 break;
1587 if(bcontinue) continue;
1589 if(spellInfo->manaCost > GetPower(POWER_MANA))
1590 continue;
1591 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1592 float range = GetSpellMaxRange(srange);
1593 float minrange = GetSpellMinRange(srange);
1594 float dist = GetDistance(pVictim);
1595 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1596 // continue;
1597 if( dist > range || dist < minrange )
1598 continue;
1599 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1600 continue;
1601 return spellInfo;
1603 return NULL;
1606 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1608 if(!pVictim)
1609 return NULL;
1611 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1613 if(!m_spells[i])
1614 continue;
1615 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1616 if(!spellInfo)
1618 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1619 continue;
1622 bool bcontinue = true;
1623 for(uint32 j=0;j<3;j++)
1625 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1627 bcontinue = false;
1628 break;
1631 if(bcontinue) continue;
1633 if(spellInfo->manaCost > GetPower(POWER_MANA))
1634 continue;
1635 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1636 float range = GetSpellMaxRange(srange);
1637 float minrange = GetSpellMinRange(srange);
1638 float dist = GetDistance(pVictim);
1639 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1640 // continue;
1641 if( dist > range || dist < minrange )
1642 continue;
1643 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1644 continue;
1645 return spellInfo;
1647 return NULL;
1650 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1652 // gamemaster in GM mode see all, including ghosts
1653 if(pl->isGameMaster())
1654 return true;
1656 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1657 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1659 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1660 return false;
1661 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1664 // Dead player see live creatures near own corpse
1665 if(isAlive())
1667 Corpse *corpse = pl->GetCorpse();
1668 if(corpse)
1670 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1671 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1672 return true;
1676 // Dead player see Spirit Healer or Spirit Guide
1677 if(isSpiritService())
1678 return true;
1680 // and not see any other
1681 return false;
1684 void Creature::CallAssistance()
1686 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1688 SetNoCallAssistance(true);
1690 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1691 if(radius > 0)
1693 std::list<Creature*> assistList;
1696 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1697 Cell cell(p);
1698 cell.data.Part.reserved = ALL_DISTRICT;
1699 cell.SetNoCreate();
1701 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1702 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1704 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1706 CellLock<GridReadGuard> cell_lock(cell, p);
1707 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1710 if (!assistList.empty())
1712 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1713 while (!assistList.empty())
1715 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1716 e->AddAssistant((*assistList.begin())->GetGUID());
1717 assistList.pop_front();
1719 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1725 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1727 // we don't need help from zombies :)
1728 if( !isAlive() )
1729 return false;
1731 // skip fighting creature
1732 if( isInCombat() )
1733 return false;
1735 // only from same creature faction
1736 if(getFaction() != u->getFaction() )
1737 return false;
1739 // only free creature
1740 if( GetCharmerOrOwnerGUID() )
1741 return false;
1743 // skip non hostile to caster enemy creatures
1744 if( !IsHostileTo(enemy) )
1745 return false;
1747 return true;
1750 void Creature::SaveRespawnTime()
1752 if(isPet() || !m_DBTableGuid)
1753 return;
1755 if(m_respawnTime > time(NULL)) // dead (no corpse)
1756 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1757 else if(m_deathTimer > 0) // dead (corpse)
1758 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1761 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1763 if(!pVictim)
1764 return true;
1766 if(!pVictim->IsInMap(this))
1767 return true;
1769 if(!pVictim->isTargetableForAttack())
1770 return true;
1772 if(!pVictim->isInAccessablePlaceFor(this))
1773 return true;
1775 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1776 return false;
1778 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1779 float AttackDist = GetAttackDistance(pVictim);
1780 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1782 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1783 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1786 CreatureDataAddon const* Creature::GetCreatureAddon() const
1788 if (m_DBTableGuid)
1790 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1791 return addon;
1794 // dependent from heroic mode entry
1795 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1798 //creature_addon table
1799 bool Creature::LoadCreaturesAddon(bool reload)
1801 CreatureDataAddon const *cainfo = GetCreatureAddon();
1802 if(!cainfo)
1803 return false;
1805 if (cainfo->mount != 0)
1806 Mount(cainfo->mount);
1808 if (cainfo->bytes0 != 0)
1809 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1811 if (cainfo->bytes1 != 0)
1812 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1814 if (cainfo->bytes2 != 0)
1815 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1817 if (cainfo->emote != 0)
1818 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1820 if (cainfo->move_flags != 0)
1821 SetUnitMovementFlags(cainfo->move_flags);
1823 if(cainfo->auras)
1825 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1827 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1828 if (!AdditionalSpellInfo)
1830 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1831 continue;
1834 // skip already applied aura
1835 if(HasAura(cAura->spell_id,cAura->effect_idx))
1837 if(!reload)
1838 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);
1840 continue;
1843 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1844 AddAura(AdditionalAura);
1845 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1848 return true;
1851 /// Send a message to LocalDefense channel for players opposition team in the zone
1852 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1854 uint32 enemy_team = attacker->GetTeam();
1856 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1857 data << (uint32)GetZoneId();
1858 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1861 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1863 m_CreatureSpellCooldowns[spell_id] = end_time;
1866 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1868 m_CreatureCategoryCooldowns[category] = apply_time;
1871 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1873 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1874 if(!spellInfo)
1875 return;
1877 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1878 if(cooldown)
1879 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1881 if(spellInfo->Category)
1882 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1884 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1887 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1889 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1890 if(!spellInfo)
1891 return false;
1893 // check global cooldown if spell affected by it
1894 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1895 return true;
1897 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1898 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1901 bool Creature::HasSpellCooldown(uint32 spell_id) const
1903 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1904 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1907 bool Creature::IsInEvadeMode() const
1909 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1912 bool Creature::HasSpell(uint32 spellID) const
1914 uint8 i;
1915 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1916 if(spellID == m_spells[i])
1917 break;
1918 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1921 time_t Creature::GetRespawnTimeEx() const
1923 time_t now = time(NULL);
1924 if(m_respawnTime > now) // dead (no corpse)
1925 return m_respawnTime;
1926 else if(m_deathTimer > 0) // dead (corpse)
1927 return now+m_respawnDelay+m_deathTimer/1000;
1928 else
1929 return now;
1932 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1934 if (m_DBTableGuid)
1936 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1938 x = data->posX;
1939 y = data->posY;
1940 z = data->posZ;
1941 if(ori)
1942 *ori = data->orientation;
1943 if(dist)
1944 *dist = data->spawndist;
1946 return;
1950 x = GetPositionX();
1951 y = GetPositionY();
1952 z = GetPositionZ();
1953 if(ori)
1954 *ori = GetOrientation();
1955 if(dist)
1956 *dist = 0;
1959 void Creature::AllLootRemovedFromCorpse()
1961 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1963 uint32 nDeathTimer;
1965 CreatureInfo const *cinfo = GetCreatureInfo();
1967 // corpse was not skinnable -> apply corpse looted timer
1968 if (!cinfo || !cinfo->SkinLootId)
1969 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1970 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1971 else
1972 nDeathTimer = 0;
1974 // update death timer only if looted timer is shorter
1975 if (m_deathTimer > nDeathTimer)
1976 m_deathTimer = nDeathTimer;
1980 uint32 Creature::getLevelForTarget( Unit const* target ) const
1982 if(!isWorldBoss())
1983 return Unit::getLevelForTarget(target);
1985 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1986 if(level < 1)
1987 return 1;
1988 if(level > 255)
1989 return 255;
1990 return level;
1993 std::string Creature::GetScriptName()
1995 return objmgr.GetScriptName(GetScriptId());
1998 uint32 Creature::GetScriptId()
2000 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2003 VendorItemData const* Creature::GetVendorItems() const
2005 return objmgr.GetNpcVendorItemList(GetEntry());
2008 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2010 if(!vItem->maxcount)
2011 return vItem->maxcount;
2013 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2014 for(; itr != m_vendorItemCounts.end(); ++itr)
2015 if(itr->itemId==vItem->item)
2016 break;
2018 if(itr == m_vendorItemCounts.end())
2019 return vItem->maxcount;
2021 VendorItemCount* vCount = &*itr;
2023 time_t ptime = time(NULL);
2025 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2027 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2029 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2030 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2032 m_vendorItemCounts.erase(itr);
2033 return vItem->maxcount;
2036 vCount->count += diff * pProto->BuyCount;
2037 vCount->lastIncrementTime = ptime;
2040 return vCount->count;
2043 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2045 if(!vItem->maxcount)
2046 return 0;
2048 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2049 for(; itr != m_vendorItemCounts.end(); ++itr)
2050 if(itr->itemId==vItem->item)
2051 break;
2053 if(itr == m_vendorItemCounts.end())
2055 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2056 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2057 return new_count;
2060 VendorItemCount* vCount = &*itr;
2062 time_t ptime = time(NULL);
2064 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2066 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2068 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2069 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2070 vCount->count += diff * pProto->BuyCount;
2071 else
2072 vCount->count = vItem->maxcount;
2075 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2076 vCount->lastIncrementTime = ptime;
2077 return vCount->count;
2080 TrainerSpellData const* Creature::GetTrainerSpells() const
2082 return objmgr.GetNpcTrainerSpells(GetEntry());
2085 // overwrite WorldObject function for proper name localization
2086 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2088 if (loc_idx >= 0)
2090 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2091 if (cl)
2093 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2094 return cl->Name[loc_idx].c_str();
2098 return GetName();