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

Revision 173, 70.0 kB (checked in by yumileroy, 17 years ago)

[svn] * Avoid access to bag item prototype for getting bag size, use related item update field instead as more fast source.
* Better check client inventory pos data received in some client packets to skip invalid cases.
* Removed some unnecessary database queries.
* Make guid lookup for adding ignore async.
* Added two parameter versions of the AsyncQuery? function
* Make queries for adding friends async. - Hunuza
* Replace some PQuery() calls with more simple Query() - Hunuza
* Mark spell as executed instead of deleteable to solve crash.
*** Source mangos.

**Its a big commit. so test with care... or without care.... whatever floats your boat.

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