[8449] Deprecate healing/damage item mods and merge internal data in to spell power.
[getmangos.git] / src / game / Creature.cpp
blob775caeb74cd2699d0ba7f4343ee86d0f5183a897
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "World.h"
23 #include "ObjectMgr.h"
24 #include "SpellMgr.h"
25 #include "Creature.h"
26 #include "QuestDef.h"
27 #include "GossipDef.h"
28 #include "Player.h"
29 #include "PoolHandler.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 "WaypointMovementGenerator.h"
38 #include "InstanceData.h"
39 #include "BattleGroundMgr.h"
40 #include "Util.h"
41 #include "GridNotifiers.h"
42 #include "GridNotifiersImpl.h"
43 #include "CellImpl.h"
45 // apply implementation of the singletons
46 #include "Policies/SingletonImp.h"
48 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
50 TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
51 if (itr != spellList.end())
52 return &itr->second;
54 return NULL;
57 bool VendorItemData::RemoveItem( uint32 item_id )
59 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
61 if((*i)->item==item_id)
63 m_items.erase(i);
64 return true;
67 return false;
70 size_t VendorItemData::FindItemSlot(uint32 item_id) const
72 for(size_t i = 0; i < m_items.size(); ++i )
73 if(m_items[i]->item==item_id)
74 return i;
75 return m_items.size();
78 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
80 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
81 if((*i)->item==item_id)
82 return *i;
83 return NULL;
86 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
88 if(Unit* victim = Unit::GetUnit(m_owner, m_victim))
90 while (!m_assistants.empty())
92 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
93 m_assistants.pop_front();
95 if (assistant && assistant->CanAssistTo(&m_owner, victim))
97 assistant->SetNoCallAssistance(true);
98 if(assistant->AI())
99 assistant->AI()->AttackStart(victim);
103 return true;
106 Creature::Creature() :
107 Unit(), i_AI(NULL),
108 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
109 m_lootMoney(0), m_lootRecipient(0),
110 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
111 m_gossipOptionLoaded(false), m_isPet(false), m_isVehicle(false), m_isTotem(false),
112 m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0),
113 m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
114 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
115 m_creatureInfo(NULL), m_isActiveObject(false), m_monsterMoveFlags(MONSTER_MOVE_WALK)
117 m_regenTimer = 200;
118 m_valuesCount = UNIT_END;
120 for(int i =0; i<4; ++i)
121 m_spells[i] = 0;
123 m_CreatureSpellCooldowns.clear();
124 m_CreatureCategoryCooldowns.clear();
125 m_GlobalCooldown = 0;
127 m_monsterMoveFlags = MONSTER_MOVE_WALK;
130 Creature::~Creature()
132 CleanupsBeforeDelete();
134 m_vendorItemCounts.clear();
136 delete i_AI;
137 i_AI = NULL;
140 void Creature::AddToWorld()
142 ///- Register the creature for guid lookup
143 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
144 Unit::AddToWorld();
147 void Creature::RemoveFromWorld()
149 ///- Remove the creature from the accessor
150 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
151 Unit::RemoveFromWorld();
154 void Creature::RemoveCorpse()
156 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
157 return;
159 m_deathTimer = 0;
160 setDeathState(DEAD);
161 ObjectAccessor::UpdateObjectVisibility(this);
162 loot.clear();
163 m_respawnTime = time(NULL) + m_respawnDelay;
165 float x,y,z,o;
166 GetRespawnCoord(x, y, z, &o);
167 GetMap()->CreatureRelocation(this,x,y,z,o);
171 * change the entry of creature until respawn
173 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
175 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
176 if(!normalInfo)
178 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
179 return false;
182 // get heroic mode entry
183 uint32 actualEntry = Entry;
184 CreatureInfo const *cinfo = normalInfo;
185 if(normalInfo->HeroicEntry)
187 //we already have valid Map pointer for current creature!
188 if(GetMap()->IsHeroic())
190 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
191 if(!cinfo)
193 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
194 return false;
199 SetEntry(Entry); // normal entry always
200 m_creatureInfo = cinfo; // map mode related always
202 // equal to player Race field, but creature does not have race
203 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
205 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
206 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
208 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
209 if (!display_id) // Cancel load if no display id
211 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
212 return false;
215 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
216 if (!minfo) // Cancel load if no model defined
218 sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load. ",Entry);
219 return false;
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 SetSheath(SHEATH_STATE_MELEE);
269 SelectLevel(GetCreatureInfo());
270 if (team == HORDE)
271 setFaction(GetCreatureInfo()->faction_H);
272 else
273 setFaction(GetCreatureInfo()->faction_A);
275 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
277 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
278 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
279 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
281 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
282 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
284 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
285 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
286 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
287 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
288 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
289 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
290 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
292 SetCanModifyStats(true);
293 UpdateAllStats();
295 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
296 if (factionTemplate) // check and error show at loading templates
298 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
299 if (factionEntry)
300 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
301 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
302 SetPvP(true);
305 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
306 m_spells[i] = GetCreatureInfo()->spells[i];
308 return true;
311 void Creature::Update(uint32 diff)
313 if(m_GlobalCooldown <= diff)
314 m_GlobalCooldown = 0;
315 else
316 m_GlobalCooldown -= diff;
318 switch( m_deathState )
320 case JUST_ALIVED:
321 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
322 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
323 break;
324 case JUST_DIED:
325 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
326 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
327 break;
328 case DEAD:
330 if( m_respawnTime <= time(NULL) )
332 DEBUG_LOG("Respawning...");
333 m_respawnTime = 0;
334 lootForPickPocketed = false;
335 lootForBody = false;
337 if(m_originalEntry != GetEntry())
338 UpdateEntry(m_originalEntry);
340 CreatureInfo const *cinfo = GetCreatureInfo();
342 SelectLevel(cinfo);
343 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
344 if (m_isDeadByDefault)
346 setDeathState(JUST_DIED);
347 SetHealth(0);
348 i_motionMaster.Clear();
349 clearUnitState(UNIT_STAT_ALL_STATE);
350 LoadCreaturesAddon(true);
352 else
353 setDeathState( JUST_ALIVED );
355 //Call AI respawn virtual function
356 i_AI->JustRespawned();
358 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), GetTypeId());
359 if (poolid)
360 poolhandler.UpdatePool(poolid, GetGUIDLow(), GetTypeId());
361 else
362 GetMap()->Add(this);
364 break;
366 case CORPSE:
368 if (m_isDeadByDefault)
369 break;
371 if( m_deathTimer <= diff )
373 RemoveCorpse();
374 DEBUG_LOG("Removing corpse... %u ", GetEntry());
376 else
378 m_deathTimer -= diff;
379 if (m_groupLootTimer && lootingGroupLeaderGUID)
381 if(diff <= m_groupLootTimer)
383 m_groupLootTimer -= diff;
385 else
387 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
388 if (group)
389 group->EndRoll();
390 m_groupLootTimer = 0;
391 lootingGroupLeaderGUID = 0;
396 break;
398 case ALIVE:
400 if (m_isDeadByDefault)
402 if( m_deathTimer <= diff )
404 RemoveCorpse();
405 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
407 else
409 m_deathTimer -= diff;
413 Unit::Update( diff );
415 // creature can be dead after Unit::Update call
416 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
417 if(!isAlive())
418 break;
420 if(!IsInEvadeMode())
422 // do not allow the AI to be changed during update
423 m_AI_locked = true;
424 i_AI->UpdateAI(diff);
425 m_AI_locked = false;
428 // creature can be dead after UpdateAI call
429 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
430 if(!isAlive())
431 break;
432 if(m_regenTimer > 0)
434 if(diff >= m_regenTimer)
435 m_regenTimer = 0;
436 else
437 m_regenTimer -= diff;
439 if (m_regenTimer != 0)
440 break;
442 if (!isInCombat() || IsPolymorphed())
443 RegenerateHealth();
445 RegenerateMana();
447 m_regenTimer = 2000;
448 break;
450 case DEAD_FALLING:
452 if (!FallGround())
453 setDeathState(JUST_DIED);
455 default:
456 break;
460 void Creature::RegenerateMana()
462 uint32 curValue = GetPower(POWER_MANA);
463 uint32 maxValue = GetMaxPower(POWER_MANA);
465 if (curValue >= maxValue)
466 return;
468 uint32 addvalue = 0;
470 // Combat and any controlled creature
471 if (isInCombat() || GetCharmerOrOwnerGUID())
473 if(!IsUnderLastManaUseEffect())
475 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
476 float Spirit = GetStat(STAT_SPIRIT);
478 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
481 else
482 addvalue = maxValue/3;
484 ModifyPower(POWER_MANA, addvalue);
487 void Creature::RegenerateHealth()
489 if (!isRegeneratingHealth())
490 return;
492 uint32 curValue = GetHealth();
493 uint32 maxValue = GetMaxHealth();
495 if (curValue >= maxValue)
496 return;
498 uint32 addvalue = 0;
500 // Not only pet, but any controlled creature
501 if(GetCharmerOrOwnerGUID())
503 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
504 float Spirit = GetStat(STAT_SPIRIT);
506 if( GetPower(POWER_MANA) > 0 )
507 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
508 else
509 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
511 else
512 addvalue = maxValue/3;
514 ModifyHealth(addvalue);
517 void Creature::DoFleeToGetAssistance()
519 if (!getVictim())
520 return;
522 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
523 if (radius >0)
525 Creature* pCreature = NULL;
527 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
528 Cell cell(p);
529 cell.data.Part.reserved = ALL_DISTRICT;
530 cell.SetNoCreate();
531 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
532 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
534 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
536 CellLock<GridReadGuard> cell_lock(cell, p);
537 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
539 SetNoSearchAssistance(true);
540 if(!pCreature)
541 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
542 else
543 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
547 bool Creature::AIM_Initialize()
549 // make sure nothing can change the AI during AI update
550 if(m_AI_locked)
552 sLog.outDebug("AIM_Initialize: failed to init, locked.");
553 return false;
556 CreatureAI * oldAI = i_AI;
557 i_motionMaster.Initialize();
558 i_AI = FactorySelector::selectAI(this);
559 if (oldAI)
560 delete oldAI;
561 return true;
564 bool Creature::Create (uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
566 ASSERT(map);
567 SetMap(map);
568 SetPhaseMask(phaseMask,false);
570 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
571 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
573 if (bResult)
575 //Notify the map's instance data.
576 //Only works if you create the object in it, not if it is moves to that map.
577 //Normally non-players do not teleport to other maps.
578 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
579 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
581 switch (GetCreatureInfo()->rank)
583 case CREATURE_ELITE_RARE:
584 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
585 break;
586 case CREATURE_ELITE_ELITE:
587 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
588 break;
589 case CREATURE_ELITE_RAREELITE:
590 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
591 break;
592 case CREATURE_ELITE_WORLDBOSS:
593 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
594 break;
595 default:
596 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
597 break;
599 LoadCreaturesAddon();
602 return bResult;
605 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
607 if(!isTrainer())
608 return false;
610 TrainerSpellData const* trainer_spells = GetTrainerSpells();
612 if(!trainer_spells || trainer_spells->spellList.empty())
614 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
615 GetGUIDLow(),GetEntry());
616 return false;
619 switch(GetCreatureInfo()->trainer_type)
621 case TRAINER_TYPE_CLASS:
622 if(pPlayer->getClass()!=GetCreatureInfo()->trainer_class)
624 if(msg)
626 pPlayer->PlayerTalkClass->ClearMenus();
627 switch(GetCreatureInfo()->trainer_class)
629 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
630 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
631 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
632 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
633 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
634 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
635 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
636 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
637 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
640 return false;
642 break;
643 case TRAINER_TYPE_PETS:
644 if(pPlayer->getClass()!=CLASS_HUNTER)
646 pPlayer->PlayerTalkClass->ClearMenus();
647 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
648 return false;
650 break;
651 case TRAINER_TYPE_MOUNTS:
652 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
654 if(msg)
656 pPlayer->PlayerTalkClass->ClearMenus();
657 switch(GetCreatureInfo()->trainer_class)
659 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
660 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
661 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
662 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
663 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
664 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
665 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
666 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
667 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
668 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
671 return false;
673 break;
674 case TRAINER_TYPE_TRADESKILLS:
675 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
677 if(msg)
679 pPlayer->PlayerTalkClass->ClearMenus();
680 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
682 return false;
684 break;
685 default:
686 return false; // checked and error output at creature_template loading
688 return true;
691 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
693 if(!isBattleMaster())
694 return false;
696 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
697 if(!msg)
698 return pPlayer->GetBGAccessByLevel(bgTypeId);
700 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
702 pPlayer->PlayerTalkClass->ClearMenus();
703 switch(bgTypeId)
705 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
706 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
707 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
708 case BATTLEGROUND_EY:
709 case BATTLEGROUND_NA:
710 case BATTLEGROUND_BE:
711 case BATTLEGROUND_AA:
712 case BATTLEGROUND_RL:
713 case BATTLEGROUND_SA:
714 case BATTLEGROUND_DS:
715 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
716 default: break;
718 return false;
720 return true;
723 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
725 return pPlayer->getLevel() >= 10
726 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
727 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
730 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
732 PlayerMenu* pm=pPlayer->PlayerTalkClass;
733 pm->ClearMenus();
735 // lazy loading single time at use
736 LoadGossipOptions();
738 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
740 GossipOption* gso=&*i;
741 if(gso->GossipId == gossipid)
743 bool cantalking=true;
744 if(gso->Id==1)
746 uint32 textid=GetNpcTextId();
747 GossipText const* gossiptext=objmgr.GetGossipText(textid);
748 if(!gossiptext)
749 cantalking=false;
751 else
753 switch (gso->Action)
755 case GOSSIP_OPTION_QUESTGIVER:
756 pPlayer->PrepareQuestMenu(GetGUID());
757 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
758 cantalking=false;
759 //pm->GetQuestMenu()->ClearMenu();
760 break;
761 case GOSSIP_OPTION_ARMORER:
762 cantalking=false; // added in special mode
763 break;
764 case GOSSIP_OPTION_SPIRITHEALER:
765 if( !pPlayer->isDead() )
766 cantalking=false;
767 break;
768 case GOSSIP_OPTION_VENDOR:
770 VendorItemData const* vItems = GetVendorItems();
771 if(!vItems || vItems->Empty())
773 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
774 GetGUIDLow(),GetEntry());
775 cantalking=false;
777 break;
779 case GOSSIP_OPTION_TRAINER:
780 if(!isCanTrainingOf(pPlayer,false))
781 cantalking=false;
782 break;
783 case GOSSIP_OPTION_UNLEARNTALENTS:
784 if(!isCanTrainingAndResetTalentsOf(pPlayer))
785 cantalking=false;
786 break;
787 case GOSSIP_OPTION_UNLEARNPETSKILLS:
788 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->trainer_class != CLASS_HUNTER)
789 cantalking=false;
790 break;
791 case GOSSIP_OPTION_TAXIVENDOR:
792 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
793 return;
794 break;
795 case GOSSIP_OPTION_BATTLEFIELD:
796 if(!isCanInteractWithBattleMaster(pPlayer,false))
797 cantalking=false;
798 break;
799 case GOSSIP_OPTION_SPIRITGUIDE:
800 case GOSSIP_OPTION_INNKEEPER:
801 case GOSSIP_OPTION_BANKER:
802 case GOSSIP_OPTION_PETITIONER:
803 case GOSSIP_OPTION_STABLEPET:
804 case GOSSIP_OPTION_TABARDDESIGNER:
805 case GOSSIP_OPTION_AUCTIONEER:
806 break; // no checks
807 default:
808 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
809 break;
813 //note for future dev: should have database fields for BoxMessage & BoxMoney
814 if(!gso->OptionText.empty() && cantalking)
816 std::string OptionText = gso->OptionText;
817 std::string BoxText = gso->BoxText;
818 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
819 if (loc_idx >= 0)
821 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
822 if (no)
824 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
825 OptionText=no->OptionText[loc_idx];
826 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
827 BoxText=no->BoxText[loc_idx];
830 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
835 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
836 if(pm->Empty())
838 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
840 isCanTrainingOf(pPlayer,true); // output error message if need
842 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
844 isCanInteractWithBattleMaster(pPlayer,true); // output error message if need
849 void Creature::sendPreparedGossip(Player* player)
851 if(!player)
852 return;
854 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
855 if (!HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !player->PlayerTalkClass->GetQuestMenu().Empty())
857 player->SendPreparedQuest(GetGUID());
858 return;
861 // in case non empty gossip menu (that not included quests list size) show it
862 // (quest entries from quest menu will be included in list)
863 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
866 void Creature::OnGossipSelect(Player* player, uint32 option)
868 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
870 if(option >= gossipmenu.MenuItemCount())
871 return;
873 uint32 action=gossipmenu.GetItem(option).m_gAction;
874 uint32 zoneid=GetZoneId();
875 uint64 guid=GetGUID();
877 GossipOption const *gossip=GetGossipOption( action );
878 if(!gossip)
880 zoneid=0;
881 gossip=GetGossipOption( action );
882 if(!gossip)
883 return;
886 switch (gossip->Action)
888 case GOSSIP_OPTION_GOSSIP:
890 uint32 textid = GetGossipTextId(action, zoneid);
891 if (textid == 0)
892 textid=GetNpcTextId();
894 player->PlayerTalkClass->CloseGossip();
895 player->PlayerTalkClass->SendTalking(textid);
896 break;
898 case GOSSIP_OPTION_SPIRITHEALER:
899 if (player->isDead())
900 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
901 break;
902 case GOSSIP_OPTION_QUESTGIVER:
903 player->PrepareQuestMenu( guid );
904 player->SendPreparedQuest( guid );
905 break;
906 case GOSSIP_OPTION_VENDOR:
907 case GOSSIP_OPTION_ARMORER:
908 player->GetSession()->SendListInventory(guid);
909 break;
910 case GOSSIP_OPTION_STABLEPET:
911 player->GetSession()->SendStablePet(guid);
912 break;
913 case GOSSIP_OPTION_TRAINER:
914 player->GetSession()->SendTrainerList(guid);
915 break;
916 case GOSSIP_OPTION_UNLEARNTALENTS:
917 player->PlayerTalkClass->CloseGossip();
918 player->SendTalentWipeConfirm(guid);
919 break;
920 case GOSSIP_OPTION_UNLEARNPETSKILLS:
921 player->PlayerTalkClass->CloseGossip();
922 player->SendPetSkillWipeConfirm();
923 break;
924 case GOSSIP_OPTION_TAXIVENDOR:
925 player->GetSession()->SendTaxiMenu(this);
926 break;
927 case GOSSIP_OPTION_INNKEEPER:
928 player->PlayerTalkClass->CloseGossip();
929 player->SetBindPoint( guid );
930 break;
931 case GOSSIP_OPTION_BANKER:
932 player->GetSession()->SendShowBank( guid );
933 break;
934 case GOSSIP_OPTION_PETITIONER:
935 player->PlayerTalkClass->CloseGossip();
936 player->GetSession()->SendPetitionShowList( guid );
937 break;
938 case GOSSIP_OPTION_TABARDDESIGNER:
939 player->PlayerTalkClass->CloseGossip();
940 player->GetSession()->SendTabardVendorActivate( guid );
941 break;
942 case GOSSIP_OPTION_AUCTIONEER:
943 player->GetSession()->SendAuctionHello( guid, this );
944 break;
945 case GOSSIP_OPTION_SPIRITGUIDE:
946 case GOSSIP_GUARD_SPELLTRAINER:
947 case GOSSIP_GUARD_SKILLTRAINER:
948 prepareGossipMenu( player,gossip->Id );
949 sendPreparedGossip( player );
950 break;
951 case GOSSIP_OPTION_BATTLEFIELD:
953 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
954 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
955 break;
957 default:
958 OnPoiSelect( player, gossip );
959 break;
964 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
966 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
968 Poi_Icon icon = ICON_POI_BLANK;
969 //need add more case.
970 switch(gossip->Action)
972 case GOSSIP_GUARD_BANK:
973 icon=ICON_POI_SMALL_HOUSE;
974 break;
975 case GOSSIP_GUARD_RIDE:
976 icon=ICON_POI_RWHORSE;
977 break;
978 case GOSSIP_GUARD_GUILD:
979 icon=ICON_POI_BLUETOWER;
980 break;
981 default:
982 icon=ICON_POI_GREYTOWER;
983 break;
985 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
986 player->PlayerTalkClass->SendTalking(textid);
987 // std::string areaname= gossip->OptionText;
988 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
992 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
994 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
996 if(!result)
997 return 0;
999 Field *fields = result->Fetch();
1000 uint32 id = fields[0].GetUInt32();
1002 delete result;
1004 return id;
1007 uint32 Creature::GetNpcTextId()
1009 if (!m_DBTableGuid)
1010 return DEFAULT_GOSSIP_MESSAGE;
1012 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1013 return pos;
1015 return DEFAULT_GOSSIP_MESSAGE;
1018 GossipOption const* Creature::GetGossipOption( uint32 id ) const
1020 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
1022 if(i->Action==id )
1023 return &*i;
1025 return NULL;
1028 void Creature::LoadGossipOptions()
1030 if(m_gossipOptionLoaded)
1031 return;
1033 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1035 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1036 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1037 if(i->NpcFlag & npcflags)
1038 addGossipOption(*i);
1040 m_gossipOptionLoaded = true;
1043 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, MonsterMovementFlags flags, uint8 type)
1045 /* uint32 timeElap = getMSTime();
1046 if ((timeElap - m_startMove) < m_moveTime)
1048 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1049 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1051 else
1053 oX = dX;
1054 oY = dY;
1057 dX = x;
1058 dY = y;
1059 m_orientation = atan2((oY - dY), (oX - dX));
1061 m_startMove = getMSTime();
1062 m_moveTime = time;*/
1063 SendMonsterMove(x, y, z, type, flags, time);
1066 Player *Creature::GetLootRecipient() const
1068 if (!m_lootRecipient) return NULL;
1069 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1072 void Creature::SetLootRecipient(Unit *unit)
1074 // set the player whose group should receive the right
1075 // to loot the creature after it dies
1076 // should be set to NULL after the loot disappears
1078 if (!unit)
1080 m_lootRecipient = 0;
1081 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1082 return;
1085 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1086 if(!player) // normal creature, no player involved
1087 return;
1089 m_lootRecipient = player->GetGUID();
1090 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1093 void Creature::SaveToDB()
1095 // this should only be used when the creature has already been loaded
1096 // preferably after adding to map, because mapid may not be valid otherwise
1097 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1098 if(!data)
1100 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1101 return;
1104 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
1107 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
1109 // update in loaded data
1110 if (!m_DBTableGuid)
1111 m_DBTableGuid = GetGUIDLow();
1112 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1114 uint32 displayId = GetNativeDisplayId();
1116 // check if it's a custom model and if not, use 0 for displayId
1117 CreatureInfo const *cinfo = GetCreatureInfo();
1118 if (cinfo)
1120 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
1121 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
1123 if (cinfo->DisplayID_A[0])
1124 if (CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
1125 if(displayId == minfo->modelid_other_gender)
1126 displayId = 0;
1128 if (displayId && cinfo->DisplayID_A[1])
1129 if (CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
1130 if(displayId == minfo->modelid_other_gender)
1131 displayId = 0;
1133 if (displayId && cinfo->DisplayID_H[0])
1134 if (CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
1135 if(displayId == minfo->modelid_other_gender)
1136 displayId = 0;
1138 if (displayId && cinfo->DisplayID_H[1])
1139 if (CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
1140 if(displayId == minfo->modelid_other_gender)
1141 displayId = 0;
1143 else
1144 displayId = 0;
1147 // data->guid = guid don't must be update at save
1148 data.id = GetEntry();
1149 data.mapid = mapid;
1150 data.phaseMask = phaseMask;
1151 data.displayid = displayId;
1152 data.equipmentId = GetEquipmentId();
1153 data.posX = GetPositionX();
1154 data.posY = GetPositionY();
1155 data.posZ = GetPositionZ();
1156 data.orientation = GetOrientation();
1157 data.spawntimesecs = m_respawnDelay;
1158 // prevent add data integrity problems
1159 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1160 data.currentwaypoint = 0;
1161 data.curhealth = GetHealth();
1162 data.curmana = GetPower(POWER_MANA);
1163 data.is_dead = m_isDeadByDefault;
1164 // prevent add data integrity problems
1165 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1166 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1167 data.spawnMask = spawnMask;
1169 // updated in DB
1170 WorldDatabase.BeginTransaction();
1172 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1174 std::ostringstream ss;
1175 ss << "INSERT INTO creature VALUES ("
1176 << m_DBTableGuid << ","
1177 << GetEntry() << ","
1178 << mapid <<","
1179 << uint32(spawnMask) << "," // cast to prevent save as symbol
1180 << uint16(GetPhaseMask()) << "," // prevent out of range error
1181 << displayId <<","
1182 << GetEquipmentId() <<","
1183 << GetPositionX() << ","
1184 << GetPositionY() << ","
1185 << GetPositionZ() << ","
1186 << GetOrientation() << ","
1187 << m_respawnDelay << "," //respawn time
1188 << (float) m_respawnradius << "," //spawn distance (float)
1189 << (uint32) (0) << "," //currentwaypoint
1190 << GetHealth() << "," //curhealth
1191 << GetPower(POWER_MANA) << "," //curmana
1192 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1193 << GetDefaultMovementType() << ")"; //default movement generator type
1195 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1197 WorldDatabase.CommitTransaction();
1200 void Creature::SelectLevel(const CreatureInfo *cinfo)
1202 uint32 rank = isPet()? 0 : cinfo->rank;
1204 // level
1205 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1206 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1207 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1208 SetLevel(level);
1210 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1212 // health
1213 float healthmod = _GetHealthMod(rank);
1215 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1216 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1217 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1219 SetCreateHealth(health);
1220 SetMaxHealth(health);
1221 SetHealth(health);
1223 // mana
1224 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1225 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1226 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1228 SetCreateMana(mana);
1229 SetMaxPower(POWER_MANA, mana); //MAX Mana
1230 SetPower(POWER_MANA, mana);
1232 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
1234 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1235 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1237 // damage
1238 float damagemod = _GetDamageMod(rank);
1240 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1241 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1243 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1244 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1246 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1249 float Creature::_GetHealthMod(int32 Rank)
1251 switch (Rank) // define rates for each elite rank
1253 case CREATURE_ELITE_NORMAL:
1254 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1255 case CREATURE_ELITE_ELITE:
1256 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1257 case CREATURE_ELITE_RAREELITE:
1258 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1259 case CREATURE_ELITE_WORLDBOSS:
1260 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1261 case CREATURE_ELITE_RARE:
1262 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1263 default:
1264 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1268 float Creature::_GetDamageMod(int32 Rank)
1270 switch (Rank) // define rates for each elite rank
1272 case CREATURE_ELITE_NORMAL:
1273 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1274 case CREATURE_ELITE_ELITE:
1275 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1276 case CREATURE_ELITE_RAREELITE:
1277 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1278 case CREATURE_ELITE_WORLDBOSS:
1279 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1280 case CREATURE_ELITE_RARE:
1281 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1282 default:
1283 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1287 float Creature::GetSpellDamageMod(int32 Rank)
1289 switch (Rank) // define rates for each elite rank
1291 case CREATURE_ELITE_NORMAL:
1292 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1293 case CREATURE_ELITE_ELITE:
1294 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1295 case CREATURE_ELITE_RAREELITE:
1296 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1297 case CREATURE_ELITE_WORLDBOSS:
1298 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1299 case CREATURE_ELITE_RARE:
1300 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1301 default:
1302 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1306 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1308 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1309 if(!cinfo)
1311 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1312 return false;
1314 m_originalEntry = Entry;
1316 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1318 if(!UpdateEntry(Entry, team, data))
1319 return false;
1321 return true;
1324 bool Creature::LoadFromDB(uint32 guid, Map *map)
1326 CreatureData const* data = objmgr.GetCreatureData(guid);
1328 if(!data)
1330 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1331 return false;
1334 m_DBTableGuid = guid;
1335 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1337 uint16 team = 0;
1338 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1339 return false;
1341 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1343 if(!IsPositionValid())
1345 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1346 return false;
1349 m_respawnradius = data->spawndist;
1351 m_respawnDelay = data->spawntimesecs;
1352 m_isDeadByDefault = data->is_dead;
1353 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1355 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1356 if(m_respawnTime > time(NULL)) // not ready to respawn
1358 m_deathState = DEAD;
1359 if(canFly())
1361 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1362 if(data->posZ - tz > 0.1)
1363 Relocate(data->posX,data->posY,tz);
1366 else if(m_respawnTime) // respawn time set but expired
1368 m_respawnTime = 0;
1369 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1372 uint32 curhealth = data->curhealth;
1373 if(curhealth)
1375 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1376 if(curhealth < 1)
1377 curhealth = 1;
1380 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1381 SetPower(POWER_MANA,data->curmana);
1383 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1385 // checked at creature_template loading
1386 m_defaultMovementType = MovementGeneratorType(data->movementType);
1388 AIM_Initialize();
1389 return true;
1392 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1394 if(equip_entry == 0)
1396 if (force)
1398 for (uint8 i = 0; i < 3; ++i)
1399 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1400 m_equipmentId = 0;
1402 return;
1405 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1406 if (!einfo)
1407 return;
1409 m_equipmentId = equip_entry;
1410 for (uint8 i = 0; i < 3; ++i)
1411 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1414 bool Creature::hasQuest(uint32 quest_id) const
1416 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1417 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1419 if(itr->second==quest_id)
1420 return true;
1422 return false;
1425 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1427 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1428 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1430 if(itr->second==quest_id)
1431 return true;
1433 return false;
1436 void Creature::DeleteFromDB()
1438 if (!m_DBTableGuid)
1440 sLog.outDebug("Trying to delete not saved creature!");
1441 return;
1444 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1445 objmgr.DeleteCreatureData(m_DBTableGuid);
1447 WorldDatabase.BeginTransaction();
1448 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1449 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1450 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1451 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1452 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1453 WorldDatabase.CommitTransaction();
1456 float Creature::GetAttackDistance(Unit const* pl) const
1458 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1459 if(aggroRate==0)
1460 return 0.0f;
1462 int32 playerlevel = pl->getLevelForTarget(this);
1463 int32 creaturelevel = getLevelForTarget(pl);
1465 int32 leveldif = playerlevel - creaturelevel;
1467 // "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."
1468 if ( leveldif < - 25)
1469 leveldif = -25;
1471 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1472 float RetDistance = 20;
1474 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1475 // radius grow if playlevel < creaturelevel
1476 RetDistance -= (float)leveldif;
1478 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1480 // detect range auras
1481 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1483 // detected range auras
1484 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1487 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1488 if(RetDistance < 5)
1489 RetDistance = 5;
1491 return (RetDistance*aggroRate);
1494 void Creature::setDeathState(DeathState s)
1496 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1498 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1500 // always save boss respawn time at death to prevent crash cheating
1501 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1502 SaveRespawnTime();
1504 if (canFly() && FallGround())
1505 return;
1507 if(!IsStopped())
1508 StopMoving();
1510 Unit::setDeathState(s);
1512 if(s == JUST_DIED)
1514 SetUInt64Value(UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1515 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1517 if(!isPet() && GetCreatureInfo()->SkinLootId)
1518 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1519 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1521 if (canFly() && FallGround())
1522 return;
1524 SetNoSearchAssistance(false);
1525 Unit::setDeathState(CORPSE);
1527 if(s == JUST_ALIVED)
1529 SetHealth(GetMaxHealth());
1530 SetLootRecipient(NULL);
1531 Unit::setDeathState(ALIVE);
1532 CreatureInfo const *cinfo = GetCreatureInfo();
1533 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1534 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1535 AddMonsterMoveFlag(MONSTER_MOVE_WALK);
1536 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1537 clearUnitState(UNIT_STAT_ALL_STATE);
1538 i_motionMaster.Clear();
1539 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1540 LoadCreaturesAddon(true);
1544 bool Creature::FallGround()
1546 // Let's abort after we called this function one time
1547 if (getDeathState() == DEAD_FALLING)
1548 return false;
1550 // Let's do with no vmap because no way to get far distance with vmap high call
1551 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1553 // Abort too if the ground is very near
1554 if (fabs(GetPositionZ() - tz) < 0.1f)
1555 return false;
1557 Unit::setDeathState(DEAD_FALLING);
1558 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1559 Relocate(GetPositionX(), GetPositionY(), tz);
1560 return true;
1563 void Creature::Respawn()
1565 RemoveCorpse();
1567 // forced recreate creature object at clients
1568 UnitVisibility currentVis = GetVisibility();
1569 SetVisibility(VISIBILITY_RESPAWN);
1570 ObjectAccessor::UpdateObjectVisibility(this);
1571 SetVisibility(currentVis); // restore visibility state
1572 ObjectAccessor::UpdateObjectVisibility(this);
1574 if(getDeathState()==DEAD)
1576 if (m_DBTableGuid)
1577 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1578 m_respawnTime = time(NULL); // respawn at next tick
1582 void Creature::ForcedDespawn()
1584 setDeathState(JUST_DIED);
1585 RemoveCorpse();
1586 SetHealth(0); // just for nice GM-mode view
1589 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1591 if (!spellInfo)
1592 return false;
1594 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1595 return true;
1597 return Unit::IsImmunedToSpell(spellInfo);
1600 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1602 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1603 return true;
1605 // Taunt immunity special flag check
1606 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1608 // Taunt aura apply check
1609 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1611 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1612 return true;
1614 // Spell effect taunt check
1615 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1616 return true;
1619 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1622 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1624 if(!pVictim)
1625 return NULL;
1627 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1629 if(!m_spells[i])
1630 continue;
1631 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1632 if(!spellInfo)
1634 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1635 continue;
1638 bool bcontinue = true;
1639 for(uint32 j=0;j<3;j++)
1641 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1642 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1643 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1644 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1647 bcontinue = false;
1648 break;
1651 if(bcontinue) continue;
1653 if(spellInfo->manaCost > GetPower(POWER_MANA))
1654 continue;
1655 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1656 float range = GetSpellMaxRange(srange);
1657 float minrange = GetSpellMinRange(srange);
1659 float dist = GetCombatDistance(pVictim);
1661 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1662 // continue;
1663 if( dist > range || dist < minrange )
1664 continue;
1665 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1666 continue;
1667 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1668 continue;
1669 return spellInfo;
1671 return NULL;
1674 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1676 if(!pVictim)
1677 return NULL;
1679 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1681 if(!m_spells[i])
1682 continue;
1683 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1684 if(!spellInfo)
1686 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1687 continue;
1690 bool bcontinue = true;
1691 for(uint32 j=0;j<3;j++)
1693 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1695 bcontinue = false;
1696 break;
1699 if(bcontinue) continue;
1701 if(spellInfo->manaCost > GetPower(POWER_MANA))
1702 continue;
1703 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1704 float range = GetSpellMaxRange(srange);
1705 float minrange = GetSpellMinRange(srange);
1707 float dist = GetCombatDistance(pVictim);
1709 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1710 // continue;
1711 if( dist > range || dist < minrange )
1712 continue;
1713 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1714 continue;
1715 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1716 continue;
1717 return spellInfo;
1719 return NULL;
1722 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1724 // gamemaster in GM mode see all, including ghosts
1725 if(pl->isGameMaster())
1726 return true;
1728 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1729 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1731 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1732 return false;
1733 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1736 // Dead player see live creatures near own corpse
1737 if(isAlive())
1739 Corpse *corpse = pl->GetCorpse();
1740 if(corpse)
1742 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1743 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1744 return true;
1748 // Dead player see Spirit Healer or Spirit Guide
1749 if(isSpiritService())
1750 return true;
1752 // and not see any other
1753 return false;
1756 void Creature::CallAssistance()
1758 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1760 SetNoCallAssistance(true);
1762 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1763 if(radius > 0)
1765 std::list<Creature*> assistList;
1768 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1769 Cell cell(p);
1770 cell.data.Part.reserved = ALL_DISTRICT;
1771 cell.SetNoCreate();
1773 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1774 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1776 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1778 CellLock<GridReadGuard> cell_lock(cell, p);
1779 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1782 if (!assistList.empty())
1784 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1785 while (!assistList.empty())
1787 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1788 e->AddAssistant((*assistList.begin())->GetGUID());
1789 assistList.pop_front();
1791 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1797 void Creature::CallForHelp(float fRadius)
1799 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1800 return;
1802 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1803 Cell cell(p);
1804 cell.data.Part.reserved = ALL_DISTRICT;
1805 cell.SetNoCreate();
1807 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1808 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1810 TypeContainerVisitor<MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo>, GridTypeMapContainer > grid_creature_searcher(worker);
1812 CellLock<GridReadGuard> cell_lock(cell, p);
1813 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1816 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1818 // we don't need help from zombies :)
1819 if (!isAlive())
1820 return false;
1822 // we don't need help from non-combatant ;)
1823 if (isCivilian())
1824 return false;
1826 // skip fighting creature
1827 if (isInCombat())
1828 return false;
1830 // only free creature
1831 if (GetCharmerOrOwnerGUID())
1832 return false;
1834 // only from same creature faction
1835 if (checkfaction)
1837 if (getFaction() != u->getFaction())
1838 return false;
1840 else
1842 if (!IsFriendlyTo(u))
1843 return false;
1846 // skip non hostile to caster enemy creatures
1847 if (!IsHostileTo(enemy))
1848 return false;
1850 return true;
1853 void Creature::SaveRespawnTime()
1855 if(isPet() || !m_DBTableGuid)
1856 return;
1858 if(m_respawnTime > time(NULL)) // dead (no corpse)
1859 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1860 else if(m_deathTimer > 0) // dead (corpse)
1861 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1864 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1866 if(!pVictim)
1867 return true;
1869 if(!pVictim->IsInMap(this))
1870 return true;
1872 if(!pVictim->isTargetableForAttack())
1873 return true;
1875 if(!pVictim->isInAccessablePlaceFor(this))
1876 return true;
1878 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1879 return false;
1881 float AttackDist = GetAttackDistance(pVictim);
1882 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1884 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1885 return !pVictim->IsWithinDist3d(CombatStartX,CombatStartY,CombatStartZ,
1886 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1889 CreatureDataAddon const* Creature::GetCreatureAddon() const
1891 if (m_DBTableGuid)
1893 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1894 return addon;
1897 // dependent from heroic mode entry
1898 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1901 //creature_addon table
1902 bool Creature::LoadCreaturesAddon(bool reload)
1904 CreatureDataAddon const *cainfo = GetCreatureAddon();
1905 if(!cainfo)
1906 return false;
1908 if (cainfo->mount != 0)
1909 Mount(cainfo->mount);
1911 if (cainfo->bytes1 != 0)
1913 // 0 StandState
1914 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1915 // 2 StandFlags
1916 // 3 StandMiscFlags
1918 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1919 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1920 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1921 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1922 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1925 if (cainfo->bytes2 != 0)
1927 // 0 SheathState
1928 // 1 Bytes2Flags
1929 // 2 UnitRename Pet only, so always 0 for default creature
1930 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1932 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1933 SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1934 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1935 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1936 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1937 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1940 if (cainfo->emote != 0)
1941 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1943 if (cainfo->move_flags != 0)
1944 SetMonsterMoveFlags(MonsterMovementFlags(cainfo->move_flags));
1946 if(cainfo->auras)
1948 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1950 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1951 if (!AdditionalSpellInfo)
1953 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1954 continue;
1957 // skip already applied aura
1958 if(HasAura(cAura->spell_id,cAura->effect_idx))
1960 if(!reload)
1961 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);
1963 continue;
1966 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1967 AddAura(AdditionalAura);
1968 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1971 return true;
1974 /// Send a message to LocalDefense channel for players opposition team in the zone
1975 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1977 uint32 enemy_team = attacker->GetTeam();
1979 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1980 data << (uint32)GetZoneId();
1981 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1984 void Creature::SetInCombatWithZone()
1986 if (!CanHaveThreatList())
1988 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1989 return;
1992 Map* pMap = GetMap();
1994 if (!pMap->IsDungeon())
1996 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1997 return;
2000 Map::PlayerList const &PlList = pMap->GetPlayers();
2002 if (PlList.isEmpty())
2003 return;
2005 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
2007 if (Player* pPlayer = i->getSource())
2009 if (pPlayer->isGameMaster())
2010 continue;
2012 if (pPlayer->isAlive())
2014 pPlayer->SetInCombatWith(this);
2015 AddThreat(pPlayer, 0.0f);
2021 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
2023 m_CreatureSpellCooldowns[spell_id] = end_time;
2026 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
2028 m_CreatureCategoryCooldowns[category] = apply_time;
2031 void Creature::AddCreatureSpellCooldown(uint32 spellid)
2033 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
2034 if(!spellInfo)
2035 return;
2037 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
2038 if(cooldown)
2039 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
2041 if(spellInfo->Category)
2042 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
2044 m_GlobalCooldown = spellInfo->StartRecoveryTime;
2047 bool Creature::HasCategoryCooldown(uint32 spell_id) const
2049 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2050 if(!spellInfo)
2051 return false;
2053 // check global cooldown if spell affected by it
2054 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
2055 return true;
2057 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
2058 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
2061 bool Creature::HasSpellCooldown(uint32 spell_id) const
2063 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
2064 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
2067 bool Creature::IsInEvadeMode() const
2069 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
2072 bool Creature::HasSpell(uint32 spellID) const
2074 uint8 i;
2075 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
2076 if(spellID == m_spells[i])
2077 break;
2078 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
2081 time_t Creature::GetRespawnTimeEx() const
2083 time_t now = time(NULL);
2084 if(m_respawnTime > now) // dead (no corpse)
2085 return m_respawnTime;
2086 else if(m_deathTimer > 0) // dead (corpse)
2087 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
2088 else
2089 return now;
2092 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
2094 if (m_DBTableGuid)
2096 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
2098 x = data->posX;
2099 y = data->posY;
2100 z = data->posZ;
2101 if(ori)
2102 *ori = data->orientation;
2103 if(dist)
2104 *dist = data->spawndist;
2106 return;
2110 x = GetPositionX();
2111 y = GetPositionY();
2112 z = GetPositionZ();
2113 if(ori)
2114 *ori = GetOrientation();
2115 if(dist)
2116 *dist = 0;
2119 void Creature::AllLootRemovedFromCorpse()
2121 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
2123 uint32 nDeathTimer;
2125 CreatureInfo const *cinfo = GetCreatureInfo();
2127 // corpse was not skinnable -> apply corpse looted timer
2128 if (!cinfo || !cinfo->SkinLootId)
2129 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
2130 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
2131 else
2132 nDeathTimer = 0;
2134 // update death timer only if looted timer is shorter
2135 if (m_deathTimer > nDeathTimer)
2136 m_deathTimer = nDeathTimer;
2140 uint32 Creature::getLevelForTarget( Unit const* target ) const
2142 if(!isWorldBoss())
2143 return Unit::getLevelForTarget(target);
2145 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2146 if(level < 1)
2147 return 1;
2148 if(level > 255)
2149 return 255;
2150 return level;
2153 std::string Creature::GetAIName() const
2155 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
2158 std::string Creature::GetScriptName() const
2160 return objmgr.GetScriptName(GetScriptId());
2163 uint32 Creature::GetScriptId() const
2165 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2168 VendorItemData const* Creature::GetVendorItems() const
2170 return objmgr.GetNpcVendorItemList(GetEntry());
2173 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2175 if(!vItem->maxcount)
2176 return vItem->maxcount;
2178 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2179 for(; itr != m_vendorItemCounts.end(); ++itr)
2180 if(itr->itemId==vItem->item)
2181 break;
2183 if(itr == m_vendorItemCounts.end())
2184 return vItem->maxcount;
2186 VendorItemCount* vCount = &*itr;
2188 time_t ptime = time(NULL);
2190 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2192 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2194 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2195 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2197 m_vendorItemCounts.erase(itr);
2198 return vItem->maxcount;
2201 vCount->count += diff * pProto->BuyCount;
2202 vCount->lastIncrementTime = ptime;
2205 return vCount->count;
2208 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2210 if(!vItem->maxcount)
2211 return 0;
2213 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2214 for(; itr != m_vendorItemCounts.end(); ++itr)
2215 if(itr->itemId==vItem->item)
2216 break;
2218 if(itr == m_vendorItemCounts.end())
2220 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2221 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2222 return new_count;
2225 VendorItemCount* vCount = &*itr;
2227 time_t ptime = time(NULL);
2229 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2231 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2233 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2234 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2235 vCount->count += diff * pProto->BuyCount;
2236 else
2237 vCount->count = vItem->maxcount;
2240 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2241 vCount->lastIncrementTime = ptime;
2242 return vCount->count;
2245 TrainerSpellData const* Creature::GetTrainerSpells() const
2247 return objmgr.GetNpcTrainerSpells(GetEntry());
2250 // overwrite WorldObject function for proper name localization
2251 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2253 if (loc_idx >= 0)
2255 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2256 if (cl)
2258 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2259 return cl->Name[loc_idx].c_str();
2263 return GetName();
2266 void Creature::SetActiveObjectState( bool on )
2268 if(m_isActiveObject==on)
2269 return;
2271 bool world = IsInWorld();
2273 Map* map;
2274 if(world)
2276 map = GetMap();
2277 map->Remove(this,false);
2280 m_isActiveObject = on;
2282 if(world)
2283 map->Add(this);
2286 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2288 float x, y, z;
2289 if(GetMotionMaster()->GetDestination(x, y, z))
2290 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2293 void Creature::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
2295 if (!transitTime)
2297 if(GetTypeId()==TYPEID_PLAYER)
2299 Traveller<Player> traveller(*(Player*)this);
2300 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2302 else
2304 Traveller<Creature> traveller(*(Creature*)this);
2305 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
2308 //float orientation = (float)atan2((double)dy, (double)dx);
2309 SendMonsterMove(x, y, z, 0, GetMonsterMoveFlags(), transitTime, player);