[6870] Not output error message at loading empty `db_script_string` table.
[getmangos.git] / src / game / Creature.cpp
blobc832804f5810af4bd14249c0dd6a320817029eb3
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 default:
450 break;
454 void Creature::RegenerateMana()
456 uint32 curValue = GetPower(POWER_MANA);
457 uint32 maxValue = GetMaxPower(POWER_MANA);
459 if (curValue >= maxValue)
460 return;
462 uint32 addvalue = 0;
464 // Combat and any controlled creature
465 if (isInCombat() || GetCharmerOrOwnerGUID())
467 if(!IsUnderLastManaUseEffect())
469 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
470 float Spirit = GetStat(STAT_SPIRIT);
472 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
475 else
476 addvalue = maxValue/3;
478 ModifyPower(POWER_MANA, addvalue);
481 void Creature::RegenerateHealth()
483 if (!isRegeneratingHealth())
484 return;
486 uint32 curValue = GetHealth();
487 uint32 maxValue = GetMaxHealth();
489 if (curValue >= maxValue)
490 return;
492 uint32 addvalue = 0;
494 // Not only pet, but any controlled creature
495 if(GetCharmerOrOwnerGUID())
497 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
498 float Spirit = GetStat(STAT_SPIRIT);
500 if( GetPower(POWER_MANA) > 0 )
501 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
502 else
503 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
505 else
506 addvalue = maxValue/3;
508 ModifyHealth(addvalue);
511 bool Creature::AIM_Initialize()
513 // make sure nothing can change the AI during AI update
514 if(m_AI_locked)
516 sLog.outDebug("AIM_Initialize: failed to init, locked.");
517 return false;
520 CreatureAI * oldAI = i_AI;
521 i_motionMaster.Initialize();
522 i_AI = FactorySelector::selectAI(this);
523 if (oldAI)
524 delete oldAI;
525 return true;
528 bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
530 SetMapId(map->GetId());
531 SetInstanceId(map->GetInstanceId());
533 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
534 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
536 if (bResult)
538 switch (GetCreatureInfo()->rank)
540 case CREATURE_ELITE_RARE:
541 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
542 break;
543 case CREATURE_ELITE_ELITE:
544 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
545 break;
546 case CREATURE_ELITE_RAREELITE:
547 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
548 break;
549 case CREATURE_ELITE_WORLDBOSS:
550 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
551 break;
552 default:
553 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
554 break;
556 LoadCreaturesAddon();
559 return bResult;
562 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
564 if(!isTrainer())
565 return false;
567 TrainerSpellData const* trainer_spells = GetTrainerSpells();
569 if(!trainer_spells || trainer_spells->spellList.empty())
571 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
572 GetGUIDLow(),GetEntry());
573 return false;
576 switch(GetCreatureInfo()->trainer_type)
578 case TRAINER_TYPE_CLASS:
579 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
581 if(msg)
583 pPlayer->PlayerTalkClass->ClearMenus();
584 switch(GetCreatureInfo()->classNum)
586 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
587 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
588 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
589 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
590 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
591 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
592 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
593 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
594 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
597 return false;
599 break;
600 case TRAINER_TYPE_PETS:
601 if(pPlayer->getClass()!=CLASS_HUNTER)
603 pPlayer->PlayerTalkClass->ClearMenus();
604 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
605 return false;
607 break;
608 case TRAINER_TYPE_MOUNTS:
609 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
611 if(msg)
613 pPlayer->PlayerTalkClass->ClearMenus();
614 switch(GetCreatureInfo()->classNum)
616 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
617 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
618 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
619 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
620 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
621 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
622 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
623 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
624 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
625 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
628 return false;
630 break;
631 case TRAINER_TYPE_TRADESKILLS:
632 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
634 if(msg)
636 pPlayer->PlayerTalkClass->ClearMenus();
637 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
639 return false;
641 break;
642 default:
643 return false; // checked and error output at creature_template loading
645 return true;
648 bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
650 if(!isBattleMaster())
651 return false;
653 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
654 if(!msg)
655 return pPlayer->GetBGAccessByLevel(bgTypeId);
657 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
659 pPlayer->PlayerTalkClass->ClearMenus();
660 switch(bgTypeId)
662 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
663 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
664 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
665 case BATTLEGROUND_EY:
666 case BATTLEGROUND_NA:
667 case BATTLEGROUND_BE:
668 case BATTLEGROUND_AA:
669 case BATTLEGROUND_RL: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
670 break;
672 return false;
674 return true;
677 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
679 return pPlayer->getLevel() >= 10
680 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
681 && pPlayer->getClass() == GetCreatureInfo()->classNum;
684 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
686 PlayerMenu* pm=pPlayer->PlayerTalkClass;
687 pm->ClearMenus();
689 // lazy loading single time at use
690 LoadGossipOptions();
692 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
694 GossipOption* gso=&*i;
695 if(gso->GossipId == gossipid)
697 bool cantalking=true;
698 if(gso->Id==1)
700 uint32 textid=GetNpcTextId();
701 GossipText * gossiptext=objmgr.GetGossipText(textid);
702 if(!gossiptext)
703 cantalking=false;
705 else
707 switch (gso->Action)
709 case GOSSIP_OPTION_QUESTGIVER:
710 pPlayer->PrepareQuestMenu(GetGUID());
711 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
712 cantalking=false;
713 //pm->GetQuestMenu()->ClearMenu();
714 break;
715 case GOSSIP_OPTION_ARMORER:
716 cantalking=false; // added in special mode
717 break;
718 case GOSSIP_OPTION_SPIRITHEALER:
719 if( !pPlayer->isDead() )
720 cantalking=false;
721 break;
722 case GOSSIP_OPTION_VENDOR:
724 VendorItemData const* vItems = GetVendorItems();
725 if(!vItems || vItems->Empty())
727 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
728 GetGUIDLow(),GetEntry());
729 cantalking=false;
731 break;
733 case GOSSIP_OPTION_TRAINER:
734 if(!isCanTrainingOf(pPlayer,false))
735 cantalking=false;
736 break;
737 case GOSSIP_OPTION_UNLEARNTALENTS:
738 if(!isCanTrainingAndResetTalentsOf(pPlayer))
739 cantalking=false;
740 break;
741 case GOSSIP_OPTION_UNLEARNPETSKILLS:
742 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
743 cantalking=false;
744 break;
745 case GOSSIP_OPTION_TAXIVENDOR:
746 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
747 return;
748 break;
749 case GOSSIP_OPTION_BATTLEFIELD:
750 if(!isCanIneractWithBattleMaster(pPlayer,false))
751 cantalking=false;
752 break;
753 case GOSSIP_OPTION_SPIRITGUIDE:
754 case GOSSIP_OPTION_INNKEEPER:
755 case GOSSIP_OPTION_BANKER:
756 case GOSSIP_OPTION_PETITIONER:
757 case GOSSIP_OPTION_STABLEPET:
758 case GOSSIP_OPTION_TABARDDESIGNER:
759 case GOSSIP_OPTION_AUCTIONEER:
760 break; // no checks
761 default:
762 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
763 break;
767 //note for future dev: should have database fields for BoxMessage & BoxMoney
768 if(!gso->OptionText.empty() && cantalking)
770 std::string OptionText = gso->OptionText;
771 std::string BoxText = gso->BoxText;
772 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
773 if (loc_idx >= 0)
775 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
776 if (no)
778 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
779 OptionText=no->OptionText[loc_idx];
780 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
781 BoxText=no->BoxText[loc_idx];
784 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
789 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
790 if(pm->Empty())
792 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
794 isCanTrainingOf(pPlayer,true); // output error message if need
796 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
798 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
803 void Creature::sendPreparedGossip(Player* player)
805 if(!player)
806 return;
808 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
810 // in case empty gossip menu open quest menu if any
811 if (gossipmenu.Empty() && GetNpcTextId() == 0)
813 player->SendPreparedQuest(GetGUID());
814 return;
817 // in case non empty gossip menu (that not included quests list size) show it
818 // (quest entries from quest menu will be included in list)
819 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
822 void Creature::OnGossipSelect(Player* player, uint32 option)
824 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
826 if(option >= gossipmenu.MenuItemCount())
827 return;
829 uint32 action=gossipmenu.GetItem(option).m_gAction;
830 uint32 zoneid=GetZoneId();
831 uint64 guid=GetGUID();
833 GossipOption const *gossip=GetGossipOption( action );
834 if(!gossip)
836 zoneid=0;
837 gossip=GetGossipOption( action );
838 if(!gossip)
839 return;
842 switch (gossip->Action)
844 case GOSSIP_OPTION_GOSSIP:
846 uint32 textid = GetGossipTextId(action, zoneid);
847 if (textid == 0)
848 textid=GetNpcTextId();
850 player->PlayerTalkClass->CloseGossip();
851 player->PlayerTalkClass->SendTalking(textid);
852 break;
854 case GOSSIP_OPTION_SPIRITHEALER:
855 if (player->isDead())
856 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
857 break;
858 case GOSSIP_OPTION_QUESTGIVER:
859 player->PrepareQuestMenu( guid );
860 player->SendPreparedQuest( guid );
861 break;
862 case GOSSIP_OPTION_VENDOR:
863 case GOSSIP_OPTION_ARMORER:
864 player->GetSession()->SendListInventory(guid);
865 break;
866 case GOSSIP_OPTION_STABLEPET:
867 player->GetSession()->SendStablePet(guid);
868 break;
869 case GOSSIP_OPTION_TRAINER:
870 player->GetSession()->SendTrainerList(guid);
871 break;
872 case GOSSIP_OPTION_UNLEARNTALENTS:
873 player->PlayerTalkClass->CloseGossip();
874 player->SendTalentWipeConfirm(guid);
875 break;
876 case GOSSIP_OPTION_UNLEARNPETSKILLS:
877 player->PlayerTalkClass->CloseGossip();
878 player->SendPetSkillWipeConfirm();
879 break;
880 case GOSSIP_OPTION_TAXIVENDOR:
881 player->GetSession()->SendTaxiMenu(this);
882 break;
883 case GOSSIP_OPTION_INNKEEPER:
884 player->PlayerTalkClass->CloseGossip();
885 player->SetBindPoint( guid );
886 break;
887 case GOSSIP_OPTION_BANKER:
888 player->GetSession()->SendShowBank( guid );
889 break;
890 case GOSSIP_OPTION_PETITIONER:
891 player->PlayerTalkClass->CloseGossip();
892 player->GetSession()->SendPetitionShowList( guid );
893 break;
894 case GOSSIP_OPTION_TABARDDESIGNER:
895 player->PlayerTalkClass->CloseGossip();
896 player->GetSession()->SendTabardVendorActivate( guid );
897 break;
898 case GOSSIP_OPTION_AUCTIONEER:
899 player->GetSession()->SendAuctionHello( guid, this );
900 break;
901 case GOSSIP_OPTION_SPIRITGUIDE:
902 case GOSSIP_GUARD_SPELLTRAINER:
903 case GOSSIP_GUARD_SKILLTRAINER:
904 prepareGossipMenu( player,gossip->Id );
905 sendPreparedGossip( player );
906 break;
907 case GOSSIP_OPTION_BATTLEFIELD:
909 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
910 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
911 break;
913 default:
914 OnPoiSelect( player, gossip );
915 break;
920 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
922 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
924 //float x,y;
925 //bool findnpc=false;
926 Poi_Icon icon = ICON_POI_0;
927 //QueryResult *result;
928 //Field *fields;
929 uint32 mapid=GetMapId();
930 Map const* map=MapManager::Instance().GetBaseMap( mapid );
931 uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
932 uint32 zoneid=Map::GetZoneId(areaflag,mapid);
933 std::string areaname= gossip->OptionText;
935 uint16 pflag;
937 // use the action relate to creaturetemplate.trainer_type ?
938 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 );
939 if(!result)
940 return;
943 fields = result->Fetch();
944 x=fields[0].GetFloat();
945 y=fields[1].GetFloat();
946 pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
947 if(pflag==areaflag)
949 findnpc=true;
950 break;
952 }while(result->NextRow());
954 delete result;
956 if(!findnpc)
958 player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
959 return;
962 //need add more case.
963 switch(gossip->Action)
965 case GOSSIP_GUARD_BANK:
966 icon=ICON_POI_HOUSE;
967 break;
968 case GOSSIP_GUARD_RIDE:
969 icon=ICON_POI_RWHORSE;
970 break;
971 case GOSSIP_GUARD_GUILD:
972 icon=ICON_POI_BLUETOWER;
973 break;
974 default:
975 icon=ICON_POI_TOWER;
976 break;
978 uint32 textid=GetGossipTextId( gossip->Action, zoneid );
979 player->PlayerTalkClass->SendTalking( textid );
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 );
988 if(!result)
989 return 0;
991 Field *fields = result->Fetch();
992 uint32 id = fields[0].GetUInt32();
994 delete result;
996 return id;
999 uint32 Creature::GetNpcTextId()
1001 if (!m_DBTableGuid)
1002 return DEFAULT_GOSSIP_MESSAGE;
1004 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1005 return pos;
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++ )
1014 if(i->Action==id )
1015 return &*i;
1017 return NULL;
1020 void Creature::LoadGossipOptions()
1022 if(m_gossipOptionLoaded)
1023 return;
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 );
1043 else
1045 oX = dX;
1046 oY = dY;
1049 dX = x;
1050 dY = y;
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
1070 if (!unit)
1072 m_lootRecipient = 0;
1073 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1074 return;
1077 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1078 if(!player) // normal creature, no player involved
1079 return;
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);
1090 if(!data)
1092 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1093 return;
1096 SaveToDB(GetMapId(), data->spawnMask);
1099 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1101 // update in loaded data
1102 if (!m_DBTableGuid)
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();
1110 if(cinfo)
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)
1119 displayId = 0;
1121 else
1122 displayId = 0;
1124 else
1125 displayId = 0;
1128 // data->guid = guid don't must be update at save
1129 data.id = GetEntry();
1130 data.mapid = mapid;
1131 data.displayid = displayId;
1132 data.equipmentId = GetEquipmentId();
1133 data.posX = GetPositionX();
1134 data.posY = GetPositionY();
1135 data.posZ = GetPositionZ();
1136 data.orientation = GetOrientation();
1137 data.spawntimesecs = m_respawnDelay;
1138 // prevent add data integrity problems
1139 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1140 data.currentwaypoint = 0;
1141 data.curhealth = GetHealth();
1142 data.curmana = GetPower(POWER_MANA);
1143 data.is_dead = m_isDeadByDefault;
1144 // prevent add data integrity problems
1145 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1146 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1147 data.spawnMask = spawnMask;
1149 // updated in DB
1150 WorldDatabase.BeginTransaction();
1152 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1154 std::ostringstream ss;
1155 ss << "INSERT INTO creature VALUES ("
1156 << m_DBTableGuid << ","
1157 << GetEntry() << ","
1158 << mapid <<","
1159 << (uint32)spawnMask << ","
1160 << displayId <<","
1161 << GetEquipmentId() <<","
1162 << GetPositionX() << ","
1163 << GetPositionY() << ","
1164 << GetPositionZ() << ","
1165 << GetOrientation() << ","
1166 << m_respawnDelay << "," //respawn time
1167 << (float) m_respawnradius << "," //spawn distance (float)
1168 << (uint32) (0) << "," //currentwaypoint
1169 << GetHealth() << "," //curhealth
1170 << GetPower(POWER_MANA) << "," //curmana
1171 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1172 << GetDefaultMovementType() << ")"; //default movement generator type
1174 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1176 WorldDatabase.CommitTransaction();
1179 void Creature::SelectLevel(const CreatureInfo *cinfo)
1181 uint32 rank = isPet()? 0 : cinfo->rank;
1183 // level
1184 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1185 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1186 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1187 SetLevel(level);
1189 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1191 // health
1192 float healthmod = _GetHealthMod(rank);
1194 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1195 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1196 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1198 SetCreateHealth(health);
1199 SetMaxHealth(health);
1200 SetHealth(health);
1202 // mana
1203 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1204 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1205 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1207 SetCreateMana(mana);
1208 SetMaxPower(POWER_MANA, mana); //MAX Mana
1209 SetPower(POWER_MANA, mana);
1211 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1212 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1214 // damage
1215 float damagemod = _GetDamageMod(rank);
1217 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1218 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1220 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1221 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1223 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1226 float Creature::_GetHealthMod(int32 Rank)
1228 switch (Rank) // define rates for each elite rank
1230 case CREATURE_ELITE_NORMAL:
1231 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1232 case CREATURE_ELITE_ELITE:
1233 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1234 case CREATURE_ELITE_RAREELITE:
1235 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1236 case CREATURE_ELITE_WORLDBOSS:
1237 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1238 case CREATURE_ELITE_RARE:
1239 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1240 default:
1241 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1245 float Creature::_GetDamageMod(int32 Rank)
1247 switch (Rank) // define rates for each elite rank
1249 case CREATURE_ELITE_NORMAL:
1250 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1251 case CREATURE_ELITE_ELITE:
1252 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1253 case CREATURE_ELITE_RAREELITE:
1254 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1255 case CREATURE_ELITE_WORLDBOSS:
1256 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1257 case CREATURE_ELITE_RARE:
1258 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1259 default:
1260 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1264 float Creature::GetSpellDamageMod(int32 Rank)
1266 switch (Rank) // define rates for each elite rank
1268 case CREATURE_ELITE_NORMAL:
1269 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1270 case CREATURE_ELITE_ELITE:
1271 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1272 case CREATURE_ELITE_RAREELITE:
1273 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1274 case CREATURE_ELITE_WORLDBOSS:
1275 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1276 case CREATURE_ELITE_RARE:
1277 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1278 default:
1279 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1283 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1285 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1286 if(!cinfo)
1288 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1289 return false;
1291 m_originalEntry = Entry;
1293 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1295 if(!UpdateEntry(Entry, team, data))
1296 return false;
1298 //Notify the map's instance data.
1299 //Only works if you create the object in it, not if it is moves to that map.
1300 //Normally non-players do not teleport to other maps.
1301 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1302 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1304 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1307 return true;
1310 bool Creature::LoadFromDB(uint32 guid, Map *map)
1312 CreatureData const* data = objmgr.GetCreatureData(guid);
1314 if(!data)
1316 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1317 return false;
1320 m_DBTableGuid = guid;
1321 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1323 uint16 team = 0;
1324 if(!Create(guid,map,data->id,team,data))
1325 return false;
1327 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1329 if(!IsPositionValid())
1331 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1332 return false;
1335 m_respawnradius = data->spawndist;
1337 m_respawnDelay = data->spawntimesecs;
1338 m_isDeadByDefault = data->is_dead;
1339 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1341 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1342 if(m_respawnTime > time(NULL)) // not ready to respawn
1343 m_deathState = DEAD;
1344 else if(m_respawnTime) // respawn time set but expired
1346 m_respawnTime = 0;
1347 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1350 uint32 curhealth = data->curhealth;
1351 if(curhealth)
1353 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1354 if(curhealth < 1)
1355 curhealth = 1;
1358 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1359 SetPower(POWER_MANA,data->curmana);
1361 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1363 // checked at creature_template loading
1364 m_defaultMovementType = MovementGeneratorType(data->movementType);
1366 AIM_Initialize();
1367 return true;
1370 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1372 if(equip_entry == 0)
1374 if (force)
1376 for (uint8 i = 0; i < 3; i++)
1378 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1379 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1380 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1382 m_equipmentId = 0;
1384 return;
1387 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1388 if (!einfo)
1389 return;
1391 m_equipmentId = equip_entry;
1392 for (uint8 i = 0; i < 3; i++)
1394 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1395 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1396 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1400 bool Creature::hasQuest(uint32 quest_id) const
1402 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1403 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1405 if(itr->second==quest_id)
1406 return true;
1408 return false;
1411 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1413 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1414 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1416 if(itr->second==quest_id)
1417 return true;
1419 return false;
1422 void Creature::DeleteFromDB()
1424 if (!m_DBTableGuid)
1426 sLog.outDebug("Trying to delete not saved creature!");
1427 return;
1430 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1431 objmgr.DeleteCreatureData(m_DBTableGuid);
1433 WorldDatabase.BeginTransaction();
1434 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1435 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1436 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1437 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1438 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1439 WorldDatabase.CommitTransaction();
1442 float Creature::GetAttackDistance(Unit const* pl) const
1444 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1445 if(aggroRate==0)
1446 return 0.0f;
1448 int32 playerlevel = pl->getLevelForTarget(this);
1449 int32 creaturelevel = getLevelForTarget(pl);
1451 int32 leveldif = playerlevel - creaturelevel;
1453 // "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."
1454 if ( leveldif < - 25)
1455 leveldif = -25;
1457 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1458 float RetDistance = 20;
1460 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1461 // radius grow if playlevel < creaturelevel
1462 RetDistance -= (float)leveldif;
1464 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1466 // detect range auras
1467 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1469 // detected range auras
1470 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1473 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1474 if(RetDistance < 5)
1475 RetDistance = 5;
1477 return (RetDistance*aggroRate);
1480 void Creature::setDeathState(DeathState s)
1482 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1484 m_deathTimer = m_corpseDelay*1000;
1486 // always save boss respawn time at death to prevent crash cheating
1487 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1488 SaveRespawnTime();
1490 if(!IsStopped())
1491 StopMoving();
1493 Unit::setDeathState(s);
1495 if(s == JUST_DIED)
1497 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1498 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1500 if(!isPet() && GetCreatureInfo()->SkinLootId)
1501 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1502 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1504 Unit::setDeathState(CORPSE);
1506 if(s == JUST_ALIVED)
1508 SetHealth(GetMaxHealth());
1509 SetLootRecipient(NULL);
1510 Unit::setDeathState(ALIVE);
1511 CreatureInfo const *cinfo = GetCreatureInfo();
1512 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1513 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1514 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1515 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1516 clearUnitState(UNIT_STAT_ALL_STATE);
1517 i_motionMaster.Clear();
1518 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1519 LoadCreaturesAddon(true);
1523 void Creature::Respawn()
1525 RemoveCorpse();
1527 // forced recreate creature object at clients
1528 UnitVisibility currentVis = GetVisibility();
1529 SetVisibility(VISIBILITY_RESPAWN);
1530 ObjectAccessor::UpdateObjectVisibility(this);
1531 SetVisibility(currentVis); // restore visibility state
1532 ObjectAccessor::UpdateObjectVisibility(this);
1534 if(getDeathState()==DEAD)
1536 if (m_DBTableGuid)
1537 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1538 m_respawnTime = time(NULL); // respawn at next tick
1542 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1544 if (!spellInfo)
1545 return false;
1547 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1548 return true;
1550 return Unit::IsImmunedToSpell(spellInfo, useCharges);
1553 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1555 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1556 return true;
1558 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1561 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1563 if(!pVictim)
1564 return NULL;
1566 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1568 if(!m_spells[i])
1569 continue;
1570 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1571 if(!spellInfo)
1573 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1574 continue;
1577 bool bcontinue = true;
1578 for(uint32 j=0;j<3;j++)
1580 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1581 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1582 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1583 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1586 bcontinue = false;
1587 break;
1590 if(bcontinue) continue;
1592 if(spellInfo->manaCost > GetPower(POWER_MANA))
1593 continue;
1594 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1595 float range = GetSpellMaxRange(srange);
1596 float minrange = GetSpellMinRange(srange);
1597 float dist = GetDistance(pVictim);
1598 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1599 // continue;
1600 if( dist > range || dist < minrange )
1601 continue;
1602 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1603 continue;
1604 return spellInfo;
1606 return NULL;
1609 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1611 if(!pVictim)
1612 return NULL;
1614 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1616 if(!m_spells[i])
1617 continue;
1618 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1619 if(!spellInfo)
1621 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1622 continue;
1625 bool bcontinue = true;
1626 for(uint32 j=0;j<3;j++)
1628 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1630 bcontinue = false;
1631 break;
1634 if(bcontinue) continue;
1636 if(spellInfo->manaCost > GetPower(POWER_MANA))
1637 continue;
1638 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1639 float range = GetSpellMaxRange(srange);
1640 float minrange = GetSpellMinRange(srange);
1641 float dist = GetDistance(pVictim);
1642 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1643 // continue;
1644 if( dist > range || dist < minrange )
1645 continue;
1646 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1647 continue;
1648 return spellInfo;
1650 return NULL;
1653 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1655 // gamemaster in GM mode see all, including ghosts
1656 if(pl->isGameMaster())
1657 return true;
1659 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1660 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1662 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1663 return false;
1664 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1667 // Dead player see live creatures near own corpse
1668 if(isAlive())
1670 Corpse *corpse = pl->GetCorpse();
1671 if(corpse)
1673 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1674 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1675 return true;
1679 // Dead player see Spirit Healer or Spirit Guide
1680 if(isSpiritService())
1681 return true;
1683 // and not see any other
1684 return false;
1687 void Creature::CallAssistance()
1689 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1691 SetNoCallAssistance(true);
1693 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1694 if(radius > 0)
1696 std::list<Creature*> assistList;
1699 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1700 Cell cell(p);
1701 cell.data.Part.reserved = ALL_DISTRICT;
1702 cell.SetNoCreate();
1704 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1705 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1707 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1709 CellLock<GridReadGuard> cell_lock(cell, p);
1710 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1713 if (!assistList.empty())
1715 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1716 while (!assistList.empty())
1718 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1719 e->AddAssistant((*assistList.begin())->GetGUID());
1720 assistList.pop_front();
1722 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1728 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1730 // we don't need help from zombies :)
1731 if( !isAlive() )
1732 return false;
1734 // skip fighting creature
1735 if( isInCombat() )
1736 return false;
1738 // only from same creature faction
1739 if(getFaction() != u->getFaction() )
1740 return false;
1742 // only free creature
1743 if( GetCharmerOrOwnerGUID() )
1744 return false;
1746 // skip non hostile to caster enemy creatures
1747 if( !IsHostileTo(enemy) )
1748 return false;
1750 return true;
1753 void Creature::SaveRespawnTime()
1755 if(isPet() || !m_DBTableGuid)
1756 return;
1758 if(m_respawnTime > time(NULL)) // dead (no corpse)
1759 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1760 else if(m_deathTimer > 0) // dead (corpse)
1761 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1764 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1766 if(!pVictim)
1767 return true;
1769 if(!pVictim->IsInMap(this))
1770 return true;
1772 if(!pVictim->isTargetableForAttack())
1773 return true;
1775 if(!pVictim->isInAccessablePlaceFor(this))
1776 return true;
1778 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1779 return false;
1781 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1782 float AttackDist = GetAttackDistance(pVictim);
1783 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1785 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1786 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1789 CreatureDataAddon const* Creature::GetCreatureAddon() const
1791 if (m_DBTableGuid)
1793 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1794 return addon;
1797 // dependent from heroic mode entry
1798 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1801 //creature_addon table
1802 bool Creature::LoadCreaturesAddon(bool reload)
1804 CreatureDataAddon const *cainfo = GetCreatureAddon();
1805 if(!cainfo)
1806 return false;
1808 if (cainfo->mount != 0)
1809 Mount(cainfo->mount);
1811 if (cainfo->bytes0 != 0)
1812 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1814 if (cainfo->bytes1 != 0)
1815 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1817 if (cainfo->bytes2 != 0)
1818 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1820 if (cainfo->emote != 0)
1821 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1823 if (cainfo->move_flags != 0)
1824 SetUnitMovementFlags(cainfo->move_flags);
1826 if(cainfo->auras)
1828 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1830 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1831 if (!AdditionalSpellInfo)
1833 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1834 continue;
1837 // skip already applied aura
1838 if(HasAura(cAura->spell_id,cAura->effect_idx))
1840 if(!reload)
1841 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);
1843 continue;
1846 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1847 AddAura(AdditionalAura);
1848 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1851 return true;
1854 /// Send a message to LocalDefense channel for players opposition team in the zone
1855 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1857 uint32 enemy_team = attacker->GetTeam();
1859 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1860 data << (uint32)GetZoneId();
1861 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1864 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1866 m_CreatureSpellCooldowns[spell_id] = end_time;
1869 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1871 m_CreatureCategoryCooldowns[category] = apply_time;
1874 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1876 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1877 if(!spellInfo)
1878 return;
1880 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1881 if(cooldown)
1882 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1884 if(spellInfo->Category)
1885 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1887 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1890 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1893 if(!spellInfo)
1894 return false;
1896 // check global cooldown if spell affected by it
1897 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1898 return true;
1900 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1901 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1904 bool Creature::HasSpellCooldown(uint32 spell_id) const
1906 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1907 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1910 bool Creature::IsInEvadeMode() const
1912 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1915 bool Creature::HasSpell(uint32 spellID) const
1917 uint8 i;
1918 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1919 if(spellID == m_spells[i])
1920 break;
1921 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1924 time_t Creature::GetRespawnTimeEx() const
1926 time_t now = time(NULL);
1927 if(m_respawnTime > now) // dead (no corpse)
1928 return m_respawnTime;
1929 else if(m_deathTimer > 0) // dead (corpse)
1930 return now+m_respawnDelay+m_deathTimer/1000;
1931 else
1932 return now;
1935 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1937 if (m_DBTableGuid)
1939 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1941 x = data->posX;
1942 y = data->posY;
1943 z = data->posZ;
1944 if(ori)
1945 *ori = data->orientation;
1946 if(dist)
1947 *dist = data->spawndist;
1949 return;
1953 x = GetPositionX();
1954 y = GetPositionY();
1955 z = GetPositionZ();
1956 if(ori)
1957 *ori = GetOrientation();
1958 if(dist)
1959 *dist = 0;
1962 void Creature::AllLootRemovedFromCorpse()
1964 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1966 uint32 nDeathTimer;
1968 CreatureInfo const *cinfo = GetCreatureInfo();
1970 // corpse was not skinnable -> apply corpse looted timer
1971 if (!cinfo || !cinfo->SkinLootId)
1972 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1973 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1974 else
1975 nDeathTimer = 0;
1977 // update death timer only if looted timer is shorter
1978 if (m_deathTimer > nDeathTimer)
1979 m_deathTimer = nDeathTimer;
1983 uint32 Creature::getLevelForTarget( Unit const* target ) const
1985 if(!isWorldBoss())
1986 return Unit::getLevelForTarget(target);
1988 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1989 if(level < 1)
1990 return 1;
1991 if(level > 255)
1992 return 255;
1993 return level;
1996 std::string Creature::GetScriptName()
1998 return objmgr.GetScriptName(GetScriptId());
2001 uint32 Creature::GetScriptId()
2003 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2006 VendorItemData const* Creature::GetVendorItems() const
2008 return objmgr.GetNpcVendorItemList(GetEntry());
2011 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2013 if(!vItem->maxcount)
2014 return vItem->maxcount;
2016 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2017 for(; itr != m_vendorItemCounts.end(); ++itr)
2018 if(itr->itemId==vItem->item)
2019 break;
2021 if(itr == m_vendorItemCounts.end())
2022 return vItem->maxcount;
2024 VendorItemCount* vCount = &*itr;
2026 time_t ptime = time(NULL);
2028 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2030 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2032 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2033 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2035 m_vendorItemCounts.erase(itr);
2036 return vItem->maxcount;
2039 vCount->count += diff * pProto->BuyCount;
2040 vCount->lastIncrementTime = ptime;
2043 return vCount->count;
2046 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2048 if(!vItem->maxcount)
2049 return 0;
2051 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2052 for(; itr != m_vendorItemCounts.end(); ++itr)
2053 if(itr->itemId==vItem->item)
2054 break;
2056 if(itr == m_vendorItemCounts.end())
2058 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2059 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2060 return new_count;
2063 VendorItemCount* vCount = &*itr;
2065 time_t ptime = time(NULL);
2067 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2069 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2071 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2072 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2073 vCount->count += diff * pProto->BuyCount;
2074 else
2075 vCount->count = vItem->maxcount;
2078 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2079 vCount->lastIncrementTime = ptime;
2080 return vCount->count;
2083 TrainerSpellData const* Creature::GetTrainerSpells() const
2085 return objmgr.GetNpcTrainerSpells(GetEntry());
2088 // overwrite WorldObject function for proper name localization
2089 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2091 if (loc_idx >= 0)
2093 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2094 if (cl)
2096 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2097 return cl->Name[loc_idx].c_str();
2101 return GetName();