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

Revision 283, 74.1 kB (checked in by yumileroy, 17 years ago)

*Alterac Valley. By Bogie and Balrok. Note: some core contents are modified. Will fix them later. Some sql are disabled because of possible conflict with offical DB. Use them at your own risk.

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