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

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

Merge with 284 (54b0e67d97fe).

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