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

Revision 229, 72.1 kB (checked in by yumileroy, 17 years ago)

[svn] *** Source: MaNGOS ***
* Fixed build extractor at Windows Vista. Author: Vladimir
* Fixed comment text and code indentifiers spelling. Author: Vladimir & Paradox.
* Access cached member lists in guild handlers instead of querying the DB. Author: Hunuza
* Small fixes in send/received packet and simple code cleanup also. Author: Vladimir
* Not output error at loading empty character_ticket table. Author: Vladimir
* Not reset display model at shapeshift aura remove if it not set at apply. Author: Arthorius
* Applied props to few files.

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