Make flying creatures fall on ground when killed.
[getmangos.git] / src / game / Creature.cpp
blob5a1a80f2e5d83a7b6645dca92a6f0950cb646722
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 //float x,y;
930 //bool findnpc=false;
931 Poi_Icon icon = ICON_POI_0;
932 //QueryResult *result;
933 //Field *fields;
934 uint32 mapid=GetMapId();
935 Map const* map=MapManager::Instance().GetBaseMap( mapid );
936 uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
937 uint32 zoneid=Map::GetZoneId(areaflag,mapid);
938 std::string areaname= gossip->OptionText;
940 uint16 pflag;
942 // use the action relate to creaturetemplate.trainer_type ?
943 result= WorldDatabase.PQuery("SELECT creature.position_x,creature.position_y FROM creature,creature_template WHERE creature.map = '%u' AND creature.id = creature_template.entry AND creature_template.trainer_type = '%u'", mapid, gossip->Action );
944 if(!result)
945 return;
948 fields = result->Fetch();
949 x=fields[0].GetFloat();
950 y=fields[1].GetFloat();
951 pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
952 if(pflag==areaflag)
954 findnpc=true;
955 break;
957 }while(result->NextRow());
959 delete result;
961 if(!findnpc)
963 player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
964 return;
967 //need add more case.
968 switch(gossip->Action)
970 case GOSSIP_GUARD_BANK:
971 icon=ICON_POI_HOUSE;
972 break;
973 case GOSSIP_GUARD_RIDE:
974 icon=ICON_POI_RWHORSE;
975 break;
976 case GOSSIP_GUARD_GUILD:
977 icon=ICON_POI_BLUETOWER;
978 break;
979 default:
980 icon=ICON_POI_TOWER;
981 break;
983 uint32 textid=GetGossipTextId( gossip->Action, zoneid );
984 player->PlayerTalkClass->SendTalking( textid );
985 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
989 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
991 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
993 if(!result)
994 return 0;
996 Field *fields = result->Fetch();
997 uint32 id = fields[0].GetUInt32();
999 delete result;
1001 return id;
1004 uint32 Creature::GetNpcTextId()
1006 if (!m_DBTableGuid)
1007 return DEFAULT_GOSSIP_MESSAGE;
1009 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1010 return pos;
1012 return DEFAULT_GOSSIP_MESSAGE;
1015 GossipOption const* Creature::GetGossipOption( uint32 id ) const
1017 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
1019 if(i->Action==id )
1020 return &*i;
1022 return NULL;
1025 void Creature::LoadGossipOptions()
1027 if(m_gossipOptionLoaded)
1028 return;
1030 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1032 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1033 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1034 if(i->NpcFlag & npcflags)
1035 addGossipOption(*i);
1037 m_gossipOptionLoaded = true;
1040 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1042 /* uint32 timeElap = getMSTime();
1043 if ((timeElap - m_startMove) < m_moveTime)
1045 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1046 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1048 else
1050 oX = dX;
1051 oY = dY;
1054 dX = x;
1055 dY = y;
1056 m_orientation = atan2((oY - dY), (oX - dX));
1058 m_startMove = getMSTime();
1059 m_moveTime = time;*/
1060 SendMonsterMove(x, y, z, type, MovementFlags, time);
1063 Player *Creature::GetLootRecipient() const
1065 if (!m_lootRecipient) return NULL;
1066 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1069 void Creature::SetLootRecipient(Unit *unit)
1071 // set the player whose group should receive the right
1072 // to loot the creature after it dies
1073 // should be set to NULL after the loot disappears
1075 if (!unit)
1077 m_lootRecipient = 0;
1078 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1079 return;
1082 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1083 if(!player) // normal creature, no player involved
1084 return;
1086 m_lootRecipient = player->GetGUID();
1087 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1090 void Creature::SaveToDB()
1092 // this should only be used when the creature has already been loaded
1093 // preferably after adding to map, because mapid may not be valid otherwise
1094 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1095 if(!data)
1097 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1098 return;
1101 SaveToDB(GetMapId(), data->spawnMask);
1104 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1106 // update in loaded data
1107 if (!m_DBTableGuid)
1108 m_DBTableGuid = GetGUIDLow();
1109 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1111 uint32 displayId = GetNativeDisplayId();
1113 // check if it's a custom model and if not, use 0 for displayId
1114 CreatureInfo const *cinfo = GetCreatureInfo();
1115 if(cinfo)
1117 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1119 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1120 if(!minfo || displayId != minfo->modelid_other_gender)
1122 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1123 if(minfo && displayId == minfo->modelid_other_gender)
1124 displayId = 0;
1126 else
1127 displayId = 0;
1129 else
1130 displayId = 0;
1133 // data->guid = guid don't must be update at save
1134 data.id = GetEntry();
1135 data.mapid = mapid;
1136 data.displayid = displayId;
1137 data.equipmentId = GetEquipmentId();
1138 data.posX = GetPositionX();
1139 data.posY = GetPositionY();
1140 data.posZ = GetPositionZ();
1141 data.orientation = GetOrientation();
1142 data.spawntimesecs = m_respawnDelay;
1143 // prevent add data integrity problems
1144 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1145 data.currentwaypoint = 0;
1146 data.curhealth = GetHealth();
1147 data.curmana = GetPower(POWER_MANA);
1148 data.is_dead = m_isDeadByDefault;
1149 // prevent add data integrity problems
1150 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1151 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1152 data.spawnMask = spawnMask;
1154 // updated in DB
1155 WorldDatabase.BeginTransaction();
1157 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1159 std::ostringstream ss;
1160 ss << "INSERT INTO creature VALUES ("
1161 << m_DBTableGuid << ","
1162 << GetEntry() << ","
1163 << mapid <<","
1164 << (uint32)spawnMask << ","
1165 << displayId <<","
1166 << GetEquipmentId() <<","
1167 << GetPositionX() << ","
1168 << GetPositionY() << ","
1169 << GetPositionZ() << ","
1170 << GetOrientation() << ","
1171 << m_respawnDelay << "," //respawn time
1172 << (float) m_respawnradius << "," //spawn distance (float)
1173 << (uint32) (0) << "," //currentwaypoint
1174 << GetHealth() << "," //curhealth
1175 << GetPower(POWER_MANA) << "," //curmana
1176 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1177 << GetDefaultMovementType() << ")"; //default movement generator type
1179 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1181 WorldDatabase.CommitTransaction();
1184 void Creature::SelectLevel(const CreatureInfo *cinfo)
1186 uint32 rank = isPet()? 0 : cinfo->rank;
1188 // level
1189 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1190 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1191 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1192 SetLevel(level);
1194 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1196 // health
1197 float healthmod = _GetHealthMod(rank);
1199 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1200 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1201 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1203 SetCreateHealth(health);
1204 SetMaxHealth(health);
1205 SetHealth(health);
1207 // mana
1208 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1209 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1210 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1212 SetCreateMana(mana);
1213 SetMaxPower(POWER_MANA, mana); //MAX Mana
1214 SetPower(POWER_MANA, mana);
1216 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1217 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1219 // damage
1220 float damagemod = _GetDamageMod(rank);
1222 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1223 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1225 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1226 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1228 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1231 float Creature::_GetHealthMod(int32 Rank)
1233 switch (Rank) // define rates for each elite rank
1235 case CREATURE_ELITE_NORMAL:
1236 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1237 case CREATURE_ELITE_ELITE:
1238 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1239 case CREATURE_ELITE_RAREELITE:
1240 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1241 case CREATURE_ELITE_WORLDBOSS:
1242 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1243 case CREATURE_ELITE_RARE:
1244 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1245 default:
1246 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1250 float Creature::_GetDamageMod(int32 Rank)
1252 switch (Rank) // define rates for each elite rank
1254 case CREATURE_ELITE_NORMAL:
1255 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1256 case CREATURE_ELITE_ELITE:
1257 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1258 case CREATURE_ELITE_RAREELITE:
1259 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1260 case CREATURE_ELITE_WORLDBOSS:
1261 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1262 case CREATURE_ELITE_RARE:
1263 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1264 default:
1265 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1269 float Creature::GetSpellDamageMod(int32 Rank)
1271 switch (Rank) // define rates for each elite rank
1273 case CREATURE_ELITE_NORMAL:
1274 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1275 case CREATURE_ELITE_ELITE:
1276 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1277 case CREATURE_ELITE_RAREELITE:
1278 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1279 case CREATURE_ELITE_WORLDBOSS:
1280 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1281 case CREATURE_ELITE_RARE:
1282 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1283 default:
1284 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1288 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1290 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1291 if(!cinfo)
1293 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1294 return false;
1296 m_originalEntry = Entry;
1298 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1300 if(!UpdateEntry(Entry, team, data))
1301 return false;
1303 //Notify the map's instance data.
1304 //Only works if you create the object in it, not if it is moves to that map.
1305 //Normally non-players do not teleport to other maps.
1306 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1307 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1309 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1312 return true;
1315 bool Creature::LoadFromDB(uint32 guid, Map *map)
1317 CreatureData const* data = objmgr.GetCreatureData(guid);
1319 if(!data)
1321 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1322 return false;
1325 m_DBTableGuid = guid;
1326 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1328 uint16 team = 0;
1329 if(!Create(guid,map,data->id,team,data))
1330 return false;
1332 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1334 if(!IsPositionValid())
1336 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1337 return false;
1340 m_respawnradius = data->spawndist;
1342 m_respawnDelay = data->spawntimesecs;
1343 m_isDeadByDefault = data->is_dead;
1344 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1346 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1347 if(m_respawnTime > time(NULL)) // not ready to respawn
1348 m_deathState = DEAD;
1349 else if(m_respawnTime) // respawn time set but expired
1351 m_respawnTime = 0;
1352 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1355 uint32 curhealth = data->curhealth;
1356 if(curhealth)
1358 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1359 if(curhealth < 1)
1360 curhealth = 1;
1363 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1364 SetPower(POWER_MANA,data->curmana);
1366 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1368 // checked at creature_template loading
1369 m_defaultMovementType = MovementGeneratorType(data->movementType);
1371 AIM_Initialize();
1372 return true;
1375 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1377 if(equip_entry == 0)
1379 if (force)
1381 for (uint8 i = 0; i < 3; i++)
1383 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1384 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1385 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1387 m_equipmentId = 0;
1389 return;
1392 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1393 if (!einfo)
1394 return;
1396 m_equipmentId = equip_entry;
1397 for (uint8 i = 0; i < 3; i++)
1399 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1400 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1401 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1405 bool Creature::hasQuest(uint32 quest_id) const
1407 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1408 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1410 if(itr->second==quest_id)
1411 return true;
1413 return false;
1416 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1418 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1419 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1421 if(itr->second==quest_id)
1422 return true;
1424 return false;
1427 void Creature::DeleteFromDB()
1429 if (!m_DBTableGuid)
1431 sLog.outDebug("Trying to delete not saved creature!");
1432 return;
1435 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1436 objmgr.DeleteCreatureData(m_DBTableGuid);
1438 WorldDatabase.BeginTransaction();
1439 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1440 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1441 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1442 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1443 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1444 WorldDatabase.CommitTransaction();
1447 float Creature::GetAttackDistance(Unit const* pl) const
1449 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1450 if(aggroRate==0)
1451 return 0.0f;
1453 int32 playerlevel = pl->getLevelForTarget(this);
1454 int32 creaturelevel = getLevelForTarget(pl);
1456 int32 leveldif = playerlevel - creaturelevel;
1458 // "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."
1459 if ( leveldif < - 25)
1460 leveldif = -25;
1462 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1463 float RetDistance = 20;
1465 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1466 // radius grow if playlevel < creaturelevel
1467 RetDistance -= (float)leveldif;
1469 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1471 // detect range auras
1472 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1474 // detected range auras
1475 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1478 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1479 if(RetDistance < 5)
1480 RetDistance = 5;
1482 return (RetDistance*aggroRate);
1485 void Creature::setDeathState(DeathState s)
1487 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1489 m_deathTimer = m_corpseDelay*1000;
1491 // always save boss respawn time at death to prevent crash cheating
1492 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1493 SaveRespawnTime();
1495 if (canFly() && FallGround())
1496 return;
1498 if(!IsStopped())
1499 StopMoving();
1501 Unit::setDeathState(s);
1503 if(s == JUST_DIED)
1505 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1506 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1508 if(!isPet() && GetCreatureInfo()->SkinLootId)
1509 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1510 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1512 if (canFly() && FallGround())
1513 return;
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(MOVEMENTFLAG_WALK_MODE);
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)
1538 return false;
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)
1545 return false;
1547 Unit::setDeathState(DEAD_FALLING);
1548 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1549 Relocate(GetPositionX(), GetPositionY(), tz);
1550 return true;
1553 void Creature::Respawn()
1555 RemoveCorpse();
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)
1566 if (m_DBTableGuid)
1567 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1568 m_respawnTime = time(NULL); // respawn at next tick
1572 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1574 if (!spellInfo)
1575 return false;
1577 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1578 return true;
1580 return Unit::IsImmunedToSpell(spellInfo, useCharges);
1583 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1585 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1586 return true;
1588 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1591 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1593 if(!pVictim)
1594 return NULL;
1596 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1598 if(!m_spells[i])
1599 continue;
1600 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1601 if(!spellInfo)
1603 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1604 continue;
1607 bool bcontinue = true;
1608 for(uint32 j=0;j<3;j++)
1610 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1611 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1612 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1613 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1616 bcontinue = false;
1617 break;
1620 if(bcontinue) continue;
1622 if(spellInfo->manaCost > GetPower(POWER_MANA))
1623 continue;
1624 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1625 float range = GetSpellMaxRange(srange);
1626 float minrange = GetSpellMinRange(srange);
1627 float dist = GetDistance(pVictim);
1628 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1629 // continue;
1630 if( dist > range || dist < minrange )
1631 continue;
1632 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1633 continue;
1634 return spellInfo;
1636 return NULL;
1639 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1641 if(!pVictim)
1642 return NULL;
1644 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1646 if(!m_spells[i])
1647 continue;
1648 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1649 if(!spellInfo)
1651 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1652 continue;
1655 bool bcontinue = true;
1656 for(uint32 j=0;j<3;j++)
1658 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1660 bcontinue = false;
1661 break;
1664 if(bcontinue) continue;
1666 if(spellInfo->manaCost > GetPower(POWER_MANA))
1667 continue;
1668 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1669 float range = GetSpellMaxRange(srange);
1670 float minrange = GetSpellMinRange(srange);
1671 float dist = GetDistance(pVictim);
1672 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1673 // continue;
1674 if( dist > range || dist < minrange )
1675 continue;
1676 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1677 continue;
1678 return spellInfo;
1680 return NULL;
1683 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1685 // gamemaster in GM mode see all, including ghosts
1686 if(pl->isGameMaster())
1687 return true;
1689 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1690 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1692 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1693 return false;
1694 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1697 // Dead player see live creatures near own corpse
1698 if(isAlive())
1700 Corpse *corpse = pl->GetCorpse();
1701 if(corpse)
1703 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1704 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1705 return true;
1709 // Dead player see Spirit Healer or Spirit Guide
1710 if(isSpiritService())
1711 return true;
1713 // and not see any other
1714 return false;
1717 void Creature::CallAssistance()
1719 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1721 SetNoCallAssistance(true);
1723 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1724 if(radius > 0)
1726 std::list<Creature*> assistList;
1729 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1730 Cell cell(p);
1731 cell.data.Part.reserved = ALL_DISTRICT;
1732 cell.SetNoCreate();
1734 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1735 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1737 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1739 CellLock<GridReadGuard> cell_lock(cell, p);
1740 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1743 if (!assistList.empty())
1745 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1746 while (!assistList.empty())
1748 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1749 e->AddAssistant((*assistList.begin())->GetGUID());
1750 assistList.pop_front();
1752 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1758 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1760 // we don't need help from zombies :)
1761 if( !isAlive() )
1762 return false;
1764 // skip fighting creature
1765 if( isInCombat() )
1766 return false;
1768 // only from same creature faction
1769 if(getFaction() != u->getFaction() )
1770 return false;
1772 // only free creature
1773 if( GetCharmerOrOwnerGUID() )
1774 return false;
1776 // skip non hostile to caster enemy creatures
1777 if( !IsHostileTo(enemy) )
1778 return false;
1780 return true;
1783 void Creature::SaveRespawnTime()
1785 if(isPet() || !m_DBTableGuid)
1786 return;
1788 if(m_respawnTime > time(NULL)) // dead (no corpse)
1789 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1790 else if(m_deathTimer > 0) // dead (corpse)
1791 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1794 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1796 if(!pVictim)
1797 return true;
1799 if(!pVictim->IsInMap(this))
1800 return true;
1802 if(!pVictim->isTargetableForAttack())
1803 return true;
1805 if(!pVictim->isInAccessablePlaceFor(this))
1806 return true;
1808 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1809 return false;
1811 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1812 float AttackDist = GetAttackDistance(pVictim);
1813 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1815 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1816 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1819 CreatureDataAddon const* Creature::GetCreatureAddon() const
1821 if (m_DBTableGuid)
1823 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1824 return addon;
1827 // dependent from heroic mode entry
1828 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1831 //creature_addon table
1832 bool Creature::LoadCreaturesAddon(bool reload)
1834 CreatureDataAddon const *cainfo = GetCreatureAddon();
1835 if(!cainfo)
1836 return false;
1838 if (cainfo->mount != 0)
1839 Mount(cainfo->mount);
1841 if (cainfo->bytes0 != 0)
1842 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1844 if (cainfo->bytes1 != 0)
1845 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1847 if (cainfo->bytes2 != 0)
1848 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1850 if (cainfo->emote != 0)
1851 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1853 if (cainfo->move_flags != 0)
1854 SetUnitMovementFlags(cainfo->move_flags);
1856 if(cainfo->auras)
1858 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1860 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1861 if (!AdditionalSpellInfo)
1863 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1864 continue;
1867 // skip already applied aura
1868 if(HasAura(cAura->spell_id,cAura->effect_idx))
1870 if(!reload)
1871 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);
1873 continue;
1876 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1877 AddAura(AdditionalAura);
1878 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1881 return true;
1884 /// Send a message to LocalDefense channel for players opposition team in the zone
1885 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1887 uint32 enemy_team = attacker->GetTeam();
1889 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1890 data << (uint32)GetZoneId();
1891 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1894 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1896 m_CreatureSpellCooldowns[spell_id] = end_time;
1899 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1901 m_CreatureCategoryCooldowns[category] = apply_time;
1904 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1906 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1907 if(!spellInfo)
1908 return;
1910 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1911 if(cooldown)
1912 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1914 if(spellInfo->Category)
1915 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1917 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1920 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1922 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1923 if(!spellInfo)
1924 return false;
1926 // check global cooldown if spell affected by it
1927 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1928 return true;
1930 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1931 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1934 bool Creature::HasSpellCooldown(uint32 spell_id) const
1936 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1937 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1940 bool Creature::IsInEvadeMode() const
1942 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1945 bool Creature::HasSpell(uint32 spellID) const
1947 uint8 i;
1948 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1949 if(spellID == m_spells[i])
1950 break;
1951 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1954 time_t Creature::GetRespawnTimeEx() const
1956 time_t now = time(NULL);
1957 if(m_respawnTime > now) // dead (no corpse)
1958 return m_respawnTime;
1959 else if(m_deathTimer > 0) // dead (corpse)
1960 return now+m_respawnDelay+m_deathTimer/1000;
1961 else
1962 return now;
1965 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1967 if (m_DBTableGuid)
1969 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1971 x = data->posX;
1972 y = data->posY;
1973 z = data->posZ;
1974 if(ori)
1975 *ori = data->orientation;
1976 if(dist)
1977 *dist = data->spawndist;
1979 return;
1983 x = GetPositionX();
1984 y = GetPositionY();
1985 z = GetPositionZ();
1986 if(ori)
1987 *ori = GetOrientation();
1988 if(dist)
1989 *dist = 0;
1992 void Creature::AllLootRemovedFromCorpse()
1994 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1996 uint32 nDeathTimer;
1998 CreatureInfo const *cinfo = GetCreatureInfo();
2000 // corpse was not skinnable -> apply corpse looted timer
2001 if (!cinfo || !cinfo->SkinLootId)
2002 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
2003 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
2004 else
2005 nDeathTimer = 0;
2007 // update death timer only if looted timer is shorter
2008 if (m_deathTimer > nDeathTimer)
2009 m_deathTimer = nDeathTimer;
2013 uint32 Creature::getLevelForTarget( Unit const* target ) const
2015 if(!isWorldBoss())
2016 return Unit::getLevelForTarget(target);
2018 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2019 if(level < 1)
2020 return 1;
2021 if(level > 255)
2022 return 255;
2023 return level;
2026 std::string Creature::GetScriptName()
2028 return objmgr.GetScriptName(GetScriptId());
2031 uint32 Creature::GetScriptId()
2033 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2036 VendorItemData const* Creature::GetVendorItems() const
2038 return objmgr.GetNpcVendorItemList(GetEntry());
2041 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2043 if(!vItem->maxcount)
2044 return vItem->maxcount;
2046 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2047 for(; itr != m_vendorItemCounts.end(); ++itr)
2048 if(itr->itemId==vItem->item)
2049 break;
2051 if(itr == m_vendorItemCounts.end())
2052 return vItem->maxcount;
2054 VendorItemCount* vCount = &*itr;
2056 time_t ptime = time(NULL);
2058 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2060 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2062 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2063 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2065 m_vendorItemCounts.erase(itr);
2066 return vItem->maxcount;
2069 vCount->count += diff * pProto->BuyCount;
2070 vCount->lastIncrementTime = ptime;
2073 return vCount->count;
2076 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2078 if(!vItem->maxcount)
2079 return 0;
2081 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2082 for(; itr != m_vendorItemCounts.end(); ++itr)
2083 if(itr->itemId==vItem->item)
2084 break;
2086 if(itr == m_vendorItemCounts.end())
2088 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2089 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2090 return new_count;
2093 VendorItemCount* vCount = &*itr;
2095 time_t ptime = time(NULL);
2097 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2099 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2101 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2102 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2103 vCount->count += diff * pProto->BuyCount;
2104 else
2105 vCount->count = vItem->maxcount;
2108 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2109 vCount->lastIncrementTime = ptime;
2110 return vCount->count;
2113 TrainerSpellData const* Creature::GetTrainerSpells() const
2115 return objmgr.GetNpcTrainerSpells(GetEntry());
2118 // overwrite WorldObject function for proper name localization
2119 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2121 if (loc_idx >= 0)
2123 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2124 if (cl)
2126 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2127 return cl->Name[loc_idx].c_str();
2131 return GetName();