root/trunk/src/game/Creature.cpp @ 130

Revision 123, 69.4 kB (checked in by yumileroy, 17 years ago)

[svn] * Changed modelid_a/h(2) values to modelid1..4, display ids are no longer incorrectly chosen based on player faction. Patch provided by WarHead?.

Original author: w12x
Date: 2008-10-27 11:48:45-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include "Common.h"
22#include "Database/DatabaseEnv.h"
23#include "WorldPacket.h"
24#include "WorldSession.h"
25#include "World.h"
26#include "ObjectMgr.h"
27#include "SpellMgr.h"
28#include "Creature.h"
29#include "QuestDef.h"
30#include "GossipDef.h"
31#include "Player.h"
32#include "Opcodes.h"
33#include "Log.h"
34#include "LootMgr.h"
35#include "MapManager.h"
36#include "CreatureAI.h"
37#include "CreatureAISelector.h"
38#include "Formulas.h"
39#include "SpellAuras.h"
40#include "WaypointMovementGenerator.h"
41#include "InstanceData.h"
42#include "BattleGround.h"
43#include "Util.h"
44#include "GridNotifiers.h"
45#include "GridNotifiersImpl.h"
46#include "CellImpl.h"
47#include "OutdoorPvPMgr.h"
48#include "GameEvent.h"
49// apply implementation of the singletons
50#include "Policies/SingletonImp.h"
51
52void TrainerSpellData::Clear()
53{
54    for (TrainerSpellList::iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
55        delete (*itr);
56    spellList.empty();
57}
58
59TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
60{
61    for(TrainerSpellList::const_iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
62        if((*itr)->spell == spell_id)
63            return *itr;
64
65    return NULL;
66}
67
68bool VendorItemData::RemoveItem( uint32 item_id )
69{
70    for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
71    {
72        if((*i)->item==item_id)
73        {
74            m_items.erase(i);
75            return true;
76        }
77    }
78    return false;
79}
80
81size_t VendorItemData::FindItemSlot(uint32 item_id) const
82{
83    for(size_t i = 0; i < m_items.size(); ++i )
84        if(m_items[i]->item==item_id)
85            return i;
86    return m_items.size();
87}
88
89VendorItem const* VendorItemData::FindItem(uint32 item_id) const
90{
91    for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
92        if((*i)->item==item_id)
93            return *i;
94    return NULL;
95}
96
97uint32 CreatureInfo::GetRandomValidModelId() const
98{
99    uint32 c = 0;
100    uint32 modelIDs[4];
101
102    if (Modelid1) modelIDs[c++] = Modelid1;
103    if (Modelid2) modelIDs[c++] = Modelid2;
104    if (Modelid3) modelIDs[c++] = Modelid3;
105    if (Modelid4) modelIDs[c++] = Modelid4;
106
107    return ((c>0) ? modelIDs[urand(0,c-1)] : 0);
108}
109
110uint32 CreatureInfo::GetFirstValidModelId() const
111{
112    if(Modelid1) return Modelid1;
113    if(Modelid2) return Modelid2;
114    if(Modelid3) return Modelid3;
115    if(Modelid4) return Modelid4;
116    return 0;
117}
118
119Creature::Creature() :
120Unit(), i_AI(NULL),
121lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
122m_lootMoney(0), m_lootRecipient(0),
123m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
124m_gossipOptionLoaded(false),m_emoteState(0), m_isPet(false), m_isTotem(false),
125m_regenTimer(2000), m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
126m_AlreadyCallAssistence(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
127m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
128{
129    m_valuesCount = UNIT_END;
130
131    for(int i =0; i<4; ++i)
132        m_spells[i] = 0;
133
134    m_CreatureSpellCooldowns.clear();
135    m_CreatureCategoryCooldowns.clear();
136    m_GlobalCooldown = 0;
137    m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
138}
139
140Creature::~Creature()
141{
142    CleanupsBeforeDelete();
143
144    m_vendorItemCounts.clear();
145
146    delete i_AI;
147    i_AI = NULL;
148}
149
150void Creature::AddToWorld()
151{
152    ///- Register the creature for guid lookup
153    if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
154    Unit::AddToWorld();
155}
156
157void Creature::RemoveFromWorld()
158{
159    ///- Remove the creature from the accessor
160    if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
161    Unit::RemoveFromWorld();
162}
163
164void Creature::RemoveCorpse()
165{
166    if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
167        return;
168
169    m_deathTimer = 0;
170    setDeathState(DEAD);
171    ObjectAccessor::UpdateObjectVisibility(this);
172    loot.clear();
173    m_respawnTime = time(NULL) + m_respawnDelay;
174
175    float x,y,z,o;
176    GetRespawnCoord(x, y, z, &o);
177    MapManager::Instance().GetMap(GetMapId(), this)->CreatureRelocation(this,x,y,z,o);
178}
179
180/**
181 * change the entry of creature until respawn
182 */
183bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
184{
185    CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
186    if(!normalInfo)
187    {
188        sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
189        return false;
190    }
191
192    // get heroic mode entry
193    uint32 actualEntry = Entry;
194    CreatureInfo const *cinfo = normalInfo;
195    if(normalInfo->HeroicEntry)
196    {
197        Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
198        if(map && map->IsHeroic())
199        {
200            cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
201            if(!cinfo)
202            {
203                sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
204                return false;
205            }
206        }
207    }
208
209    SetUInt32Value(OBJECT_FIELD_ENTRY, Entry);              // normal entry always
210    m_creatureInfo = cinfo;                                 // map mode related always
211
212    // Cancel load if no model defined
213    if (!(cinfo->GetFirstValidModelId()))
214    {
215        sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load. ",Entry);
216        return false;
217    }
218
219    uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
220    CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
221    if (!minfo)
222    {
223        sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
224        return false;
225    }
226    else
227        display_id = minfo->modelid;                        // it can be different (for another gender)
228
229    SetDisplayId(display_id);
230    SetNativeDisplayId(display_id);
231    SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
232
233    // Load creature equipment
234    if(!data || data->equipmentId == 0)
235    {                                                       // use default from the template
236        LoadEquipment(cinfo->equipmentId);
237    }
238    else if(data && data->equipmentId != -1)
239    {                                                       // override, -1 means no equipment
240        LoadEquipment(data->equipmentId);
241    }
242
243    SetName(normalInfo->Name);                              // at normal entry always
244
245    SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
246    SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
247
248    SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
249
250    SetSpeed(MOVE_WALK,     cinfo->speed );
251    SetSpeed(MOVE_RUN,      cinfo->speed );
252    SetSpeed(MOVE_SWIM,     cinfo->speed );
253
254    SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
255
256    // checked at loading
257    m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
258    if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
259        m_defaultMovementType = IDLE_MOTION_TYPE;
260
261    return true;
262}
263
264bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
265{
266    if(!InitEntry(Entry,team,data))
267        return false;
268
269    m_regenHealth = GetCreatureInfo()->RegenHealth;
270
271    // creatures always have melee weapon ready if any
272    SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
273    SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_AURAS );
274
275    SelectLevel(GetCreatureInfo());
276    if (team == HORDE)
277        SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
278    else
279        SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
280
281    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
282        SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag | gameeventmgr.GetNPCFlag(this));
283    else
284        SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
285
286    SetAttackTime(BASE_ATTACK,  GetCreatureInfo()->baseattacktime);
287    SetAttackTime(OFF_ATTACK,   GetCreatureInfo()->baseattacktime);
288    SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
289
290    SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->Flags);
291    SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
292
293    SetModifierValue(UNIT_MOD_ARMOR,             BASE_VALUE, float(GetCreatureInfo()->armor));
294    SetModifierValue(UNIT_MOD_RESISTANCE_HOLY,   BASE_VALUE, float(GetCreatureInfo()->resistance1));
295    SetModifierValue(UNIT_MOD_RESISTANCE_FIRE,   BASE_VALUE, float(GetCreatureInfo()->resistance2));
296    SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
297    SetModifierValue(UNIT_MOD_RESISTANCE_FROST,  BASE_VALUE, float(GetCreatureInfo()->resistance4));
298    SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
299    SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
300
301    SetCanModifyStats(true);
302    UpdateAllStats();
303
304    FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
305    if (factionTemplate)                                    // check and error show at loading templates
306    {
307        FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
308        if (factionEntry)
309            if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
310                (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
311                SetPvP(true);
312    }
313
314    m_spells[0] = GetCreatureInfo()->spell1;
315    m_spells[1] = GetCreatureInfo()->spell2;
316    m_spells[2] = GetCreatureInfo()->spell3;
317    m_spells[3] = GetCreatureInfo()->spell4;
318
319    return true;
320}
321
322void Creature::Update(uint32 diff)
323{
324    if(m_GlobalCooldown <= diff)
325        m_GlobalCooldown = 0;
326    else
327        m_GlobalCooldown -= diff;
328
329    switch( m_deathState )
330    {
331        case JUST_ALIVED:
332            // Dont must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
333            sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
334            break;
335        case JUST_DIED:
336            // Dont must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
337            sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
338            break;
339        case DEAD:
340        {
341            if( m_respawnTime <= time(NULL) )
342            {
343                DEBUG_LOG("Respawning...");
344                m_respawnTime = 0;
345                lootForPickPocketed = false;
346                lootForBody         = false;
347
348                if(m_originalEntry != GetUInt32Value(OBJECT_FIELD_ENTRY))
349                    UpdateEntry(m_originalEntry);
350
351                CreatureInfo const *cinfo = GetCreatureInfo();
352
353                SelectLevel(cinfo);
354                SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
355                if (m_isDeadByDefault)
356                {
357                    setDeathState(JUST_DIED);
358                    SetHealth(0);
359                    i_motionMaster.Clear();
360                    clearUnitState(UNIT_STAT_ALL_STATE);
361                    LoadCreaturesAddon(true);
362                }
363                else
364                    setDeathState( JUST_ALIVED );
365
366                //Call AI respawn virtual function
367                i_AI->JustRespawned();
368
369                MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
370            }
371            break;
372        }
373        case CORPSE:
374        {
375            if (m_isDeadByDefault)
376                break;
377
378            if( m_deathTimer <= diff )
379            {
380                RemoveCorpse();
381                DEBUG_LOG("Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY));
382            }
383            else
384            {
385                m_deathTimer -= diff;
386                if (m_groupLootTimer && lootingGroupLeaderGUID)
387                {
388                    if(diff <= m_groupLootTimer)
389                    {
390                        m_groupLootTimer -= diff;
391                    }
392                    else
393                    {
394                        Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
395                        if (group)
396                            group->EndRoll();
397                        m_groupLootTimer = 0;
398                        lootingGroupLeaderGUID = 0;
399                    }
400                }
401            }
402
403            break;
404        }
405        case ALIVE:
406        {
407            if (m_isDeadByDefault)
408            {
409                if( m_deathTimer <= diff )
410                {
411                    RemoveCorpse();
412                    DEBUG_LOG("Removing alive corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY));
413                }
414                else
415                {
416                    m_deathTimer -= diff;
417                }
418            }
419
420            Unit::Update( diff );
421
422            // creature can be dead after Unit::Update call
423            // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
424            if(!isAlive())
425                break;
426
427            if(!IsInEvadeMode())
428            {
429                // do not allow the AI to be changed during update
430                m_AI_locked = true;
431                i_AI->UpdateAI(diff);
432                m_AI_locked = false;
433            }
434
435            // creature can be dead after UpdateAI call
436            // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
437            if(!isAlive())
438                break;
439            if(m_regenTimer > 0)
440            {
441                if(diff >= m_regenTimer)
442                    m_regenTimer = 0;
443                else
444                    m_regenTimer -= diff;
445            }
446            if (m_regenTimer != 0)
447                break;
448
449            if (!isInCombat() || IsPolymorphed())
450                RegenerateHealth();
451
452            RegenerateMana();
453
454            m_regenTimer = 2000;
455            break;
456        }
457        default:
458            break;
459    }
460}
461
462void Creature::RegenerateMana()
463{
464    uint32 curValue = GetPower(POWER_MANA);
465    uint32 maxValue = GetMaxPower(POWER_MANA);
466
467    if (curValue >= maxValue)
468        return;
469
470    uint32 addvalue = 0;
471
472    // Combat and any controlled creature
473    if (isInCombat() || GetCharmerOrOwnerGUID())
474    {
475        if(!IsUnderLastManaUseEffect())
476        {
477            float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
478            float Spirit = GetStat(STAT_SPIRIT);
479
480            addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
481        }
482    }
483    else
484        addvalue = maxValue/3;
485
486    ModifyPower(POWER_MANA, addvalue);
487}
488
489void Creature::RegenerateHealth()
490{
491    if (!isRegeneratingHealth())
492        return;
493
494    uint32 curValue = GetHealth();
495    uint32 maxValue = GetMaxHealth();
496
497    if (curValue >= maxValue)
498        return;
499
500    uint32 addvalue = 0;
501
502    // Not only pet, but any controelled creature
503    if(GetCharmerOrOwnerGUID())
504    {
505        float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
506        float Spirit = GetStat(STAT_SPIRIT);
507
508        if( GetPower(POWER_MANA) > 0 )
509            addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
510        else
511            addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
512    }
513    else
514        addvalue = maxValue/3;
515
516    ModifyHealth(addvalue);
517}
518
519bool Creature::AIM_Initialize()
520{
521    // make sure nothing can change the AI during AI update
522    if(m_AI_locked)
523    {
524        sLog.outDebug("AIM_Initialize: failed to init, locked.");
525        return false;
526    }
527
528    CreatureAI * oldAI = i_AI;
529    i_motionMaster.Initialize();
530    i_AI = FactorySelector::selectAI(this);
531    if (oldAI)
532        delete oldAI;
533    return true;
534}
535
536bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
537{
538    SetMapId(map->GetId());
539    SetInstanceId(map->GetInstanceId());
540
541    //oX = x;     oY = y;    dX = x;    dY = y;    m_moveTime = 0;    m_startMove = 0;
542    const bool bResult = CreateFromProto(guidlow, Entry, team, data);
543
544    if (bResult)
545    {
546        switch (GetCreatureInfo()->rank)
547        {
548            case CREATURE_ELITE_RARE:
549                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
550                break;
551            case CREATURE_ELITE_ELITE:
552                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
553                break;
554            case CREATURE_ELITE_RAREELITE:
555                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
556                break;
557            case CREATURE_ELITE_WORLDBOSS:
558                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
559                break;
560            default:
561                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
562                break;
563        }
564        LoadCreaturesAddon();
565    }
566
567    return bResult;
568}
569
570bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
571{
572    if(!isTrainer())
573        return false;
574
575    TrainerSpellData const* trainer_spells = GetTrainerSpells();
576
577
578    if(!trainer_spells || trainer_spells->spellList.empty())
579    {
580        sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
581            GetGUIDLow(),GetEntry());
582        return false;
583    }
584
585    switch(GetCreatureInfo()->trainer_type)
586    {
587        case TRAINER_TYPE_CLASS:
588            if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
589            {
590                if(msg)
591                {
592                    pPlayer->PlayerTalkClass->ClearMenus();
593                    switch(GetCreatureInfo()->classNum)
594                    {
595                        case CLASS_DRUID:  pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
596                        case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
597                        case CLASS_MAGE:   pPlayer->PlayerTalkClass->SendGossipMenu(  328,GetGUID()); break;
598                        case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
599                        case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
600                        case CLASS_ROGUE:  pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
601                        case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
602                        case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
603                        case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
604                    }
605                }
606                return false;
607            }
608            break;
609        case TRAINER_TYPE_PETS:
610            if(pPlayer->getClass()!=CLASS_HUNTER)
611            {
612                pPlayer->PlayerTalkClass->ClearMenus();
613                pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
614                return false;
615            }
616            break;
617        case TRAINER_TYPE_MOUNTS:
618            if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
619            {
620                if(msg)
621                {
622                    pPlayer->PlayerTalkClass->ClearMenus();
623                    switch(GetCreatureInfo()->classNum)
624                    {
625                        case RACE_DWARF:        pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
626                        case RACE_GNOME:        pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
627                        case RACE_HUMAN:        pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
628                        case RACE_NIGHTELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
629                        case RACE_ORC:          pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
630                        case RACE_TAUREN:       pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
631                        case RACE_TROLL:        pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
632                        case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
633                        case RACE_BLOODELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
634                        case RACE_DRAENEI:      pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
635                    }
636                }
637                return false;
638            }
639            break;
640        case TRAINER_TYPE_TRADESKILLS:
641            if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
642            {
643                if(msg)
644                {
645                    pPlayer->PlayerTalkClass->ClearMenus();
646                    pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
647                }
648                return false;
649            }
650            break;
651        default:
652            return false;                                   // checked and error output at creature_template loading
653    }
654    return true;
655}
656
657bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
658{
659    if(!isBattleMaster())
660        return false;
661
662    uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
663    if(!msg)
664        return pPlayer->GetBGAccessByLevel(bgTypeId);
665
666    if(!pPlayer->GetBGAccessByLevel(bgTypeId))
667    {
668        pPlayer->PlayerTalkClass->ClearMenus();
669        switch(bgTypeId)
670        {
671            case BATTLEGROUND_AV:  pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
672            case BATTLEGROUND_WS:  pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
673            case BATTLEGROUND_AB:  pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
674            case BATTLEGROUND_EY:
675            case BATTLEGROUND_NA:
676            case BATTLEGROUND_BE:
677            case BATTLEGROUND_AA:
678            case BATTLEGROUND_RL:  pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
679            break;
680        }
681        return false;
682    }
683    return true;
684}
685
686bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
687{
688    return pPlayer->getLevel() >= 10
689        && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
690        && pPlayer->getClass() == GetCreatureInfo()->classNum;
691}
692
693void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
694{
695    PlayerMenu* pm=pPlayer->PlayerTalkClass;
696    pm->ClearMenus();
697
698    // lazy loading single time at use
699    LoadGossipOptions();
700
701    GossipOption* gso;
702    GossipOption* ingso;
703
704    for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
705    {
706        gso=&*i;
707        if(gso->GossipId == gossipid)
708        {
709            bool cantalking=true;
710            if(gso->Id==1)
711            {
712                uint32 textid=GetNpcTextId();
713                GossipText * gossiptext=objmgr.GetGossipText(textid);
714                if(!gossiptext)
715                    cantalking=false;
716            }
717            else
718            {
719                switch (gso->Action)
720                {
721                    case GOSSIP_OPTION_QUESTGIVER:
722                        pPlayer->PrepareQuestMenu(GetGUID());
723                        //if (pm->GetQuestMenu()->MenuItemCount() == 0)
724                        cantalking=false;
725                        //pm->GetQuestMenu()->ClearMenu();
726                        break;
727                    case GOSSIP_OPTION_ARMORER:
728                        cantalking=false;                   // added in special mode
729                        break;
730                    case GOSSIP_OPTION_SPIRITHEALER:
731                        if( !pPlayer->isDead() )
732                            cantalking=false;
733                        break;
734                    case GOSSIP_OPTION_VENDOR:
735                    {
736                        VendorItemData const* vItems = GetVendorItems();
737                        if(!vItems || vItems->Empty())
738                        {
739                            sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
740                                GetGUIDLow(),GetEntry());
741                            cantalking=false;
742                        }
743                        break;
744                    }
745                    case GOSSIP_OPTION_TRAINER:
746                        if(!isCanTrainingOf(pPlayer,false))
747                            cantalking=false;
748                        break;
749                    case GOSSIP_OPTION_UNLEARNTALENTS:
750                        if(!isCanTrainingAndResetTalentsOf(pPlayer))
751                            cantalking=false;
752                        break;
753                    case GOSSIP_OPTION_UNLEARNPETSKILLS:
754                        if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
755                            cantalking=false;
756                        break;
757                    case GOSSIP_OPTION_TAXIVENDOR:
758                        if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
759                            return;
760                        break;
761                    case GOSSIP_OPTION_BATTLEFIELD:
762                        if(!isCanIneractWithBattleMaster(pPlayer,false))
763                            cantalking=false;
764                        break;
765                    case GOSSIP_OPTION_SPIRITGUIDE:
766                    case GOSSIP_OPTION_INNKEEPER:
767                    case GOSSIP_OPTION_BANKER:
768                    case GOSSIP_OPTION_PETITIONER:
769                    case GOSSIP_OPTION_STABLEPET:
770                    case GOSSIP_OPTION_TABARDDESIGNER:
771                    case GOSSIP_OPTION_AUCTIONEER:
772                        break;                              // no checks
773                    case GOSSIP_OPTION_OUTDOORPVP:
774                        if ( !sOutdoorPvPMgr.CanTalkTo(pPlayer,this,(*gso)) )
775                            cantalking = false;
776                        break;
777                    default:
778                        sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetGUIDLow(),GetEntry(),gso->Action);
779                        break;
780                }
781            }
782
783            if(!gso->Option.empty() && cantalking )
784            {                                               //note for future dev: should have database fields for BoxMessage & BoxMoney
785                pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,gso->Option, gossipid,gso->Action,"",0,false);
786                ingso=gso;
787            }
788        }
789    }
790
791    ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
792    if(pm->Empty())
793    {
794        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
795        {
796            isCanTrainingOf(pPlayer,true);                  // output error message if need
797        }
798        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
799        {
800            isCanIneractWithBattleMaster(pPlayer,true);     // output error message if need
801        }
802    }
803}
804
805void Creature::sendPreparedGossip(Player* player)
806{
807    if(!player)
808        return;
809
810    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
811
812    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT) // if world event npc then
813        gameeventmgr.HandleWorldEventGossip(player, this);      // update world state with progress
814
815    // in case empty gossip menu open quest menu if any
816    if (gossipmenu.Empty() && GetNpcTextId() == 0)
817    {
818        player->SendPreparedQuest(GetGUID());
819        return;
820    }
821
822    // in case non empty gossip menu (that not included quests list size) show it
823    // (quest entries from quest menu wiill be included in list)
824    player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
825}
826
827void Creature::OnGossipSelect(Player* player, uint32 option)
828{
829    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
830
831    if(option >= gossipmenu.MenuItemCount())
832        return;
833
834    uint32 action=gossipmenu.GetItem(option).m_gAction;
835    uint32 zoneid=GetZoneId();
836    uint64 guid=GetGUID();
837    GossipOption const *gossip=GetGossipOption( action );
838    uint32 textid;
839    if(!gossip)
840    {
841        zoneid=0;
842        gossip=GetGossipOption( action );
843        if(!gossip)
844            return;
845    }
846    textid=GetGossipTextId( action, zoneid);
847    if(textid==0)
848        textid=GetNpcTextId();
849
850    switch (gossip->Action)
851    {
852        case GOSSIP_OPTION_GOSSIP:
853            player->PlayerTalkClass->CloseGossip();
854            player->PlayerTalkClass->SendTalking( textid );
855            break;
856        case GOSSIP_OPTION_OUTDOORPVP:
857            sOutdoorPvPMgr.HandleGossipOption(player, GetGUID(), option);
858            break;
859        case GOSSIP_OPTION_SPIRITHEALER:
860            if( player->isDead() )
861                CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
862            break;
863        case GOSSIP_OPTION_QUESTGIVER:
864            player->PrepareQuestMenu( guid );
865            player->SendPreparedQuest( guid );
866            break;
867        case GOSSIP_OPTION_VENDOR:
868        case GOSSIP_OPTION_ARMORER:
869            player->GetSession()->SendListInventory(guid);
870            break;
871        case GOSSIP_OPTION_STABLEPET:
872            player->GetSession()->SendStablePet(guid);
873            break;
874        case GOSSIP_OPTION_TRAINER:
875            player->GetSession()->SendTrainerList(guid);
876            break;
877        case GOSSIP_OPTION_UNLEARNTALENTS:
878            player->PlayerTalkClass->CloseGossip();
879            player->SendTalentWipeConfirm(guid);
880            break;
881        case GOSSIP_OPTION_UNLEARNPETSKILLS:
882            player->PlayerTalkClass->CloseGossip();
883            player->SendPetSkillWipeConfirm();
884            break;
885        case GOSSIP_OPTION_TAXIVENDOR:
886            player->GetSession()->SendTaxiMenu(this);
887            break;
888        case GOSSIP_OPTION_INNKEEPER:
889            player->PlayerTalkClass->CloseGossip();
890            player->SetBindPoint( guid );
891            break;
892        case GOSSIP_OPTION_BANKER:
893            player->GetSession()->SendShowBank( guid );
894            break;
895        case GOSSIP_OPTION_PETITIONER:
896            player->PlayerTalkClass->CloseGossip();
897            player->GetSession()->SendPetitionShowList( guid );
898            break;
899        case GOSSIP_OPTION_TABARDDESIGNER:
900            player->PlayerTalkClass->CloseGossip();
901            player->GetSession()->SendTabardVendorActivate( guid );
902            break;
903        case GOSSIP_OPTION_AUCTIONEER:
904            player->GetSession()->SendAuctionHello( guid, this );
905            break;
906        case GOSSIP_OPTION_SPIRITGUIDE:
907        case GOSSIP_GUARD_SPELLTRAINER:
908        case GOSSIP_GUARD_SKILLTRAINER:
909            prepareGossipMenu( player,gossip->Id );
910            sendPreparedGossip( player );
911            break;
912        case GOSSIP_OPTION_BATTLEFIELD:
913        {
914            uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
915            player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
916            break;
917        }
918        default:
919            OnPoiSelect( player, gossip );
920            break;
921    }
922
923}
924
925void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
926{
927    if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
928    {
929        //float x,y;
930        //bool findnpc=false;
931        Poi_Icon icon = ICON_POI_0;
932        //QueryResult *result;
933        //Field *fields;
934        uint32 mapid=GetMapId();
935        Map const* map=MapManager::Instance().GetBaseMap( mapid );
936        uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
937        uint32 zoneid=Map::GetZoneId(areaflag,mapid);
938        std::string areaname= gossip->Option;
939        /*
940        uint16 pflag;
941
942        // use the action relate to creaturetemplate.trainer_type ?
943        result= WorldDatabase.PQuery("SELECT creature.position_x,creature.position_y FROM creature,creature_template WHERE creature.map = '%u' AND creature.id = creature_template.entry AND creature_template.trainer_type = '%u'", mapid, gossip->Action );
944        if(!result)
945            return;
946        do
947        {
948            fields = result->Fetch();
949            x=fields[0].GetFloat();
950            y=fields[1].GetFloat();
951            pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
952            if(pflag==areaflag)
953            {
954                findnpc=true;
955                break;
956            }
957        }while(result->NextRow());
958
959        delete result;
960
961        if(!findnpc)
962        {
963            player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
964            return;
965        }*/
966
967        //need add more case.
968        switch(gossip->Action)
969        {
970            case GOSSIP_GUARD_BANK:
971                icon=ICON_POI_HOUSE;
972                break;
973            case GOSSIP_GUARD_RIDE:
974                icon=ICON_POI_RWHORSE;
975                break;
976            case GOSSIP_GUARD_GUILD:
977                icon=ICON_POI_BLUETOWER;
978                break;
979            default:
980                icon=ICON_POI_TOWER;
981                break;
982        }
983        uint32 textid=GetGossipTextId( gossip->Action, zoneid );
984        player->PlayerTalkClass->SendTalking( textid );
985        // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
986    }
987}
988
989uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
990{
991    QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
992
993    if(!result)
994        return 0;
995
996    Field *fields = result->Fetch();
997    uint32 id = fields[0].GetUInt32();
998
999    delete result;
1000
1001    return id;
1002}
1003
1004uint32 Creature::GetNpcTextId()
1005{
1006    // don't cache / use cache in case it's a world event announcer
1007    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
1008        if(uint32 textid = gameeventmgr.GetNpcTextId(m_DBTableGuid))
1009            return textid;
1010
1011    if (!m_DBTableGuid)
1012        return DEFAULT_GOSSIP_MESSAGE;
1013
1014    if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1015        return pos;
1016
1017    return DEFAULT_GOSSIP_MESSAGE;
1018}
1019
1020GossipOption const* Creature::GetGossipOption( uint32 id ) const
1021{
1022    for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
1023    {
1024        if(i->Action==id )
1025            return &*i;
1026    }
1027    return NULL;
1028}
1029
1030void Creature::ResetGossipOptions()
1031{
1032    m_gossipOptionLoaded = false;
1033    m_goptions.clear();
1034}
1035
1036void Creature::LoadGossipOptions()
1037{
1038    if(m_gossipOptionLoaded)
1039        return;
1040
1041    uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1042
1043    QueryResult *result = WorldDatabase.PQuery( "SELECT id,gossip_id,npcflag,icon,action,option_text FROM npc_option WHERE (npcflag & %u)<>0", npcflags );
1044
1045    if(!result)
1046        return;
1047
1048    GossipOption go;
1049    do
1050    {
1051        Field *fields = result->Fetch();
1052        go.Id= fields[0].GetUInt32();
1053        go.GossipId = fields[1].GetUInt32();
1054        go.NpcFlag=fields[2].GetUInt32();
1055        go.Icon=fields[3].GetUInt32();
1056        go.Action=fields[4].GetUInt32();
1057        go.Option=fields[5].GetCppString();
1058        addGossipOption(go);
1059    }while( result->NextRow() );
1060    delete result;
1061
1062    m_gossipOptionLoaded = true;
1063}
1064
1065void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1066{
1067    /*    uint32 timeElap = getMSTime();
1068        if ((timeElap - m_startMove) < m_moveTime)
1069        {
1070            oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1071            oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1072        }
1073        else
1074        {
1075            oX = dX;
1076            oY = dY;
1077        }
1078
1079        dX = x;
1080        dY = y;
1081        m_orientation = atan2((oY - dY), (oX - dX));
1082
1083        m_startMove = getMSTime();
1084        m_moveTime = time;*/
1085    SendMonsterMove(x, y, z, type, MovementFlags, time);
1086}
1087
1088Player *Creature::GetLootRecipient() const
1089{
1090    if (!m_lootRecipient) return NULL;
1091    else return ObjectAccessor::FindPlayer(m_lootRecipient);
1092}
1093
1094void Creature::SetLootRecipient(Unit *unit)
1095{
1096    // set the player whose group should receive the right
1097    // to loot the creature after it dies
1098    // should be set to NULL after the loot disappears
1099
1100    if (!unit)
1101    {
1102        m_lootRecipient = 0;
1103        RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1104        return;
1105    }
1106
1107    Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1108    if(!player)                                             // normal creature, no player involved
1109        return;
1110
1111    m_lootRecipient = player->GetGUID();
1112    SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1113}
1114
1115void Creature::SaveToDB()
1116{
1117    // this should only be used when the creature has already been loaded
1118    // perferably after adding to map, because mapid may not be valid otherwise
1119    CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1120    if(!data)
1121    {
1122        sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1123        return;
1124    }
1125
1126    SaveToDB(GetMapId(), data->spawnMask);
1127}
1128
1129void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1130{
1131    // update in loaded data
1132    if (!m_DBTableGuid)
1133        m_DBTableGuid = GetGUIDLow();
1134    CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1135
1136    uint32 displayId = GetNativeDisplayId();
1137
1138    // check if it's a custom model and if not, use 0 for displayId
1139    CreatureInfo const *cinfo = GetCreatureInfo();
1140    if(cinfo)
1141    {
1142        if(displayId == cinfo->Modelid1 || displayId == cinfo->Modelid2 ||
1143            displayId == cinfo->Modelid3 || displayId == cinfo->Modelid4) displayId = 0;
1144    }
1145
1146    // data->guid = guid don't must be update at save
1147    data.id = GetEntry();
1148    data.mapid = mapid;
1149    data.displayid = displayId;
1150    data.equipmentId = GetEquipmentId();
1151    data.posX = GetPositionX();
1152    data.posY = GetPositionY();
1153    data.posZ = GetPositionZ();
1154    data.orientation = GetOrientation();
1155    data.spawntimesecs = m_respawnDelay;
1156    // prevent add data integrity problems
1157    data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1158    data.currentwaypoint = 0;
1159    data.curhealth = GetHealth();
1160    data.curmana = GetPower(POWER_MANA);
1161    data.is_dead = m_isDeadByDefault;
1162    // prevent add data integrity problems
1163    data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1164        ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1165    data.spawnMask = spawnMask;
1166
1167    // updated in DB
1168    WorldDatabase.BeginTransaction();
1169
1170    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1171
1172    std::ostringstream ss;
1173    ss << "INSERT INTO creature VALUES ("
1174        << m_DBTableGuid << ","
1175        << GetEntry() << ","
1176        << mapid <<","
1177        << (uint32)spawnMask << ","
1178        << displayId <<","
1179        << GetEquipmentId() <<","
1180        << GetPositionX() << ","
1181        << GetPositionY() << ","
1182        << GetPositionZ() << ","
1183        << GetOrientation() << ","
1184        << m_respawnDelay << ","                            //respawn time
1185        << (float) m_respawnradius << ","                   //spawn distance (float)
1186        << (uint32) (0) << ","                              //currentwaypoint
1187        << GetHealth() << ","                               //curhealth
1188        << GetPower(POWER_MANA) << ","                      //curmana
1189        << (m_isDeadByDefault ? 1 : 0) << ","               //is_dead
1190        << GetDefaultMovementType() << ")";                 //default movement generator type
1191
1192    WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1193
1194    WorldDatabase.CommitTransaction();
1195}
1196
1197void Creature::SelectLevel(const CreatureInfo *cinfo)
1198{
1199    uint32 rank = isPet()? 0 : cinfo->rank;
1200
1201    // level
1202    uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1203    uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1204    uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1205    SetLevel(level);
1206
1207    float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1208
1209    // health
1210    float healthmod = _GetHealthMod(rank);
1211
1212    uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1213    uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1214    uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1215
1216    SetCreateHealth(health);
1217    SetMaxHealth(health);
1218    SetHealth(health);
1219
1220    // mana
1221    uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1222    uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1223    uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1224
1225    SetCreateMana(mana);
1226    SetMaxPower(POWER_MANA, mana);                          //MAX Mana
1227    SetPower(POWER_MANA, mana);
1228
1229    SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1230    SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1231
1232    // damage
1233    float damagemod = _GetDamageMod(rank);
1234
1235    SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1236    SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1237
1238    SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1239    SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1240
1241    SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1242}
1243
1244float Creature::_GetHealthMod(int32 Rank)
1245{
1246    switch (Rank)                                           // define rates for each elite rank
1247    {
1248        case CREATURE_ELITE_NORMAL:
1249            return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1250        case CREATURE_ELITE_ELITE:
1251            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1252        case CREATURE_ELITE_RAREELITE:
1253            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1254        case CREATURE_ELITE_WORLDBOSS:
1255            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1256        case CREATURE_ELITE_RARE:
1257            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1258        default:
1259            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1260    }
1261}
1262
1263float Creature::_GetDamageMod(int32 Rank)
1264{
1265    switch (Rank)                                           // define rates for each elite rank
1266    {
1267        case CREATURE_ELITE_NORMAL:
1268            return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1269        case CREATURE_ELITE_ELITE:
1270            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1271        case CREATURE_ELITE_RAREELITE:
1272            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1273        case CREATURE_ELITE_WORLDBOSS:
1274            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1275        case CREATURE_ELITE_RARE:
1276            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1277        default:
1278            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1279    }
1280}
1281
1282float Creature::GetSpellDamageMod(int32 Rank)
1283{
1284    switch (Rank)                                           // define rates for each elite rank
1285    {
1286        case CREATURE_ELITE_NORMAL:
1287            return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1288        case CREATURE_ELITE_ELITE:
1289            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1290        case CREATURE_ELITE_RAREELITE:
1291            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1292        case CREATURE_ELITE_WORLDBOSS:
1293            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1294        case CREATURE_ELITE_RARE:
1295            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1296        default:
1297            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1298    }
1299}
1300
1301bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1302{
1303    CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1304    if(!cinfo)
1305    {
1306        sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1307        return false;
1308    }
1309    m_originalEntry = Entry;
1310
1311    Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1312
1313    if(!UpdateEntry(Entry, team, data))
1314        return false;
1315
1316    //Notify the map's instance data.
1317    //Only works if you create the object in it, not if it is moves to that map.
1318    //Normally non-players do not teleport to other maps.
1319    Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1320    if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1321    {
1322        ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1323    }
1324
1325    return true;
1326}
1327
1328bool Creature::LoadFromDB(uint32 guid, Map *map)
1329{
1330    CreatureData const* data = objmgr.GetCreatureData(guid);
1331
1332    if(!data)
1333    {
1334        sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1335        return false;
1336    }
1337
1338    m_DBTableGuid = guid;
1339    if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1340
1341    uint16 team = 0;
1342    if(!Create(guid,map,data->id,team,data))
1343        return false;
1344
1345    Relocate(data->posX,data->posY,data->posZ,data->orientation);
1346
1347    if(!IsPositionValid())
1348    {
1349        sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1350        return false;
1351    }
1352
1353    m_respawnradius = data->spawndist;
1354
1355    m_respawnDelay = data->spawntimesecs;
1356    m_isDeadByDefault = data->is_dead;
1357    m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1358
1359    m_respawnTime  = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1360    if(m_respawnTime > time(NULL))                          // not ready to respawn
1361        m_deathState = DEAD;
1362    else if(m_respawnTime)                                  // respawn time set but expired
1363    {
1364        m_respawnTime = 0;
1365        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1366    }
1367
1368    uint32 curhealth = data->curhealth;
1369    if(curhealth)
1370    {
1371        curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1372        if(curhealth < 1)
1373            curhealth = 1;
1374    }
1375
1376    SetHealth(m_deathState == ALIVE ? curhealth : 0);
1377    SetPower(POWER_MANA,data->curmana);
1378
1379    SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1380
1381    // checked at creature_template loading
1382    m_defaultMovementType = MovementGeneratorType(data->movementType);
1383
1384    AIM_Initialize();
1385    return true;
1386}
1387
1388void Creature::LoadEquipment(uint32 equip_entry, bool force)
1389{
1390    if(equip_entry == 0)
1391    {
1392        if (force)
1393        {
1394            for (uint8 i=0;i<3;i++)
1395            {
1396                SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1397                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1398                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1399            }
1400            m_equipmentId = 0;
1401        }
1402        return;
1403    }
1404
1405    EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1406    if (!einfo)
1407        return;
1408
1409    m_equipmentId = equip_entry;
1410    for (uint8 i=0;i<3;i++)
1411    {
1412        SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1413        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1414        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1415    }
1416}
1417
1418bool Creature::hasQuest(uint32 quest_id) const
1419{
1420    QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1421    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1422    {
1423        if(itr->second==quest_id)
1424            return true;
1425    }
1426    return false;
1427}
1428
1429bool Creature::hasInvolvedQuest(uint32 quest_id) const
1430{
1431    QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1432    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1433    {
1434        if(itr->second==quest_id)
1435            return true;
1436    }
1437    return false;
1438}
1439
1440void Creature::DeleteFromDB()
1441{
1442    if (!m_DBTableGuid)
1443    {
1444        sLog.outDebug("Trying to delete not saved creature!");
1445        return;
1446    }
1447
1448    objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1449    objmgr.DeleteCreatureData(m_DBTableGuid);
1450
1451    WorldDatabase.BeginTransaction();
1452    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1453    WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1454    WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1455    WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1456    WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1457    WorldDatabase.CommitTransaction();
1458}
1459
1460float Creature::GetAttackDistance(Unit const* pl) const
1461{
1462    float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1463    if(aggroRate==0)
1464        return 0.0f;
1465
1466    int32 playerlevel   = pl->getLevelForTarget(this);
1467    int32 creaturelevel = getLevelForTarget(pl);
1468
1469    int32 leveldif       = playerlevel - creaturelevel;
1470
1471    // "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."
1472    if ( leveldif < - 25)
1473        leveldif = -25;
1474
1475    // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1476    float RetDistance = 20;
1477
1478    // "Aggro Radius varries with level difference at a rate of roughly 1 yard/level"
1479    // radius grow if playlevel < creaturelevel
1480    RetDistance -= (float)leveldif;
1481
1482    if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1483    {
1484        // detect range auras
1485        RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1486
1487        // detected range auras
1488        RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1489    }
1490
1491    // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1492    if(RetDistance < 5)
1493        RetDistance = 5;
1494
1495    return (RetDistance*aggroRate);
1496}
1497
1498void Creature::setDeathState(DeathState s)
1499{
1500    if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1501    {
1502        m_deathTimer = m_corpseDelay*1000;
1503
1504        // always save boss respawn time at death to prevent crash cheating
1505        if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1506            SaveRespawnTime();
1507
1508        if(!IsStopped())
1509            StopMoving();
1510    }
1511    Unit::setDeathState(s);
1512
1513    if(s == JUST_DIED)
1514    {
1515        SetUInt64Value (UNIT_FIELD_TARGET,0);               // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1516        SetUInt32Value(UNIT_NPC_FLAGS, 0);
1517
1518        if(!isPet() && GetCreatureInfo()->SkinLootId)
1519            if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1520                SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1521
1522        Unit::setDeathState(CORPSE);
1523    }
1524    if(s == JUST_ALIVED)
1525    {
1526        SetHealth(GetMaxHealth());
1527        SetLootRecipient(NULL);
1528        Unit::setDeathState(ALIVE);
1529        CreatureInfo const *cinfo = GetCreatureInfo();
1530        SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1531        RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1532        AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1533        SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1534        clearUnitState(UNIT_STAT_ALL_STATE);
1535        i_motionMaster.Clear();
1536        SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1537        LoadCreaturesAddon(true);
1538    }
1539}
1540
1541void Creature::Respawn()
1542{
1543    RemoveCorpse();
1544
1545    // forced recreate creature object at clients
1546    UnitVisibility currentVis = GetVisibility();
1547    SetVisibility(VISIBILITY_RESPAWN);
1548    ObjectAccessor::UpdateObjectVisibility(this);
1549    SetVisibility(currentVis);                              // restore visibility state
1550    ObjectAccessor::UpdateObjectVisibility(this);
1551
1552    if(getDeathState()==DEAD)
1553    {
1554        if (m_DBTableGuid)
1555            objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1556        m_respawnTime = time(NULL);                         // respawn at next tick
1557    }
1558}
1559
1560bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1561{
1562    if (!spellInfo)
1563        return false;
1564
1565    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1566        return true;
1567
1568    return Unit::IsImmunedToSpell(spellInfo, useCharges);
1569}
1570
1571bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1572{
1573    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1574        return true;
1575
1576    return Unit::IsImmunedToSpellEffect(effect, mechanic);
1577}
1578
1579SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1580{
1581    if(!pVictim)
1582        return NULL;
1583
1584    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1585    {
1586        if(!m_spells[i])
1587            continue;
1588        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1589        if(!spellInfo)
1590        {
1591            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1592            continue;
1593        }
1594
1595        bool bcontinue = true;
1596        for(uint32 j=0;j<3;j++)
1597        {
1598            if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE )       ||
1599                (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL)            ||
1600                (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1601                (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1602                )
1603            {
1604                bcontinue = false;
1605                break;
1606            }
1607        }
1608        if(bcontinue) continue;
1609
1610        if(spellInfo->manaCost > GetPower(POWER_MANA))
1611            continue;
1612        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1613        float range = GetSpellMaxRange(srange);
1614        float minrange = GetSpellMinRange(srange);
1615        float dist = GetDistance(pVictim);
1616        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1617        //    continue;
1618        if( dist > range || dist < minrange )
1619            continue;
1620        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1621            continue;
1622        return spellInfo;
1623    }
1624    return NULL;
1625}
1626
1627SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1628{
1629    if(!pVictim)
1630        return NULL;
1631
1632    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1633    {
1634        if(!m_spells[i])
1635            continue;
1636        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1637        if(!spellInfo)
1638        {
1639            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1640            continue;
1641        }
1642
1643        bool bcontinue = true;
1644        for(uint32 j=0;j<3;j++)
1645        {
1646            if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1647            {
1648                bcontinue = false;
1649                break;
1650            }
1651        }
1652        if(bcontinue) continue;
1653
1654        if(spellInfo->manaCost > GetPower(POWER_MANA))
1655            continue;
1656        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1657        float range = GetSpellMaxRange(srange);
1658        float minrange = GetSpellMinRange(srange);
1659        float dist = GetDistance(pVictim);
1660        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1661        //    continue;
1662        if( dist > range || dist < minrange )
1663            continue;
1664        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1665            continue;
1666        return spellInfo;
1667    }
1668    return NULL;
1669}
1670
1671bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1672{
1673    // gamemaster in GM mode see all, including ghosts
1674    if(pl->isGameMaster())
1675        return true;
1676
1677    // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1678    if(pl->isAlive() || pl->GetDeathTimer() > 0)
1679    {
1680        if( GetEntry() == VISUAL_WAYPOINT && !pl->isGameMaster() )
1681            return false;
1682        return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1683    }
1684
1685    // Dead player see live creatures near own corpse
1686    if(isAlive())
1687    {
1688        Corpse *corpse = pl->GetCorpse();
1689        if(corpse)
1690        {
1691            // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1692            if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1693                return true;
1694        }
1695    }
1696
1697    // Dead player see Spirit Healer or Spirit Guide
1698    if(isSpiritService())
1699        return true;
1700
1701    // and not see any other
1702    return false;
1703}
1704
1705void Creature::DoFleeToGetAssistance(float radius) // Optional parameter
1706{
1707    if (!getVictim())
1708        return;
1709
1710    Creature* pCreature = NULL;
1711
1712    CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1713    Cell cell(p);
1714    cell.data.Part.reserved = ALL_DISTRICT;
1715    cell.SetNoCreate();
1716
1717    Trinity::NearestAssistCreatureInCreatureRangeCheck u_check(this,getVictim(),radius);
1718    Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck> searcher(pCreature, u_check);
1719
1720    TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1721
1722    CellLock<GridReadGuard> cell_lock(cell, p);
1723    cell_lock->Visit(cell_lock, grid_creature_searcher, *(GetMap()));
1724
1725    if(!GetMotionMaster()->empty() && (GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE))
1726        GetMotionMaster()->Clear(false);
1727    if(pCreature == NULL)
1728    {
1729        GetMotionMaster()->MoveIdle();
1730        GetMotionMaster()->MoveFleeing(getVictim());
1731    }
1732    else
1733    {
1734        GetMotionMaster()->MoveIdle();
1735        GetMotionMaster()->MovePoint(0,pCreature->GetPositionX(),pCreature->GetPositionY(),pCreature->GetPositionZ());
1736    }
1737}
1738
1739void Creature::CallAssistence()
1740{
1741    if( !m_AlreadyCallAssistence && getVictim() && !isPet() && !isCharmed())
1742    {
1743        SetNoCallAssistence(true);
1744
1745        float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS);
1746        if(radius > 0)
1747        {
1748            std::list<Creature*> assistList;
1749
1750            {
1751                CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1752                Cell cell(p);
1753                cell.data.Part.reserved = ALL_DISTRICT;
1754                cell.SetNoCreate();
1755
1756                Trinity::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1757                Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1758
1759                TypeContainerVisitor<Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1760
1761                CellLock<GridReadGuard> cell_lock(cell, p);
1762                cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
1763            }
1764
1765            for(std::list<Creature*>::iterator iter = assistList.begin(); iter != assistList.end(); ++iter)
1766            {
1767                (*iter)->SetNoCallAssistence(true);
1768                if((*iter)->AI())
1769                    (*iter)->AI()->AttackStart(getVictim());
1770            }
1771        }
1772    }
1773}
1774
1775void Creature::SaveRespawnTime()
1776{
1777    if(isPet() || !m_DBTableGuid)
1778        return;
1779
1780    if(m_respawnTime > time(NULL))                          // dead (no corpse)
1781        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1782    else if(m_deathTimer > 0)                               // dead (corpse)
1783        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1784}
1785
1786bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1787{
1788    if(!pVictim)
1789        return true;
1790
1791    if(!pVictim->IsInMap(this))
1792        return true;
1793
1794    if(!pVictim->isTargetableForAttack())
1795        return true;
1796
1797    if(!pVictim->isInAccessablePlaceFor(this))
1798        return true;
1799
1800    if(sMapStore.LookupEntry(GetMapId())->Instanceable())
1801        return false;
1802
1803    float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1804    float AttackDist = GetAttackDistance(pVictim);
1805    uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1806
1807    //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and ouf of combat every update tick.
1808    return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1809}
1810
1811CreatureDataAddon const* Creature::GetCreatureAddon() const
1812{
1813    if (m_DBTableGuid)
1814    {
1815        if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1816            return addon;
1817    }
1818
1819    // dependent from heroic mode entry
1820    return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1821}
1822
1823//creature_addon table
1824bool Creature::LoadCreaturesAddon(bool reload)
1825{
1826    CreatureDataAddon const *cainfo = GetCreatureAddon();
1827    if(!cainfo)
1828        return false;
1829
1830    if (cainfo->mount != 0)
1831        Mount(cainfo->mount);
1832
1833    if (cainfo->bytes0 != 0)
1834        SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1835
1836    if (cainfo->bytes1 != 0)
1837        SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1838
1839    if (cainfo->bytes2 != 0)
1840        SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1841
1842    if (cainfo->emote != 0)
1843        SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1844
1845    if (cainfo->move_flags != 0)
1846        SetUnitMovementFlags(cainfo->move_flags);
1847
1848    if(cainfo->auras)
1849    {
1850        for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1851        {
1852            SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1853            if (!AdditionalSpellInfo)
1854            {
1855                sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1856                continue;
1857            }
1858
1859            // skip already applied aura
1860            if(HasAura(cAura->spell_id,cAura->effect_idx))
1861            {
1862                if(!reload)
1863                    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);
1864
1865                continue;
1866            }
1867
1868            Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1869            AddAura(AdditionalAura);
1870            sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1871        }
1872    }
1873    return true;
1874}
1875
1876/// Send a message to LocalDefense channel for players oposition team in the zone
1877void Creature::SendZoneUnderAttackMessage(Player* attacker)
1878{
1879    uint32 enemy_team = attacker->GetTeam();
1880
1881    WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1882    data << (uint32)GetZoneId();
1883    sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1884}
1885
1886void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1887{
1888    m_CreatureSpellCooldowns[spell_id] = end_time;
1889}
1890
1891void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1892{
1893    m_CreatureCategoryCooldowns[category] = apply_time;
1894}
1895
1896void Creature::AddCreatureSpellCooldown(uint32 spellid)
1897{
1898    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1899    if(!spellInfo)
1900        return;
1901
1902    uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1903    if(cooldown)
1904        _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1905
1906    if(spellInfo->Category)
1907        _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1908
1909    m_GlobalCooldown = spellInfo->StartRecoveryTime;
1910}
1911
1912bool Creature::HasCategoryCooldown(uint32 spell_id) const
1913{
1914    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1915    if(!spellInfo)
1916        return false;
1917
1918    // check global cooldown if spell affected by it
1919    if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1920        return true;
1921
1922    CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1923    return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1924}
1925
1926bool Creature::HasSpellCooldown(uint32 spell_id) const
1927{
1928    CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1929    return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1930}
1931
1932bool Creature::IsInEvadeMode() const
1933{
1934    return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1935}
1936
1937bool Creature::HasSpell(uint32 spellID) const
1938{
1939    uint8 i;
1940    for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1941        if(spellID == m_spells[i])
1942            break;
1943    return i < CREATURE_MAX_SPELLS;                         //broke before end of iteration of known spells
1944}
1945
1946time_t Creature::GetRespawnTimeEx() const
1947{
1948    time_t now = time(NULL);
1949    if(m_respawnTime > now)                                 // dead (no corpse)
1950        return m_respawnTime;
1951    else if(m_deathTimer > 0)                               // dead (corpse)
1952        return now+m_respawnDelay+m_deathTimer/1000;
1953    else
1954        return now;
1955}
1956
1957void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1958{
1959    if (m_DBTableGuid)
1960    {
1961        if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1962        {
1963            x = data->posX;
1964            y = data->posY;
1965            z = data->posZ;
1966            if(ori)
1967                *ori = data->orientation;
1968            if(dist)
1969                *dist = data->spawndist;
1970
1971            return;
1972        }
1973    }
1974
1975    x = GetPositionX();
1976    y = GetPositionY();
1977    z = GetPositionZ();
1978    if(ori)
1979        *ori = GetOrientation();
1980    if(dist)
1981        *dist = 0;
1982}
1983
1984void Creature::AllLootRemovedFromCorpse()
1985{
1986    if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1987    {
1988        uint32 nDeathTimer;
1989
1990        CreatureInfo const *cinfo = GetCreatureInfo();
1991
1992        // corpse was not skinnable -> apply corpse looted timer
1993        if (!cinfo || !cinfo->SkinLootId)
1994            nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1995        // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1996        else
1997            nDeathTimer = 0;
1998
1999        // update death timer only if looted timer is shorter
2000        if (m_deathTimer > nDeathTimer)
2001            m_deathTimer = nDeathTimer;
2002    }
2003}
2004
2005uint32 Creature::getLevelForTarget( Unit const* target ) const
2006{
2007    if(!isWorldBoss())
2008        return Unit::getLevelForTarget(target);
2009
2010    uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2011    if(level < 1)
2012        return 1;
2013    if(level > 255)
2014        return 255;
2015    return level;
2016}
2017
2018char const* Creature::GetScriptName() const
2019{
2020    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
2021}
2022
2023
2024VendorItemData const* Creature::GetVendorItems() const
2025{
2026    return objmgr.GetNpcVendorItemList(GetEntry());
2027}
2028
2029uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2030{
2031    if(!vItem->maxcount)
2032        return vItem->maxcount;
2033
2034    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2035    for(; itr != m_vendorItemCounts.end(); ++itr)
2036        if(itr->itemId==vItem->item)
2037            break;
2038
2039    if(itr == m_vendorItemCounts.end())
2040        return vItem->maxcount;
2041
2042    VendorItemCount* vCount = &*itr;
2043
2044    time_t ptime = time(NULL);
2045
2046    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2047    {
2048        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2049
2050        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2051        if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2052        {
2053            m_vendorItemCounts.erase(itr);       
2054            return vItem->maxcount;
2055        }
2056
2057        vCount->count += diff * pProto->BuyCount;
2058        vCount->lastIncrementTime = ptime;
2059    }
2060
2061    return vCount->count;
2062}
2063
2064uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2065{
2066    if(!vItem->maxcount)
2067        return 0;
2068
2069    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2070    for(; itr != m_vendorItemCounts.end(); ++itr)
2071        if(itr->itemId==vItem->item)
2072            break;
2073
2074    if(itr == m_vendorItemCounts.end())
2075    {
2076        uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2077        m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2078        return new_count;
2079    }
2080
2081    VendorItemCount* vCount = &*itr;
2082
2083    time_t ptime = time(NULL);
2084
2085    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2086    {
2087        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2088
2089        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2090        if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2091            vCount->count += diff * pProto->BuyCount;
2092        else
2093            vCount->count = vItem->maxcount;
2094    }
2095
2096    vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2097    vCount->lastIncrementTime = ptime;
2098    return vCount->count;
2099}
2100
2101TrainerSpellData const* Creature::GetTrainerSpells() const
2102{
2103    return objmgr.GetNpcTrainerSpells(GetEntry());
2104}
Note: See TracBrowser for help on using the browser.