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

Revision 272, 72.6 kB (checked in by yumileroy, 17 years ago)

Delete possessed AI only on creature delete.

Original author: gvcoman
Date: 2008-11-16 14:38:02-05:00

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