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
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
23 #include "ObjectMgr.h"
27 #include "GossipDef.h"
29 #include "PoolHandler.h"
33 #include "MapManager.h"
34 #include "CreatureAI.h"
35 #include "CreatureAISelector.h"
37 #include "WaypointMovementGenerator.h"
38 #include "InstanceData.h"
39 #include "BattleGroundMgr.h"
41 #include "GridNotifiers.h"
42 #include "GridNotifiersImpl.h"
45 // apply implementation of the singletons
46 #include "Policies/SingletonImp.h"
48 TrainerSpell
const* TrainerSpellData::Find(uint32 spell_id
) const
50 TrainerSpellMap::const_iterator itr
= spellList
.find(spell_id
);
51 if (itr
!= spellList
.end())
57 bool VendorItemData::RemoveItem( uint32 item_id
)
59 for(VendorItemList::iterator i
= m_items
.begin(); i
!= m_items
.end(); ++i
)
61 if((*i
)->item
==item_id
)
70 size_t VendorItemData::FindItemSlot(uint32 item_id
) const
72 for(size_t i
= 0; i
< m_items
.size(); ++i
)
73 if(m_items
[i
]->item
==item_id
)
75 return m_items
.size();
78 VendorItem
const* VendorItemData::FindItem(uint32 item_id
) const
80 for(VendorItemList::const_iterator i
= m_items
.begin(); i
!= m_items
.end(); ++i
)
81 if((*i
)->item
==item_id
)
86 bool AssistDelayEvent::Execute(uint64
/*e_time*/, uint32
/*p_time*/)
88 if(Unit
* victim
= Unit::GetUnit(m_owner
, m_victim
))
90 while (!m_assistants
.empty())
92 Creature
* assistant
= (Creature
*)Unit::GetUnit(m_owner
, *m_assistants
.begin());
93 m_assistants
.pop_front();
95 if (assistant
&& assistant
->CanAssistTo(&m_owner
, victim
))
97 assistant
->SetNoCallAssistance(true);
99 assistant
->AI()->AttackStart(victim
);
106 Creature::Creature() :
108 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
109 m_lootMoney(0), m_lootRecipient(0),
110 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f
),
111 m_gossipOptionLoaded(false), m_isPet(false), m_isVehicle(false), m_isTotem(false),
112 m_defaultMovementType(IDLE_MOTION_TYPE
), m_DBTableGuid(0), m_equipmentId(0), m_AlreadyCallAssistance(false),
113 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL
),
114 m_creatureInfo(NULL
), m_isActiveObject(false), m_AlreadySearchedAssistance(false)
117 m_valuesCount
= UNIT_END
;
119 for(int i
=0; i
<4; ++i
)
122 m_CreatureSpellCooldowns
.clear();
123 m_CreatureCategoryCooldowns
.clear();
124 m_GlobalCooldown
= 0;
125 m_unit_movement_flags
= MONSTER_MOVE_WALK
;
128 Creature::~Creature()
130 CleanupsBeforeDelete();
132 m_vendorItemCounts
.clear();
138 void Creature::AddToWorld()
140 ///- Register the creature for guid lookup
141 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
145 void Creature::RemoveFromWorld()
147 ///- Remove the creature from the accessor
148 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
149 Unit::RemoveFromWorld();
152 void Creature::RemoveCorpse()
154 if( getDeathState()!=CORPSE
&& !m_isDeadByDefault
|| getDeathState()!=ALIVE
&& m_isDeadByDefault
)
159 ObjectAccessor::UpdateObjectVisibility(this);
161 m_respawnTime
= time(NULL
) + m_respawnDelay
;
164 GetRespawnCoord(x
, y
, z
, &o
);
165 GetMap()->CreatureRelocation(this,x
,y
,z
,o
);
169 * change the entry of creature until respawn
171 bool Creature::InitEntry(uint32 Entry
, uint32 team
, const CreatureData
*data
)
173 CreatureInfo
const *normalInfo
= objmgr
.GetCreatureTemplate(Entry
);
176 sLog
.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry
);
180 // get heroic mode entry
181 uint32 actualEntry
= Entry
;
182 CreatureInfo
const *cinfo
= normalInfo
;
183 if(normalInfo
->HeroicEntry
)
185 Map
*map
= MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
186 if(map
&& map
->IsHeroic())
188 cinfo
= objmgr
.GetCreatureTemplate(normalInfo
->HeroicEntry
);
191 sLog
.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry
);
197 SetEntry(Entry
); // normal entry always
198 m_creatureInfo
= cinfo
; // map mode related always
200 // equal to player Race field, but creature does not have race
201 SetByteValue(UNIT_FIELD_BYTES_0
, 0, 0);
203 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
204 SetByteValue(UNIT_FIELD_BYTES_0
, 1, uint8(cinfo
->unit_class
));
206 if (cinfo
->DisplayID_A
== 0 || cinfo
->DisplayID_H
== 0) // Cancel load if no model defined
208 sLog
.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry
);
212 uint32 display_id
= objmgr
.ChooseDisplayId(team
, GetCreatureInfo(), data
);
213 CreatureModelInfo
const *minfo
= objmgr
.GetCreatureModelRandomGender(display_id
);
216 sLog
.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry
, display_id
);
220 display_id
= minfo
->modelid
; // it can be different (for another gender)
222 SetDisplayId(display_id
);
223 SetNativeDisplayId(display_id
);
224 SetByteValue(UNIT_FIELD_BYTES_0
, 2, minfo
->gender
);
226 // Load creature equipment
227 if(!data
|| data
->equipmentId
== 0)
228 { // use default from the template
229 LoadEquipment(cinfo
->equipmentId
);
231 else if(data
&& data
->equipmentId
!= -1)
232 { // override, -1 means no equipment
233 LoadEquipment(data
->equipmentId
);
236 SetName(normalInfo
->Name
); // at normal entry always
238 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
,minfo
->bounding_radius
);
239 SetFloatValue(UNIT_FIELD_COMBATREACH
,minfo
->combat_reach
);
241 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
243 SetSpeed(MOVE_WALK
, cinfo
->speed
);
244 SetSpeed(MOVE_RUN
, cinfo
->speed
);
245 SetSpeed(MOVE_SWIM
, cinfo
->speed
);
247 SetFloatValue(OBJECT_FIELD_SCALE_X
, cinfo
->scale
);
249 // checked at loading
250 m_defaultMovementType
= MovementGeneratorType(cinfo
->MovementType
);
251 if(!m_respawnradius
&& m_defaultMovementType
==RANDOM_MOTION_TYPE
)
252 m_defaultMovementType
= IDLE_MOTION_TYPE
;
257 bool Creature::UpdateEntry(uint32 Entry
, uint32 team
, const CreatureData
*data
)
259 if(!InitEntry(Entry
,team
,data
))
262 m_regenHealth
= GetCreatureInfo()->RegenHealth
;
264 // creatures always have melee weapon ready if any
265 SetSheath(SHEATH_STATE_MELEE
);
267 SelectLevel(GetCreatureInfo());
269 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE
, GetCreatureInfo()->faction_H
);
271 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE
, GetCreatureInfo()->faction_A
);
273 SetUInt32Value(UNIT_NPC_FLAGS
,GetCreatureInfo()->npcflag
);
275 SetAttackTime(BASE_ATTACK
, GetCreatureInfo()->baseattacktime
);
276 SetAttackTime(OFF_ATTACK
, GetCreatureInfo()->baseattacktime
);
277 SetAttackTime(RANGED_ATTACK
,GetCreatureInfo()->rangeattacktime
);
279 SetUInt32Value(UNIT_FIELD_FLAGS
,GetCreatureInfo()->unit_flags
);
280 SetUInt32Value(UNIT_DYNAMIC_FLAGS
,GetCreatureInfo()->dynamicflags
);
282 SetModifierValue(UNIT_MOD_ARMOR
, BASE_VALUE
, float(GetCreatureInfo()->armor
));
283 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(GetCreatureInfo()->resistance1
));
284 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(GetCreatureInfo()->resistance2
));
285 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(GetCreatureInfo()->resistance3
));
286 SetModifierValue(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(GetCreatureInfo()->resistance4
));
287 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(GetCreatureInfo()->resistance5
));
288 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(GetCreatureInfo()->resistance6
));
290 SetCanModifyStats(true);
293 FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(GetCreatureInfo()->faction_A
);
294 if (factionTemplate
) // check and error show at loading templates
296 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(factionTemplate
->faction
);
298 if( !(GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_CIVILIAN
) &&
299 (factionEntry
->team
== ALLIANCE
|| factionEntry
->team
== HORDE
) )
303 for(int i
=0; i
< CREATURE_MAX_SPELLS
; ++i
)
304 m_spells
[i
] = GetCreatureInfo()->spells
[i
];
309 void Creature::Update(uint32 diff
)
311 if(m_GlobalCooldown
<= diff
)
312 m_GlobalCooldown
= 0;
314 m_GlobalCooldown
-= diff
;
316 switch( m_deathState
)
319 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
320 sLog
.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
323 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
324 sLog
.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
328 if( m_respawnTime
<= time(NULL
) )
330 DEBUG_LOG("Respawning...");
332 lootForPickPocketed
= false;
335 if(m_originalEntry
!= GetEntry())
336 UpdateEntry(m_originalEntry
);
338 CreatureInfo
const *cinfo
= GetCreatureInfo();
341 SetUInt32Value(UNIT_DYNAMIC_FLAGS
, 0);
342 if (m_isDeadByDefault
)
344 setDeathState(JUST_DIED
);
346 i_motionMaster
.Clear();
347 clearUnitState(UNIT_STAT_ALL_STATE
);
348 LoadCreaturesAddon(true);
351 setDeathState( JUST_ALIVED
);
353 //Call AI respawn virtual function
354 i_AI
->JustRespawned();
356 uint16 poolid
= poolhandler
.IsPartOfAPool(GetGUIDLow(), GetTypeId());
358 poolhandler
.UpdatePool(poolid
, GetGUIDLow(), GetTypeId());
366 if (m_isDeadByDefault
)
369 if( m_deathTimer
<= diff
)
372 DEBUG_LOG("Removing corpse... %u ", GetEntry());
376 m_deathTimer
-= diff
;
377 if (m_groupLootTimer
&& lootingGroupLeaderGUID
)
379 if(diff
<= m_groupLootTimer
)
381 m_groupLootTimer
-= diff
;
385 Group
* group
= objmgr
.GetGroupByLeader(lootingGroupLeaderGUID
);
388 m_groupLootTimer
= 0;
389 lootingGroupLeaderGUID
= 0;
398 if (m_isDeadByDefault
)
400 if( m_deathTimer
<= diff
)
403 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
407 m_deathTimer
-= diff
;
411 Unit::Update( diff
);
413 // creature can be dead after Unit::Update call
414 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
420 // do not allow the AI to be changed during update
422 i_AI
->UpdateAI(diff
);
426 // creature can be dead after UpdateAI call
427 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
432 if(diff
>= m_regenTimer
)
435 m_regenTimer
-= diff
;
437 if (m_regenTimer
!= 0)
440 if (!isInCombat() || IsPolymorphed())
451 setDeathState(JUST_DIED
);
458 void Creature::RegenerateMana()
460 uint32 curValue
= GetPower(POWER_MANA
);
461 uint32 maxValue
= GetMaxPower(POWER_MANA
);
463 if (curValue
>= maxValue
)
468 // Combat and any controlled creature
469 if (isInCombat() || GetCharmerOrOwnerGUID())
471 if(!IsUnderLastManaUseEffect())
473 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
474 float Spirit
= GetStat(STAT_SPIRIT
);
476 addvalue
= uint32((Spirit
/5.0f
+ 17.0f
) * ManaIncreaseRate
);
480 addvalue
= maxValue
/3;
482 ModifyPower(POWER_MANA
, addvalue
);
485 void Creature::RegenerateHealth()
487 if (!isRegeneratingHealth())
490 uint32 curValue
= GetHealth();
491 uint32 maxValue
= GetMaxHealth();
493 if (curValue
>= maxValue
)
498 // Not only pet, but any controlled creature
499 if(GetCharmerOrOwnerGUID())
501 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
502 float Spirit
= GetStat(STAT_SPIRIT
);
504 if( GetPower(POWER_MANA
) > 0 )
505 addvalue
= uint32(Spirit
* 0.25 * HealthIncreaseRate
);
507 addvalue
= uint32(Spirit
* 0.80 * HealthIncreaseRate
);
510 addvalue
= maxValue
/3;
512 ModifyHealth(addvalue
);
515 void Creature::DoFleeToGetAssistance()
520 float radius
= sWorld
.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS
);
523 Creature
* pCreature
= NULL
;
525 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
527 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
529 MaNGOS::NearestAssistCreatureInCreatureRangeCheck
u_check(this, getVictim(), radius
);
530 MaNGOS::CreatureLastSearcher
<MaNGOS::NearestAssistCreatureInCreatureRangeCheck
> searcher(this, pCreature
, u_check
);
532 TypeContainerVisitor
<MaNGOS::CreatureLastSearcher
<MaNGOS::NearestAssistCreatureInCreatureRangeCheck
>, GridTypeMapContainer
> grid_creature_searcher(searcher
);
534 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
535 cell_lock
->Visit(cell_lock
, grid_creature_searcher
, *GetMap());
537 SetNoSearchAssistance(true);
539 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld
.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY
));
541 GetMotionMaster()->MoveSeekAssistance(pCreature
->GetPositionX(), pCreature
->GetPositionY(), pCreature
->GetPositionZ());
545 bool Creature::AIM_Initialize()
547 // make sure nothing can change the AI during AI update
550 sLog
.outDebug("AIM_Initialize: failed to init, locked.");
554 CreatureAI
* oldAI
= i_AI
;
555 i_motionMaster
.Initialize();
556 i_AI
= FactorySelector::selectAI(this);
562 bool Creature::Create (uint32 guidlow
, Map
*map
, uint32 phaseMask
, uint32 Entry
, uint32 team
, const CreatureData
*data
)
564 SetMapId(map
->GetId());
565 SetInstanceId(map
->GetInstanceId());
566 SetPhaseMask(phaseMask
,false);
568 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
569 const bool bResult
= CreateFromProto(guidlow
, Entry
, team
, data
);
573 switch (GetCreatureInfo()->rank
)
575 case CREATURE_ELITE_RARE
:
576 m_corpseDelay
= sWorld
.getConfig(CONFIG_CORPSE_DECAY_RARE
);
578 case CREATURE_ELITE_ELITE
:
579 m_corpseDelay
= sWorld
.getConfig(CONFIG_CORPSE_DECAY_ELITE
);
581 case CREATURE_ELITE_RAREELITE
:
582 m_corpseDelay
= sWorld
.getConfig(CONFIG_CORPSE_DECAY_RAREELITE
);
584 case CREATURE_ELITE_WORLDBOSS
:
585 m_corpseDelay
= sWorld
.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS
);
588 m_corpseDelay
= sWorld
.getConfig(CONFIG_CORPSE_DECAY_NORMAL
);
591 LoadCreaturesAddon();
597 bool Creature::isCanTrainingOf(Player
* pPlayer
, bool msg
) const
602 TrainerSpellData
const* trainer_spells
= GetTrainerSpells();
604 if(!trainer_spells
|| trainer_spells
->spellList
.empty())
606 sLog
.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
607 GetGUIDLow(),GetEntry());
611 switch(GetCreatureInfo()->trainer_type
)
613 case TRAINER_TYPE_CLASS
:
614 if(pPlayer
->getClass()!=GetCreatureInfo()->trainer_class
)
618 pPlayer
->PlayerTalkClass
->ClearMenus();
619 switch(GetCreatureInfo()->trainer_class
)
621 case CLASS_DRUID
: pPlayer
->PlayerTalkClass
->SendGossipMenu( 4913,GetGUID()); break;
622 case CLASS_HUNTER
: pPlayer
->PlayerTalkClass
->SendGossipMenu(10090,GetGUID()); break;
623 case CLASS_MAGE
: pPlayer
->PlayerTalkClass
->SendGossipMenu( 328,GetGUID()); break;
624 case CLASS_PALADIN
:pPlayer
->PlayerTalkClass
->SendGossipMenu( 1635,GetGUID()); break;
625 case CLASS_PRIEST
: pPlayer
->PlayerTalkClass
->SendGossipMenu( 4436,GetGUID()); break;
626 case CLASS_ROGUE
: pPlayer
->PlayerTalkClass
->SendGossipMenu( 4797,GetGUID()); break;
627 case CLASS_SHAMAN
: pPlayer
->PlayerTalkClass
->SendGossipMenu( 5003,GetGUID()); break;
628 case CLASS_WARLOCK
:pPlayer
->PlayerTalkClass
->SendGossipMenu( 5836,GetGUID()); break;
629 case CLASS_WARRIOR
:pPlayer
->PlayerTalkClass
->SendGossipMenu( 4985,GetGUID()); break;
635 case TRAINER_TYPE_PETS
:
636 if(pPlayer
->getClass()!=CLASS_HUNTER
)
638 pPlayer
->PlayerTalkClass
->ClearMenus();
639 pPlayer
->PlayerTalkClass
->SendGossipMenu(3620,GetGUID());
643 case TRAINER_TYPE_MOUNTS
:
644 if(GetCreatureInfo()->trainer_race
&& pPlayer
->getRace() != GetCreatureInfo()->trainer_race
)
648 pPlayer
->PlayerTalkClass
->ClearMenus();
649 switch(GetCreatureInfo()->trainer_class
)
651 case RACE_DWARF
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5865,GetGUID()); break;
652 case RACE_GNOME
: pPlayer
->PlayerTalkClass
->SendGossipMenu(4881,GetGUID()); break;
653 case RACE_HUMAN
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5861,GetGUID()); break;
654 case RACE_NIGHTELF
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5862,GetGUID()); break;
655 case RACE_ORC
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5863,GetGUID()); break;
656 case RACE_TAUREN
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5864,GetGUID()); break;
657 case RACE_TROLL
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5816,GetGUID()); break;
658 case RACE_UNDEAD_PLAYER
:pPlayer
->PlayerTalkClass
->SendGossipMenu( 624,GetGUID()); break;
659 case RACE_BLOODELF
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5862,GetGUID()); break;
660 case RACE_DRAENEI
: pPlayer
->PlayerTalkClass
->SendGossipMenu(5864,GetGUID()); break;
666 case TRAINER_TYPE_TRADESKILLS
:
667 if(GetCreatureInfo()->trainer_spell
&& !pPlayer
->HasSpell(GetCreatureInfo()->trainer_spell
))
671 pPlayer
->PlayerTalkClass
->ClearMenus();
672 pPlayer
->PlayerTalkClass
->SendGossipMenu(11031,GetGUID());
678 return false; // checked and error output at creature_template loading
683 bool Creature::isCanInteractWithBattleMaster(Player
* pPlayer
, bool msg
) const
685 if(!isBattleMaster())
688 BattleGroundTypeId bgTypeId
= sBattleGroundMgr
.GetBattleMasterBG(GetEntry());
690 return pPlayer
->GetBGAccessByLevel(bgTypeId
);
692 if(!pPlayer
->GetBGAccessByLevel(bgTypeId
))
694 pPlayer
->PlayerTalkClass
->ClearMenus();
697 case BATTLEGROUND_AV
: pPlayer
->PlayerTalkClass
->SendGossipMenu(7616,GetGUID()); break;
698 case BATTLEGROUND_WS
: pPlayer
->PlayerTalkClass
->SendGossipMenu(7599,GetGUID()); break;
699 case BATTLEGROUND_AB
: pPlayer
->PlayerTalkClass
->SendGossipMenu(7642,GetGUID()); break;
700 case BATTLEGROUND_EY
:
701 case BATTLEGROUND_NA
:
702 case BATTLEGROUND_BE
:
703 case BATTLEGROUND_AA
:
704 case BATTLEGROUND_RL
:
705 case BATTLEGROUND_SA
:
706 case BATTLEGROUND_DS
:
707 case BATTLEGROUND_RV
: pPlayer
->PlayerTalkClass
->SendGossipMenu(10024,GetGUID()); break;
715 bool Creature::isCanTrainingAndResetTalentsOf(Player
* pPlayer
) const
717 return pPlayer
->getLevel() >= 10
718 && GetCreatureInfo()->trainer_type
== TRAINER_TYPE_CLASS
719 && pPlayer
->getClass() == GetCreatureInfo()->trainer_class
;
722 void Creature::prepareGossipMenu( Player
*pPlayer
,uint32 gossipid
)
724 PlayerMenu
* pm
=pPlayer
->PlayerTalkClass
;
727 // lazy loading single time at use
730 for( GossipOptionList::iterator i
= m_goptions
.begin( ); i
!= m_goptions
.end( ); ++i
)
732 GossipOption
* gso
=&*i
;
733 if(gso
->GossipId
== gossipid
)
735 bool cantalking
=true;
738 uint32 textid
=GetNpcTextId();
739 GossipText
const* gossiptext
=objmgr
.GetGossipText(textid
);
747 case GOSSIP_OPTION_QUESTGIVER
:
748 pPlayer
->PrepareQuestMenu(GetGUID());
749 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
751 //pm->GetQuestMenu()->ClearMenu();
753 case GOSSIP_OPTION_ARMORER
:
754 cantalking
=false; // added in special mode
756 case GOSSIP_OPTION_SPIRITHEALER
:
757 if( !pPlayer
->isDead() )
760 case GOSSIP_OPTION_VENDOR
:
762 VendorItemData
const* vItems
= GetVendorItems();
763 if(!vItems
|| vItems
->Empty())
765 sLog
.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
766 GetGUIDLow(),GetEntry());
771 case GOSSIP_OPTION_TRAINER
:
772 if(!isCanTrainingOf(pPlayer
,false))
775 case GOSSIP_OPTION_UNLEARNTALENTS
:
776 if(!isCanTrainingAndResetTalentsOf(pPlayer
))
779 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
780 if(!pPlayer
->GetPet() || pPlayer
->GetPet()->getPetType() != HUNTER_PET
|| pPlayer
->GetPet()->m_spells
.size() <= 1 || GetCreatureInfo()->trainer_type
!= TRAINER_TYPE_PETS
|| GetCreatureInfo()->trainer_class
!= CLASS_HUNTER
)
783 case GOSSIP_OPTION_TAXIVENDOR
:
784 if ( pPlayer
->GetSession()->SendLearnNewTaxiNode(this) )
787 case GOSSIP_OPTION_BATTLEFIELD
:
788 if(!isCanInteractWithBattleMaster(pPlayer
,false))
791 case GOSSIP_OPTION_SPIRITGUIDE
:
792 case GOSSIP_OPTION_INNKEEPER
:
793 case GOSSIP_OPTION_BANKER
:
794 case GOSSIP_OPTION_PETITIONER
:
795 case GOSSIP_OPTION_STABLEPET
:
796 case GOSSIP_OPTION_TABARDDESIGNER
:
797 case GOSSIP_OPTION_AUCTIONEER
:
800 sLog
.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso
->Action
);
805 //note for future dev: should have database fields for BoxMessage & BoxMoney
806 if(!gso
->OptionText
.empty() && cantalking
)
808 std::string OptionText
= gso
->OptionText
;
809 std::string BoxText
= gso
->BoxText
;
810 int loc_idx
= pPlayer
->GetSession()->GetSessionDbLocaleIndex();
813 NpcOptionLocale
const *no
= objmgr
.GetNpcOptionLocale(gso
->Id
);
816 if (no
->OptionText
.size() > loc_idx
&& !no
->OptionText
[loc_idx
].empty())
817 OptionText
=no
->OptionText
[loc_idx
];
818 if (no
->BoxText
.size() > loc_idx
&& !no
->BoxText
[loc_idx
].empty())
819 BoxText
=no
->BoxText
[loc_idx
];
822 pm
->GetGossipMenu().AddMenuItem((uint8
)gso
->Icon
,OptionText
, gossipid
,gso
->Action
,BoxText
,gso
->BoxMoney
,gso
->Coded
);
827 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
830 if(HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_TRAINER
))
832 isCanTrainingOf(pPlayer
,true); // output error message if need
834 if(HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_BATTLEMASTER
))
836 isCanInteractWithBattleMaster(pPlayer
,true); // output error message if need
841 void Creature::sendPreparedGossip(Player
* player
)
846 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
847 if (!HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_GOSSIP
) && !player
->PlayerTalkClass
->GetQuestMenu().Empty())
849 player
->SendPreparedQuest(GetGUID());
853 // in case non empty gossip menu (that not included quests list size) show it
854 // (quest entries from quest menu will be included in list)
855 player
->PlayerTalkClass
->SendGossipMenu(GetNpcTextId(), GetGUID());
858 void Creature::OnGossipSelect(Player
* player
, uint32 option
)
860 GossipMenu
& gossipmenu
= player
->PlayerTalkClass
->GetGossipMenu();
862 if(option
>= gossipmenu
.MenuItemCount())
865 uint32 action
=gossipmenu
.GetItem(option
).m_gAction
;
866 uint32 zoneid
=GetZoneId();
867 uint64 guid
=GetGUID();
869 GossipOption
const *gossip
=GetGossipOption( action
);
873 gossip
=GetGossipOption( action
);
878 switch (gossip
->Action
)
880 case GOSSIP_OPTION_GOSSIP
:
882 uint32 textid
= GetGossipTextId(action
, zoneid
);
884 textid
=GetNpcTextId();
886 player
->PlayerTalkClass
->CloseGossip();
887 player
->PlayerTalkClass
->SendTalking(textid
);
890 case GOSSIP_OPTION_SPIRITHEALER
:
891 if (player
->isDead())
892 CastSpell(this,17251,true,NULL
,NULL
,player
->GetGUID());
894 case GOSSIP_OPTION_QUESTGIVER
:
895 player
->PrepareQuestMenu( guid
);
896 player
->SendPreparedQuest( guid
);
898 case GOSSIP_OPTION_VENDOR
:
899 case GOSSIP_OPTION_ARMORER
:
900 player
->GetSession()->SendListInventory(guid
);
902 case GOSSIP_OPTION_STABLEPET
:
903 player
->GetSession()->SendStablePet(guid
);
905 case GOSSIP_OPTION_TRAINER
:
906 player
->GetSession()->SendTrainerList(guid
);
908 case GOSSIP_OPTION_UNLEARNTALENTS
:
909 player
->PlayerTalkClass
->CloseGossip();
910 player
->SendTalentWipeConfirm(guid
);
912 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
913 player
->PlayerTalkClass
->CloseGossip();
914 player
->SendPetSkillWipeConfirm();
916 case GOSSIP_OPTION_TAXIVENDOR
:
917 player
->GetSession()->SendTaxiMenu(this);
919 case GOSSIP_OPTION_INNKEEPER
:
920 player
->PlayerTalkClass
->CloseGossip();
921 player
->SetBindPoint( guid
);
923 case GOSSIP_OPTION_BANKER
:
924 player
->GetSession()->SendShowBank( guid
);
926 case GOSSIP_OPTION_PETITIONER
:
927 player
->PlayerTalkClass
->CloseGossip();
928 player
->GetSession()->SendPetitionShowList( guid
);
930 case GOSSIP_OPTION_TABARDDESIGNER
:
931 player
->PlayerTalkClass
->CloseGossip();
932 player
->GetSession()->SendTabardVendorActivate( guid
);
934 case GOSSIP_OPTION_AUCTIONEER
:
935 player
->GetSession()->SendAuctionHello( guid
, this );
937 case GOSSIP_OPTION_SPIRITGUIDE
:
938 case GOSSIP_GUARD_SPELLTRAINER
:
939 case GOSSIP_GUARD_SKILLTRAINER
:
940 prepareGossipMenu( player
,gossip
->Id
);
941 sendPreparedGossip( player
);
943 case GOSSIP_OPTION_BATTLEFIELD
:
945 BattleGroundTypeId bgTypeId
= sBattleGroundMgr
.GetBattleMasterBG(GetEntry());
946 player
->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId
);
950 OnPoiSelect( player
, gossip
);
956 void Creature::OnPoiSelect(Player
* player
, GossipOption
const *gossip
)
958 if(gossip
->GossipId
==GOSSIP_GUARD_SPELLTRAINER
|| gossip
->GossipId
==GOSSIP_GUARD_SKILLTRAINER
)
960 Poi_Icon icon
= ICON_POI_BLANK
;
961 //need add more case.
962 switch(gossip
->Action
)
964 case GOSSIP_GUARD_BANK
:
965 icon
=ICON_POI_SMALL_HOUSE
;
967 case GOSSIP_GUARD_RIDE
:
968 icon
=ICON_POI_RWHORSE
;
970 case GOSSIP_GUARD_GUILD
:
971 icon
=ICON_POI_BLUETOWER
;
974 icon
=ICON_POI_GREYTOWER
;
977 uint32 textid
= GetGossipTextId( gossip
->Action
, GetZoneId() );
978 player
->PlayerTalkClass
->SendTalking(textid
);
979 // std::string areaname= gossip->OptionText;
980 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
984 uint32
Creature::GetGossipTextId(uint32 action
, uint32 zoneid
)
986 QueryResult
*result
= WorldDatabase
.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action
, zoneid
);
991 Field
*fields
= result
->Fetch();
992 uint32 id
= fields
[0].GetUInt32();
999 uint32
Creature::GetNpcTextId()
1002 return DEFAULT_GOSSIP_MESSAGE
;
1004 if(uint32 pos
= objmgr
.GetNpcGossip(m_DBTableGuid
))
1007 return DEFAULT_GOSSIP_MESSAGE
;
1010 GossipOption
const* Creature::GetGossipOption( uint32 id
) const
1012 for( GossipOptionList::const_iterator i
= m_goptions
.begin( ); i
!= m_goptions
.end( ); ++i
)
1020 void Creature::LoadGossipOptions()
1022 if(m_gossipOptionLoaded
)
1025 uint32 npcflags
=GetUInt32Value(UNIT_NPC_FLAGS
);
1027 CacheNpcOptionList
const& noList
= objmgr
.GetNpcOptions ();
1028 for (CacheNpcOptionList::const_iterator i
= noList
.begin (); i
!= noList
.end (); ++i
)
1029 if(i
->NpcFlag
& npcflags
)
1030 addGossipOption(*i
);
1032 m_gossipOptionLoaded
= true;
1035 void Creature::AI_SendMoveToPacket(float x
, float y
, float z
, uint32 time
, uint32 MovementFlags
, uint8 type
)
1037 /* uint32 timeElap = getMSTime();
1038 if ((timeElap - m_startMove) < m_moveTime)
1040 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1041 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1051 m_orientation = atan2((oY - dY), (oX - dX));
1053 m_startMove = getMSTime();
1054 m_moveTime = time;*/
1055 SendMonsterMove(x
, y
, z
, type
, MovementFlags
, time
);
1058 Player
*Creature::GetLootRecipient() const
1060 if (!m_lootRecipient
) return NULL
;
1061 else return ObjectAccessor::FindPlayer(m_lootRecipient
);
1064 void Creature::SetLootRecipient(Unit
*unit
)
1066 // set the player whose group should receive the right
1067 // to loot the creature after it dies
1068 // should be set to NULL after the loot disappears
1072 m_lootRecipient
= 0;
1073 RemoveFlag(UNIT_DYNAMIC_FLAGS
, UNIT_DYNFLAG_OTHER_TAGGER
);
1077 Player
* player
= unit
->GetCharmerOrOwnerPlayerOrPlayerItself();
1078 if(!player
) // normal creature, no player involved
1081 m_lootRecipient
= player
->GetGUID();
1082 SetFlag(UNIT_DYNAMIC_FLAGS
, UNIT_DYNFLAG_OTHER_TAGGER
);
1085 void Creature::SaveToDB()
1087 // this should only be used when the creature has already been loaded
1088 // preferably after adding to map, because mapid may not be valid otherwise
1089 CreatureData
const *data
= objmgr
.GetCreatureData(m_DBTableGuid
);
1092 sLog
.outError("Creature::SaveToDB failed, cannot get creature data!");
1096 SaveToDB(GetMapId(), data
->spawnMask
,GetPhaseMask());
1099 void Creature::SaveToDB(uint32 mapid
, uint8 spawnMask
, uint32 phaseMask
)
1101 // update in loaded data
1103 m_DBTableGuid
= GetGUIDLow();
1104 CreatureData
& data
= objmgr
.NewOrExistCreatureData(m_DBTableGuid
);
1106 uint32 displayId
= GetNativeDisplayId();
1108 // check if it's a custom model and if not, use 0 for displayId
1109 CreatureInfo
const *cinfo
= GetCreatureInfo();
1112 if(displayId
!= cinfo
->DisplayID_A
&& displayId
!= cinfo
->DisplayID_H
)
1114 CreatureModelInfo
const *minfo
= objmgr
.GetCreatureModelInfo(cinfo
->DisplayID_A
);
1115 if(!minfo
|| displayId
!= minfo
->modelid_other_gender
)
1117 minfo
= objmgr
.GetCreatureModelInfo(cinfo
->DisplayID_H
);
1118 if(minfo
&& displayId
== minfo
->modelid_other_gender
)
1128 // data->guid = guid don't must be update at save
1129 data
.id
= GetEntry();
1131 data
.phaseMask
= phaseMask
;
1132 data
.displayid
= displayId
;
1133 data
.equipmentId
= GetEquipmentId();
1134 data
.posX
= GetPositionX();
1135 data
.posY
= GetPositionY();
1136 data
.posZ
= GetPositionZ();
1137 data
.orientation
= GetOrientation();
1138 data
.spawntimesecs
= m_respawnDelay
;
1139 // prevent add data integrity problems
1140 data
.spawndist
= GetDefaultMovementType()==IDLE_MOTION_TYPE
? 0 : m_respawnradius
;
1141 data
.currentwaypoint
= 0;
1142 data
.curhealth
= GetHealth();
1143 data
.curmana
= GetPower(POWER_MANA
);
1144 data
.is_dead
= m_isDeadByDefault
;
1145 // prevent add data integrity problems
1146 data
.movementType
= !m_respawnradius
&& GetDefaultMovementType()==RANDOM_MOTION_TYPE
1147 ? IDLE_MOTION_TYPE
: GetDefaultMovementType();
1148 data
.spawnMask
= spawnMask
;
1151 WorldDatabase
.BeginTransaction();
1153 WorldDatabase
.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid
);
1155 std::ostringstream ss
;
1156 ss
<< "INSERT INTO creature VALUES ("
1157 << m_DBTableGuid
<< ","
1158 << GetEntry() << ","
1160 << uint32(spawnMask
) << "," // cast to prevent save as symbol
1161 << uint16(GetPhaseMask()) << "," // prevent out of range error
1163 << GetEquipmentId() <<","
1164 << GetPositionX() << ","
1165 << GetPositionY() << ","
1166 << GetPositionZ() << ","
1167 << GetOrientation() << ","
1168 << m_respawnDelay
<< "," //respawn time
1169 << (float) m_respawnradius
<< "," //spawn distance (float)
1170 << (uint32
) (0) << "," //currentwaypoint
1171 << GetHealth() << "," //curhealth
1172 << GetPower(POWER_MANA
) << "," //curmana
1173 << (m_isDeadByDefault
? 1 : 0) << "," //is_dead
1174 << GetDefaultMovementType() << ")"; //default movement generator type
1176 WorldDatabase
.PExecuteLog( ss
.str( ).c_str( ) );
1178 WorldDatabase
.CommitTransaction();
1181 void Creature::SelectLevel(const CreatureInfo
*cinfo
)
1183 uint32 rank
= isPet()? 0 : cinfo
->rank
;
1186 uint32 minlevel
= std::min(cinfo
->maxlevel
, cinfo
->minlevel
);
1187 uint32 maxlevel
= std::max(cinfo
->maxlevel
, cinfo
->minlevel
);
1188 uint32 level
= minlevel
== maxlevel
? minlevel
: urand(minlevel
, maxlevel
);
1191 float rellevel
= maxlevel
== minlevel
? 0 : (float(level
- minlevel
))/(maxlevel
- minlevel
);
1194 float healthmod
= _GetHealthMod(rank
);
1196 uint32 minhealth
= std::min(cinfo
->maxhealth
, cinfo
->minhealth
);
1197 uint32 maxhealth
= std::max(cinfo
->maxhealth
, cinfo
->minhealth
);
1198 uint32 health
= uint32(healthmod
* (minhealth
+ uint32(rellevel
*(maxhealth
- minhealth
))));
1200 SetCreateHealth(health
);
1201 SetMaxHealth(health
);
1205 uint32 minmana
= std::min(cinfo
->maxmana
, cinfo
->minmana
);
1206 uint32 maxmana
= std::max(cinfo
->maxmana
, cinfo
->minmana
);
1207 uint32 mana
= minmana
+ uint32(rellevel
*(maxmana
- minmana
));
1209 SetCreateMana(mana
);
1210 SetMaxPower(POWER_MANA
, mana
); //MAX Mana
1211 SetPower(POWER_MANA
, mana
);
1213 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
1215 SetModifierValue(UNIT_MOD_HEALTH
, BASE_VALUE
, health
);
1216 SetModifierValue(UNIT_MOD_MANA
, BASE_VALUE
, mana
);
1219 float damagemod
= _GetDamageMod(rank
);
1221 SetBaseWeaponDamage(BASE_ATTACK
, MINDAMAGE
, cinfo
->mindmg
* damagemod
);
1222 SetBaseWeaponDamage(BASE_ATTACK
, MAXDAMAGE
, cinfo
->maxdmg
* damagemod
);
1224 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
,cinfo
->minrangedmg
* damagemod
);
1225 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
,cinfo
->maxrangedmg
* damagemod
);
1227 SetModifierValue(UNIT_MOD_ATTACK_POWER
, BASE_VALUE
, cinfo
->attackpower
* damagemod
);
1230 float Creature::_GetHealthMod(int32 Rank
)
1232 switch (Rank
) // define rates for each elite rank
1234 case CREATURE_ELITE_NORMAL
:
1235 return sWorld
.getRate(RATE_CREATURE_NORMAL_HP
);
1236 case CREATURE_ELITE_ELITE
:
1237 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_HP
);
1238 case CREATURE_ELITE_RAREELITE
:
1239 return sWorld
.getRate(RATE_CREATURE_ELITE_RAREELITE_HP
);
1240 case CREATURE_ELITE_WORLDBOSS
:
1241 return sWorld
.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP
);
1242 case CREATURE_ELITE_RARE
:
1243 return sWorld
.getRate(RATE_CREATURE_ELITE_RARE_HP
);
1245 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_HP
);
1249 float Creature::_GetDamageMod(int32 Rank
)
1251 switch (Rank
) // define rates for each elite rank
1253 case CREATURE_ELITE_NORMAL
:
1254 return sWorld
.getRate(RATE_CREATURE_NORMAL_DAMAGE
);
1255 case CREATURE_ELITE_ELITE
:
1256 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE
);
1257 case CREATURE_ELITE_RAREELITE
:
1258 return sWorld
.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE
);
1259 case CREATURE_ELITE_WORLDBOSS
:
1260 return sWorld
.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE
);
1261 case CREATURE_ELITE_RARE
:
1262 return sWorld
.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE
);
1264 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE
);
1268 float Creature::GetSpellDamageMod(int32 Rank
)
1270 switch (Rank
) // define rates for each elite rank
1272 case CREATURE_ELITE_NORMAL
:
1273 return sWorld
.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE
);
1274 case CREATURE_ELITE_ELITE
:
1275 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE
);
1276 case CREATURE_ELITE_RAREELITE
:
1277 return sWorld
.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE
);
1278 case CREATURE_ELITE_WORLDBOSS
:
1279 return sWorld
.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE
);
1280 case CREATURE_ELITE_RARE
:
1281 return sWorld
.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE
);
1283 return sWorld
.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE
);
1287 bool Creature::CreateFromProto(uint32 guidlow
, uint32 Entry
, uint32 team
, const CreatureData
*data
)
1289 CreatureInfo
const *cinfo
= objmgr
.GetCreatureTemplate(Entry
);
1292 sLog
.outErrorDb("Creature entry %u does not exist.", Entry
);
1295 m_originalEntry
= Entry
;
1297 Object::_Create(guidlow
, Entry
, HIGHGUID_UNIT
);
1299 if(!UpdateEntry(Entry
, team
, data
))
1302 //Notify the map's instance data.
1303 //Only works if you create the object in it, not if it is moves to that map.
1304 //Normally non-players do not teleport to other maps.
1305 Map
*map
= MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1306 if(map
&& map
->IsDungeon() && ((InstanceMap
*)map
)->GetInstanceData())
1308 ((InstanceMap
*)map
)->GetInstanceData()->OnCreatureCreate(this);
1314 bool Creature::LoadFromDB(uint32 guid
, Map
*map
)
1316 CreatureData
const* data
= objmgr
.GetCreatureData(guid
);
1320 sLog
.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid
);
1324 m_DBTableGuid
= guid
;
1325 if (map
->GetInstanceId() != 0) guid
= objmgr
.GenerateLowGuid(HIGHGUID_UNIT
);
1328 if(!Create(guid
,map
,data
->phaseMask
,data
->id
,team
,data
))
1331 Relocate(data
->posX
,data
->posY
,data
->posZ
,data
->orientation
);
1333 if(!IsPositionValid())
1335 sLog
.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1339 m_respawnradius
= data
->spawndist
;
1341 m_respawnDelay
= data
->spawntimesecs
;
1342 m_isDeadByDefault
= data
->is_dead
;
1343 m_deathState
= m_isDeadByDefault
? DEAD
: ALIVE
;
1345 m_respawnTime
= objmgr
.GetCreatureRespawnTime(m_DBTableGuid
,GetInstanceId());
1346 if(m_respawnTime
> time(NULL
)) // not ready to respawn
1348 m_deathState
= DEAD
;
1351 float tz
= GetMap()->GetHeight(data
->posX
,data
->posY
,data
->posZ
,false);
1352 if(data
->posZ
- tz
> 0.1)
1353 Relocate(data
->posX
,data
->posY
,tz
);
1356 else if(m_respawnTime
) // respawn time set but expired
1359 objmgr
.SaveCreatureRespawnTime(m_DBTableGuid
,GetInstanceId(),0);
1362 uint32 curhealth
= data
->curhealth
;
1365 curhealth
= uint32(curhealth
*_GetHealthMod(GetCreatureInfo()->rank
));
1370 SetHealth(m_deathState
== ALIVE
? curhealth
: 0);
1371 SetPower(POWER_MANA
,data
->curmana
);
1373 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool
));
1375 // checked at creature_template loading
1376 m_defaultMovementType
= MovementGeneratorType(data
->movementType
);
1382 void Creature::LoadEquipment(uint32 equip_entry
, bool force
)
1384 if(equip_entry
== 0)
1388 for (uint8 i
= 0; i
< 3; ++i
)
1389 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID
+ i
, 0);
1395 EquipmentInfo
const *einfo
= objmgr
.GetEquipmentInfo(equip_entry
);
1399 m_equipmentId
= equip_entry
;
1400 for (uint8 i
= 0; i
< 3; ++i
)
1401 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID
+ i
, einfo
->equipentry
[i
]);
1404 bool Creature::hasQuest(uint32 quest_id
) const
1406 QuestRelations
const& qr
= objmgr
.mCreatureQuestRelations
;
1407 for(QuestRelations::const_iterator itr
= qr
.lower_bound(GetEntry()); itr
!= qr
.upper_bound(GetEntry()); ++itr
)
1409 if(itr
->second
==quest_id
)
1415 bool Creature::hasInvolvedQuest(uint32 quest_id
) const
1417 QuestRelations
const& qr
= objmgr
.mCreatureQuestInvolvedRelations
;
1418 for(QuestRelations::const_iterator itr
= qr
.lower_bound(GetEntry()); itr
!= qr
.upper_bound(GetEntry()); ++itr
)
1420 if(itr
->second
==quest_id
)
1426 void Creature::DeleteFromDB()
1430 sLog
.outDebug("Trying to delete not saved creature!");
1434 objmgr
.SaveCreatureRespawnTime(m_DBTableGuid
,GetInstanceId(),0);
1435 objmgr
.DeleteCreatureData(m_DBTableGuid
);
1437 WorldDatabase
.BeginTransaction();
1438 WorldDatabase
.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid
);
1439 WorldDatabase
.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid
);
1440 WorldDatabase
.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid
);
1441 WorldDatabase
.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid
);
1442 WorldDatabase
.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid
);
1443 WorldDatabase
.CommitTransaction();
1446 float Creature::GetAttackDistance(Unit
const* pl
) const
1448 float aggroRate
= sWorld
.getRate(RATE_CREATURE_AGGRO
);
1452 int32 playerlevel
= pl
->getLevelForTarget(this);
1453 int32 creaturelevel
= getLevelForTarget(pl
);
1455 int32 leveldif
= playerlevel
- creaturelevel
;
1457 // "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."
1458 if ( leveldif
< - 25)
1461 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1462 float RetDistance
= 20;
1464 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1465 // radius grow if playlevel < creaturelevel
1466 RetDistance
-= (float)leveldif
;
1468 if(creaturelevel
+5 <= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
1470 // detect range auras
1471 RetDistance
+= GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE
);
1473 // detected range auras
1474 RetDistance
+= pl
->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE
);
1477 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1481 return (RetDistance
*aggroRate
);
1484 void Creature::setDeathState(DeathState s
)
1486 if((s
== JUST_DIED
&& !m_isDeadByDefault
)||(s
== JUST_ALIVED
&& m_isDeadByDefault
))
1488 m_deathTimer
= m_corpseDelay
*IN_MILISECONDS
;
1490 // always save boss respawn time at death to prevent crash cheating
1491 if(sWorld
.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY
) || isWorldBoss())
1494 if (canFly() && FallGround())
1500 Unit::setDeathState(s
);
1504 SetUInt64Value (UNIT_FIELD_TARGET
,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1505 SetUInt32Value(UNIT_NPC_FLAGS
, 0);
1507 if(!isPet() && GetCreatureInfo()->SkinLootId
)
1508 if ( LootTemplates_Skinning
.HaveLootFor(GetCreatureInfo()->SkinLootId
) )
1509 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
1511 if (canFly() && FallGround())
1514 SetNoSearchAssistance(false);
1515 Unit::setDeathState(CORPSE
);
1517 if(s
== JUST_ALIVED
)
1519 SetHealth(GetMaxHealth());
1520 SetLootRecipient(NULL
);
1521 Unit::setDeathState(ALIVE
);
1522 CreatureInfo
const *cinfo
= GetCreatureInfo();
1523 SetUInt32Value(UNIT_DYNAMIC_FLAGS
, 0);
1524 RemoveFlag (UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
1525 AddUnitMovementFlag(MONSTER_MOVE_WALK
);
1526 SetUInt32Value(UNIT_NPC_FLAGS
, cinfo
->npcflag
);
1527 clearUnitState(UNIT_STAT_ALL_STATE
);
1528 i_motionMaster
.Clear();
1529 SetMeleeDamageSchool(SpellSchools(cinfo
->dmgschool
));
1530 LoadCreaturesAddon(true);
1534 bool Creature::FallGround()
1536 // Let's abort after we called this function one time
1537 if (getDeathState() == DEAD_FALLING
)
1540 // Let's do with no vmap because no way to get far distance with vmap high call
1541 float tz
= GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1543 // Abort too if the ground is very near
1544 if (fabs(GetPositionZ() - tz
) < 0.1f
)
1547 Unit::setDeathState(DEAD_FALLING
);
1548 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz
);
1549 Relocate(GetPositionX(), GetPositionY(), tz
);
1553 void Creature::Respawn()
1557 // forced recreate creature object at clients
1558 UnitVisibility currentVis
= GetVisibility();
1559 SetVisibility(VISIBILITY_RESPAWN
);
1560 ObjectAccessor::UpdateObjectVisibility(this);
1561 SetVisibility(currentVis
); // restore visibility state
1562 ObjectAccessor::UpdateObjectVisibility(this);
1564 if(getDeathState()==DEAD
)
1567 objmgr
.SaveCreatureRespawnTime(m_DBTableGuid
,GetInstanceId(),0);
1568 m_respawnTime
= time(NULL
); // respawn at next tick
1572 bool Creature::IsImmunedToSpell(SpellEntry
const* spellInfo
)
1577 if (GetCreatureInfo()->MechanicImmuneMask
& (1 << (spellInfo
->Mechanic
- 1)))
1580 return Unit::IsImmunedToSpell(spellInfo
);
1583 bool Creature::IsImmunedToSpellEffect(SpellEntry
const* spellInfo
, uint32 index
) const
1585 if (GetCreatureInfo()->MechanicImmuneMask
& (1 << (spellInfo
->EffectMechanic
[index
] - 1)))
1588 // Taunt immunity special flag check
1589 if (GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NOT_TAUNTABLE
)
1591 // Taunt aura apply check
1592 if (spellInfo
->Effect
[index
] == SPELL_EFFECT_APPLY_AURA
)
1594 if (spellInfo
->EffectApplyAuraName
[index
] == SPELL_AURA_MOD_TAUNT
)
1597 // Spell effect taunt check
1598 else if (spellInfo
->Effect
[index
] == SPELL_EFFECT_ATTACK_ME
)
1602 return Unit::IsImmunedToSpellEffect(spellInfo
, index
);
1605 SpellEntry
const *Creature::reachWithSpellAttack(Unit
*pVictim
)
1610 for(uint32 i
=0; i
< CREATURE_MAX_SPELLS
; ++i
)
1614 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(m_spells
[i
] );
1617 sLog
.outError("WORLD: unknown spell id %i", m_spells
[i
]);
1621 bool bcontinue
= true;
1622 for(uint32 j
=0;j
<3;j
++)
1624 if( (spellInfo
->Effect
[j
] == SPELL_EFFECT_SCHOOL_DAMAGE
) ||
1625 (spellInfo
->Effect
[j
] == SPELL_EFFECT_INSTAKILL
) ||
1626 (spellInfo
->Effect
[j
] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE
) ||
1627 (spellInfo
->Effect
[j
] == SPELL_EFFECT_HEALTH_LEECH
)
1634 if(bcontinue
) continue;
1636 if(spellInfo
->manaCost
> GetPower(POWER_MANA
))
1638 SpellRangeEntry
const* srange
= sSpellRangeStore
.LookupEntry(spellInfo
->rangeIndex
);
1639 float range
= GetSpellMaxRange(srange
);
1640 float minrange
= GetSpellMinRange(srange
);
1642 float dist
= GetCombatDistance(pVictim
);
1644 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1646 if( dist
> range
|| dist
< minrange
)
1648 if(spellInfo
->PreventionType
== SPELL_PREVENTION_TYPE_SILENCE
&& HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SILENCED
))
1650 if(spellInfo
->PreventionType
== SPELL_PREVENTION_TYPE_PACIFY
&& HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PACIFIED
))
1657 SpellEntry
const *Creature::reachWithSpellCure(Unit
*pVictim
)
1662 for(uint32 i
=0; i
< CREATURE_MAX_SPELLS
; ++i
)
1666 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(m_spells
[i
] );
1669 sLog
.outError("WORLD: unknown spell id %i", m_spells
[i
]);
1673 bool bcontinue
= true;
1674 for(uint32 j
=0;j
<3;j
++)
1676 if( (spellInfo
->Effect
[j
] == SPELL_EFFECT_HEAL
) )
1682 if(bcontinue
) continue;
1684 if(spellInfo
->manaCost
> GetPower(POWER_MANA
))
1686 SpellRangeEntry
const* srange
= sSpellRangeStore
.LookupEntry(spellInfo
->rangeIndex
);
1687 float range
= GetSpellMaxRange(srange
);
1688 float minrange
= GetSpellMinRange(srange
);
1690 float dist
= GetCombatDistance(pVictim
);
1692 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1694 if( dist
> range
|| dist
< minrange
)
1696 if(spellInfo
->PreventionType
== SPELL_PREVENTION_TYPE_SILENCE
&& HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SILENCED
))
1698 if(spellInfo
->PreventionType
== SPELL_PREVENTION_TYPE_PACIFY
&& HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PACIFIED
))
1705 bool Creature::IsVisibleInGridForPlayer(Player
* pl
) const
1707 // gamemaster in GM mode see all, including ghosts
1708 if(pl
->isGameMaster())
1711 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1712 if(pl
->isAlive() || pl
->GetDeathTimer() > 0)
1714 if(GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_INVISIBLE
)
1716 return isAlive() || m_deathTimer
> 0 || m_isDeadByDefault
&& m_deathState
==CORPSE
;
1719 // Dead player see live creatures near own corpse
1722 Corpse
*corpse
= pl
->GetCorpse();
1725 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1726 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
1731 // Dead player see Spirit Healer or Spirit Guide
1732 if(isSpiritService())
1735 // and not see any other
1739 void Creature::CallAssistance()
1741 if( !m_AlreadyCallAssistance
&& getVictim() && !isPet() && !isCharmed())
1743 SetNoCallAssistance(true);
1745 float radius
= sWorld
.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS
);
1748 std::list
<Creature
*> assistList
;
1751 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1753 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1756 MaNGOS::AnyAssistCreatureInRangeCheck
u_check(this, getVictim(), radius
);
1757 MaNGOS::CreatureListSearcher
<MaNGOS::AnyAssistCreatureInRangeCheck
> searcher(this, assistList
, u_check
);
1759 TypeContainerVisitor
<MaNGOS::CreatureListSearcher
<MaNGOS::AnyAssistCreatureInRangeCheck
>, GridTypeMapContainer
> grid_creature_searcher(searcher
);
1761 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1762 cell_lock
->Visit(cell_lock
, grid_creature_searcher
, *GetMap());
1765 if (!assistList
.empty())
1767 AssistDelayEvent
*e
= new AssistDelayEvent(getVictim()->GetGUID(), *this);
1768 while (!assistList
.empty())
1770 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1771 e
->AddAssistant((*assistList
.begin())->GetGUID());
1772 assistList
.pop_front();
1774 m_Events
.AddEvent(e
, m_Events
.CalculateTime(sWorld
.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY
)));
1780 bool Creature::CanAssistTo(const Unit
* u
, const Unit
* enemy
, bool checkfaction
/*= true*/) const
1782 // we don't need help from zombies :)
1786 // skip fighting creature
1790 // only free creature
1791 if (GetCharmerOrOwnerGUID())
1794 // only from same creature faction
1797 if (getFaction() != u
->getFaction())
1802 if (!IsFriendlyTo(u
))
1806 // skip non hostile to caster enemy creatures
1807 if (!IsHostileTo(enemy
))
1813 void Creature::SaveRespawnTime()
1815 if(isPet() || !m_DBTableGuid
)
1818 if(m_respawnTime
> time(NULL
)) // dead (no corpse)
1819 objmgr
.SaveCreatureRespawnTime(m_DBTableGuid
,GetInstanceId(),m_respawnTime
);
1820 else if(m_deathTimer
> 0) // dead (corpse)
1821 objmgr
.SaveCreatureRespawnTime(m_DBTableGuid
,GetInstanceId(),time(NULL
)+m_respawnDelay
+m_deathTimer
/IN_MILISECONDS
);
1824 bool Creature::IsOutOfThreatArea(Unit
* pVictim
) const
1829 if(!pVictim
->IsInMap(this))
1832 if(!pVictim
->isTargetableForAttack())
1835 if(!pVictim
->isInAccessablePlaceFor(this))
1838 if(sMapStore
.LookupEntry(GetMapId())->IsDungeon())
1841 float AttackDist
= GetAttackDistance(pVictim
);
1842 uint32 ThreatRadius
= sWorld
.getConfig(CONFIG_THREAT_RADIUS
);
1844 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1845 return !pVictim
->IsWithinDist3d(CombatStartX
,CombatStartY
,CombatStartZ
,
1846 ThreatRadius
> AttackDist
? ThreatRadius
: AttackDist
);
1849 CreatureDataAddon
const* Creature::GetCreatureAddon() const
1853 if(CreatureDataAddon
const* addon
= ObjectMgr::GetCreatureAddon(m_DBTableGuid
))
1857 // dependent from heroic mode entry
1858 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry
);
1861 //creature_addon table
1862 bool Creature::LoadCreaturesAddon(bool reload
)
1864 CreatureDataAddon
const *cainfo
= GetCreatureAddon();
1868 if (cainfo
->mount
!= 0)
1869 Mount(cainfo
->mount
);
1871 if (cainfo
->bytes1
!= 0)
1872 SetUInt32Value(UNIT_FIELD_BYTES_1
, cainfo
->bytes1
);
1874 if (cainfo
->bytes2
!= 0)
1875 SetUInt32Value(UNIT_FIELD_BYTES_2
, cainfo
->bytes2
);
1877 if (cainfo
->emote
!= 0)
1878 SetUInt32Value(UNIT_NPC_EMOTESTATE
, cainfo
->emote
);
1880 if (cainfo
->move_flags
!= 0)
1881 SetUnitMovementFlags(cainfo
->move_flags
);
1885 for (CreatureDataAddonAura
const* cAura
= cainfo
->auras
; cAura
->spell_id
; ++cAura
)
1887 SpellEntry
const *AdditionalSpellInfo
= sSpellStore
.LookupEntry(cAura
->spell_id
);
1888 if (!AdditionalSpellInfo
)
1890 sLog
.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura
->spell_id
);
1894 // skip already applied aura
1895 if(HasAura(cAura
->spell_id
,cAura
->effect_idx
))
1898 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
);
1903 Aura
* AdditionalAura
= CreateAura(AdditionalSpellInfo
, cAura
->effect_idx
, NULL
, this, this, 0);
1904 AddAura(AdditionalAura
);
1905 sLog
.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura
->spell_id
, AdditionalSpellInfo
->EffectApplyAuraName
[0],GetGUIDLow(),GetEntry());
1911 /// Send a message to LocalDefense channel for players opposition team in the zone
1912 void Creature::SendZoneUnderAttackMessage(Player
* attacker
)
1914 uint32 enemy_team
= attacker
->GetTeam();
1916 WorldPacket
data(SMSG_ZONE_UNDER_ATTACK
,4);
1917 data
<< (uint32
)GetZoneId();
1918 sWorld
.SendGlobalMessage(&data
,NULL
,(enemy_team
==ALLIANCE
? HORDE
: ALLIANCE
));
1921 void Creature::_AddCreatureSpellCooldown(uint32 spell_id
, time_t end_time
)
1923 m_CreatureSpellCooldowns
[spell_id
] = end_time
;
1926 void Creature::_AddCreatureCategoryCooldown(uint32 category
, time_t apply_time
)
1928 m_CreatureCategoryCooldowns
[category
] = apply_time
;
1931 void Creature::AddCreatureSpellCooldown(uint32 spellid
)
1933 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellid
);
1937 uint32 cooldown
= GetSpellRecoveryTime(spellInfo
);
1939 _AddCreatureSpellCooldown(spellid
, time(NULL
) + cooldown
/IN_MILISECONDS
);
1941 if(spellInfo
->Category
)
1942 _AddCreatureCategoryCooldown(spellInfo
->Category
, time(NULL
));
1944 m_GlobalCooldown
= spellInfo
->StartRecoveryTime
;
1947 bool Creature::HasCategoryCooldown(uint32 spell_id
) const
1949 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
1953 // check global cooldown if spell affected by it
1954 if (spellInfo
->StartRecoveryCategory
> 0 && m_GlobalCooldown
> 0)
1957 CreatureSpellCooldowns::const_iterator itr
= m_CreatureCategoryCooldowns
.find(spellInfo
->Category
);
1958 return(itr
!= m_CreatureCategoryCooldowns
.end() && time_t(itr
->second
+ (spellInfo
->CategoryRecoveryTime
/ IN_MILISECONDS
)) > time(NULL
));
1961 bool Creature::HasSpellCooldown(uint32 spell_id
) const
1963 CreatureSpellCooldowns::const_iterator itr
= m_CreatureSpellCooldowns
.find(spell_id
);
1964 return (itr
!= m_CreatureSpellCooldowns
.end() && itr
->second
> time(NULL
)) || HasCategoryCooldown(spell_id
);
1967 bool Creature::IsInEvadeMode() const
1969 return !i_motionMaster
.empty() && i_motionMaster
.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE
;
1972 bool Creature::HasSpell(uint32 spellID
) const
1975 for(i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
1976 if(spellID
== m_spells
[i
])
1978 return i
< CREATURE_MAX_SPELLS
; //broke before end of iteration of known spells
1981 time_t Creature::GetRespawnTimeEx() const
1983 time_t now
= time(NULL
);
1984 if(m_respawnTime
> now
) // dead (no corpse)
1985 return m_respawnTime
;
1986 else if(m_deathTimer
> 0) // dead (corpse)
1987 return now
+m_respawnDelay
+m_deathTimer
/IN_MILISECONDS
;
1992 void Creature::GetRespawnCoord( float &x
, float &y
, float &z
, float* ori
, float* dist
) const
1996 if (CreatureData
const* data
= objmgr
.GetCreatureData(GetDBTableGUIDLow()))
2002 *ori
= data
->orientation
;
2004 *dist
= data
->spawndist
;
2014 *ori
= GetOrientation();
2019 void Creature::AllLootRemovedFromCorpse()
2021 if (!HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
))
2025 CreatureInfo
const *cinfo
= GetCreatureInfo();
2027 // corpse was not skinnable -> apply corpse looted timer
2028 if (!cinfo
|| !cinfo
->SkinLootId
)
2029 nDeathTimer
= (uint32
)((m_corpseDelay
* IN_MILISECONDS
) * sWorld
.getRate(RATE_CORPSE_DECAY_LOOTED
));
2030 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
2034 // update death timer only if looted timer is shorter
2035 if (m_deathTimer
> nDeathTimer
)
2036 m_deathTimer
= nDeathTimer
;
2040 uint32
Creature::getLevelForTarget( Unit
const* target
) const
2043 return Unit::getLevelForTarget(target
);
2045 uint32 level
= target
->getLevel()+sWorld
.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF
);
2053 std::string
Creature::GetAIName() const
2055 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName
;
2058 std::string
Creature::GetScriptName() const
2060 return objmgr
.GetScriptName(GetScriptId());
2063 uint32
Creature::GetScriptId() const
2065 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID
;
2068 VendorItemData
const* Creature::GetVendorItems() const
2070 return objmgr
.GetNpcVendorItemList(GetEntry());
2073 uint32
Creature::GetVendorItemCurrentCount(VendorItem
const* vItem
)
2075 if(!vItem
->maxcount
)
2076 return vItem
->maxcount
;
2078 VendorItemCounts::iterator itr
= m_vendorItemCounts
.begin();
2079 for(; itr
!= m_vendorItemCounts
.end(); ++itr
)
2080 if(itr
->itemId
==vItem
->item
)
2083 if(itr
== m_vendorItemCounts
.end())
2084 return vItem
->maxcount
;
2086 VendorItemCount
* vCount
= &*itr
;
2088 time_t ptime
= time(NULL
);
2090 if( vCount
->lastIncrementTime
+ vItem
->incrtime
<= ptime
)
2092 ItemPrototype
const* pProto
= objmgr
.GetItemPrototype(vItem
->item
);
2094 uint32 diff
= uint32((ptime
- vCount
->lastIncrementTime
)/vItem
->incrtime
);
2095 if((vCount
->count
+ diff
* pProto
->BuyCount
) >= vItem
->maxcount
)
2097 m_vendorItemCounts
.erase(itr
);
2098 return vItem
->maxcount
;
2101 vCount
->count
+= diff
* pProto
->BuyCount
;
2102 vCount
->lastIncrementTime
= ptime
;
2105 return vCount
->count
;
2108 uint32
Creature::UpdateVendorItemCurrentCount(VendorItem
const* vItem
, uint32 used_count
)
2110 if(!vItem
->maxcount
)
2113 VendorItemCounts::iterator itr
= m_vendorItemCounts
.begin();
2114 for(; itr
!= m_vendorItemCounts
.end(); ++itr
)
2115 if(itr
->itemId
==vItem
->item
)
2118 if(itr
== m_vendorItemCounts
.end())
2120 uint32 new_count
= vItem
->maxcount
> used_count
? vItem
->maxcount
-used_count
: 0;
2121 m_vendorItemCounts
.push_back(VendorItemCount(vItem
->item
,new_count
));
2125 VendorItemCount
* vCount
= &*itr
;
2127 time_t ptime
= time(NULL
);
2129 if( vCount
->lastIncrementTime
+ vItem
->incrtime
<= ptime
)
2131 ItemPrototype
const* pProto
= objmgr
.GetItemPrototype(vItem
->item
);
2133 uint32 diff
= uint32((ptime
- vCount
->lastIncrementTime
)/vItem
->incrtime
);
2134 if((vCount
->count
+ diff
* pProto
->BuyCount
) < vItem
->maxcount
)
2135 vCount
->count
+= diff
* pProto
->BuyCount
;
2137 vCount
->count
= vItem
->maxcount
;
2140 vCount
->count
= vCount
->count
> used_count
? vCount
->count
-used_count
: 0;
2141 vCount
->lastIncrementTime
= ptime
;
2142 return vCount
->count
;
2145 TrainerSpellData
const* Creature::GetTrainerSpells() const
2147 return objmgr
.GetNpcTrainerSpells(GetEntry());
2150 // overwrite WorldObject function for proper name localization
2151 const char* Creature::GetNameForLocaleIdx(int32 loc_idx
) const
2155 CreatureLocale
const *cl
= objmgr
.GetCreatureLocale(GetEntry());
2158 if (cl
->Name
.size() > loc_idx
&& !cl
->Name
[loc_idx
].empty())
2159 return cl
->Name
[loc_idx
].c_str();
2166 void Creature::SetActiveObjectState( bool on
)
2168 if(m_isActiveObject
==on
)
2171 bool world
= IsInWorld();
2177 map
->Remove(this,false);
2180 m_isActiveObject
= on
;