Merge branch 'master' into 303
[getmangos.git] / src / game / Creature.cpp
blob3b8887e7c628793c9e2b82ea3b78d10e61d98bb6
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), m_isVehicle(false),
121 m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
122 m_AlreadyCallAssistance(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
123 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
125 m_regenTimer = 200;
126 m_valuesCount = UNIT_END;
128 for(int i =0; i<4; ++i)
129 m_spells[i] = 0;
131 m_CreatureSpellCooldowns.clear();
132 m_CreatureCategoryCooldowns.clear();
133 m_GlobalCooldown = 0;
134 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
137 Creature::~Creature()
139 CleanupsBeforeDelete();
141 m_vendorItemCounts.clear();
143 delete i_AI;
144 i_AI = NULL;
147 void Creature::AddToWorld()
149 ///- Register the creature for guid lookup
150 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
151 Unit::AddToWorld();
154 void Creature::RemoveFromWorld()
156 ///- Remove the creature from the accessor
157 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
158 Unit::RemoveFromWorld();
161 void Creature::RemoveCorpse()
163 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
164 return;
166 m_deathTimer = 0;
167 setDeathState(DEAD);
168 ObjectAccessor::UpdateObjectVisibility(this);
169 loot.clear();
170 m_respawnTime = time(NULL) + m_respawnDelay;
172 float x,y,z,o;
173 GetRespawnCoord(x, y, z, &o);
174 GetMap()->CreatureRelocation(this,x,y,z,o);
178 * change the entry of creature until respawn
180 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
182 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
183 if(!normalInfo)
185 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
186 return false;
189 // get heroic mode entry
190 uint32 actualEntry = Entry;
191 CreatureInfo const *cinfo = normalInfo;
192 if(normalInfo->HeroicEntry)
194 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
195 if(map && map->IsHeroic())
197 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
198 if(!cinfo)
200 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
201 return false;
206 SetEntry(Entry); // normal entry always
207 m_creatureInfo = cinfo; // map mode related always
209 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
211 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
212 return false;
215 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
216 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
217 if (!minfo)
219 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
220 return false;
222 else
223 display_id = minfo->modelid; // it can be different (for another gender)
225 SetDisplayId(display_id);
226 SetNativeDisplayId(display_id);
227 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
229 // Load creature equipment
230 if(!data || data->equipmentId == 0)
231 { // use default from the template
232 LoadEquipment(cinfo->equipmentId);
234 else if(data && data->equipmentId != -1)
235 { // override, -1 means no equipment
236 LoadEquipment(data->equipmentId);
239 SetName(normalInfo->Name); // at normal entry always
241 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
242 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
244 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
246 SetSpeed(MOVE_WALK, cinfo->speed );
247 SetSpeed(MOVE_RUN, cinfo->speed );
248 SetSpeed(MOVE_SWIM, cinfo->speed );
250 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
252 // checked at loading
253 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
254 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
255 m_defaultMovementType = IDLE_MOTION_TYPE;
257 return true;
260 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
262 if(!InitEntry(Entry,team,data))
263 return false;
265 m_regenHealth = GetCreatureInfo()->RegenHealth;
267 // creatures always have melee weapon ready if any
268 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
270 SelectLevel(GetCreatureInfo());
271 if (team == HORDE)
272 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
273 else
274 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
276 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
278 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
279 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
280 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
282 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
283 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
285 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
286 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
287 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
288 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
289 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
290 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
291 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
293 SetCanModifyStats(true);
294 UpdateAllStats();
296 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
297 if (factionTemplate) // check and error show at loading templates
299 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
300 if (factionEntry)
301 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
302 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
303 SetPvP(true);
306 m_spells[0] = GetCreatureInfo()->spell1;
307 m_spells[1] = GetCreatureInfo()->spell2;
308 m_spells[2] = GetCreatureInfo()->spell3;
309 m_spells[3] = GetCreatureInfo()->spell4;
311 return true;
314 void Creature::Update(uint32 diff)
316 if(m_GlobalCooldown <= diff)
317 m_GlobalCooldown = 0;
318 else
319 m_GlobalCooldown -= diff;
321 switch( m_deathState )
323 case JUST_ALIVED:
324 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
325 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
326 break;
327 case JUST_DIED:
328 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
329 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
330 break;
331 case DEAD:
333 if( m_respawnTime <= time(NULL) )
335 DEBUG_LOG("Respawning...");
336 m_respawnTime = 0;
337 lootForPickPocketed = false;
338 lootForBody = false;
340 if(m_originalEntry != GetEntry())
341 UpdateEntry(m_originalEntry);
343 CreatureInfo const *cinfo = GetCreatureInfo();
345 SelectLevel(cinfo);
346 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
347 if (m_isDeadByDefault)
349 setDeathState(JUST_DIED);
350 SetHealth(0);
351 i_motionMaster.Clear();
352 clearUnitState(UNIT_STAT_ALL_STATE);
353 LoadCreaturesAddon(true);
355 else
356 setDeathState( JUST_ALIVED );
358 //Call AI respawn virtual function
359 i_AI->JustRespawned();
361 GetMap()->Add(this);
363 break;
365 case CORPSE:
367 if (m_isDeadByDefault)
368 break;
370 if( m_deathTimer <= diff )
372 RemoveCorpse();
373 DEBUG_LOG("Removing corpse... %u ", GetEntry());
375 else
377 m_deathTimer -= diff;
378 if (m_groupLootTimer && lootingGroupLeaderGUID)
380 if(diff <= m_groupLootTimer)
382 m_groupLootTimer -= diff;
384 else
386 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
387 if (group)
388 group->EndRoll();
389 m_groupLootTimer = 0;
390 lootingGroupLeaderGUID = 0;
395 break;
397 case ALIVE:
399 if (m_isDeadByDefault)
401 if( m_deathTimer <= diff )
403 RemoveCorpse();
404 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
406 else
408 m_deathTimer -= diff;
412 Unit::Update( diff );
414 // creature can be dead after Unit::Update call
415 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
416 if(!isAlive())
417 break;
419 if(!IsInEvadeMode())
421 // do not allow the AI to be changed during update
422 m_AI_locked = true;
423 i_AI->UpdateAI(diff);
424 m_AI_locked = false;
427 // creature can be dead after UpdateAI call
428 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
429 if(!isAlive())
430 break;
431 if(m_regenTimer > 0)
433 if(diff >= m_regenTimer)
434 m_regenTimer = 0;
435 else
436 m_regenTimer -= diff;
438 if (m_regenTimer != 0)
439 break;
441 if (!isInCombat() || IsPolymorphed())
442 RegenerateHealth();
444 RegenerateMana();
446 m_regenTimer = 2000;
447 break;
449 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:
670 case BATTLEGROUND_SA:
671 case BATTLEGROUND_DS:
672 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
673 default: break;
675 return false;
677 return true;
680 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
682 return pPlayer->getLevel() >= 10
683 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
684 && pPlayer->getClass() == GetCreatureInfo()->classNum;
687 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
689 PlayerMenu* pm=pPlayer->PlayerTalkClass;
690 pm->ClearMenus();
692 // lazy loading single time at use
693 LoadGossipOptions();
695 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
697 GossipOption* gso=&*i;
698 if(gso->GossipId == gossipid)
700 bool cantalking=true;
701 if(gso->Id==1)
703 uint32 textid=GetNpcTextId();
704 GossipText * gossiptext=objmgr.GetGossipText(textid);
705 if(!gossiptext)
706 cantalking=false;
708 else
710 switch (gso->Action)
712 case GOSSIP_OPTION_QUESTGIVER:
713 pPlayer->PrepareQuestMenu(GetGUID());
714 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
715 cantalking=false;
716 //pm->GetQuestMenu()->ClearMenu();
717 break;
718 case GOSSIP_OPTION_ARMORER:
719 cantalking=false; // added in special mode
720 break;
721 case GOSSIP_OPTION_SPIRITHEALER:
722 if( !pPlayer->isDead() )
723 cantalking=false;
724 break;
725 case GOSSIP_OPTION_VENDOR:
727 VendorItemData const* vItems = GetVendorItems();
728 if(!vItems || vItems->Empty())
730 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
731 GetGUIDLow(),GetEntry());
732 cantalking=false;
734 break;
736 case GOSSIP_OPTION_TRAINER:
737 if(!isCanTrainingOf(pPlayer,false))
738 cantalking=false;
739 break;
740 case GOSSIP_OPTION_UNLEARNTALENTS:
741 if(!isCanTrainingAndResetTalentsOf(pPlayer))
742 cantalking=false;
743 break;
744 case GOSSIP_OPTION_UNLEARNPETSKILLS:
745 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
746 cantalking=false;
747 break;
748 case GOSSIP_OPTION_TAXIVENDOR:
749 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
750 return;
751 break;
752 case GOSSIP_OPTION_BATTLEFIELD:
753 if(!isCanIneractWithBattleMaster(pPlayer,false))
754 cantalking=false;
755 break;
756 case GOSSIP_OPTION_SPIRITGUIDE:
757 case GOSSIP_OPTION_INNKEEPER:
758 case GOSSIP_OPTION_BANKER:
759 case GOSSIP_OPTION_PETITIONER:
760 case GOSSIP_OPTION_STABLEPET:
761 case GOSSIP_OPTION_TABARDDESIGNER:
762 case GOSSIP_OPTION_AUCTIONEER:
763 break; // no checks
764 default:
765 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
766 break;
770 //note for future dev: should have database fields for BoxMessage & BoxMoney
771 if(!gso->OptionText.empty() && cantalking)
773 std::string OptionText = gso->OptionText;
774 std::string BoxText = gso->BoxText;
775 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
776 if (loc_idx >= 0)
778 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
779 if (no)
781 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
782 OptionText=no->OptionText[loc_idx];
783 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
784 BoxText=no->BoxText[loc_idx];
787 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
792 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
793 if(pm->Empty())
795 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
797 isCanTrainingOf(pPlayer,true); // output error message if need
799 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
801 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
806 void Creature::sendPreparedGossip(Player* player)
808 if(!player)
809 return;
811 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
813 // in case empty gossip menu open quest menu if any
814 if (gossipmenu.Empty() && GetNpcTextId() == 0)
816 player->SendPreparedQuest(GetGUID());
817 return;
820 // in case non empty gossip menu (that not included quests list size) show it
821 // (quest entries from quest menu will be included in list)
822 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
825 void Creature::OnGossipSelect(Player* player, uint32 option)
827 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
829 if(option >= gossipmenu.MenuItemCount())
830 return;
832 uint32 action=gossipmenu.GetItem(option).m_gAction;
833 uint32 zoneid=GetZoneId();
834 uint64 guid=GetGUID();
836 GossipOption const *gossip=GetGossipOption( action );
837 if(!gossip)
839 zoneid=0;
840 gossip=GetGossipOption( action );
841 if(!gossip)
842 return;
845 switch (gossip->Action)
847 case GOSSIP_OPTION_GOSSIP:
849 uint32 textid = GetGossipTextId(action, zoneid);
850 if (textid == 0)
851 textid=GetNpcTextId();
853 player->PlayerTalkClass->CloseGossip();
854 player->PlayerTalkClass->SendTalking(textid);
855 break;
857 case GOSSIP_OPTION_SPIRITHEALER:
858 if (player->isDead())
859 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
860 break;
861 case GOSSIP_OPTION_QUESTGIVER:
862 player->PrepareQuestMenu( guid );
863 player->SendPreparedQuest( guid );
864 break;
865 case GOSSIP_OPTION_VENDOR:
866 case GOSSIP_OPTION_ARMORER:
867 player->GetSession()->SendListInventory(guid);
868 break;
869 case GOSSIP_OPTION_STABLEPET:
870 player->GetSession()->SendStablePet(guid);
871 break;
872 case GOSSIP_OPTION_TRAINER:
873 player->GetSession()->SendTrainerList(guid);
874 break;
875 case GOSSIP_OPTION_UNLEARNTALENTS:
876 player->PlayerTalkClass->CloseGossip();
877 player->SendTalentWipeConfirm(guid);
878 break;
879 case GOSSIP_OPTION_UNLEARNPETSKILLS:
880 player->PlayerTalkClass->CloseGossip();
881 player->SendPetSkillWipeConfirm();
882 break;
883 case GOSSIP_OPTION_TAXIVENDOR:
884 player->GetSession()->SendTaxiMenu(this);
885 break;
886 case GOSSIP_OPTION_INNKEEPER:
887 player->PlayerTalkClass->CloseGossip();
888 player->SetBindPoint( guid );
889 break;
890 case GOSSIP_OPTION_BANKER:
891 player->GetSession()->SendShowBank( guid );
892 break;
893 case GOSSIP_OPTION_PETITIONER:
894 player->PlayerTalkClass->CloseGossip();
895 player->GetSession()->SendPetitionShowList( guid );
896 break;
897 case GOSSIP_OPTION_TABARDDESIGNER:
898 player->PlayerTalkClass->CloseGossip();
899 player->GetSession()->SendTabardVendorActivate( guid );
900 break;
901 case GOSSIP_OPTION_AUCTIONEER:
902 player->GetSession()->SendAuctionHello( guid, this );
903 break;
904 case GOSSIP_OPTION_SPIRITGUIDE:
905 case GOSSIP_GUARD_SPELLTRAINER:
906 case GOSSIP_GUARD_SKILLTRAINER:
907 prepareGossipMenu( player,gossip->Id );
908 sendPreparedGossip( player );
909 break;
910 case GOSSIP_OPTION_BATTLEFIELD:
912 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
913 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
914 break;
916 default:
917 OnPoiSelect( player, gossip );
918 break;
923 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
925 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
927 //float x,y;
928 //bool findnpc=false;
929 Poi_Icon icon = ICON_POI_0;
930 //QueryResult *result;
931 //Field *fields;
932 uint32 mapid=GetMapId();
933 Map const* map=MapManager::Instance().GetBaseMap( mapid );
934 uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
935 uint32 zoneid=Map::GetZoneId(areaflag,mapid);
936 std::string areaname= gossip->OptionText;
938 uint16 pflag;
940 // use the action relate to creaturetemplate.trainer_type ?
941 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 );
942 if(!result)
943 return;
946 fields = result->Fetch();
947 x=fields[0].GetFloat();
948 y=fields[1].GetFloat();
949 pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
950 if(pflag==areaflag)
952 findnpc=true;
953 break;
955 }while(result->NextRow());
957 delete result;
959 if(!findnpc)
961 player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
962 return;
965 //need add more case.
966 switch(gossip->Action)
968 case GOSSIP_GUARD_BANK:
969 icon=ICON_POI_HOUSE;
970 break;
971 case GOSSIP_GUARD_RIDE:
972 icon=ICON_POI_RWHORSE;
973 break;
974 case GOSSIP_GUARD_GUILD:
975 icon=ICON_POI_BLUETOWER;
976 break;
977 default:
978 icon=ICON_POI_TOWER;
979 break;
981 uint32 textid=GetGossipTextId( gossip->Action, zoneid );
982 player->PlayerTalkClass->SendTalking( textid );
983 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
987 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
989 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
991 if(!result)
992 return 0;
994 Field *fields = result->Fetch();
995 uint32 id = fields[0].GetUInt32();
997 delete result;
999 return id;
1002 uint32 Creature::GetNpcTextId()
1004 if (!m_DBTableGuid)
1005 return DEFAULT_GOSSIP_MESSAGE;
1007 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1008 return pos;
1010 return DEFAULT_GOSSIP_MESSAGE;
1013 GossipOption const* Creature::GetGossipOption( uint32 id ) const
1015 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
1017 if(i->Action==id )
1018 return &*i;
1020 return NULL;
1023 void Creature::LoadGossipOptions()
1025 if(m_gossipOptionLoaded)
1026 return;
1028 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1030 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1031 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1032 if(i->NpcFlag & npcflags)
1033 addGossipOption(*i);
1035 m_gossipOptionLoaded = true;
1038 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1040 /* uint32 timeElap = getMSTime();
1041 if ((timeElap - m_startMove) < m_moveTime)
1043 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1044 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1046 else
1048 oX = dX;
1049 oY = dY;
1052 dX = x;
1053 dY = y;
1054 m_orientation = atan2((oY - dY), (oX - dX));
1056 m_startMove = getMSTime();
1057 m_moveTime = time;*/
1058 SendMonsterMove(x, y, z, type, MovementFlags, time);
1061 Player *Creature::GetLootRecipient() const
1063 if (!m_lootRecipient) return NULL;
1064 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1067 void Creature::SetLootRecipient(Unit *unit)
1069 // set the player whose group should receive the right
1070 // to loot the creature after it dies
1071 // should be set to NULL after the loot disappears
1073 if (!unit)
1075 m_lootRecipient = 0;
1076 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1077 return;
1080 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1081 if(!player) // normal creature, no player involved
1082 return;
1084 m_lootRecipient = player->GetGUID();
1085 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1088 void Creature::SaveToDB()
1090 // this should only be used when the creature has already been loaded
1091 // preferably after adding to map, because mapid may not be valid otherwise
1092 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1093 if(!data)
1095 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1096 return;
1099 SaveToDB(GetMapId(), data->spawnMask);
1102 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1104 // update in loaded data
1105 if (!m_DBTableGuid)
1106 m_DBTableGuid = GetGUIDLow();
1107 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1109 uint32 displayId = GetNativeDisplayId();
1111 // check if it's a custom model and if not, use 0 for displayId
1112 CreatureInfo const *cinfo = GetCreatureInfo();
1113 if(cinfo)
1115 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1117 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1118 if(!minfo || displayId != minfo->modelid_other_gender)
1120 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1121 if(minfo && displayId == minfo->modelid_other_gender)
1122 displayId = 0;
1124 else
1125 displayId = 0;
1127 else
1128 displayId = 0;
1131 // data->guid = guid don't must be update at save
1132 data.id = GetEntry();
1133 data.mapid = mapid;
1134 data.displayid = displayId;
1135 data.equipmentId = GetEquipmentId();
1136 data.posX = GetPositionX();
1137 data.posY = GetPositionY();
1138 data.posZ = GetPositionZ();
1139 data.orientation = GetOrientation();
1140 data.spawntimesecs = m_respawnDelay;
1141 // prevent add data integrity problems
1142 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1143 data.currentwaypoint = 0;
1144 data.curhealth = GetHealth();
1145 data.curmana = GetPower(POWER_MANA);
1146 data.is_dead = m_isDeadByDefault;
1147 // prevent add data integrity problems
1148 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1149 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1150 data.spawnMask = spawnMask;
1152 // updated in DB
1153 WorldDatabase.BeginTransaction();
1155 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1157 std::ostringstream ss;
1158 ss << "INSERT INTO creature VALUES ("
1159 << m_DBTableGuid << ","
1160 << GetEntry() << ","
1161 << mapid <<","
1162 << (uint32)spawnMask << ","
1163 << displayId <<","
1164 << GetEquipmentId() <<","
1165 << GetPositionX() << ","
1166 << GetPositionY() << ","
1167 << GetPositionZ() << ","
1168 << GetOrientation() << ","
1169 << m_respawnDelay << "," //respawn time
1170 << (float) m_respawnradius << "," //spawn distance (float)
1171 << (uint32) (0) << "," //currentwaypoint
1172 << GetHealth() << "," //curhealth
1173 << GetPower(POWER_MANA) << "," //curmana
1174 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1175 << GetDefaultMovementType() << ")"; //default movement generator type
1177 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1179 WorldDatabase.CommitTransaction();
1182 void Creature::SelectLevel(const CreatureInfo *cinfo)
1184 uint32 rank = isPet()? 0 : cinfo->rank;
1186 // level
1187 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1188 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1189 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1190 SetLevel(level);
1192 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1194 // health
1195 float healthmod = _GetHealthMod(rank);
1197 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1198 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1199 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1201 SetCreateHealth(health);
1202 SetMaxHealth(health);
1203 SetHealth(health);
1205 // mana
1206 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1207 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1208 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1210 SetCreateMana(mana);
1211 SetMaxPower(POWER_MANA, mana); //MAX Mana
1212 SetPower(POWER_MANA, mana);
1214 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1215 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1217 // damage
1218 float damagemod = _GetDamageMod(rank);
1220 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1221 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1223 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1224 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1226 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1229 float Creature::_GetHealthMod(int32 Rank)
1231 switch (Rank) // define rates for each elite rank
1233 case CREATURE_ELITE_NORMAL:
1234 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1235 case CREATURE_ELITE_ELITE:
1236 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1237 case CREATURE_ELITE_RAREELITE:
1238 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1239 case CREATURE_ELITE_WORLDBOSS:
1240 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1241 case CREATURE_ELITE_RARE:
1242 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1243 default:
1244 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1248 float Creature::_GetDamageMod(int32 Rank)
1250 switch (Rank) // define rates for each elite rank
1252 case CREATURE_ELITE_NORMAL:
1253 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1254 case CREATURE_ELITE_ELITE:
1255 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1256 case CREATURE_ELITE_RAREELITE:
1257 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1258 case CREATURE_ELITE_WORLDBOSS:
1259 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1260 case CREATURE_ELITE_RARE:
1261 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1262 default:
1263 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1267 float Creature::GetSpellDamageMod(int32 Rank)
1269 switch (Rank) // define rates for each elite rank
1271 case CREATURE_ELITE_NORMAL:
1272 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1273 case CREATURE_ELITE_ELITE:
1274 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1275 case CREATURE_ELITE_RAREELITE:
1276 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1277 case CREATURE_ELITE_WORLDBOSS:
1278 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1279 case CREATURE_ELITE_RARE:
1280 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1281 default:
1282 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1286 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1288 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1289 if(!cinfo)
1291 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1292 return false;
1294 m_originalEntry = Entry;
1296 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1298 if(!UpdateEntry(Entry, team, data))
1299 return false;
1301 //Notify the map's instance data.
1302 //Only works if you create the object in it, not if it is moves to that map.
1303 //Normally non-players do not teleport to other maps.
1304 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1305 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1307 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1310 return true;
1313 bool Creature::LoadFromDB(uint32 guid, Map *map)
1315 CreatureData const* data = objmgr.GetCreatureData(guid);
1317 if(!data)
1319 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1320 return false;
1323 m_DBTableGuid = guid;
1324 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1326 uint16 team = 0;
1327 if(!Create(guid,map,data->id,team,data))
1328 return false;
1330 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1332 if(!IsPositionValid())
1334 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1335 return false;
1338 m_respawnradius = data->spawndist;
1340 m_respawnDelay = data->spawntimesecs;
1341 m_isDeadByDefault = data->is_dead;
1342 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1344 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1345 if(m_respawnTime > time(NULL)) // not ready to respawn
1346 m_deathState = DEAD;
1347 else if(m_respawnTime) // respawn time set but expired
1349 m_respawnTime = 0;
1350 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1353 uint32 curhealth = data->curhealth;
1354 if(curhealth)
1356 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1357 if(curhealth < 1)
1358 curhealth = 1;
1361 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1362 SetPower(POWER_MANA,data->curmana);
1364 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1366 // checked at creature_template loading
1367 m_defaultMovementType = MovementGeneratorType(data->movementType);
1369 AIM_Initialize();
1370 return true;
1373 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1375 if(equip_entry == 0)
1377 if (force)
1379 for (uint8 i = 0; i < 3; i++)
1380 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1381 m_equipmentId = 0;
1383 return;
1386 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1387 if (!einfo)
1388 return;
1390 m_equipmentId = equip_entry;
1391 for (uint8 i = 0; i < 3; i++)
1392 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1395 bool Creature::hasQuest(uint32 quest_id) const
1397 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1398 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1400 if(itr->second==quest_id)
1401 return true;
1403 return false;
1406 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1408 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1409 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1411 if(itr->second==quest_id)
1412 return true;
1414 return false;
1417 void Creature::DeleteFromDB()
1419 if (!m_DBTableGuid)
1421 sLog.outDebug("Trying to delete not saved creature!");
1422 return;
1425 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1426 objmgr.DeleteCreatureData(m_DBTableGuid);
1428 WorldDatabase.BeginTransaction();
1429 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1430 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1431 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1432 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1433 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1434 WorldDatabase.CommitTransaction();
1437 float Creature::GetAttackDistance(Unit const* pl) const
1439 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1440 if(aggroRate==0)
1441 return 0.0f;
1443 int32 playerlevel = pl->getLevelForTarget(this);
1444 int32 creaturelevel = getLevelForTarget(pl);
1446 int32 leveldif = playerlevel - creaturelevel;
1448 // "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."
1449 if ( leveldif < - 25)
1450 leveldif = -25;
1452 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1453 float RetDistance = 20;
1455 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1456 // radius grow if playlevel < creaturelevel
1457 RetDistance -= (float)leveldif;
1459 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1461 // detect range auras
1462 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1464 // detected range auras
1465 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1468 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1469 if(RetDistance < 5)
1470 RetDistance = 5;
1472 return (RetDistance*aggroRate);
1475 void Creature::setDeathState(DeathState s)
1477 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1479 m_deathTimer = m_corpseDelay*1000;
1481 // always save boss respawn time at death to prevent crash cheating
1482 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1483 SaveRespawnTime();
1485 if(!IsStopped())
1486 StopMoving();
1488 Unit::setDeathState(s);
1490 if(s == JUST_DIED)
1492 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1493 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1495 if(!isPet() && GetCreatureInfo()->SkinLootId)
1496 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1497 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1499 Unit::setDeathState(CORPSE);
1501 if(s == JUST_ALIVED)
1503 SetHealth(GetMaxHealth());
1504 SetLootRecipient(NULL);
1505 Unit::setDeathState(ALIVE);
1506 CreatureInfo const *cinfo = GetCreatureInfo();
1507 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1508 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1509 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1510 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1511 clearUnitState(UNIT_STAT_ALL_STATE);
1512 i_motionMaster.Clear();
1513 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1514 LoadCreaturesAddon(true);
1518 void Creature::Respawn()
1520 RemoveCorpse();
1522 // forced recreate creature object at clients
1523 UnitVisibility currentVis = GetVisibility();
1524 SetVisibility(VISIBILITY_RESPAWN);
1525 ObjectAccessor::UpdateObjectVisibility(this);
1526 SetVisibility(currentVis); // restore visibility state
1527 ObjectAccessor::UpdateObjectVisibility(this);
1529 if(getDeathState()==DEAD)
1531 if (m_DBTableGuid)
1532 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1533 m_respawnTime = time(NULL); // respawn at next tick
1537 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1539 if (!spellInfo)
1540 return false;
1542 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1543 return true;
1545 return Unit::IsImmunedToSpell(spellInfo, useCharges);
1548 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1550 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1551 return true;
1553 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1556 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1558 if(!pVictim)
1559 return NULL;
1561 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1563 if(!m_spells[i])
1564 continue;
1565 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1566 if(!spellInfo)
1568 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1569 continue;
1572 bool bcontinue = true;
1573 for(uint32 j=0;j<3;j++)
1575 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1576 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1577 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1578 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1581 bcontinue = false;
1582 break;
1585 if(bcontinue) continue;
1587 if(spellInfo->manaCost > GetPower(POWER_MANA))
1588 continue;
1589 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1590 float range = GetSpellMaxRange(srange);
1591 float minrange = GetSpellMinRange(srange);
1592 float dist = GetDistance(pVictim);
1593 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1594 // continue;
1595 if( dist > range || dist < minrange )
1596 continue;
1597 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1598 continue;
1599 return spellInfo;
1601 return NULL;
1604 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1606 if(!pVictim)
1607 return NULL;
1609 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1611 if(!m_spells[i])
1612 continue;
1613 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1614 if(!spellInfo)
1616 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1617 continue;
1620 bool bcontinue = true;
1621 for(uint32 j=0;j<3;j++)
1623 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1625 bcontinue = false;
1626 break;
1629 if(bcontinue) continue;
1631 if(spellInfo->manaCost > GetPower(POWER_MANA))
1632 continue;
1633 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1634 float range = GetSpellMaxRange(srange);
1635 float minrange = GetSpellMinRange(srange);
1636 float dist = GetDistance(pVictim);
1637 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1638 // continue;
1639 if( dist > range || dist < minrange )
1640 continue;
1641 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1642 continue;
1643 return spellInfo;
1645 return NULL;
1648 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1650 // gamemaster in GM mode see all, including ghosts
1651 if(pl->isGameMaster())
1652 return true;
1654 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1655 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1657 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1658 return false;
1659 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1662 // Dead player see live creatures near own corpse
1663 if(isAlive())
1665 Corpse *corpse = pl->GetCorpse();
1666 if(corpse)
1668 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1669 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1670 return true;
1674 // Dead player see Spirit Healer or Spirit Guide
1675 if(isSpiritService())
1676 return true;
1678 // and not see any other
1679 return false;
1682 void Creature::CallAssistance()
1684 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1686 SetNoCallAssistance(true);
1688 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1689 if(radius > 0)
1691 std::list<Creature*> assistList;
1694 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1695 Cell cell(p);
1696 cell.data.Part.reserved = ALL_DISTRICT;
1697 cell.SetNoCreate();
1699 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1700 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1702 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1704 CellLock<GridReadGuard> cell_lock(cell, p);
1705 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1708 if (!assistList.empty())
1710 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1711 while (!assistList.empty())
1713 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1714 e->AddAssistant((*assistList.begin())->GetGUID());
1715 assistList.pop_front();
1717 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1723 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1725 // we don't need help from zombies :)
1726 if( !isAlive() )
1727 return false;
1729 // skip fighting creature
1730 if( isInCombat() )
1731 return false;
1733 // only from same creature faction
1734 if(getFaction() != u->getFaction() )
1735 return false;
1737 // only free creature
1738 if( GetCharmerOrOwnerGUID() )
1739 return false;
1741 // skip non hostile to caster enemy creatures
1742 if( !IsHostileTo(enemy) )
1743 return false;
1745 return true;
1748 void Creature::SaveRespawnTime()
1750 if(isPet() || !m_DBTableGuid)
1751 return;
1753 if(m_respawnTime > time(NULL)) // dead (no corpse)
1754 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1755 else if(m_deathTimer > 0) // dead (corpse)
1756 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1759 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1761 if(!pVictim)
1762 return true;
1764 if(!pVictim->IsInMap(this))
1765 return true;
1767 if(!pVictim->isTargetableForAttack())
1768 return true;
1770 if(!pVictim->isInAccessablePlaceFor(this))
1771 return true;
1773 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1774 return false;
1776 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1777 float AttackDist = GetAttackDistance(pVictim);
1778 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1780 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1781 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1784 CreatureDataAddon const* Creature::GetCreatureAddon() const
1786 if (m_DBTableGuid)
1788 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1789 return addon;
1792 // dependent from heroic mode entry
1793 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1796 //creature_addon table
1797 bool Creature::LoadCreaturesAddon(bool reload)
1799 CreatureDataAddon const *cainfo = GetCreatureAddon();
1800 if(!cainfo)
1801 return false;
1803 if (cainfo->mount != 0)
1804 Mount(cainfo->mount);
1806 if (cainfo->bytes0 != 0)
1807 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1809 if (cainfo->bytes1 != 0)
1810 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1812 if (cainfo->bytes2 != 0)
1813 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1815 if (cainfo->emote != 0)
1816 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1818 if (cainfo->move_flags != 0)
1819 SetUnitMovementFlags(cainfo->move_flags);
1821 if(cainfo->auras)
1823 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1825 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1826 if (!AdditionalSpellInfo)
1828 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1829 continue;
1832 // skip already applied aura
1833 if(HasAura(cAura->spell_id,cAura->effect_idx))
1835 if(!reload)
1836 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);
1838 continue;
1841 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1842 AddAura(AdditionalAura);
1843 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1846 return true;
1849 /// Send a message to LocalDefense channel for players opposition team in the zone
1850 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1852 uint32 enemy_team = attacker->GetTeam();
1854 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1855 data << (uint32)GetZoneId();
1856 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1859 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1861 m_CreatureSpellCooldowns[spell_id] = end_time;
1864 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1866 m_CreatureCategoryCooldowns[category] = apply_time;
1869 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1871 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1872 if(!spellInfo)
1873 return;
1875 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1876 if(cooldown)
1877 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1879 if(spellInfo->Category)
1880 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1882 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1885 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1887 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1888 if(!spellInfo)
1889 return false;
1891 // check global cooldown if spell affected by it
1892 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1893 return true;
1895 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1896 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1899 bool Creature::HasSpellCooldown(uint32 spell_id) const
1901 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1902 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1905 bool Creature::IsInEvadeMode() const
1907 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1910 bool Creature::HasSpell(uint32 spellID) const
1912 uint8 i;
1913 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1914 if(spellID == m_spells[i])
1915 break;
1916 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1919 time_t Creature::GetRespawnTimeEx() const
1921 time_t now = time(NULL);
1922 if(m_respawnTime > now) // dead (no corpse)
1923 return m_respawnTime;
1924 else if(m_deathTimer > 0) // dead (corpse)
1925 return now+m_respawnDelay+m_deathTimer/1000;
1926 else
1927 return now;
1930 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1932 if (m_DBTableGuid)
1934 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1936 x = data->posX;
1937 y = data->posY;
1938 z = data->posZ;
1939 if(ori)
1940 *ori = data->orientation;
1941 if(dist)
1942 *dist = data->spawndist;
1944 return;
1948 x = GetPositionX();
1949 y = GetPositionY();
1950 z = GetPositionZ();
1951 if(ori)
1952 *ori = GetOrientation();
1953 if(dist)
1954 *dist = 0;
1957 void Creature::AllLootRemovedFromCorpse()
1959 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1961 uint32 nDeathTimer;
1963 CreatureInfo const *cinfo = GetCreatureInfo();
1965 // corpse was not skinnable -> apply corpse looted timer
1966 if (!cinfo || !cinfo->SkinLootId)
1967 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1968 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1969 else
1970 nDeathTimer = 0;
1972 // update death timer only if looted timer is shorter
1973 if (m_deathTimer > nDeathTimer)
1974 m_deathTimer = nDeathTimer;
1978 uint32 Creature::getLevelForTarget( Unit const* target ) const
1980 if(!isWorldBoss())
1981 return Unit::getLevelForTarget(target);
1983 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1984 if(level < 1)
1985 return 1;
1986 if(level > 255)
1987 return 255;
1988 return level;
1991 std::string Creature::GetScriptName()
1993 return objmgr.GetScriptName(GetScriptId());
1996 uint32 Creature::GetScriptId()
1998 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2001 VendorItemData const* Creature::GetVendorItems() const
2003 return objmgr.GetNpcVendorItemList(GetEntry());
2006 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2008 if(!vItem->maxcount)
2009 return vItem->maxcount;
2011 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2012 for(; itr != m_vendorItemCounts.end(); ++itr)
2013 if(itr->itemId==vItem->item)
2014 break;
2016 if(itr == m_vendorItemCounts.end())
2017 return vItem->maxcount;
2019 VendorItemCount* vCount = &*itr;
2021 time_t ptime = time(NULL);
2023 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2025 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2027 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2028 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2030 m_vendorItemCounts.erase(itr);
2031 return vItem->maxcount;
2034 vCount->count += diff * pProto->BuyCount;
2035 vCount->lastIncrementTime = ptime;
2038 return vCount->count;
2041 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2043 if(!vItem->maxcount)
2044 return 0;
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())
2053 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2054 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2055 return new_count;
2058 VendorItemCount* vCount = &*itr;
2060 time_t ptime = time(NULL);
2062 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2064 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2066 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2067 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2068 vCount->count += diff * pProto->BuyCount;
2069 else
2070 vCount->count = vItem->maxcount;
2073 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2074 vCount->lastIncrementTime = ptime;
2075 return vCount->count;
2078 TrainerSpellData const* Creature::GetTrainerSpells() const
2080 return objmgr.GetNpcTrainerSpells(GetEntry());
2083 // overwrite WorldObject function for proper name localization
2084 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2086 if (loc_idx >= 0)
2088 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2089 if (cl)
2091 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2092 return cl->Name[loc_idx].c_str();
2096 return GetName();