[6922] Whitespace and newline fixes
[getmangos.git] / src / game / Creature.cpp
blob8ab1b3258815515d996cce6cfd9732f8545102b1
1 /*
2 * Copyright (C) 2005-2008 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),
121 m_regenTimer(2000), 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_valuesCount = UNIT_END;
127 for(int i =0; i<4; ++i)
128 m_spells[i] = 0;
130 m_CreatureSpellCooldowns.clear();
131 m_CreatureCategoryCooldowns.clear();
132 m_GlobalCooldown = 0;
133 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
136 Creature::~Creature()
138 CleanupsBeforeDelete();
140 m_vendorItemCounts.clear();
142 delete i_AI;
143 i_AI = NULL;
146 void Creature::AddToWorld()
148 ///- Register the creature for guid lookup
149 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
150 Unit::AddToWorld();
153 void Creature::RemoveFromWorld()
155 ///- Remove the creature from the accessor
156 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
157 Unit::RemoveFromWorld();
160 void Creature::RemoveCorpse()
162 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
163 return;
165 m_deathTimer = 0;
166 setDeathState(DEAD);
167 ObjectAccessor::UpdateObjectVisibility(this);
168 loot.clear();
169 m_respawnTime = time(NULL) + m_respawnDelay;
171 float x,y,z,o;
172 GetRespawnCoord(x, y, z, &o);
173 GetMap()->CreatureRelocation(this,x,y,z,o);
177 * change the entry of creature until respawn
179 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
181 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
182 if(!normalInfo)
184 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
185 return false;
188 // get heroic mode entry
189 uint32 actualEntry = Entry;
190 CreatureInfo const *cinfo = normalInfo;
191 if(normalInfo->HeroicEntry)
193 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
194 if(map && map->IsHeroic())
196 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
197 if(!cinfo)
199 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
200 return false;
205 SetEntry(Entry); // normal entry always
206 m_creatureInfo = cinfo; // map mode related always
208 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
210 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
211 return false;
214 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
215 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
216 if (!minfo)
218 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
219 return false;
221 else
222 display_id = minfo->modelid; // it can be different (for another gender)
224 SetDisplayId(display_id);
225 SetNativeDisplayId(display_id);
226 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
228 // Load creature equipment
229 if(!data || data->equipmentId == 0)
230 { // use default from the template
231 LoadEquipment(cinfo->equipmentId);
233 else if(data && data->equipmentId != -1)
234 { // override, -1 means no equipment
235 LoadEquipment(data->equipmentId);
238 SetName(normalInfo->Name); // at normal entry always
240 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
241 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
243 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
245 SetSpeed(MOVE_WALK, cinfo->speed );
246 SetSpeed(MOVE_RUN, cinfo->speed );
247 SetSpeed(MOVE_SWIM, cinfo->speed );
249 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
251 // checked at loading
252 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
253 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
254 m_defaultMovementType = IDLE_MOTION_TYPE;
256 return true;
259 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
261 if(!InitEntry(Entry,team,data))
262 return false;
264 m_regenHealth = GetCreatureInfo()->RegenHealth;
266 // creatures always have melee weapon ready if any
267 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
268 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_AURAS );
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: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
675 break;
677 return false;
679 return true;
682 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
684 return pPlayer->getLevel() >= 10
685 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
686 && pPlayer->getClass() == GetCreatureInfo()->classNum;
689 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
691 PlayerMenu* pm=pPlayer->PlayerTalkClass;
692 pm->ClearMenus();
694 // lazy loading single time at use
695 LoadGossipOptions();
697 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
699 GossipOption* gso=&*i;
700 if(gso->GossipId == gossipid)
702 bool cantalking=true;
703 if(gso->Id==1)
705 uint32 textid=GetNpcTextId();
706 GossipText * gossiptext=objmgr.GetGossipText(textid);
707 if(!gossiptext)
708 cantalking=false;
710 else
712 switch (gso->Action)
714 case GOSSIP_OPTION_QUESTGIVER:
715 pPlayer->PrepareQuestMenu(GetGUID());
716 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
717 cantalking=false;
718 //pm->GetQuestMenu()->ClearMenu();
719 break;
720 case GOSSIP_OPTION_ARMORER:
721 cantalking=false; // added in special mode
722 break;
723 case GOSSIP_OPTION_SPIRITHEALER:
724 if( !pPlayer->isDead() )
725 cantalking=false;
726 break;
727 case GOSSIP_OPTION_VENDOR:
729 VendorItemData const* vItems = GetVendorItems();
730 if(!vItems || vItems->Empty())
732 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
733 GetGUIDLow(),GetEntry());
734 cantalking=false;
736 break;
738 case GOSSIP_OPTION_TRAINER:
739 if(!isCanTrainingOf(pPlayer,false))
740 cantalking=false;
741 break;
742 case GOSSIP_OPTION_UNLEARNTALENTS:
743 if(!isCanTrainingAndResetTalentsOf(pPlayer))
744 cantalking=false;
745 break;
746 case GOSSIP_OPTION_UNLEARNPETSKILLS:
747 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
748 cantalking=false;
749 break;
750 case GOSSIP_OPTION_TAXIVENDOR:
751 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
752 return;
753 break;
754 case GOSSIP_OPTION_BATTLEFIELD:
755 if(!isCanIneractWithBattleMaster(pPlayer,false))
756 cantalking=false;
757 break;
758 case GOSSIP_OPTION_SPIRITGUIDE:
759 case GOSSIP_OPTION_INNKEEPER:
760 case GOSSIP_OPTION_BANKER:
761 case GOSSIP_OPTION_PETITIONER:
762 case GOSSIP_OPTION_STABLEPET:
763 case GOSSIP_OPTION_TABARDDESIGNER:
764 case GOSSIP_OPTION_AUCTIONEER:
765 break; // no checks
766 default:
767 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
768 break;
772 //note for future dev: should have database fields for BoxMessage & BoxMoney
773 if(!gso->OptionText.empty() && cantalking)
775 std::string OptionText = gso->OptionText;
776 std::string BoxText = gso->BoxText;
777 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
778 if (loc_idx >= 0)
780 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
781 if (no)
783 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
784 OptionText=no->OptionText[loc_idx];
785 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
786 BoxText=no->BoxText[loc_idx];
789 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
794 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
795 if(pm->Empty())
797 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
799 isCanTrainingOf(pPlayer,true); // output error message if need
801 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
803 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
808 void Creature::sendPreparedGossip(Player* player)
810 if(!player)
811 return;
813 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
815 // in case empty gossip menu open quest menu if any
816 if (gossipmenu.Empty() && GetNpcTextId() == 0)
818 player->SendPreparedQuest(GetGUID());
819 return;
822 // in case non empty gossip menu (that not included quests list size) show it
823 // (quest entries from quest menu will be included in list)
824 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
827 void Creature::OnGossipSelect(Player* player, uint32 option)
829 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
831 if(option >= gossipmenu.MenuItemCount())
832 return;
834 uint32 action=gossipmenu.GetItem(option).m_gAction;
835 uint32 zoneid=GetZoneId();
836 uint64 guid=GetGUID();
838 GossipOption const *gossip=GetGossipOption( action );
839 if(!gossip)
841 zoneid=0;
842 gossip=GetGossipOption( action );
843 if(!gossip)
844 return;
847 switch (gossip->Action)
849 case GOSSIP_OPTION_GOSSIP:
851 uint32 textid = GetGossipTextId(action, zoneid);
852 if (textid == 0)
853 textid=GetNpcTextId();
855 player->PlayerTalkClass->CloseGossip();
856 player->PlayerTalkClass->SendTalking(textid);
857 break;
859 case GOSSIP_OPTION_SPIRITHEALER:
860 if (player->isDead())
861 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
862 break;
863 case GOSSIP_OPTION_QUESTGIVER:
864 player->PrepareQuestMenu( guid );
865 player->SendPreparedQuest( guid );
866 break;
867 case GOSSIP_OPTION_VENDOR:
868 case GOSSIP_OPTION_ARMORER:
869 player->GetSession()->SendListInventory(guid);
870 break;
871 case GOSSIP_OPTION_STABLEPET:
872 player->GetSession()->SendStablePet(guid);
873 break;
874 case GOSSIP_OPTION_TRAINER:
875 player->GetSession()->SendTrainerList(guid);
876 break;
877 case GOSSIP_OPTION_UNLEARNTALENTS:
878 player->PlayerTalkClass->CloseGossip();
879 player->SendTalentWipeConfirm(guid);
880 break;
881 case GOSSIP_OPTION_UNLEARNPETSKILLS:
882 player->PlayerTalkClass->CloseGossip();
883 player->SendPetSkillWipeConfirm();
884 break;
885 case GOSSIP_OPTION_TAXIVENDOR:
886 player->GetSession()->SendTaxiMenu(this);
887 break;
888 case GOSSIP_OPTION_INNKEEPER:
889 player->PlayerTalkClass->CloseGossip();
890 player->SetBindPoint( guid );
891 break;
892 case GOSSIP_OPTION_BANKER:
893 player->GetSession()->SendShowBank( guid );
894 break;
895 case GOSSIP_OPTION_PETITIONER:
896 player->PlayerTalkClass->CloseGossip();
897 player->GetSession()->SendPetitionShowList( guid );
898 break;
899 case GOSSIP_OPTION_TABARDDESIGNER:
900 player->PlayerTalkClass->CloseGossip();
901 player->GetSession()->SendTabardVendorActivate( guid );
902 break;
903 case GOSSIP_OPTION_AUCTIONEER:
904 player->GetSession()->SendAuctionHello( guid, this );
905 break;
906 case GOSSIP_OPTION_SPIRITGUIDE:
907 case GOSSIP_GUARD_SPELLTRAINER:
908 case GOSSIP_GUARD_SKILLTRAINER:
909 prepareGossipMenu( player,gossip->Id );
910 sendPreparedGossip( player );
911 break;
912 case GOSSIP_OPTION_BATTLEFIELD:
914 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
915 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
916 break;
918 default:
919 OnPoiSelect( player, gossip );
920 break;
925 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
927 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
929 Poi_Icon icon = ICON_POI_0;
930 //need add more case.
931 switch(gossip->Action)
933 case GOSSIP_GUARD_BANK:
934 icon=ICON_POI_HOUSE;
935 break;
936 case GOSSIP_GUARD_RIDE:
937 icon=ICON_POI_RWHORSE;
938 break;
939 case GOSSIP_GUARD_GUILD:
940 icon=ICON_POI_BLUETOWER;
941 break;
942 default:
943 icon=ICON_POI_TOWER;
944 break;
946 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
947 player->PlayerTalkClass->SendTalking(textid);
948 // std::string areaname= gossip->OptionText;
949 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
953 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
955 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
957 if(!result)
958 return 0;
960 Field *fields = result->Fetch();
961 uint32 id = fields[0].GetUInt32();
963 delete result;
965 return id;
968 uint32 Creature::GetNpcTextId()
970 if (!m_DBTableGuid)
971 return DEFAULT_GOSSIP_MESSAGE;
973 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
974 return pos;
976 return DEFAULT_GOSSIP_MESSAGE;
979 GossipOption const* Creature::GetGossipOption( uint32 id ) const
981 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
983 if(i->Action==id )
984 return &*i;
986 return NULL;
989 void Creature::LoadGossipOptions()
991 if(m_gossipOptionLoaded)
992 return;
994 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
996 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
997 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
998 if(i->NpcFlag & npcflags)
999 addGossipOption(*i);
1001 m_gossipOptionLoaded = true;
1004 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1006 /* uint32 timeElap = getMSTime();
1007 if ((timeElap - m_startMove) < m_moveTime)
1009 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1010 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1012 else
1014 oX = dX;
1015 oY = dY;
1018 dX = x;
1019 dY = y;
1020 m_orientation = atan2((oY - dY), (oX - dX));
1022 m_startMove = getMSTime();
1023 m_moveTime = time;*/
1024 SendMonsterMove(x, y, z, type, MovementFlags, time);
1027 Player *Creature::GetLootRecipient() const
1029 if (!m_lootRecipient) return NULL;
1030 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1033 void Creature::SetLootRecipient(Unit *unit)
1035 // set the player whose group should receive the right
1036 // to loot the creature after it dies
1037 // should be set to NULL after the loot disappears
1039 if (!unit)
1041 m_lootRecipient = 0;
1042 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1043 return;
1046 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1047 if(!player) // normal creature, no player involved
1048 return;
1050 m_lootRecipient = player->GetGUID();
1051 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1054 void Creature::SaveToDB()
1056 // this should only be used when the creature has already been loaded
1057 // preferably after adding to map, because mapid may not be valid otherwise
1058 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1059 if(!data)
1061 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1062 return;
1065 SaveToDB(GetMapId(), data->spawnMask);
1068 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1070 // update in loaded data
1071 if (!m_DBTableGuid)
1072 m_DBTableGuid = GetGUIDLow();
1073 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1075 uint32 displayId = GetNativeDisplayId();
1077 // check if it's a custom model and if not, use 0 for displayId
1078 CreatureInfo const *cinfo = GetCreatureInfo();
1079 if(cinfo)
1081 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1083 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1084 if(!minfo || displayId != minfo->modelid_other_gender)
1086 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1087 if(minfo && displayId == minfo->modelid_other_gender)
1088 displayId = 0;
1090 else
1091 displayId = 0;
1093 else
1094 displayId = 0;
1097 // data->guid = guid don't must be update at save
1098 data.id = GetEntry();
1099 data.mapid = mapid;
1100 data.displayid = displayId;
1101 data.equipmentId = GetEquipmentId();
1102 data.posX = GetPositionX();
1103 data.posY = GetPositionY();
1104 data.posZ = GetPositionZ();
1105 data.orientation = GetOrientation();
1106 data.spawntimesecs = m_respawnDelay;
1107 // prevent add data integrity problems
1108 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1109 data.currentwaypoint = 0;
1110 data.curhealth = GetHealth();
1111 data.curmana = GetPower(POWER_MANA);
1112 data.is_dead = m_isDeadByDefault;
1113 // prevent add data integrity problems
1114 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1115 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1116 data.spawnMask = spawnMask;
1118 // updated in DB
1119 WorldDatabase.BeginTransaction();
1121 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1123 std::ostringstream ss;
1124 ss << "INSERT INTO creature VALUES ("
1125 << m_DBTableGuid << ","
1126 << GetEntry() << ","
1127 << mapid <<","
1128 << (uint32)spawnMask << ","
1129 << displayId <<","
1130 << GetEquipmentId() <<","
1131 << GetPositionX() << ","
1132 << GetPositionY() << ","
1133 << GetPositionZ() << ","
1134 << GetOrientation() << ","
1135 << m_respawnDelay << "," //respawn time
1136 << (float) m_respawnradius << "," //spawn distance (float)
1137 << (uint32) (0) << "," //currentwaypoint
1138 << GetHealth() << "," //curhealth
1139 << GetPower(POWER_MANA) << "," //curmana
1140 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1141 << GetDefaultMovementType() << ")"; //default movement generator type
1143 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1145 WorldDatabase.CommitTransaction();
1148 void Creature::SelectLevel(const CreatureInfo *cinfo)
1150 uint32 rank = isPet()? 0 : cinfo->rank;
1152 // level
1153 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1154 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1155 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1156 SetLevel(level);
1158 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1160 // health
1161 float healthmod = _GetHealthMod(rank);
1163 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1164 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1165 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1167 SetCreateHealth(health);
1168 SetMaxHealth(health);
1169 SetHealth(health);
1171 // mana
1172 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1173 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1174 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1176 SetCreateMana(mana);
1177 SetMaxPower(POWER_MANA, mana); //MAX Mana
1178 SetPower(POWER_MANA, mana);
1180 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1181 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1183 // damage
1184 float damagemod = _GetDamageMod(rank);
1186 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1187 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1189 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1190 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1192 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1195 float Creature::_GetHealthMod(int32 Rank)
1197 switch (Rank) // define rates for each elite rank
1199 case CREATURE_ELITE_NORMAL:
1200 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1201 case CREATURE_ELITE_ELITE:
1202 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1203 case CREATURE_ELITE_RAREELITE:
1204 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1205 case CREATURE_ELITE_WORLDBOSS:
1206 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1207 case CREATURE_ELITE_RARE:
1208 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1209 default:
1210 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1214 float Creature::_GetDamageMod(int32 Rank)
1216 switch (Rank) // define rates for each elite rank
1218 case CREATURE_ELITE_NORMAL:
1219 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1220 case CREATURE_ELITE_ELITE:
1221 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1222 case CREATURE_ELITE_RAREELITE:
1223 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1224 case CREATURE_ELITE_WORLDBOSS:
1225 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1226 case CREATURE_ELITE_RARE:
1227 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1228 default:
1229 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1233 float Creature::GetSpellDamageMod(int32 Rank)
1235 switch (Rank) // define rates for each elite rank
1237 case CREATURE_ELITE_NORMAL:
1238 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1239 case CREATURE_ELITE_ELITE:
1240 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1241 case CREATURE_ELITE_RAREELITE:
1242 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1243 case CREATURE_ELITE_WORLDBOSS:
1244 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1245 case CREATURE_ELITE_RARE:
1246 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1247 default:
1248 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1252 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1254 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1255 if(!cinfo)
1257 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1258 return false;
1260 m_originalEntry = Entry;
1262 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1264 if(!UpdateEntry(Entry, team, data))
1265 return false;
1267 //Notify the map's instance data.
1268 //Only works if you create the object in it, not if it is moves to that map.
1269 //Normally non-players do not teleport to other maps.
1270 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1271 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1273 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1276 return true;
1279 bool Creature::LoadFromDB(uint32 guid, Map *map)
1281 CreatureData const* data = objmgr.GetCreatureData(guid);
1283 if(!data)
1285 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1286 return false;
1289 m_DBTableGuid = guid;
1290 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1292 uint16 team = 0;
1293 if(!Create(guid,map,data->id,team,data))
1294 return false;
1296 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1298 if(!IsPositionValid())
1300 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1301 return false;
1304 m_respawnradius = data->spawndist;
1306 m_respawnDelay = data->spawntimesecs;
1307 m_isDeadByDefault = data->is_dead;
1308 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1310 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1311 if(m_respawnTime > time(NULL)) // not ready to respawn
1313 m_deathState = DEAD;
1314 if(canFly())
1316 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1317 if(data->posZ - tz > 0.1)
1318 Relocate(data->posX,data->posY,tz);
1321 else if(m_respawnTime) // respawn time set but expired
1323 m_respawnTime = 0;
1324 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1327 uint32 curhealth = data->curhealth;
1328 if(curhealth)
1330 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1331 if(curhealth < 1)
1332 curhealth = 1;
1335 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1336 SetPower(POWER_MANA,data->curmana);
1338 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1340 // checked at creature_template loading
1341 m_defaultMovementType = MovementGeneratorType(data->movementType);
1343 AIM_Initialize();
1344 return true;
1347 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1349 if(equip_entry == 0)
1351 if (force)
1353 for (uint8 i = 0; i < 3; i++)
1355 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1356 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1357 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1359 m_equipmentId = 0;
1361 return;
1364 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1365 if (!einfo)
1366 return;
1368 m_equipmentId = equip_entry;
1369 for (uint8 i = 0; i < 3; i++)
1371 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1372 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1373 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1377 bool Creature::hasQuest(uint32 quest_id) const
1379 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1380 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1382 if(itr->second==quest_id)
1383 return true;
1385 return false;
1388 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1390 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1391 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1393 if(itr->second==quest_id)
1394 return true;
1396 return false;
1399 void Creature::DeleteFromDB()
1401 if (!m_DBTableGuid)
1403 sLog.outDebug("Trying to delete not saved creature!");
1404 return;
1407 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1408 objmgr.DeleteCreatureData(m_DBTableGuid);
1410 WorldDatabase.BeginTransaction();
1411 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1412 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1413 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1414 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1415 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1416 WorldDatabase.CommitTransaction();
1419 float Creature::GetAttackDistance(Unit const* pl) const
1421 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1422 if(aggroRate==0)
1423 return 0.0f;
1425 int32 playerlevel = pl->getLevelForTarget(this);
1426 int32 creaturelevel = getLevelForTarget(pl);
1428 int32 leveldif = playerlevel - creaturelevel;
1430 // "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."
1431 if ( leveldif < - 25)
1432 leveldif = -25;
1434 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1435 float RetDistance = 20;
1437 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1438 // radius grow if playlevel < creaturelevel
1439 RetDistance -= (float)leveldif;
1441 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1443 // detect range auras
1444 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1446 // detected range auras
1447 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1450 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1451 if(RetDistance < 5)
1452 RetDistance = 5;
1454 return (RetDistance*aggroRate);
1457 void Creature::setDeathState(DeathState s)
1459 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1461 m_deathTimer = m_corpseDelay*1000;
1463 // always save boss respawn time at death to prevent crash cheating
1464 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1465 SaveRespawnTime();
1467 if (canFly() && FallGround())
1468 return;
1470 if(!IsStopped())
1471 StopMoving();
1473 Unit::setDeathState(s);
1475 if(s == JUST_DIED)
1477 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1478 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1480 if(!isPet() && GetCreatureInfo()->SkinLootId)
1481 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1482 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1484 if (canFly() && FallGround())
1485 return;
1487 Unit::setDeathState(CORPSE);
1489 if(s == JUST_ALIVED)
1491 SetHealth(GetMaxHealth());
1492 SetLootRecipient(NULL);
1493 Unit::setDeathState(ALIVE);
1494 CreatureInfo const *cinfo = GetCreatureInfo();
1495 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1496 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1497 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1498 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1499 clearUnitState(UNIT_STAT_ALL_STATE);
1500 i_motionMaster.Clear();
1501 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1502 LoadCreaturesAddon(true);
1506 bool Creature::FallGround()
1508 // Let's abort after we called this function one time
1509 if (getDeathState() == DEAD_FALLING)
1510 return false;
1512 // Let's do with no vmap because no way to get far distance with vmap high call
1513 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1515 // Abort too if the ground is very near
1516 if (fabs(GetPositionZ() - tz) < 0.1f)
1517 return false;
1519 Unit::setDeathState(DEAD_FALLING);
1520 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1521 Relocate(GetPositionX(), GetPositionY(), tz);
1522 return true;
1525 void Creature::Respawn()
1527 RemoveCorpse();
1529 // forced recreate creature object at clients
1530 UnitVisibility currentVis = GetVisibility();
1531 SetVisibility(VISIBILITY_RESPAWN);
1532 ObjectAccessor::UpdateObjectVisibility(this);
1533 SetVisibility(currentVis); // restore visibility state
1534 ObjectAccessor::UpdateObjectVisibility(this);
1536 if(getDeathState()==DEAD)
1538 if (m_DBTableGuid)
1539 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1540 m_respawnTime = time(NULL); // respawn at next tick
1544 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1546 if (!spellInfo)
1547 return false;
1549 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1550 return true;
1552 return Unit::IsImmunedToSpell(spellInfo, useCharges);
1555 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1557 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1558 return true;
1560 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1563 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1565 if(!pVictim)
1566 return NULL;
1568 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1570 if(!m_spells[i])
1571 continue;
1572 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1573 if(!spellInfo)
1575 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1576 continue;
1579 bool bcontinue = true;
1580 for(uint32 j=0;j<3;j++)
1582 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1583 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1584 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1585 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1588 bcontinue = false;
1589 break;
1592 if(bcontinue) continue;
1594 if(spellInfo->manaCost > GetPower(POWER_MANA))
1595 continue;
1596 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1597 float range = GetSpellMaxRange(srange);
1598 float minrange = GetSpellMinRange(srange);
1599 float dist = GetDistance(pVictim);
1600 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1601 // continue;
1602 if( dist > range || dist < minrange )
1603 continue;
1604 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1605 continue;
1606 return spellInfo;
1608 return NULL;
1611 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1613 if(!pVictim)
1614 return NULL;
1616 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1618 if(!m_spells[i])
1619 continue;
1620 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1621 if(!spellInfo)
1623 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1624 continue;
1627 bool bcontinue = true;
1628 for(uint32 j=0;j<3;j++)
1630 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1632 bcontinue = false;
1633 break;
1636 if(bcontinue) continue;
1638 if(spellInfo->manaCost > GetPower(POWER_MANA))
1639 continue;
1640 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1641 float range = GetSpellMaxRange(srange);
1642 float minrange = GetSpellMinRange(srange);
1643 float dist = GetDistance(pVictim);
1644 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1645 // continue;
1646 if( dist > range || dist < minrange )
1647 continue;
1648 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1649 continue;
1650 return spellInfo;
1652 return NULL;
1655 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1657 // gamemaster in GM mode see all, including ghosts
1658 if(pl->isGameMaster())
1659 return true;
1661 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1662 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1664 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1665 return false;
1666 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1669 // Dead player see live creatures near own corpse
1670 if(isAlive())
1672 Corpse *corpse = pl->GetCorpse();
1673 if(corpse)
1675 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1676 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1677 return true;
1681 // Dead player see Spirit Healer or Spirit Guide
1682 if(isSpiritService())
1683 return true;
1685 // and not see any other
1686 return false;
1689 void Creature::CallAssistance()
1691 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1693 SetNoCallAssistance(true);
1695 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1696 if(radius > 0)
1698 std::list<Creature*> assistList;
1701 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1702 Cell cell(p);
1703 cell.data.Part.reserved = ALL_DISTRICT;
1704 cell.SetNoCreate();
1706 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1707 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1709 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1711 CellLock<GridReadGuard> cell_lock(cell, p);
1712 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1715 if (!assistList.empty())
1717 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1718 while (!assistList.empty())
1720 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1721 e->AddAssistant((*assistList.begin())->GetGUID());
1722 assistList.pop_front();
1724 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1730 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1732 // we don't need help from zombies :)
1733 if( !isAlive() )
1734 return false;
1736 // skip fighting creature
1737 if( isInCombat() )
1738 return false;
1740 // only from same creature faction
1741 if(getFaction() != u->getFaction() )
1742 return false;
1744 // only free creature
1745 if( GetCharmerOrOwnerGUID() )
1746 return false;
1748 // skip non hostile to caster enemy creatures
1749 if( !IsHostileTo(enemy) )
1750 return false;
1752 return true;
1755 void Creature::SaveRespawnTime()
1757 if(isPet() || !m_DBTableGuid)
1758 return;
1760 if(m_respawnTime > time(NULL)) // dead (no corpse)
1761 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1762 else if(m_deathTimer > 0) // dead (corpse)
1763 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1766 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1768 if(!pVictim)
1769 return true;
1771 if(!pVictim->IsInMap(this))
1772 return true;
1774 if(!pVictim->isTargetableForAttack())
1775 return true;
1777 if(!pVictim->isInAccessablePlaceFor(this))
1778 return true;
1780 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1781 return false;
1783 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1784 float AttackDist = GetAttackDistance(pVictim);
1785 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1787 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1788 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1791 CreatureDataAddon const* Creature::GetCreatureAddon() const
1793 if (m_DBTableGuid)
1795 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1796 return addon;
1799 // dependent from heroic mode entry
1800 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1803 //creature_addon table
1804 bool Creature::LoadCreaturesAddon(bool reload)
1806 CreatureDataAddon const *cainfo = GetCreatureAddon();
1807 if(!cainfo)
1808 return false;
1810 if (cainfo->mount != 0)
1811 Mount(cainfo->mount);
1813 if (cainfo->bytes0 != 0)
1814 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1816 if (cainfo->bytes1 != 0)
1817 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1819 if (cainfo->bytes2 != 0)
1820 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1822 if (cainfo->emote != 0)
1823 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1825 if (cainfo->move_flags != 0)
1826 SetUnitMovementFlags(cainfo->move_flags);
1828 if(cainfo->auras)
1830 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1832 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1833 if (!AdditionalSpellInfo)
1835 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1836 continue;
1839 // skip already applied aura
1840 if(HasAura(cAura->spell_id,cAura->effect_idx))
1842 if(!reload)
1843 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);
1845 continue;
1848 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1849 AddAura(AdditionalAura);
1850 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1853 return true;
1856 /// Send a message to LocalDefense channel for players opposition team in the zone
1857 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1859 uint32 enemy_team = attacker->GetTeam();
1861 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1862 data << (uint32)GetZoneId();
1863 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1866 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1868 m_CreatureSpellCooldowns[spell_id] = end_time;
1871 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1873 m_CreatureCategoryCooldowns[category] = apply_time;
1876 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1878 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1879 if(!spellInfo)
1880 return;
1882 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1883 if(cooldown)
1884 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1886 if(spellInfo->Category)
1887 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1889 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1892 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1894 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1895 if(!spellInfo)
1896 return false;
1898 // check global cooldown if spell affected by it
1899 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1900 return true;
1902 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1903 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1906 bool Creature::HasSpellCooldown(uint32 spell_id) const
1908 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1909 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1912 bool Creature::IsInEvadeMode() const
1914 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1917 bool Creature::HasSpell(uint32 spellID) const
1919 uint8 i;
1920 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1921 if(spellID == m_spells[i])
1922 break;
1923 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1926 time_t Creature::GetRespawnTimeEx() const
1928 time_t now = time(NULL);
1929 if(m_respawnTime > now) // dead (no corpse)
1930 return m_respawnTime;
1931 else if(m_deathTimer > 0) // dead (corpse)
1932 return now+m_respawnDelay+m_deathTimer/1000;
1933 else
1934 return now;
1937 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1939 if (m_DBTableGuid)
1941 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1943 x = data->posX;
1944 y = data->posY;
1945 z = data->posZ;
1946 if(ori)
1947 *ori = data->orientation;
1948 if(dist)
1949 *dist = data->spawndist;
1951 return;
1955 x = GetPositionX();
1956 y = GetPositionY();
1957 z = GetPositionZ();
1958 if(ori)
1959 *ori = GetOrientation();
1960 if(dist)
1961 *dist = 0;
1964 void Creature::AllLootRemovedFromCorpse()
1966 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1968 uint32 nDeathTimer;
1970 CreatureInfo const *cinfo = GetCreatureInfo();
1972 // corpse was not skinnable -> apply corpse looted timer
1973 if (!cinfo || !cinfo->SkinLootId)
1974 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1975 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1976 else
1977 nDeathTimer = 0;
1979 // update death timer only if looted timer is shorter
1980 if (m_deathTimer > nDeathTimer)
1981 m_deathTimer = nDeathTimer;
1985 uint32 Creature::getLevelForTarget( Unit const* target ) const
1987 if(!isWorldBoss())
1988 return Unit::getLevelForTarget(target);
1990 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1991 if(level < 1)
1992 return 1;
1993 if(level > 255)
1994 return 255;
1995 return level;
1998 std::string Creature::GetScriptName()
2000 return objmgr.GetScriptName(GetScriptId());
2003 uint32 Creature::GetScriptId()
2005 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2008 VendorItemData const* Creature::GetVendorItems() const
2010 return objmgr.GetNpcVendorItemList(GetEntry());
2013 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2015 if(!vItem->maxcount)
2016 return vItem->maxcount;
2018 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2019 for(; itr != m_vendorItemCounts.end(); ++itr)
2020 if(itr->itemId==vItem->item)
2021 break;
2023 if(itr == m_vendorItemCounts.end())
2024 return vItem->maxcount;
2026 VendorItemCount* vCount = &*itr;
2028 time_t ptime = time(NULL);
2030 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2032 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2034 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2035 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2037 m_vendorItemCounts.erase(itr);
2038 return vItem->maxcount;
2041 vCount->count += diff * pProto->BuyCount;
2042 vCount->lastIncrementTime = ptime;
2045 return vCount->count;
2048 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2050 if(!vItem->maxcount)
2051 return 0;
2053 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2054 for(; itr != m_vendorItemCounts.end(); ++itr)
2055 if(itr->itemId==vItem->item)
2056 break;
2058 if(itr == m_vendorItemCounts.end())
2060 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2061 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2062 return new_count;
2065 VendorItemCount* vCount = &*itr;
2067 time_t ptime = time(NULL);
2069 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2071 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2073 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2074 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2075 vCount->count += diff * pProto->BuyCount;
2076 else
2077 vCount->count = vItem->maxcount;
2080 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2081 vCount->lastIncrementTime = ptime;
2082 return vCount->count;
2085 TrainerSpellData const* Creature::GetTrainerSpells() const
2087 return objmgr.GetNpcTrainerSpells(GetEntry());
2090 // overwrite WorldObject function for proper name localization
2091 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2093 if (loc_idx >= 0)
2095 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2096 if (cl)
2098 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2099 return cl->Name[loc_idx].c_str();
2103 return GetName();