root/trunk/src/game/ObjectMgr.cpp @ 34

Revision 34, 254.0 kB (checked in by yumileroy, 17 years ago)

[svn] * Removing useless data accidentally committed.
* Applying ImpConfig? patch.
* Note: QUEUE_FOR_GM currently disabled as it's not compatible with the ACE patch. Anyone care to rewrite it?
* Note2: This is untested - I may have done some mistakes here and there. Will try to compile now.

Original author: XTZGZoReX
Date: 2008-10-10 13:37:21-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18
19#include "Common.h"
20#include "Database/DatabaseEnv.h"
21#include "Database/SQLStorage.h"
22
23#include "Log.h"
24#include "MapManager.h"
25#include "ObjectMgr.h"
26#include "SpellMgr.h"
27#include "UpdateMask.h"
28#include "World.h"
29#include "WorldSession.h"
30#include "Group.h"
31#include "Guild.h"
32#include "ArenaTeam.h"
33#include "Transports.h"
34#include "ProgressBar.h"
35#include "Policies/SingletonImp.h"
36#include "Language.h"
37#include "GameEvent.h"
38#include "Spell.h"
39#include "Chat.h"
40#include "InstanceSaveMgr.h"
41#include "SpellAuras.h"
42#include "Util.h"
43
44INSTANTIATE_SINGLETON_1(ObjectMgr);
45
46ScriptMapMap sQuestEndScripts;
47ScriptMapMap sQuestStartScripts;
48ScriptMapMap sSpellScripts;
49ScriptMapMap sGameObjectScripts;
50ScriptMapMap sEventScripts;
51
52bool normalizePlayerName(std::string& name)
53{
54    if(name.empty())
55        return false;
56
57    wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
58    size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
59
60    if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
61        return false;
62
63    wstr_buf[0] = wcharToUpper(wstr_buf[0]);
64    for(size_t i = 1; i < wstr_len; ++i)
65        wstr_buf[i] = wcharToLower(wstr_buf[i]);
66
67    if(!WStrToUtf8(wstr_buf,wstr_len,name))
68        return false;
69
70    return true;
71}
72
73LanguageDesc lang_description[LANGUAGES_COUNT] =
74{
75    { LANG_ADDON,           0, 0                       },
76    { LANG_UNIVERSAL,       0, 0                       },
77    { LANG_ORCISH,        669, SKILL_LANG_ORCISH       },
78    { LANG_DARNASSIAN,    671, SKILL_LANG_DARNASSIAN   },
79    { LANG_TAURAHE,       670, SKILL_LANG_TAURAHE      },
80    { LANG_DWARVISH,      672, SKILL_LANG_DWARVEN      },
81    { LANG_COMMON,        668, SKILL_LANG_COMMON       },
82    { LANG_DEMONIC,       815, SKILL_LANG_DEMON_TONGUE },
83    { LANG_TITAN,         816, SKILL_LANG_TITAN        },
84    { LANG_THALASSIAN,    813, SKILL_LANG_THALASSIAN   },
85    { LANG_DRACONIC,      814, SKILL_LANG_DRACONIC     },
86    { LANG_KALIMAG,       817, SKILL_LANG_OLD_TONGUE   },
87    { LANG_GNOMISH,      7340, SKILL_LANG_GNOMISH      },
88    { LANG_TROLL,        7341, SKILL_LANG_TROLL        },
89    { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK  },
90    { LANG_DRAENEI,     29932, SKILL_LANG_DRAENEI      },
91    { LANG_ZOMBIE,          0, 0                       },
92    { LANG_GNOMISH_BINARY,  0, 0                       },
93    { LANG_GOBLIN_BINARY,   0, 0                       }
94};
95
96LanguageDesc const* GetLanguageDescByID(uint32 lang)
97{
98    for(int i = 0; i < LANGUAGES_COUNT; ++i)
99    {
100        if(uint32(lang_description[i].lang_id) == lang)
101            return &lang_description[i];
102    }
103
104    return NULL;
105}
106
107ObjectMgr::ObjectMgr()
108{
109    m_hiCharGuid        = 1;
110    m_hiCreatureGuid    = 1;
111    m_hiPetGuid         = 1;
112    m_hiItemGuid        = 1;
113    m_hiGoGuid          = 1;
114    m_hiDoGuid          = 1;
115    m_hiCorpseGuid      = 1;
116
117    m_hiPetNumber       = 1;
118
119    mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
120    mGuildBankTabPrice[0] = 100;
121    mGuildBankTabPrice[1] = 250;
122    mGuildBankTabPrice[2] = 500;
123    mGuildBankTabPrice[3] = 1000;
124    mGuildBankTabPrice[4] = 2500;
125    mGuildBankTabPrice[5] = 5000;
126
127    // Only zero condition left, others will be added while loading DB tables
128    mConditions.resize(1);
129}
130
131ObjectMgr::~ObjectMgr()
132{
133    for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
134    {
135        delete i->second;
136    }
137    mQuestTemplates.clear( );
138
139    for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
140    {
141        delete i->second;
142    }
143    mGossipText.clear( );
144
145    mAreaTriggers.clear();
146
147    for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
148    {
149        delete[] i->second;
150    }
151    petInfo.clear();
152
153    // free only if loaded
154    for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
155        delete[] playerClassInfo[class_].levelInfo;
156
157    for (int race = 0; race < MAX_RACES; ++race)
158        for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
159            delete[] playerInfo[race][class_].levelInfo;
160
161    // free group and guild objects
162    for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
163        delete (*itr);
164    for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
165        delete (*itr);
166
167    for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
168        delete itr->second;
169
170    for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
171        itr->second.Clear();
172
173    for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
174        itr->second.Clear();
175}
176
177Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
178{
179    for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
180        if ((*itr)->GetLeaderGUID() == guid)
181            return *itr;
182
183    return NULL;
184}
185
186Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
187{
188    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
189        if ((*itr)->GetId() == GuildId)
190            return *itr;
191
192    return NULL;
193}
194
195Guild * ObjectMgr::GetGuildByName(std::string guildname) const
196{
197    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
198        if ((*itr)->GetName() == guildname)
199            return *itr;
200
201    return NULL;
202}
203
204std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
205{
206    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
207        if ((*itr)->GetId() == GuildId)
208            return (*itr)->GetName();
209
210    return "";
211}
212
213Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
214{
215    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
216        if( (*itr)->GetLeader() == guid)
217            return *itr;
218
219    return NULL;
220}
221
222ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
223{
224    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
225        if ((*itr)->GetId() == ArenaTeamId)
226            return *itr;
227
228    return NULL;
229}
230
231ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
232{
233    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
234        if ((*itr)->GetName() == arenateamname)
235            return *itr;
236
237    return NULL;
238}
239
240ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
241{
242    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
243        if ((*itr)->GetCaptain() == guid)
244            return *itr;
245
246    return NULL;
247}
248
249AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
250{
251    switch ( location )
252    {
253        case 6:                                             //horde
254            return & mHordeAuctions;
255            break;
256        case 2:                                             //alliance
257            return & mAllianceAuctions;
258            break;
259        default:                                            //neutral
260            return & mNeutralAuctions;
261    }
262}
263
264uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
265{
266    if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
267        return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
268    else
269        return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
270}
271
272uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
273{
274    float percentance;                                      // in 0..1
275    if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
276        percentance = 0.75f;
277    else
278        percentance = 0.15f;
279
280    percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
281
282    return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
283}
284
285/// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
286uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
287{
288    uint32 outbid = (currentBid / 100) * 5;
289    if (!outbid)
290        outbid = 1;
291    return outbid;
292}
293
294//does not clear ram
295void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
296{
297    Item *pItem = GetAItem(auction->item_guidlow);
298    if(!pItem)
299        return;
300
301    uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
302    Player *bidder = GetPlayer(bidder_guid);
303
304    uint32 bidder_accId = 0;
305
306    // data for gm.log
307    if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
308    {
309        uint32 bidder_security = 0;
310        std::string bidder_name;
311        if (bidder)
312        {
313            bidder_accId = bidder->GetSession()->GetAccountId();
314            bidder_security = bidder->GetSession()->GetSecurity();
315            bidder_name = bidder->GetName();
316        }
317        else
318        {
319            bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
320            bidder_security = GetSecurityByAccount(bidder_accId);
321
322            if(bidder_security > SEC_PLAYER )               // not do redundant DB requests
323            {
324                if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
325                    bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
326            }
327        }
328
329        if( bidder_security > SEC_PLAYER )
330        {
331            std::string owner_name;
332            if(!GetPlayerNameByGUID(auction->owner,owner_name))
333                owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
334
335            uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
336
337            sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
338                bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
339        }
340    }
341    else if(!bidder)
342        bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
343
344    // receiver exist
345    if(bidder || bidder_accId)
346    {
347        std::ostringstream msgAuctionWonSubject;
348        msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
349
350        std::ostringstream msgAuctionWonBody;
351        msgAuctionWonBody.width(16);
352        msgAuctionWonBody << std::right << std::hex << auction->owner;
353        msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
354        sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
355
356        //prepare mail data... :
357        uint32 itemTextId = this->CreateItemText( msgAuctionWonBody.str() );
358
359        // set owner to bidder (to prevent delete item with sender char deleting)
360        // owner in `data` will set at mail receive and item extracting
361        CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
362        CharacterDatabase.CommitTransaction();
363
364        MailItemsInfo mi;
365        mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
366
367        if (bidder)
368            bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
369        else
370            RemoveAItem(pItem->GetGUIDLow());               // we have to remove the item, before we delete it !!
371
372        // will delete item or place to receiver mail list
373        WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
374    }
375    // receiver not exist
376    else
377    {
378        CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
379        RemoveAItem(pItem->GetGUIDLow());                   // we have to remove the item, before we delete it !!
380        delete pItem;
381    }
382}
383
384void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
385{
386    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
387    Player *owner = GetPlayer(owner_guid);
388
389    // owner exist (online or offline)
390    if(owner || GetPlayerAccountIdByGUID(owner_guid))
391    {
392        std::ostringstream msgAuctionSalePendingSubject;
393        msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
394
395        std::ostringstream msgAuctionSalePendingBody;
396        uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
397
398        time_t distrTime = time(NULL) + HOUR;
399
400        msgAuctionSalePendingBody.width(16);
401        msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
402        msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
403        msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
404        msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
405
406        sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
407
408        uint32 itemTextId = this->CreateItemText( msgAuctionSalePendingBody.str() );
409
410        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
411    }
412}
413
414//call this method to send mail to auction owner, when auction is successful, it does not clear ram
415void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
416{
417    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
418    Player *owner = GetPlayer(owner_guid);
419
420    uint32 owner_accId = 0;
421    if(!owner)
422        owner_accId = GetPlayerAccountIdByGUID(owner_guid);
423
424    // owner exist
425    if(owner || owner_accId)
426    {
427        std::ostringstream msgAuctionSuccessfulSubject;
428        msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
429
430        std::ostringstream auctionSuccessfulBody;
431        uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
432
433        auctionSuccessfulBody.width(16);
434        auctionSuccessfulBody << std::right << std::hex << auction->bidder;
435        auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
436        auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
437
438        sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
439
440        uint32 itemTextId = this->CreateItemText( auctionSuccessfulBody.str() );
441
442        uint32 profit = auction->bid + auction->deposit - auctionCut;
443
444        if (owner)
445        {
446            //send auction owner notification, bidder must be current!
447            owner->GetSession()->SendAuctionOwnerNotification( auction );
448        }
449
450        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
451    }
452}
453
454//does not clear ram
455void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
456{                                                           //return an item in auction to its owner by mail
457    Item *pItem = GetAItem(auction->item_guidlow);
458    if(!pItem)
459    {
460        sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
461        return;
462    }
463
464    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
465    Player *owner = GetPlayer(owner_guid);
466
467    uint32 owner_accId = 0;
468    if(!owner)
469        owner_accId = GetPlayerAccountIdByGUID(owner_guid);
470
471    // owner exist
472    if(owner || owner_accId)
473    {
474        std::ostringstream subject;
475        subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
476
477        if ( owner )
478            owner->GetSession()->SendAuctionOwnerNotification( auction );
479        else
480            RemoveAItem(pItem->GetGUIDLow());               // we have to remove the item, before we delete it !!
481
482        MailItemsInfo mi;
483        mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
484
485        // will delete item or place to receiver mail list
486        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
487
488    }
489    // owner not found
490    else
491    {
492        CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
493        RemoveAItem(pItem->GetGUIDLow());                   // we have to remove the item, before we delete it !!
494        delete pItem;
495    }
496}
497
498CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
499{
500    return sCreatureStorage.LookupEntry<CreatureInfo>(id);
501}
502
503void ObjectMgr::LoadCreatureLocales()
504{
505    QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,subname_loc1,name_loc2,subname_loc2,name_loc3,subname_loc3,name_loc4,subname_loc4,name_loc5,subname_loc5,name_loc6,subname_loc6,name_loc7,subname_loc7,name_loc8,subname_loc8 FROM locales_creature");
506
507    if(!result)
508    {
509        barGoLink bar(1);
510
511        bar.step();
512
513        sLog.outString("");
514        sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
515        return;
516    }
517
518    barGoLink bar(result->GetRowCount());
519
520    do
521    {
522        Field *fields = result->Fetch();
523        bar.step();
524
525        uint32 entry = fields[0].GetUInt32();
526
527        CreatureLocale& data = mCreatureLocaleMap[entry];
528
529        for(int i = 1; i < MAX_LOCALE; ++i)
530        {
531            std::string str = fields[1+2*(i-1)].GetCppString();
532            if(!str.empty())
533            {
534                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
535                if(idx >= 0)
536                {
537                    if(data.Name.size() <= idx)
538                        data.Name.resize(idx+1);
539
540                    data.Name[idx] = str;
541                }
542            }
543            str = fields[1+2*(i-1)+1].GetCppString();
544            if(!str.empty())
545            {
546                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
547                if(idx >= 0)
548                {
549                    if(data.SubName.size() <= idx)
550                        data.SubName.resize(idx+1);
551
552                    data.SubName[idx] = str;
553                }
554            }
555        }
556    } while (result->NextRow());
557
558    delete result;
559
560    sLog.outString();
561    sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
562}
563
564void ObjectMgr::LoadCreatureTemplates()
565{
566    sCreatureStorage.Load();
567
568    sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
569    sLog.outString();
570
571    std::set<uint32> heroicEntries;                         // already loaded heroic value in creatures
572    std::set<uint32> hasHeroicEntries;                      // already loaded creatures with heroic entry values
573
574    // check data correctness
575    for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
576    {
577        CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
578        if(!cInfo)
579            continue;
580
581        if(cInfo->HeroicEntry)
582        {
583            CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
584            if(!heroicInfo)
585            {
586                sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
587                continue;
588            }
589
590            if(heroicEntries.find(i)!=heroicEntries.end())
591            {
592                sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
593                continue;
594            }
595
596            if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
597            {
598                sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
599                continue;
600            }
601
602            if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
603            {
604                sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
605                continue;
606            }
607
608            if(cInfo->npcflag != heroicInfo->npcflag)
609            {
610                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `npcflag` in heroic mode.",i);
611                continue;
612            }
613
614            if(cInfo->classNum != heroicInfo->classNum)
615            {
616                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `classNum` in heroic mode.",i);
617                continue;
618            }
619
620            if(cInfo->race != heroicInfo->race)
621            {
622                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `race` in heroic mode.",i);
623                continue;
624            }
625
626            if(cInfo->trainer_type != heroicInfo->trainer_type)
627            {
628                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `trainer_type` in heroic mode.",i);
629                continue;
630            }
631
632            if(cInfo->trainer_spell != heroicInfo->trainer_spell)
633            {
634                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `trainer_spell` in heroic mode.",i);
635                continue;
636            }
637
638            hasHeroicEntries.insert(i);
639            heroicEntries.insert(cInfo->HeroicEntry);
640        }
641
642        FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
643        if(!factionTemplate)
644            sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
645
646        factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
647        if(!factionTemplate)
648            sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
649
650        CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
651        if (!minfo)
652            sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
653        minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
654        if (!minfo)
655            sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
656
657        if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
658        {
659            sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
660            const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
661        }
662
663        if(cInfo->baseattacktime == 0)
664            const_cast<CreatureInfo*>(cInfo)->baseattacktime  = BASE_ATTACK_TIME;
665
666        if(cInfo->rangeattacktime == 0)
667            const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
668
669        if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
670            sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
671
672        if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
673        {
674            sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
675            const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
676        }
677
678        if(cInfo->PetSpellDataId)
679        {
680            CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
681            if(!spellDataId)
682                sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
683        }
684
685        if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
686        {
687            sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
688            const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
689        }
690
691        if(cInfo->equipmentId > 0)                          // 0 no equipment
692        {
693            if(!GetEquipmentInfo(cInfo->equipmentId))
694            {
695                sLog.outErrorDb("Table `creature_template` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", cInfo->Entry, cInfo->equipmentId);
696                const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
697            }
698        }
699
700        /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
701        if(cInfo->scale <= 0.0f)
702        {
703            CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
704            const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
705        }
706    }
707}
708
709void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
710{
711    // Now add the auras, format "spellid effectindex spellid effectindex..."
712    char *p,*s;
713    std::vector<int> val;
714    s=p=(char*)reinterpret_cast<char const*>(addon->auras);
715    if(p)
716    {
717        while (p[0]!=0)
718        {
719            ++p;
720            if (p[0]==' ')
721            {
722                val.push_back(atoi(s));
723                s=++p;
724            }
725        }
726        if (p!=s)
727            val.push_back(atoi(s));
728
729        // free char* loaded memory
730        delete[] (char*)reinterpret_cast<char const*>(addon->auras);
731
732        // wrong list
733        if (val.size()%2)
734        {
735            addon->auras = NULL;
736            sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
737            return;
738        }
739    }
740
741    // empty list
742    if(val.empty())
743    {
744        addon->auras = NULL;
745        return;
746    }
747
748    // replace by new strucutres array
749    const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
750
751    int i=0;
752    for(int j=0;j<val.size()/2;++j)
753    {
754        CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
755        cAura.spell_id = (uint32)val[2*j+0];
756        cAura.effect_idx  = (uint32)val[2*j+1];
757        if ( cAura.effect_idx > 2 )
758        {
759            sLog.outErrorDb("Creature (%s: %u) has wrong effect %u for spell %u in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
760            continue;
761        }
762        SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
763        if (!AdditionalSpellInfo)
764        {
765            sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
766            continue;
767        }
768
769        if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
770        {
771            sLog.outErrorDb("Creature (%s: %u) has not aura effect %u of spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
772            continue;
773        }
774
775        ++i;
776    }
777
778    // fill terminator element (after last added)
779    CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
780    endAura.spell_id   = 0;
781    endAura.effect_idx = 0;
782}
783
784void ObjectMgr::LoadCreatureAddons()
785{
786    sCreatureInfoAddonStorage.Load();
787
788    sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
789    sLog.outString();
790
791    // check data correctness and convert 'auras'
792    for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
793    {
794        CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
795        if(!addon)
796            continue;
797
798        ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
799
800        if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
801            sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
802    }
803
804    sCreatureDataAddonStorage.Load();
805
806    sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
807    sLog.outString();
808
809    // check data correctness and convert 'auras'
810    for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
811    {
812        CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
813        if(!addon)
814            continue;
815
816        ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
817
818        if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
819            sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
820    }
821}
822
823EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
824{
825    return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
826}
827
828void ObjectMgr::LoadEquipmentTemplates()
829{
830    sEquipmentStorage.Load();
831
832    sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
833    sLog.outString();
834}
835
836CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
837{
838    return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
839}
840
841uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
842{
843    // Load creature model (display id)
844    uint32 display_id;
845    if (!data || data->displayid == 0)                      // use defaults from the template
846    {
847        // DisplayID_A is used if no team is given
848        if (team == HORDE)
849            display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
850        else
851            display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
852    }
853    else                                                    // overriden in creature data
854        display_id = data->displayid;
855
856    return display_id;
857}
858
859CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
860{
861    CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
862    if(!minfo)
863        return NULL;
864
865    // If a model for another gender exists, 50% chance to use it
866    if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
867    {
868        CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
869        if(!minfo_tmp)
870        {
871            sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
872            return minfo;                                   // not fatal, just use the previous one
873        }
874        else
875            return minfo_tmp;
876    }
877    else
878        return minfo;
879}
880
881void ObjectMgr::LoadCreatureModelInfo()
882{
883    sCreatureModelStorage.Load();
884
885    sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
886    sLog.outString();
887}
888
889void ObjectMgr::LoadCreatures()
890{
891    uint32 count = 0;
892    //                                                0              1   2    3
893    QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
894    //   4             5           6           7           8            9              10         11
895        "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
896    //   12         13       14          15            16         17
897        "curhealth, curmana, DeathState, MovementType, spawnMask, event "
898        "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
899
900    if(!result)
901    {
902        barGoLink bar(1);
903
904        bar.step();
905
906        sLog.outString("");
907        sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
908        return;
909    }
910
911    // build single time for check creature data
912    std::set<uint32> heroicCreatures;
913    for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
914        if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
915            if(cInfo->HeroicEntry)
916                heroicCreatures.insert(cInfo->HeroicEntry);
917
918    barGoLink bar(result->GetRowCount());
919
920    do
921    {
922        Field *fields = result->Fetch();
923        bar.step();
924
925        uint32 guid = fields[0].GetUInt32();
926
927        CreatureData& data = mCreatureDataMap[guid];
928
929        data.id             = fields[ 1].GetUInt32();
930        data.mapid          = fields[ 2].GetUInt32();
931        data.displayid      = fields[ 3].GetUInt32();
932        data.equipmentId    = fields[ 4].GetUInt32();
933        data.posX           = fields[ 5].GetFloat();
934        data.posY           = fields[ 6].GetFloat();
935        data.posZ           = fields[ 7].GetFloat();
936        data.orientation    = fields[ 8].GetFloat();
937        data.spawntimesecs  = fields[ 9].GetUInt32();
938        data.spawndist      = fields[10].GetFloat();
939        data.currentwaypoint= fields[11].GetUInt32();
940        data.curhealth      = fields[12].GetUInt32();
941        data.curmana        = fields[13].GetUInt32();
942        data.is_dead        = fields[14].GetBool();
943        data.movementType   = fields[15].GetUInt8();
944        data.spawnMask      = fields[16].GetUInt8();
945        int16 gameEvent     = fields[17].GetInt16();
946
947        CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
948        if(!cInfo)
949        {
950            sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
951            continue;
952        }
953
954        if(heroicCreatures.find(data.id)!=heroicCreatures.end())
955        {
956            sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template_substitution`, skipped.",guid,data.id );
957            continue;
958        }
959
960        if(data.equipmentId > 0)                            // -1 no equipment, 0 use default
961        {
962            if(!GetEquipmentInfo(data.equipmentId))
963            {
964                sLog.outErrorDb("Table `creature` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", data.id, data.equipmentId);
965                data.equipmentId = -1;
966            }
967        }
968
969        if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
970        {
971            sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`RegenHealth`=1 and low current health (%u), `creature_template`.`minhealth`=%u.",guid,data.id,data.curhealth, cInfo->minhealth );
972            data.curhealth = cInfo->minhealth;
973        }
974
975        if(data.curmana < cInfo->minmana)
976        {
977            sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with low current mana (%u), `creature_template`.`minmana`=%u.",guid,data.id,data.curmana, cInfo->minmana );
978            data.curmana = cInfo->minmana;
979        }
980
981        if(data.spawndist < 0.0f)
982        {
983            sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
984            data.spawndist = 0.0f;
985        }
986        else if(data.movementType == RANDOM_MOTION_TYPE)
987        {
988            if(data.spawndist == 0.0f)
989            {
990                sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=1 (random movement) but with `spawndist`=0, replace by idle movement type (0).",guid,data.id );
991                data.movementType = IDLE_MOTION_TYPE;
992            }
993        }
994        else if(data.movementType == IDLE_MOTION_TYPE)
995        {
996            if(data.spawndist != 0.0f)
997            {
998                sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
999                data.spawndist = 0.0f;
1000            }
1001        }
1002
1003        if (gameEvent==0)                                   // if not this is to be managed by GameEvent System
1004            AddCreatureToGrid(guid, &data);
1005        ++count;
1006
1007    } while (result->NextRow());
1008
1009    delete result;
1010
1011    sLog.outString();
1012    sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1013}
1014
1015void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1016{
1017    uint8 mask = data->spawnMask;
1018    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1019    {
1020        if(mask & 1)
1021        {
1022            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1023            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1024
1025            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1026            cell_guids.creatures.insert(guid);
1027        }
1028    }
1029}
1030
1031void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1032{
1033    uint8 mask = data->spawnMask;
1034    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1035    {
1036        if(mask & 1)
1037        {
1038            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1039            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1040
1041            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1042            cell_guids.creatures.erase(guid);
1043        }
1044    }
1045}
1046
1047void ObjectMgr::LoadGameobjects()
1048{
1049    uint32 count = 0;
1050
1051    //                                                0                1   2    3           4           5           6
1052    QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1053    //   7          8          9          10         11             12            13     14         15
1054        "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1055        "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1056
1057    if(!result)
1058    {
1059        barGoLink bar(1);
1060
1061        bar.step();
1062
1063        sLog.outString();
1064        sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1065        return;
1066    }
1067
1068    barGoLink bar(result->GetRowCount());
1069
1070    do
1071    {
1072        Field *fields = result->Fetch();
1073        bar.step();
1074
1075        uint32 guid = fields[0].GetUInt32();
1076
1077        GameObjectData& data = mGameObjectDataMap[guid];
1078
1079        data.id             = fields[ 1].GetUInt32();
1080        data.mapid          = fields[ 2].GetUInt32();
1081        data.posX           = fields[ 3].GetFloat();
1082        data.posY           = fields[ 4].GetFloat();
1083        data.posZ           = fields[ 5].GetFloat();
1084        data.orientation    = fields[ 6].GetFloat();
1085        data.rotation0      = fields[ 7].GetFloat();
1086        data.rotation1      = fields[ 8].GetFloat();
1087        data.rotation2      = fields[ 9].GetFloat();
1088        data.rotation3      = fields[10].GetFloat();
1089        data.spawntimesecs  = fields[11].GetInt32();
1090        data.animprogress   = fields[12].GetUInt32();
1091        data.go_state       = fields[13].GetUInt32();
1092        data.spawnMask      = fields[14].GetUInt8();
1093        int16 gameEvent     = fields[15].GetInt16();
1094
1095        GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1096        if(!gInfo)
1097        {
1098            sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1099            continue;
1100        }
1101
1102        if (gameEvent==0)                                   // if not this is to be managed by GameEvent System
1103            AddGameobjectToGrid(guid, &data);
1104        ++count;
1105
1106    } while (result->NextRow());
1107
1108    delete result;
1109
1110    sLog.outString();
1111    sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1112}
1113
1114void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1115{
1116    uint8 mask = data->spawnMask;
1117    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1118    {
1119        if(mask & 1)
1120        {
1121            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1122            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1123
1124            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1125            cell_guids.gameobjects.insert(guid);
1126        }
1127    }
1128}
1129
1130void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1131{
1132    uint8 mask = data->spawnMask;
1133    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1134    {
1135        if(mask & 1)
1136        {
1137            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1138            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1139
1140            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1141            cell_guids.gameobjects.erase(guid);
1142        }
1143    }
1144}
1145
1146void ObjectMgr::LoadCreatureRespawnTimes()
1147{
1148    // remove outdated data
1149    WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1150
1151    uint32 count = 0;
1152
1153    QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1154
1155    if(!result)
1156    {
1157        barGoLink bar(1);
1158
1159        bar.step();
1160
1161        sLog.outString();
1162        sLog.outString(">> Loaded 0 creature respawn time.");
1163        return;
1164    }
1165
1166    barGoLink bar(result->GetRowCount());
1167
1168    do
1169    {
1170        Field *fields = result->Fetch();
1171        bar.step();
1172
1173        uint32 loguid       = fields[0].GetUInt32();
1174        uint64 respawn_time = fields[1].GetUInt64();
1175        uint32 instance     = fields[2].GetUInt32();
1176
1177        mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1178
1179        ++count;
1180    } while (result->NextRow());
1181
1182    delete result;
1183
1184    sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1185    sLog.outString();
1186}
1187
1188void ObjectMgr::LoadGameobjectRespawnTimes()
1189{
1190    // remove outdated data
1191    WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1192
1193    uint32 count = 0;
1194
1195    QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1196
1197    if(!result)
1198    {
1199        barGoLink bar(1);
1200
1201        bar.step();
1202
1203        sLog.outString();
1204        sLog.outString(">> Loaded 0 gameobject respawn time.");
1205        return;
1206    }
1207
1208    barGoLink bar(result->GetRowCount());
1209
1210    do
1211    {
1212        Field *fields = result->Fetch();
1213        bar.step();
1214
1215        uint32 loguid       = fields[0].GetUInt32();
1216        uint64 respawn_time = fields[1].GetUInt64();
1217        uint32 instance     = fields[2].GetUInt32();
1218
1219        mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1220
1221        ++count;
1222    } while (result->NextRow());
1223
1224    delete result;
1225
1226    sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1227    sLog.outString();
1228}
1229
1230// name must be checked to correctness (if received) before call this function
1231uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1232{
1233    uint64 guid = 0;
1234
1235    CharacterDatabase.escape_string(name);
1236
1237    // Player name safe to sending to DB (checked at login) and this function using
1238    QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1239    if(result)
1240    {
1241        guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1242
1243        delete result;
1244    }
1245
1246    return guid;
1247}
1248
1249bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1250{
1251    // prevent DB access for online player
1252    if(Player* player = GetPlayer(guid))
1253    {
1254        name = player->GetName();
1255        return true;
1256    }
1257
1258    QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1259
1260    if(result)
1261    {
1262        name = (*result)[0].GetCppString();
1263        delete result;
1264        return true;
1265    }
1266
1267    return false;
1268}
1269
1270uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1271{
1272    QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1273
1274    if(result)
1275    {
1276        uint8 race = (*result)[0].GetUInt8();
1277        delete result;
1278        return Player::TeamForRace(race);
1279    }
1280
1281    return 0;
1282}
1283
1284uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1285{
1286    QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1287    if(result)
1288    {
1289        uint32 acc = (*result)[0].GetUInt32();
1290        delete result;
1291        return acc;
1292    }
1293
1294    return 0;
1295}
1296
1297uint32 ObjectMgr::GetSecurityByAccount(uint32 acc_id) const
1298{
1299    QueryResult *result = loginDatabase.PQuery("SELECT gmlevel FROM account WHERE id = '%u'", acc_id);
1300    if(result)
1301    {
1302        uint32 sec = (*result)[0].GetUInt32();
1303        delete result;
1304        return sec;
1305    }
1306
1307    return 0;
1308}
1309
1310bool ObjectMgr::GetAccountNameByAccount(uint32 acc_id, std::string &name) const
1311{
1312    QueryResult *result = loginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id);
1313    if(result)
1314    {
1315        name = (*result)[0].GetCppString();
1316        delete result;
1317        return true;
1318    }
1319
1320    return false;
1321}
1322
1323uint32 ObjectMgr::GetAccountByAccountName(std::string name) const
1324{
1325    loginDatabase.escape_string(name);
1326    QueryResult *result = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", name.c_str());
1327    if(result)
1328    {
1329        uint32 id = (*result)[0].GetUInt32();
1330        delete result;
1331        return id;
1332    }
1333
1334    return 0;
1335}
1336
1337void ObjectMgr::LoadAuctions()
1338{
1339    QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1340    if( !result )
1341        return;
1342
1343    Field *fields = result->Fetch();
1344    uint32 AuctionCount=fields[0].GetUInt32();
1345    delete result;
1346
1347    if(!AuctionCount)
1348        return;
1349
1350    result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1351    if( !result )
1352        return;
1353
1354    barGoLink bar( AuctionCount );
1355
1356    AuctionEntry *aItem;
1357
1358    do
1359    {
1360        fields = result->Fetch();
1361
1362        bar.step();
1363
1364        aItem = new AuctionEntry;
1365        aItem->Id = fields[0].GetUInt32();
1366        aItem->auctioneer = fields[1].GetUInt32();
1367        aItem->item_guidlow = fields[2].GetUInt32();
1368        aItem->item_template = fields[3].GetUInt32();
1369        aItem->owner = fields[4].GetUInt32();
1370        aItem->buyout = fields[5].GetUInt32();
1371        aItem->time = fields[6].GetUInt32();
1372        aItem->bidder = fields[7].GetUInt32();
1373        aItem->bid = fields[8].GetUInt32();
1374        aItem->startbid = fields[9].GetUInt32();
1375        aItem->deposit = fields[10].GetUInt32();
1376        aItem->location = fields[11].GetUInt8();
1377        //check if sold item exists
1378        if ( this->GetAItem( aItem->item_guidlow ) )
1379        {
1380            GetAuctionsMap( aItem->location )->AddAuction(aItem);
1381        }
1382        else
1383        {
1384            CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1385            sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1386            delete aItem;
1387        }
1388    } while (result->NextRow());
1389    delete result;
1390
1391    sLog.outString();
1392    sLog.outString( ">> Loaded %u auctions", AuctionCount );
1393    sLog.outString();
1394}
1395
1396void ObjectMgr::LoadItemLocales()
1397{
1398    QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,description_loc1,name_loc2,description_loc2,name_loc3,description_loc3,name_loc4,description_loc4,name_loc5,description_loc5,name_loc6,description_loc6,name_loc7,description_loc7,name_loc8,description_loc8 FROM locales_item");
1399
1400    if(!result)
1401    {
1402        barGoLink bar(1);
1403
1404        bar.step();
1405
1406        sLog.outString("");
1407        sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1408        return;
1409    }
1410
1411    barGoLink bar(result->GetRowCount());
1412
1413    do
1414    {
1415        Field *fields = result->Fetch();
1416        bar.step();
1417
1418        uint32 entry = fields[0].GetUInt32();
1419
1420        ItemLocale& data = mItemLocaleMap[entry];
1421
1422        for(int i = 1; i < MAX_LOCALE; ++i)
1423        {
1424            std::string str = fields[1+2*(i-1)].GetCppString();
1425            if(!str.empty())
1426            {
1427                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1428                if(idx >= 0)
1429                {
1430                    if(data.Name.size() <= idx)
1431                        data.Name.resize(idx+1);
1432
1433                    data.Name[idx] = str;
1434                }
1435            }
1436
1437            str = fields[1+2*(i-1)+1].GetCppString();
1438            if(!str.empty())
1439            {
1440                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1441                if(idx >= 0)
1442                {
1443                    if(data.Description.size() <= idx)
1444                        data.Description.resize(idx+1);
1445
1446                    data.Description[idx] = str;
1447                }
1448            }
1449        }
1450    } while (result->NextRow());
1451
1452    delete result;
1453
1454    sLog.outString();
1455    sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1456}
1457
1458void ObjectMgr::LoadItemPrototypes()
1459{
1460    sItemStorage.Load ();
1461    sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1462    sLog.outString();
1463
1464    // check data correctness
1465    for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1466    {
1467        ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1468        ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1469        if(!proto)
1470        {
1471            /* to many errors, and possible not all items really used in game
1472            if (dbcitem)
1473                sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1474            */
1475            continue;
1476        }
1477
1478        if(dbcitem)
1479        {
1480            if(proto->InventoryType != dbcitem->InventoryType)
1481            {
1482                sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1483                // It safe let use InventoryType from DB
1484            }
1485
1486            if(proto->DisplayInfoID != dbcitem->DisplayId)
1487            {
1488                sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1489                const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1490            }
1491            if(proto->Sheath != dbcitem->Sheath)
1492            {
1493                sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u  (using it).",i,proto->Sheath,dbcitem->Sheath);
1494                const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1495            }
1496        }
1497        else
1498        {
1499            sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1500        }
1501
1502        if(proto->Class >= MAX_ITEM_CLASS)
1503        {
1504            sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1505            const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_JUNK;
1506        }
1507
1508        if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1509        {
1510            sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1511            const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1512        }
1513
1514        if(proto->Quality >= MAX_ITEM_QUALITY)
1515        {
1516            sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1517            const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1518        }
1519
1520        if(proto->BuyCount <= 0)
1521        {
1522            sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1523            const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1524        }
1525
1526        if(proto->InventoryType >= MAX_INVTYPE)
1527        {
1528            sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1529            const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1530        }
1531
1532        if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1533        {
1534            sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1535            const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1536        }
1537
1538        if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1539        {
1540            sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1541        }
1542
1543        if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1544        {
1545            sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1546        }
1547
1548        if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1549        {
1550            sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1551            const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1552        }
1553
1554        if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1555            sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1556
1557        if(proto->RequiredReputationFaction)
1558        {
1559            if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1560            {
1561                sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1562                const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1563            }
1564
1565            if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1566                sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1567        }
1568        else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1569            sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1570
1571        if(proto->Stackable==0)
1572        {
1573            sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1574            const_cast<ItemPrototype*>(proto)->Stackable = 1;
1575        }
1576        else if(proto->Stackable > 255)
1577        {
1578            sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1579            const_cast<ItemPrototype*>(proto)->Stackable = 255;
1580        }
1581
1582        for (int j = 0; j < 10; j++)
1583        {
1584            // for ItemStatValue != 0
1585            if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1586            {
1587                sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1588                const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1589            }
1590        }
1591
1592        for (int j = 0; j < 5; j++)
1593        {
1594            if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1595            {
1596                sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1597                const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1598            }
1599        }
1600
1601        // special format
1602        if(proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN)
1603        {
1604            // spell_1
1605            if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1606            {
1607                sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format",i,0+1,proto->Spells[0].SpellTrigger);
1608                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1609                const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1610                const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1611                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1612            }
1613
1614            // spell_2 have learning spell
1615            if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1616            {
1617                sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format.",i,1+1,proto->Spells[1].SpellTrigger);
1618                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1619                const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1620                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1621            }
1622            else if(!proto->Spells[1].SpellId)
1623            {
1624                sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1625                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1626                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1627            }
1628            else
1629            {
1630                SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1631                if(!spellInfo)
1632                {
1633                    sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1634                    const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1635                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1636                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1637                }
1638                // allowed only in special format
1639                else if(proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN)
1640                {
1641                    sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1642                    const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1643                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1644                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1645                }
1646            }
1647
1648            // spell_3*,spell_4*,spell_5* is empty
1649            for (int j = 2; j < 5; j++)
1650            {
1651                if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1652                {
1653                    sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1654                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1655                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1656                }
1657                else if(proto->Spells[j].SpellId != 0)
1658                {
1659                    sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1660                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1661                }
1662            }
1663        }
1664        // normal spell list
1665        else
1666        {
1667            for (int j = 0; j < 5; j++)
1668            {
1669                if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1670                {
1671                    sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1672                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1673                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1674                }
1675
1676                if(proto->Spells[j].SpellId)
1677                {
1678                    SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1679                    if(!spellInfo)
1680                    {
1681                        sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1682                        const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1683                    }
1684                    // allowed only in special format
1685                    else if(proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN)
1686                    {
1687                        sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1688                        const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1689                    }
1690                }
1691            }
1692        }
1693
1694        if(proto->Bonding >= MAX_BIND_TYPE)
1695            sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1696
1697        if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1698            sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1699
1700        if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1701            sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1702
1703        if(proto->Sheath >= MAX_SHEATHETYPE)
1704        {
1705            sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1706            const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1707        }
1708
1709        if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1710        {
1711            sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1712            const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1713        }
1714
1715        if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1716        {
1717            sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1718            const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1719        }
1720
1721        if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1722        {
1723            sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1724            const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1725        }
1726
1727        if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1728            sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1729
1730        if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1731            sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1732
1733        if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1734            sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1735
1736        for (int j = 0; j < 3; j++)
1737        {
1738            if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1739            {
1740                sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1741                const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1742            }
1743        }
1744
1745        if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1746            sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1747
1748        if(proto->FoodType >= MAX_PET_DIET)
1749        {
1750            sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1751            const_cast<ItemPrototype*>(proto)->FoodType = 0;
1752        }
1753    }
1754
1755    // this DBC used currently only for check item templates in DB.
1756    sItemStore.Clear();
1757}
1758
1759void ObjectMgr::LoadAuctionItems()
1760{
1761    QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1762
1763    if( !result )
1764        return;
1765
1766    barGoLink bar( result->GetRowCount() );
1767
1768    uint32 count = 0;
1769
1770    Field *fields;
1771    do
1772    {
1773        bar.step();
1774
1775        fields = result->Fetch();
1776        uint32 item_guid        = fields[0].GetUInt32();
1777        uint32 item_template    = fields[1].GetUInt32();
1778
1779        ItemPrototype const *proto = GetItemPrototype(item_template);
1780
1781        if(!proto)
1782        {
1783            sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1784            continue;
1785        }
1786
1787        Item *item = NewItemOrBag(proto);
1788
1789        if(!item->LoadFromDB(item_guid,0))
1790        {
1791            delete item;
1792            continue;
1793        }
1794        AddAItem(item);
1795
1796        ++count;
1797    }
1798    while( result->NextRow() );
1799
1800    delete result;
1801
1802    sLog.outString();
1803    sLog.outString( ">> Loaded %u auction items", count );
1804}
1805
1806void ObjectMgr::LoadPetLevelInfo()
1807{
1808    // Loading levels data
1809    {
1810        //                                                 0               1      2   3     4    5    6    7     8    9
1811        QueryResult *result  = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1812
1813        uint32 count = 0;
1814
1815        if (!result)
1816        {
1817            barGoLink bar( 1 );
1818
1819            sLog.outString();
1820            sLog.outString( ">> Loaded %u level pet stats definitions", count );
1821            sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1822            return;
1823        }
1824
1825        barGoLink bar( result->GetRowCount() );
1826
1827        do
1828        {
1829            Field* fields = result->Fetch();
1830
1831            uint32 creature_id = fields[0].GetUInt32();
1832            if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1833            {
1834                sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1835                continue;
1836            }
1837
1838            uint32 current_level = fields[1].GetUInt32();
1839            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1840            {
1841                if(current_level > 255)                     // hardcoded level maximum
1842                    sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1843                else
1844                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1845                continue;
1846            }
1847            else if(current_level < 1)
1848            {
1849                sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1850                continue;
1851            }
1852
1853            PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1854
1855            if(pInfoMapEntry==NULL)
1856                pInfoMapEntry =  new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1857
1858            // data for level 1 stored in [0] array element, ...
1859            PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1860
1861            pLevelInfo->health = fields[2].GetUInt16();
1862            pLevelInfo->mana   = fields[3].GetUInt16();
1863            pLevelInfo->armor  = fields[9].GetUInt16();
1864
1865            for (int i = 0; i < MAX_STATS; i++)
1866            {
1867                pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1868            }
1869
1870            bar.step();
1871            ++count;
1872        }
1873        while (result->NextRow());
1874
1875        delete result;
1876
1877        sLog.outString();
1878        sLog.outString( ">> Loaded %u level pet stats definitions", count );
1879    }
1880
1881    // Fill gaps and check integrity
1882    for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1883    {
1884        PetLevelInfo* pInfo = itr->second;
1885
1886        // fatal error if no level 1 data
1887        if(!pInfo || pInfo[0].health == 0 )
1888        {
1889            sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1890            exit(1);
1891        }
1892
1893        // fill level gaps
1894        for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1895        {
1896            if(pInfo[level].health == 0)
1897            {
1898                sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1899                pInfo[level] = pInfo[level-1];
1900            }
1901        }
1902    }
1903}
1904
1905PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1906{
1907    if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1908        level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1909
1910    PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1911    if(itr == petInfo.end())
1912        return NULL;
1913
1914    return &itr->second[level-1];                           // data for level 1 stored in [0] array element, ...
1915}
1916
1917void ObjectMgr::LoadPlayerInfo()
1918{
1919    // Load playercreate
1920    {
1921        //                                                0     1      2    3     4           5           6
1922        QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1923
1924        uint32 count = 0;
1925
1926        if (!result)
1927        {
1928            barGoLink bar( 1 );
1929
1930            sLog.outString();
1931            sLog.outString( ">> Loaded %u player create definitions", count );
1932            sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1933            exit(1);
1934        }
1935
1936        barGoLink bar( result->GetRowCount() );
1937
1938        do
1939        {
1940            Field* fields = result->Fetch();
1941
1942            uint32 current_race = fields[0].GetUInt32();
1943            uint32 current_class = fields[1].GetUInt32();
1944            uint32 mapId     = fields[2].GetUInt32();
1945            uint32 zoneId    = fields[3].GetUInt32();
1946            float  positionX = fields[4].GetFloat();
1947            float  positionY = fields[5].GetFloat();
1948            float  positionZ = fields[6].GetFloat();
1949
1950            if(current_race >= MAX_RACES)
1951            {
1952                sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1953                continue;
1954            }
1955
1956            ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1957            if(!rEntry)
1958            {
1959                sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1960                continue;
1961            }
1962
1963            if(current_class >= MAX_CLASSES)
1964            {
1965                sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1966                continue;
1967            }
1968
1969            if(!sChrClassesStore.LookupEntry(current_class))
1970            {
1971                sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1972                continue;
1973            }
1974
1975            // accept DB data only for valid position (and non instanceable)
1976            if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1977            {
1978                sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1979                continue;
1980            }
1981
1982            if( sMapStore.LookupEntry(mapId)->Instanceable() )
1983            {
1984                sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1985                continue;
1986            }
1987
1988            PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1989
1990            pInfo->mapId     = mapId;
1991            pInfo->zoneId    = zoneId;
1992            pInfo->positionX = positionX;
1993            pInfo->positionY = positionY;
1994            pInfo->positionZ = positionZ;
1995
1996            pInfo->displayId_m = rEntry->model_m;
1997            pInfo->displayId_f = rEntry->model_f;
1998
1999            bar.step();
2000            ++count;
2001        }
2002        while (result->NextRow());
2003
2004        delete result;
2005
2006        sLog.outString();
2007        sLog.outString( ">> Loaded %u player create definitions", count );
2008    }
2009
2010    // Load playercreate items
2011    {
2012        //                                                0     1      2       3
2013        QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2014
2015        uint32 count = 0;
2016
2017        if (!result)
2018        {
2019            barGoLink bar( 1 );
2020
2021            sLog.outString();
2022            sLog.outString( ">> Loaded %u player create items", count );
2023            sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2024        }
2025        else
2026        {
2027            barGoLink bar( result->GetRowCount() );
2028
2029            do
2030            {
2031                Field* fields = result->Fetch();
2032
2033                uint32 current_race = fields[0].GetUInt32();
2034                if(current_race >= MAX_RACES)
2035                {
2036                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2037                    continue;
2038                }
2039
2040                uint32 current_class = fields[1].GetUInt32();
2041                if(current_class >= MAX_CLASSES)
2042                {
2043                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2044                    continue;
2045                }
2046
2047                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2048
2049                uint32 item_id = fields[2].GetUInt32();
2050
2051                if(!GetItemPrototype(item_id))
2052                {
2053                    sLog.outErrorDb("Item id %u (race %u class %u) in `playercreateinfo_item` table but not listed in `item_template`, ignoring.",item_id,current_race,current_class);
2054                    continue;
2055                }
2056
2057                uint32 amount  = fields[3].GetUInt32();
2058
2059                if(!amount)
2060                {
2061                    sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2062                    continue;
2063                }
2064
2065                pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2066
2067                bar.step();
2068                ++count;
2069            }
2070            while(result->NextRow());
2071
2072            delete result;
2073
2074            sLog.outString();
2075            sLog.outString( ">> Loaded %u player create items", count );
2076        }
2077    }
2078
2079    // Load playercreate spells
2080    {
2081        //                                                0     1      2      3
2082        QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2083
2084        QueryResult *result = NULL;
2085        if(sWorld.getConfig(CONFIG_START_ALL_SPELLS))
2086                result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell_custom");
2087        else
2088                result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2089
2090        uint32 count = 0;
2091
2092        if (!result)
2093        {
2094            barGoLink bar( 1 );
2095
2096            sLog.outString();
2097            sLog.outString( ">> Loaded %u player create spells", count );
2098            sLog.outErrorDb( "Error loading player starting spells or empty table.");
2099        }
2100        else
2101        {
2102            barGoLink bar( result->GetRowCount() );
2103
2104            do
2105            {
2106                Field* fields = result->Fetch();
2107
2108                uint32 current_race = fields[0].GetUInt32();
2109                if(current_race >= MAX_RACES)
2110                {
2111                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2112                    continue;
2113                }
2114
2115                uint32 current_class = fields[1].GetUInt32();
2116                if(current_class >= MAX_CLASSES)
2117                {
2118                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2119                    continue;
2120                }
2121
2122                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2123                pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2124
2125                bar.step();
2126                ++count;
2127            }
2128            while( result->NextRow() );
2129
2130            delete result;
2131
2132            sLog.outString();
2133            sLog.outString( ">> Loaded %u player create spells", count );
2134        }
2135    }
2136
2137    // Load playercreate actions
2138    {
2139        //                                                0     1      2       3       4     5
2140        QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2141
2142        uint32 count = 0;
2143
2144        if (!result)
2145        {
2146            barGoLink bar( 1 );
2147
2148            sLog.outString();
2149            sLog.outString( ">> Loaded %u player create actions", count );
2150            sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2151        }
2152        else
2153        {
2154            barGoLink bar( result->GetRowCount() );
2155
2156            do
2157            {
2158                Field* fields = result->Fetch();
2159
2160                uint32 current_race = fields[0].GetUInt32();
2161                if(current_race >= MAX_RACES)
2162                {
2163                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2164                    continue;
2165                }
2166
2167                uint32 current_class = fields[1].GetUInt32();
2168                if(current_class >= MAX_CLASSES)
2169                {
2170                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2171                    continue;
2172                }
2173
2174                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2175                pInfo->action[0].push_back(fields[2].GetUInt16());
2176                pInfo->action[1].push_back(fields[3].GetUInt16());
2177                pInfo->action[2].push_back(fields[4].GetUInt16());
2178                pInfo->action[3].push_back(fields[5].GetUInt16());
2179
2180                bar.step();
2181                ++count;
2182            }
2183            while( result->NextRow() );
2184
2185            delete result;
2186
2187            sLog.outString();
2188            sLog.outString( ">> Loaded %u player create actions", count );
2189        }
2190    }
2191
2192    // Loading levels data (class only dependent)
2193    {
2194        //                                                 0      1      2       3
2195        QueryResult *result  = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2196
2197        uint32 count = 0;
2198
2199        if (!result)
2200        {
2201            barGoLink bar( 1 );
2202
2203            sLog.outString();
2204            sLog.outString( ">> Loaded %u level health/mana definitions", count );
2205            sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2206            exit(1);
2207        }
2208
2209        barGoLink bar( result->GetRowCount() );
2210
2211        do
2212        {
2213            Field* fields = result->Fetch();
2214
2215            uint32 current_class = fields[0].GetUInt32();
2216            if(current_class >= MAX_CLASSES)
2217            {
2218                sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2219                continue;
2220            }
2221
2222            uint32 current_level = fields[1].GetUInt32();
2223            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2224            {
2225                if(current_level > 255)                     // hardcoded level maximum
2226                    sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2227                else
2228                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2229                continue;
2230            }
2231
2232            PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2233
2234            if(!pClassInfo->levelInfo)
2235                pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2236
2237            PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2238
2239            pClassLevelInfo->basehealth = fields[2].GetUInt16();
2240            pClassLevelInfo->basemana   = fields[3].GetUInt16();
2241
2242            bar.step();
2243            ++count;
2244        }
2245        while (result->NextRow());
2246
2247        delete result;
2248
2249        sLog.outString();
2250        sLog.outString( ">> Loaded %u level health/mana definitions", count );
2251    }
2252
2253    // Fill gaps and check integrity
2254    for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2255    {
2256        // skip non existed classes
2257        if(!sChrClassesStore.LookupEntry(class_))
2258            continue;
2259
2260        PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2261
2262        // fatal error if no level 1 data
2263        if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2264        {
2265            sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2266            exit(1);
2267        }
2268
2269        // fill level gaps
2270        for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2271        {
2272            if(pClassInfo->levelInfo[level].basehealth == 0)
2273            {
2274                sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2275                pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2276            }
2277        }
2278    }
2279
2280    // Loading levels data (class/race dependent)
2281    {
2282        //                                                 0     1      2      3    4    5    6    7
2283        QueryResult *result  = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2284
2285        uint32 count = 0;
2286
2287        if (!result)
2288        {
2289            barGoLink bar( 1 );
2290
2291            sLog.outString();
2292            sLog.outString( ">> Loaded %u level stats definitions", count );
2293            sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2294            exit(1);
2295        }
2296
2297        barGoLink bar( result->GetRowCount() );
2298
2299        do
2300        {
2301            Field* fields = result->Fetch();
2302
2303            uint32 current_race = fields[0].GetUInt32();
2304            if(current_race >= MAX_RACES)
2305            {
2306                sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2307                continue;
2308            }
2309
2310            uint32 current_class = fields[1].GetUInt32();
2311            if(current_class >= MAX_CLASSES)
2312            {
2313                sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2314                continue;
2315            }
2316
2317            uint32 current_level = fields[2].GetUInt32();
2318            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2319            {
2320                if(current_level > 255)                     // hardcoded level maximum
2321                    sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2322                else
2323                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2324                continue;
2325            }
2326
2327            PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2328
2329            if(!pInfo->levelInfo)
2330                pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2331
2332            PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2333
2334            for (int i = 0; i < MAX_STATS; i++)
2335            {
2336                pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2337            }
2338
2339            bar.step();
2340            ++count;
2341        }
2342        while (result->NextRow());
2343
2344        delete result;
2345
2346        sLog.outString();
2347        sLog.outString( ">> Loaded %u level stats definitions", count );
2348    }
2349
2350    // Fill gaps and check integrity
2351    for (int race = 0; race < MAX_RACES; ++race)
2352    {
2353        // skip non existed races
2354        if(!sChrRacesStore.LookupEntry(race))
2355            continue;
2356
2357        for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2358        {
2359            // skip non existed classes
2360            if(!sChrClassesStore.LookupEntry(class_))
2361                continue;
2362
2363            PlayerInfo* pInfo = &playerInfo[race][class_];
2364
2365            // skip non loaded combinations
2366            if(!pInfo->displayId_m || !pInfo->displayId_f)
2367                continue;
2368
2369            // skip expansion races if not playing with expansion
2370            if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2371                continue;
2372
2373            // fatal error if no level 1 data
2374            if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2375            {
2376                sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2377                exit(1);
2378            }
2379
2380            // fill level gaps
2381            for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2382            {
2383                if(pInfo->levelInfo[level].stats[0] == 0)
2384                {
2385                    sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2386                    pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2387                }
2388            }
2389        }
2390    }
2391}
2392
2393void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2394{
2395    if(level < 1 || class_ >= MAX_CLASSES)
2396        return;
2397
2398    PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2399
2400    if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2401        level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2402
2403    *info = pInfo->levelInfo[level-1];
2404}
2405
2406void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2407{
2408    if(level < 1 || race   >= MAX_RACES || class_ >= MAX_CLASSES)
2409        return;
2410
2411    PlayerInfo const* pInfo = &playerInfo[race][class_];
2412    if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2413        return;
2414
2415    if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2416        *info = pInfo->levelInfo[level-1];
2417    else
2418        BuildPlayerLevelInfo(race,class_,level,info);
2419}
2420
2421void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2422{
2423    // base data (last known level)
2424    *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2425
2426    for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2427    {
2428        switch(_class)
2429        {
2430            case CLASS_WARRIOR:
2431                info->stats[STAT_STRENGTH]  += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2432                info->stats[STAT_STAMINA]   += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2433                info->stats[STAT_AGILITY]   += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2434                info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2435                info->stats[STAT_SPIRIT]    += (lvl > 9 && !(lvl%2) ? 1: 0);
2436                break;
2437            case CLASS_PALADIN:
2438                info->stats[STAT_STRENGTH]  += (lvl > 3  ? 1: 0);
2439                info->stats[STAT_STAMINA]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2440                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2441                info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2442                info->stats[STAT_SPIRIT]    += (lvl > 7 ? 1: 0);
2443                break;
2444            case CLASS_HUNTER:
2445                info->stats[STAT_STRENGTH]  += (lvl > 4  ? 1: 0);
2446                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2447                info->stats[STAT_AGILITY]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2448                info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2449                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2450                break;
2451            case CLASS_ROGUE:
2452                info->stats[STAT_STRENGTH]  += (lvl > 5  ? 1: 0);
2453                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2454                info->stats[STAT_AGILITY]   += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2455                info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2456                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2457                break;
2458            case CLASS_PRIEST:
2459                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2460                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2461                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2462                info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2463                info->stats[STAT_SPIRIT]    += (lvl > 3  ? 1: 0);
2464                break;
2465            case CLASS_SHAMAN:
2466                info->stats[STAT_STRENGTH]  += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2467                info->stats[STAT_STAMINA]   += (lvl > 4 ? 1: 0);
2468                info->stats[STAT_AGILITY]   += (lvl > 7 && !(lvl%2) ? 1: 0);
2469                info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2470                info->stats[STAT_SPIRIT]    += (lvl > 4 ? 1: 0);
2471                break;
2472            case CLASS_MAGE:
2473                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2474                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2475                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2476                info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2477                info->stats[STAT_SPIRIT]    += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2478                break;
2479            case CLASS_WARLOCK:
2480                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2481                info->stats[STAT_STAMINA]   += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2482                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2483                info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2484                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2485                break;
2486            case CLASS_DRUID:
2487                info->stats[STAT_STRENGTH]  += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2488                info->stats[STAT_STAMINA]   += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2489                info->stats[STAT_AGILITY]   += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2490                info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2491                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2492        }
2493    }
2494}
2495
2496void ObjectMgr::LoadGuilds()
2497{
2498    Guild *newguild;
2499    uint32 count = 0;
2500
2501    QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2502
2503    if( !result )
2504    {
2505
2506        barGoLink bar( 1 );
2507
2508        bar.step();
2509
2510        sLog.outString();
2511        sLog.outString( ">> Loaded %u guild definitions", count );
2512        return;
2513    }
2514
2515    barGoLink bar( result->GetRowCount() );
2516
2517    do
2518    {
2519        Field *fields = result->Fetch();
2520
2521        bar.step();
2522        ++count;
2523
2524        newguild = new Guild;
2525        if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2526        {
2527            newguild->Disband();
2528            delete newguild;
2529            continue;
2530        }
2531        AddGuild(newguild);
2532
2533    }while( result->NextRow() );
2534
2535    delete result;
2536
2537    sLog.outString();
2538    sLog.outString( ">> Loaded %u guild definitions", count );
2539}
2540
2541void ObjectMgr::LoadArenaTeams()
2542{
2543    uint32 count = 0;
2544
2545    QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2546
2547    if( !result )
2548    {
2549
2550        barGoLink bar( 1 );
2551
2552        bar.step();
2553
2554        sLog.outString();
2555        sLog.outString( ">> Loaded %u arenateam definitions", count );
2556        return;
2557    }
2558
2559    barGoLink bar( result->GetRowCount() );
2560
2561    do
2562    {
2563        Field *fields = result->Fetch();
2564
2565        bar.step();
2566        ++count;
2567
2568        ArenaTeam *newarenateam = new ArenaTeam;
2569        if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2570        {
2571            delete newarenateam;
2572            continue;
2573        }
2574        AddArenaTeam(newarenateam);
2575    }while( result->NextRow() );
2576
2577    delete result;
2578
2579    sLog.outString();
2580    sLog.outString( ">> Loaded %u arenateam definitions", count );
2581}
2582
2583void ObjectMgr::LoadGroups()
2584{
2585    // -- loading groups --
2586    Group *group = NULL;
2587    uint64 leaderGuid = 0;
2588    uint32 count = 0;
2589    //                                                     0         1              2           3           4              5      6      7      8      9      10     11     12     13      14          15
2590    QueryResult *result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2591
2592    if( !result )
2593    {
2594        barGoLink bar( 1 );
2595
2596        bar.step();
2597
2598        sLog.outString();
2599        sLog.outString( ">> Loaded %u group definitions", count );
2600        return;
2601    }
2602
2603    barGoLink bar( result->GetRowCount() );
2604
2605    do
2606    {
2607        bar.step();
2608        Field *fields = result->Fetch();
2609        ++count;
2610        leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2611
2612        group = new Group;
2613        if(!group->LoadGroupFromDB(leaderGuid, result, false))
2614        {
2615            group->Disband();
2616            delete group;
2617            continue;
2618        }
2619        AddGroup(group);
2620    }while( result->NextRow() );
2621
2622    delete result;
2623
2624    sLog.outString();
2625    sLog.outString( ">> Loaded %u group definitions", count );
2626
2627    // -- loading members --
2628    count = 0;
2629    group = NULL;
2630    leaderGuid = 0;
2631    //                                        0           1          2         3
2632    result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2633    if(!result)
2634    {
2635        barGoLink bar( 1 );
2636        bar.step();
2637    }
2638    else
2639    {
2640        barGoLink bar( result->GetRowCount() );
2641        do
2642        {
2643            bar.step();
2644            Field *fields = result->Fetch();
2645            count++;
2646            leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2647            if(!group || group->GetLeaderGUID() != leaderGuid)
2648            {
2649                group = GetGroupByLeader(leaderGuid);
2650                if(!group)
2651                {
2652                    sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2653                    CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2654                    continue;
2655                }
2656            }
2657
2658            if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2659            {
2660                sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2661                CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2662            }
2663        }while( result->NextRow() );
2664        delete result;
2665    }
2666
2667    // clean groups
2668    // TODO: maybe delete from the DB before loading in this case
2669    for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2670    {
2671        if((*itr)->GetMembersCount() < 2)
2672        {
2673            (*itr)->Disband();
2674            delete *itr;
2675            mGroupSet.erase(itr++);
2676        }
2677        else
2678            ++itr;
2679    }
2680
2681    // -- loading instances --
2682    count = 0;
2683    group = NULL;
2684    leaderGuid = 0;
2685    result = CharacterDatabase.PQuery(
2686        //      0           1    2         3          4           5
2687        "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2688        // 6
2689        "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2690        "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2691    );
2692
2693    if(!result)
2694    {
2695        barGoLink bar( 1 );
2696        bar.step();
2697    }
2698    else
2699    {
2700        barGoLink bar( result->GetRowCount() );
2701        do
2702        {
2703            bar.step();
2704            Field *fields = result->Fetch();
2705            count++;
2706            leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2707            if(!group || group->GetLeaderGUID() != leaderGuid)
2708            {
2709                group = GetGroupByLeader(leaderGuid);
2710                if(!group)
2711                {
2712                    sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2713                    continue;
2714                }
2715            }
2716
2717            InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2718            group->BindToInstance(save, fields[3].GetBool(), true);
2719        }while( result->NextRow() );
2720        delete result;
2721    }
2722
2723    sLog.outString();
2724    sLog.outString( ">> Loaded %u group-instance binds total", count );
2725
2726    sLog.outString();
2727    sLog.outString( ">> Loaded %u group members total", count );
2728}
2729
2730void ObjectMgr::LoadQuests()
2731{
2732    // For reload case
2733    for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2734        delete itr->second;
2735    mQuestTemplates.clear();
2736
2737    mExclusiveQuestGroups.clear();
2738
2739    //                                                0      1       2           3             4         5           6     7              8
2740    QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2741    //   9                    10                 11                     12                   13                     14                   15                16
2742        "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2743    //   17          18            19           20           21           22              23                24         25            26
2744        "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2745    //   27     28       29          30               31                32       33              34              35              36
2746        "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2747    //   37          38          39          40          41             42             43             44
2748        "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2749    //   45            46            47            48            49               50               51               52               53             54             54             55
2750        "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2751    //   57                  58                  59                  60                  61                     62                     63                     64
2752        "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2753    //   65             66             67             68
2754        "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2755    //   69                70                71                72                73                74
2756        "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2757    //   75                   76                   77                   78                   79                   80
2758        "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2759    //   81          82          83          84          85             86             87             88
2760        "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2761    //   89              90              91              92              93              94            95            96            97            98
2762        "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2763    //   99             100               101       102           103                104               105         106     107     108
2764        "RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2765    //   109            110            111            112           113              114            115                116                117                118
2766        "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2767    //   119          120
2768        "StartScript, CompleteScript"
2769        " FROM quest_template");
2770    if(result == NULL)
2771    {
2772        barGoLink bar( 1 );
2773        bar.step();
2774
2775        sLog.outString();
2776        sLog.outString( ">> Loaded 0 quests definitions" );
2777        sLog.outErrorDb("`quest_template` table is empty!");
2778        return;
2779    }
2780
2781    // create multimap previous quest for each existed quest
2782    // some quests can have many previous maps set by NextQuestId in previous quest
2783    // for example set of race quests can lead to single not race specific quest
2784    barGoLink bar( result->GetRowCount() );
2785    do
2786    {
2787        bar.step();
2788        Field *fields = result->Fetch();
2789
2790        Quest * newQuest = new Quest(fields);
2791        mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2792    } while( result->NextRow() );
2793
2794    delete result;
2795
2796    // Post processing
2797    for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2798    {
2799        Quest * qinfo = iter->second;
2800
2801        // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2802
2803        if( qinfo->GetQuestMethod() >= 3 )
2804        {
2805            sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2806        }
2807
2808        if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2809        {
2810            sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2811                qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2812            qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2813        }
2814
2815        if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2816        {
2817            if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2818            {
2819                sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2820                qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2821            }
2822        }
2823
2824        if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2825        {
2826            // at auto-reward can be rewarded only RewChoiceItemId[0]
2827            for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2828            {
2829                if(uint32 id = qinfo->RewChoiceItemId[j])
2830                {
2831                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2832                        qinfo->GetQuestId(),j+1,id,j+1);
2833                    // no changes, quest ignore this data
2834                }
2835            }
2836        }
2837
2838        // client quest log visual (area case)
2839        if( qinfo->ZoneOrSort > 0 )
2840        {
2841            if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2842            {
2843                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2844                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2845                // no changes, quest not dependent from this value but can have problems at client
2846            }
2847        }
2848        // client quest log visual (sort case)
2849        if( qinfo->ZoneOrSort < 0 )
2850        {
2851            QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2852            if( !qSort )
2853            {
2854                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2855                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2856                // no changes, quest not dependent from this value but can have problems at client (note some may be 0, we must allow this so no check)
2857            }
2858            //check SkillOrClass value (class case).
2859            if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2860            {
2861                // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2862                if(qinfo->SkillOrClass < 0)
2863                {
2864                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2865                        qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2866                }
2867            }
2868            //check for proper SkillOrClass value (skill case)
2869            if(int32 skill_id =  SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2870            {
2871                // skill is positive value in SkillOrClass
2872                if(qinfo->SkillOrClass != skill_id )
2873                {
2874                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2875                        qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2876                    //override, and force proper value here?
2877                }
2878            }
2879        }
2880
2881        // SkillOrClass (class case)
2882        if( qinfo->SkillOrClass < 0 )
2883        {
2884            if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2885            {
2886                sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2887                    qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2888            }
2889        }
2890        // SkillOrClass (skill case)
2891        if( qinfo->SkillOrClass > 0 )
2892        {
2893            if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2894            {
2895                sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2896                    qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2897            }
2898        }
2899
2900        if( qinfo->RequiredSkillValue )
2901        {
2902            if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2903            {
2904                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2905                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2906                // no changes, quest can't be done for this requirement
2907            }
2908
2909            if( qinfo->SkillOrClass <= 0 )
2910            {
2911                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2912                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2913                // no changes, quest can't be done for this requirement (fail at wrong skill id)
2914            }
2915        }
2916        // else Skill quests can have 0 skill level, this is ok
2917
2918        if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2919        {
2920            sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2921                qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2922            // no changes, quest can't be done for this requirement
2923        }
2924
2925        if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2926        {
2927            sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2928                qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2929            // no changes, quest can't be done for this requirement
2930        }
2931
2932        if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2933        {
2934            sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2935                qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2936            // no changes, quest can't be done for this requirement
2937        }
2938
2939        if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2940        {
2941            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2942                qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2943            // no changes, quest can't be done for this requirement
2944        }
2945
2946        if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2947        {
2948            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2949                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2950            // no changes, quest can't be done for this requirement
2951        }
2952
2953        if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2954        {
2955            sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2956                qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2957            // warning
2958        }
2959
2960        if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2961        {
2962            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2963                qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2964            // warning
2965        }
2966
2967        if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2968        {
2969            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2970                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2971            // warning
2972        }
2973
2974        if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2975        {
2976            sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2977                qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2978            qinfo->CharTitleId = 0;
2979            // quest can't reward this title
2980        }
2981
2982        if(qinfo->SrcItemId)
2983        {
2984            if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2985            {
2986                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2987                    qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2988                qinfo->SrcItemId = 0;                       // quest can't be done for this requirement
2989            }
2990            else if(qinfo->SrcItemCount==0)
2991            {
2992                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2993                    qinfo->GetQuestId(),qinfo->SrcItemId);
2994                qinfo->SrcItemCount = 1;                    // update to 1 for allow quest work for backward comptibility with DB
2995            }
2996        }
2997        else if(qinfo->SrcItemCount>0)
2998        {
2999            sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3000                qinfo->GetQuestId(),qinfo->SrcItemCount);
3001            qinfo->SrcItemCount=0;                          // no quest work changes in fact
3002        }
3003
3004        if(qinfo->SrcSpell)
3005        {
3006            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3007            if(!spellInfo)
3008            {
3009                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3010                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3011                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
3012            }
3013            else if(!SpellMgr::IsSpellValid(spellInfo))
3014            {
3015                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3016                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3017                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
3018            }
3019        }
3020
3021        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3022        {
3023            uint32 id = qinfo->ReqItemId[j];
3024            if(id)
3025            {
3026                if(qinfo->ReqItemCount[j]==0)
3027                {
3028                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3029                        qinfo->GetQuestId(),j+1,id,j+1);
3030                    // no changes, quest can't be done for this requirement
3031                }
3032
3033                qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3034
3035                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3036                {
3037                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3038                        qinfo->GetQuestId(),j+1,id,id);
3039                    qinfo->ReqItemCount[j] = 0;             // prevent incorrect work of quest
3040                }
3041            }
3042            else if(qinfo->ReqItemCount[j]>0)
3043            {
3044                sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3045                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3046                qinfo->ReqItemCount[j] = 0;                 // prevent incorrect work of quest
3047            }
3048        }
3049
3050        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3051        {
3052            uint32 id = qinfo->ReqSourceId[j];
3053            if(id)
3054            {
3055                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3056                {
3057                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3058                        qinfo->GetQuestId(),j+1,id,id);
3059                    // no changes, quest can't be done for this requirement
3060                }
3061
3062                if(!qinfo->ReqSourceCount[j])
3063                {
3064                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3065                        qinfo->GetQuestId(),j+1,id,j+1);
3066                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3067                }
3068
3069                if(!qinfo->ReqSourceRef[j])
3070                {
3071                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3072                        qinfo->GetQuestId(),j+1,id,j+1);
3073                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3074                }
3075            }
3076            else
3077            {
3078                if(qinfo->ReqSourceCount[j]>0)
3079                {
3080                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3081                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3082                    // no changes, quest ignore this data
3083                }
3084
3085                if(qinfo->ReqSourceRef[j]>0)
3086                {
3087                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3088                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3089                    // no changes, quest ignore this data
3090                }
3091            }
3092        }
3093
3094        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3095        {
3096            uint32 ref = qinfo->ReqSourceRef[j];
3097            if(ref)
3098            {
3099                if(ref > QUEST_OBJECTIVES_COUNT)
3100                {
3101                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3102                        qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3103                    // no changes, quest can't be done for this requirement
3104                }
3105                else
3106                if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3107                {
3108                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3109                        qinfo->GetQuestId(),j+1,ref,ref,ref);
3110                    // no changes, quest can't be done for this requirement
3111                }
3112                else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3113                {
3114                    sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3115                        qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3116                    // no changes, quest can't be done for this requirement
3117                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3118                }
3119            }
3120        }
3121
3122        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3123        {
3124            uint32 id = qinfo->ReqSpell[j];
3125            if(id)
3126            {
3127                SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3128                if(!spellInfo)
3129                {
3130                    sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3131                        qinfo->GetQuestId(),j+1,id,id);
3132                    // no changes, quest can't be done for this requirement
3133                }
3134
3135                if(!qinfo->ReqCreatureOrGOId[j])
3136                {
3137                    bool found = false;
3138                    for(int k = 0; k < 3; ++k)
3139                    {
3140                        if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3141                            spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3142                        {
3143                            found = true;
3144                            break;
3145                        }
3146                    }
3147
3148                    if(found)
3149                    {
3150                        if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3151                        {
3152                            sLog.outErrorDb("Spell (id: %u) have SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT for quest %u and ReqCreatureOrGOId%d = 0, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Quest flags or ReqCreatureOrGOId%d must be fixed, quest modified to enable objective.",spellInfo->Id,qinfo->QuestId,j+1,j+1);
3153
3154                            // this will prevent quest completing without objective
3155                            const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3156                        }
3157                    }
3158                    else
3159                    {
3160                        sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u and ReqCreatureOrGOId%d = 0 but spell %u does not have SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT effect for this quest, quest can't be done.",
3161                            qinfo->GetQuestId(),j+1,id,j+1,id);
3162                        // no changes, quest can't be done for this requirement
3163                    }
3164                }
3165            }
3166        }
3167
3168        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3169        {
3170            int32 id = qinfo->ReqCreatureOrGOId[j];
3171            if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3172            {
3173                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3174                    qinfo->GetQuestId(),j+1,id,uint32(-id));
3175                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3176            }
3177
3178            if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3179            {
3180                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3181                    qinfo->GetQuestId(),j+1,id,uint32(id));
3182                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3183            }
3184
3185            if(id)
3186            {
3187                // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3188
3189                qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3190
3191                if(!qinfo->ReqCreatureOrGOCount[j])
3192                {
3193                    sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3194                        qinfo->GetQuestId(),j+1,id,j+1);
3195                    // no changes, quest can be incorrectly done, but we already report this
3196                }
3197            }
3198            else if(qinfo->ReqCreatureOrGOCount[j]>0)
3199            {
3200                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3201                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3202                // no changes, quest ignore this data
3203            }
3204        }
3205
3206        for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3207        {
3208            uint32 id = qinfo->RewChoiceItemId[j];
3209            if(id)
3210            {
3211                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3212                {
3213                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3214                        qinfo->GetQuestId(),j+1,id,id);
3215                    qinfo->RewChoiceItemId[j] = 0;          // no changes, quest will not reward this
3216                }
3217
3218                if(!qinfo->RewChoiceItemCount[j])
3219                {
3220                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3221                        qinfo->GetQuestId(),j+1,id,j+1);
3222                    // no changes, quest can't be done
3223                }
3224            }
3225            else if(qinfo->RewChoiceItemCount[j]>0)
3226            {
3227                sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3228                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3229                // no changes, quest ignore this data
3230            }
3231        }
3232
3233        for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3234        {
3235            uint32 id = qinfo->RewItemId[j];
3236            if(id)
3237            {
3238                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3239                {
3240                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3241                        qinfo->GetQuestId(),j+1,id,id);
3242                    qinfo->RewItemId[j] = 0;                // no changes, quest will not reward this item
3243                }
3244
3245                if(!qinfo->RewItemCount[j])
3246                {
3247                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3248                        qinfo->GetQuestId(),j+1,id,j+1);
3249                    // no changes
3250                }
3251            }
3252            else if(qinfo->RewItemCount[j]>0)
3253            {
3254                sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3255                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3256                // no changes, quest ignore this data
3257            }
3258        }
3259
3260        for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3261        {
3262            if(qinfo->RewRepFaction[j])
3263            {
3264                if(!qinfo->RewRepValue[j])
3265                {
3266                    sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3267                        qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3268                    // no changes
3269                }
3270
3271                if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3272                {
3273                    sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but raw faction (faction.dbc) %u does not exist, quest will not reward reputation for this faction.",
3274                        qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3275                    qinfo->RewRepFaction[j] = 0;            // quest will not reward this
3276                }
3277            }
3278            else if(qinfo->RewRepValue[j]!=0)
3279            {
3280                sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3281                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3282                // no changes, quest ignore this data
3283            }
3284        }
3285
3286        if(qinfo->RewSpell)
3287        {
3288            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3289
3290            if(!spellInfo)
3291            {
3292                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3293                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3294                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3295            }
3296
3297            else if(!SpellMgr::IsSpellValid(spellInfo))
3298            {
3299                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3300                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3301                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3302            }
3303
3304        }
3305
3306        if(qinfo->RewSpellCast)
3307        {
3308            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3309
3310            if(!spellInfo)
3311            {
3312                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3313                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3314                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3315            }
3316
3317            else if(!SpellMgr::IsSpellValid(spellInfo))
3318            {
3319                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3320                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3321                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3322            }
3323
3324        }
3325
3326        if(qinfo->RewMailTemplateId)
3327        {
3328            if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3329            {
3330                sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template  %u does not exist, quest will not have a mail reward.",
3331                    qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3332                qinfo->RewMailTemplateId = 0;               // no mail will send to player
3333                qinfo->RewMailDelaySecs = 0;                // no mail will send to player
3334            }
3335        }
3336
3337        if(qinfo->NextQuestInChain)
3338        {
3339            if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3340            {
3341                sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3342                    qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3343                qinfo->NextQuestInChain = 0;
3344            }
3345            else
3346                mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3347        }
3348
3349        // fill additional data stores
3350        if(qinfo->PrevQuestId)
3351        {
3352            if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3353            {
3354                sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3355            }
3356            else
3357            {
3358                qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3359            }
3360        }
3361
3362        if(qinfo->NextQuestId)
3363        {
3364            if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3365            {
3366                sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3367            }
3368            else
3369            {
3370                int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3371                mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3372            }
3373        }
3374
3375        if(qinfo->ExclusiveGroup)
3376            mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3377        if(qinfo->LimitTime)
3378            qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3379    }
3380
3381    // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3382    for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3383    {
3384        SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3385        if(!spellInfo)
3386            continue;
3387
3388        for(int j = 0; j < 3; ++j)
3389        {
3390            if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3391                continue;
3392
3393            uint32 quest_id = spellInfo->EffectMiscValue[j];
3394
3395            Quest const* quest = GetQuestTemplate(quest_id);
3396
3397            // some quest referenced in spells not exist (outdataed spells)
3398            if(!quest)
3399                continue;
3400
3401            if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3402            {
3403                sLog.outErrorDb("Spell (id: %u) have SPELL_EFFECT_QUEST_COMPLETE for quest %u , but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Quest flags must be fixed, quest modified to enable objective.",spellInfo->Id,quest_id);
3404
3405                // this will prevent quest completing without objective
3406                const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3407            }
3408        }
3409    }
3410
3411    sLog.outString();
3412    sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3413}
3414
3415void ObjectMgr::LoadQuestLocales()
3416{
3417    QueryResult *result = WorldDatabase.Query("SELECT entry,"
3418        "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3419        "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3420        "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3421        "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3422        "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3423        "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3424        "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3425        "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3426        " FROM locales_quest"
3427        );
3428
3429    if(!result)
3430    {
3431        barGoLink bar(1);
3432
3433        bar.step();
3434
3435        sLog.outString("");
3436        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3437        return;
3438    }
3439
3440    barGoLink bar(result->GetRowCount());
3441
3442    do
3443    {
3444        Field *fields = result->Fetch();
3445        bar.step();
3446
3447        uint32 entry = fields[0].GetUInt32();
3448
3449        QuestLocale& data = mQuestLocaleMap[entry];
3450
3451        for(int i = 1; i < MAX_LOCALE; ++i)
3452        {
3453            std::string str = fields[1+10*(i-1)].GetCppString();
3454            if(!str.empty())
3455            {
3456                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3457                if(idx >= 0)
3458                {
3459                    if(data.Title.size() <= idx)
3460                        data.Title.resize(idx+1);
3461
3462                    data.Title[idx] = str;
3463                }
3464            }
3465            str = fields[1+10*(i-1)+1].GetCppString();
3466            if(!str.empty())
3467            {
3468                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3469                if(idx >= 0)
3470                {
3471                    if(data.Details.size() <= idx)
3472                        data.Details.resize(idx+1);
3473
3474                    data.Details[idx] = str;
3475                }
3476            }
3477            str = fields[1+10*(i-1)+2].GetCppString();
3478            if(!str.empty())
3479            {
3480                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3481                if(idx >= 0)
3482                {
3483                    if(data.Objectives.size() <= idx)
3484                        data.Objectives.resize(idx+1);
3485
3486                    data.Objectives[idx] = str;
3487                }
3488            }
3489            str = fields[1+10*(i-1)+3].GetCppString();
3490            if(!str.empty())
3491            {
3492                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3493                if(idx >= 0)
3494                {
3495                    if(data.OfferRewardText.size() <= idx)
3496                        data.OfferRewardText.resize(idx+1);
3497
3498                    data.OfferRewardText[idx] = str;
3499                }
3500            }
3501            str = fields[1+10*(i-1)+4].GetCppString();
3502            if(!str.empty())
3503            {
3504                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3505                if(idx >= 0)
3506                {
3507                    if(data.RequestItemsText.size() <= idx)
3508                        data.RequestItemsText.resize(idx+1);
3509
3510                    data.RequestItemsText[idx] = str;
3511                }
3512            }
3513            str = fields[1+10*(i-1)+5].GetCppString();
3514            if(!str.empty())
3515            {
3516                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3517                if(idx >= 0)
3518                {
3519                    if(data.EndText.size() <= idx)
3520                        data.EndText.resize(idx+1);
3521
3522                    data.EndText[idx] = str;
3523                }
3524            }
3525            for(int k = 0; k < 4; ++k)
3526            {
3527                str = fields[1+10*(i-1)+6+k].GetCppString();
3528                if(!str.empty())
3529                {
3530                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3531                    if(idx >= 0)
3532                    {
3533                        if(data.ObjectiveText[k].size() <= idx)
3534                            data.ObjectiveText[k].resize(idx+1);
3535
3536                        data.ObjectiveText[k][idx] = str;
3537                    }
3538                }
3539            }
3540        }
3541    } while (result->NextRow());
3542
3543    delete result;
3544
3545    sLog.outString();
3546    sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3547}
3548
3549void ObjectMgr::LoadPetCreateSpells()
3550{
3551    QueryResult *result = WorldDatabase.PQuery("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3552    if(!result)
3553    {
3554        barGoLink bar( 1 );
3555        bar.step();
3556
3557        sLog.outString();
3558        sLog.outString( ">> Loaded 0 pet create spells" );
3559        sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3560        return;
3561    }
3562
3563    uint32 count = 0;
3564
3565    barGoLink bar( result->GetRowCount() );
3566
3567    mPetCreateSpell.clear();
3568
3569    do
3570    {
3571        Field *fields = result->Fetch();
3572        bar.step();
3573
3574        uint32 creature_id = fields[0].GetUInt32();
3575
3576        if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3577            continue;
3578
3579        PetCreateSpellEntry PetCreateSpell;
3580        for(int i = 0; i < 4; i++)
3581        {
3582            PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3583
3584            if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3585                sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3586        }
3587
3588        mPetCreateSpell[creature_id] = PetCreateSpell;
3589
3590        ++count;
3591    }
3592    while (result->NextRow());
3593
3594    delete result;
3595
3596    sLog.outString();
3597    sLog.outString( ">> Loaded %u pet create spells", count );
3598}
3599
3600void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3601{
3602    if(sWorld.IsScriptScheduled())                          // function don't must be called in time scripts use.
3603        return;
3604
3605    sLog.outString( "%s :", tablename);
3606
3607    scripts.clear();                                        // need for reload support
3608
3609    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3610
3611    uint32 count = 0;
3612
3613    if( !result )
3614    {
3615        barGoLink bar( 1 );
3616        bar.step();
3617
3618        sLog.outString();
3619        sLog.outString( ">> Loaded %u script definitions", count );
3620        return;
3621    }
3622
3623    barGoLink bar( result->GetRowCount() );
3624
3625    do
3626    {
3627        bar.step();
3628
3629        Field *fields = result->Fetch();
3630        ScriptInfo tmp;
3631        tmp.id = fields[0].GetUInt32();
3632        tmp.delay = fields[1].GetUInt32();
3633        tmp.command = fields[2].GetUInt32();
3634        tmp.datalong = fields[3].GetUInt32();
3635        tmp.datalong2 = fields[4].GetUInt32();
3636        tmp.datatext = fields[5].GetCppString();
3637        tmp.x = fields[6].GetFloat();
3638        tmp.y = fields[7].GetFloat();
3639        tmp.z = fields[8].GetFloat();
3640        tmp.o = fields[9].GetFloat();
3641
3642        // generic command args check
3643        switch(tmp.command)
3644        {
3645            case SCRIPT_COMMAND_TALK:
3646            {
3647                if(tmp.datalong > 3)
3648                {
3649                    sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3650                    continue;
3651                }
3652                break;
3653            }
3654
3655            case SCRIPT_COMMAND_TELEPORT_TO:
3656            {
3657                if(!sMapStore.LookupEntry(tmp.datalong))
3658                {
3659                    sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3660                    continue;
3661                }
3662
3663                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3664                {
3665                    sLog.outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.x,tmp.y,tmp.id);
3666                    continue;
3667                }
3668                break;
3669            }
3670
3671            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3672            {
3673                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3674                {
3675                    sLog.outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.x,tmp.y,tmp.id);
3676                    continue;
3677                }
3678
3679                if(!GetCreatureTemplate(tmp.datalong))
3680                {
3681                    sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3682                    continue;
3683                }
3684                break;
3685            }
3686
3687            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3688            {
3689                GameObjectData const* data = GetGOData(tmp.datalong);
3690                if(!data)
3691                {
3692                    sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3693                    continue;
3694                }
3695
3696                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3697                if(!info)
3698                {
3699                    sLog.outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,data->id,tmp.id);
3700                    continue;
3701                }
3702
3703                if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3704                    info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3705                    info->type==GAMEOBJECT_TYPE_DOOR        ||
3706                    info->type==GAMEOBJECT_TYPE_BUTTON      ||
3707                    info->type==GAMEOBJECT_TYPE_TRAP )
3708                {
3709                    sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3710                    continue;
3711                }
3712                break;
3713            }
3714            case SCRIPT_COMMAND_OPEN_DOOR:
3715            case SCRIPT_COMMAND_CLOSE_DOOR:
3716            {
3717                GameObjectData const* data = GetGOData(tmp.datalong);
3718                if(!data)
3719                {
3720                    sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in %s for script id %u",tablename,tmp.datalong,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
3721                    continue;
3722                }
3723
3724                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3725                if(!info)
3726                {
3727                    sLog.outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in %s for script id %u",tablename,tmp.datalong,data->id,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
3728                    continue;
3729                }
3730
3731                if( info->type!=GAMEOBJECT_TYPE_DOOR)
3732                {
3733                    sLog.outErrorDb("Table `%s` has gameobject type (%u) non supported by command %s for script id %u",tablename,info->id,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
3734                    continue;
3735                }
3736
3737                break;
3738            }
3739            case SCRIPT_COMMAND_QUEST_EXPLORED:
3740            {
3741                Quest const* quest = GetQuestTemplate(tmp.datalong);
3742                if(!quest)
3743                {
3744                    sLog.outErrorDb("Table `%s` has invalid quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",tablename,tmp.datalong,tmp.id);
3745                    continue;
3746                }
3747
3748                if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3749                {
3750                    sLog.outErrorDb("Table `%s` has quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.",tablename,tmp.datalong,tmp.id);
3751
3752                    // this will prevent quest completing without objective
3753                    const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3754
3755                    // continue; - quest objective requiremet set and command can be allowed
3756                }
3757
3758                if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3759                {
3760                    sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",tablename,tmp.datalong2,tmp.id);
3761                    continue;
3762                }
3763
3764                if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3765                {
3766                    sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(DEFAULT_VISIBILITY_DISTANCE));
3767                    continue;
3768                }
3769
3770                if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3771                {
3772                    sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(INTERACTION_DISTANCE));
3773                    continue;
3774                }
3775
3776                break;
3777            }
3778
3779            case SCRIPT_COMMAND_REMOVE_AURA:
3780            case SCRIPT_COMMAND_CAST_SPELL:
3781            {
3782                if(!sSpellStore.LookupEntry(tmp.datalong))
3783                {
3784                    sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",tablename,tmp.datalong,tmp.id);
3785                    continue;
3786                }
3787                break;
3788            }
3789        }
3790
3791        if (scripts.find(tmp.id) == scripts.end())
3792        {
3793            ScriptMap emptyMap;
3794            scripts[tmp.id] = emptyMap;
3795        }
3796        scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3797
3798        ++count;
3799    } while( result->NextRow() );
3800
3801    delete result;
3802
3803    sLog.outString();
3804    sLog.outString( ">> Loaded %u script definitions", count );
3805}
3806
3807void ObjectMgr::LoadGameObjectScripts()
3808{
3809    LoadScripts(sGameObjectScripts,    "gameobject_scripts");
3810
3811    // check ids
3812    for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3813    {
3814        if(!GetGOData(itr->first))
3815            sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3816    }
3817}
3818
3819void ObjectMgr::LoadQuestEndScripts()
3820{
3821    LoadScripts(sQuestEndScripts,  "quest_end_scripts");
3822
3823    // check ids
3824    for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3825    {
3826        if(!GetQuestTemplate(itr->first))
3827            sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3828    }
3829}
3830
3831void ObjectMgr::LoadQuestStartScripts()
3832{
3833    LoadScripts(sQuestStartScripts,"quest_start_scripts");
3834
3835    // check ids
3836    for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3837    {
3838        if(!GetQuestTemplate(itr->first))
3839            sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3840    }
3841}
3842
3843void ObjectMgr::LoadSpellScripts()
3844{
3845    LoadScripts(sSpellScripts, "spell_scripts");
3846
3847    // check ids
3848    for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3849    {
3850        SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3851
3852        if(!spellInfo)
3853        {
3854            sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3855            continue;
3856        }
3857
3858        //check for correct spellEffect
3859        bool found = false;
3860        for(int i=0; i<3; ++i)
3861        {
3862            // skip empty effects
3863            if( !spellInfo->Effect[i] )
3864                continue;
3865
3866            if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3867            {
3868                found =  true;
3869                break;
3870            }
3871        }
3872
3873        if(!found)
3874            sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3875    }
3876}
3877
3878void ObjectMgr::LoadEventScripts()
3879{
3880    LoadScripts(sEventScripts, "event_scripts");
3881
3882    std::set<uint32> evt_scripts;
3883    // Load all possible script entries from gameobjects
3884    for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3885    {
3886        GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3887        if (goInfo)
3888        {
3889            switch(goInfo->type)
3890            {
3891                case GAMEOBJECT_TYPE_GOOBER:
3892                    if(goInfo->goober.eventId)
3893                        evt_scripts.insert(goInfo->goober.eventId);
3894                    break;
3895                case GAMEOBJECT_TYPE_CHEST:
3896                    if(goInfo->chest.eventId)
3897                        evt_scripts.insert(goInfo->chest.eventId);
3898                    break;
3899                default:
3900                    break;
3901            }
3902        }
3903    }
3904    // Load all possible script entries from spells
3905    for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3906    {
3907        SpellEntry const * spell = sSpellStore.LookupEntry(i);
3908        if (spell)
3909        {
3910            for(int j=0; j<3; ++j)
3911            {
3912                if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3913                {
3914                    if (spell->EffectMiscValue[j])
3915                        evt_scripts.insert(spell->EffectMiscValue[j]);
3916                }
3917            }
3918        }
3919    }
3920    // Then check if all scripts are in above list of possible script entries
3921    for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3922    {
3923        std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3924        if (itr2 == evt_scripts.end())
3925            sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not refering to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
3926    }
3927}
3928
3929void ObjectMgr::LoadItemTexts()
3930{
3931    QueryResult *result = CharacterDatabase.PQuery("SELECT id, text FROM item_text");
3932
3933    uint32 count = 0;
3934
3935    if( !result )
3936    {
3937        barGoLink bar( 1 );
3938        bar.step();
3939
3940        sLog.outString();
3941        sLog.outString( ">> Loaded %u item pages", count );
3942        return;
3943    }
3944
3945    barGoLink bar( result->GetRowCount() );
3946
3947    Field* fields;
3948    do
3949    {
3950        bar.step();
3951
3952        fields = result->Fetch();
3953
3954        mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3955
3956        ++count;
3957
3958    } while ( result->NextRow() );
3959
3960    delete result;
3961
3962    sLog.outString();
3963    sLog.outString( ">> Loaded %u item texts", count );
3964}
3965
3966void ObjectMgr::LoadPageTexts()
3967{
3968    sPageTextStore.Free();                                  // for reload case
3969
3970    sPageTextStore.Load();
3971    sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3972    sLog.outString();
3973
3974    for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3975    {
3976        // check data correctness
3977        PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3978        if(!page)
3979            continue;
3980
3981        if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3982        {
3983            sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3984            continue;
3985        }
3986
3987        // detect circular reference
3988        std::set<uint32> checkedPages;
3989        for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
3990        {
3991            if(!pageItr->Next_Page)
3992                break;
3993            checkedPages.insert(pageItr->Page_ID);
3994            if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
3995            {
3996                std::ostringstream ss;
3997                ss<< "The text page(s) ";
3998                for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
3999                    ss << *itr << " ";
4000                ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4001                    << pageItr->Page_ID <<" to 0";
4002                sLog.outErrorDb(ss.str().c_str());
4003                const_cast<PageText*>(pageItr)->Next_Page = 0;
4004                break;
4005            }
4006        }
4007    }
4008}
4009
4010void ObjectMgr::LoadPageTextLocales()
4011{
4012    QueryResult *result = WorldDatabase.PQuery("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4013
4014    if(!result)
4015    {
4016        barGoLink bar(1);
4017
4018        bar.step();
4019
4020        sLog.outString("");
4021        sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4022        return;
4023    }
4024
4025    barGoLink bar(result->GetRowCount());
4026
4027    do
4028    {
4029        Field *fields = result->Fetch();
4030        bar.step();
4031
4032        uint32 entry = fields[0].GetUInt32();
4033
4034        PageTextLocale& data = mPageTextLocaleMap[entry];
4035
4036        for(int i = 1; i < MAX_LOCALE; ++i)
4037        {
4038            std::string str = fields[i].GetCppString();
4039            if(str.empty())
4040                continue;
4041
4042            int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4043            if(idx >= 0)
4044            {
4045                if(data.Text.size() <= idx)
4046                    data.Text.resize(idx+1);
4047
4048                data.Text[idx] = str;
4049            }
4050        }
4051
4052    } while (result->NextRow());
4053
4054    delete result;
4055
4056    sLog.outString();
4057    sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4058}
4059
4060void ObjectMgr::LoadInstanceTemplate()
4061{
4062    sInstanceTemplate.Load();
4063
4064    for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4065    {
4066        InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4067        if(!temp) continue;
4068        const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4069        if(!entry)
4070        {
4071            sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4072            continue;
4073        }
4074        else if(!entry->HasResetTime())
4075            continue;
4076
4077        if(temp->reset_delay == 0)
4078        {
4079            // use defaults from the DBC
4080            if(entry->SupportsHeroicMode())
4081            {
4082                temp->reset_delay = entry->resetTimeHeroic / DAY;
4083            }
4084            else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4085            {
4086                temp->reset_delay = entry->resetTimeRaid / DAY;
4087            }
4088        }
4089
4090        // the reset_delay must be atleast one day
4091        temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4092    }
4093
4094    sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4095    sLog.outString();
4096}
4097
4098void ObjectMgr::AddGossipText(GossipText *pGText)
4099{
4100    ASSERT( pGText->Text_ID );
4101    ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4102    mGossipText[pGText->Text_ID] = pGText;
4103}
4104
4105GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4106{
4107    GossipTextMap::const_iterator itr;
4108    for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4109    {
4110        if(itr->second->Text_ID == Text_ID)
4111            return itr->second;
4112    }
4113    return NULL;
4114}
4115
4116void ObjectMgr::LoadGossipText()
4117{
4118    GossipText *pGText;
4119    QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4120
4121    int count = 0;
4122    if( !result )
4123    {
4124        barGoLink bar( 1 );
4125        bar.step();
4126
4127        sLog.outString();
4128        sLog.outString( ">> Loaded %u npc texts", count );
4129        return;
4130    }
4131
4132    int cic;
4133
4134    barGoLink bar( result->GetRowCount() );
4135
4136    do
4137    {
4138        ++count;
4139        cic = 0;
4140
4141        Field *fields = result->Fetch();
4142
4143        bar.step();
4144
4145        pGText = new GossipText;
4146        pGText->Text_ID    = fields[cic++].GetUInt32();
4147
4148        for (int i=0; i< 8; i++)
4149        {
4150            pGText->Options[i].Text_0           = fields[cic++].GetCppString();
4151            pGText->Options[i].Text_1           = fields[cic++].GetCppString();
4152
4153            pGText->Options[i].Language         = fields[cic++].GetUInt32();
4154            pGText->Options[i].Probability      = fields[cic++].GetFloat();
4155
4156            pGText->Options[i].Emotes[0]._Delay  = fields[cic++].GetUInt32();
4157            pGText->Options[i].Emotes[0]._Emote  = fields[cic++].GetUInt32();
4158
4159            pGText->Options[i].Emotes[1]._Delay  = fields[cic++].GetUInt32();
4160            pGText->Options[i].Emotes[1]._Emote  = fields[cic++].GetUInt32();
4161
4162            pGText->Options[i].Emotes[2]._Delay  = fields[cic++].GetUInt32();
4163            pGText->Options[i].Emotes[2]._Emote  = fields[cic++].GetUInt32();
4164        }
4165
4166        if ( !pGText->Text_ID ) continue;
4167        AddGossipText( pGText );
4168
4169    } while( result->NextRow() );
4170
4171    sLog.outString();
4172    sLog.outString( ">> Loaded %u npc texts", count );
4173    delete result;
4174}
4175
4176void ObjectMgr::LoadNpcTextLocales()
4177{
4178    QueryResult *result = WorldDatabase.Query("SELECT entry,"
4179        "Text0_0_loc1,Text0_1_loc1,Text1_0_loc1,Text1_1_loc1,Text2_0_loc1,Text2_1_loc1,Text3_0_loc1,Text3_1_loc1,Text4_0_loc1,Text4_1_loc1,Text5_0_loc1,Text5_1_loc1,Text6_0_loc1,Text6_1_loc1,Text7_0_loc1,Text7_1_loc1,"
4180        "Text0_0_loc2,Text0_1_loc2,Text1_0_loc2,Text1_1_loc2,Text2_0_loc2,Text2_1_loc2,Text3_0_loc2,Text3_1_loc1,Text4_0_loc2,Text4_1_loc2,Text5_0_loc2,Text5_1_loc2,Text6_0_loc2,Text6_1_loc2,Text7_0_loc2,Text7_1_loc2,"
4181        "Text0_0_loc3,Text0_1_loc3,Text1_0_loc3,Text1_1_loc3,Text2_0_loc3,Text2_1_loc3,Text3_0_loc3,Text3_1_loc1,Text4_0_loc3,Text4_1_loc3,Text5_0_loc3,Text5_1_loc3,Text6_0_loc3,Text6_1_loc3,Text7_0_loc3,Text7_1_loc3,"
4182        "Text0_0_loc4,Text0_1_loc4,Text1_0_loc4,Text1_1_loc4,Text2_0_loc4,Text2_1_loc4,Text3_0_loc4,Text3_1_loc1,Text4_0_loc4,Text4_1_loc4,Text5_0_loc4,Text5_1_loc4,Text6_0_loc4,Text6_1_loc4,Text7_0_loc4,Text7_1_loc4,"
4183        "Text0_0_loc5,Text0_1_loc5,Text1_0_loc5,Text1_1_loc5,Text2_0_loc5,Text2_1_loc5,Text3_0_loc5,Text3_1_loc1,Text4_0_loc5,Text4_1_loc5,Text5_0_loc5,Text5_1_loc5,Text6_0_loc5,Text6_1_loc5,Text7_0_loc5,Text7_1_loc5,"
4184        "Text0_0_loc6,Text0_1_loc6,Text1_0_loc6,Text1_1_loc6,Text2_0_loc6,Text2_1_loc6,Text3_0_loc6,Text3_1_loc1,Text4_0_loc6,Text4_1_loc6,Text5_0_loc6,Text5_1_loc6,Text6_0_loc6,Text6_1_loc6,Text7_0_loc6,Text7_1_loc6,"
4185        "Text0_0_loc7,Text0_1_loc7,Text1_0_loc7,Text1_1_loc7,Text2_0_loc7,Text2_1_loc7,Text3_0_loc7,Text3_1_loc1,Text4_0_loc7,Text4_1_loc7,Text5_0_loc7,Text5_1_loc7,Text6_0_loc7,Text6_1_loc7,Text7_0_loc7,Text7_1_loc7, "
4186        "Text0_0_loc8,Text0_1_loc8,Text1_0_loc8,Text1_1_loc8,Text2_0_loc8,Text2_1_loc8,Text3_0_loc8,Text3_1_loc1,Text4_0_loc8,Text4_1_loc8,Text5_0_loc8,Text5_1_loc8,Text6_0_loc8,Text6_1_loc8,Text7_0_loc8,Text7_1_loc8 "
4187        " FROM locales_npc_text");
4188
4189    if(!result)
4190    {
4191        barGoLink bar(1);
4192
4193        bar.step();
4194
4195        sLog.outString("");
4196        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4197        return;
4198    }
4199
4200    barGoLink bar(result->GetRowCount());
4201
4202    do
4203    {
4204        Field *fields = result->Fetch();
4205        bar.step();
4206
4207        uint32 entry = fields[0].GetUInt32();
4208
4209        NpcTextLocale& data = mNpcTextLocaleMap[entry];
4210
4211        for(int i=1; i<MAX_LOCALE; ++i)
4212        {
4213            for(int j=0; j<8; ++j)
4214            {
4215                std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4216                if(!str0.empty())
4217                {
4218                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4219                    if(idx >= 0)
4220                    {
4221                        if(data.Text_0[j].size() <= idx)
4222                            data.Text_0[j].resize(idx+1);
4223
4224                        data.Text_0[j][idx] = str0;
4225                    }
4226                }
4227                std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4228                if(!str1.empty())
4229                {
4230                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4231                    if(idx >= 0)
4232                    {
4233                        if(data.Text_1[j].size() <= idx)
4234                            data.Text_1[j].resize(idx+1);
4235
4236                        data.Text_1[j][idx] = str1;
4237                    }
4238                }
4239            }
4240        }
4241    } while (result->NextRow());
4242
4243    delete result;
4244
4245    sLog.outString();
4246    sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4247}
4248
4249//not very fast function but it is called only once a day, or on starting-up
4250void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4251{
4252    time_t basetime = time(NULL);
4253    sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4254    //delete all old mails without item and without body immediately, if starting server
4255    if (!serverUp)
4256        CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4257    //                                                     0  1           2      3        4          5         6           7   8       9
4258    QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" I64FMTD "'", (uint64)basetime);
4259    if ( !result )
4260        return;                                             // any mails need to be returned or deleted
4261    Field *fields;
4262    //std::ostringstream delitems, delmails; //will be here for optimization
4263    //bool deletemail = false, deleteitem = false;
4264    //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4265    //delmails << "DELETE FROM mail WHERE id IN ( "
4266    do
4267    {
4268        fields = result->Fetch();
4269        Mail *m = new Mail;
4270        m->messageID = fields[0].GetUInt32();
4271        m->messageType = fields[1].GetUInt8();
4272        m->sender = fields[2].GetUInt32();
4273        m->receiver = fields[3].GetUInt32();
4274        m->itemTextId = fields[4].GetUInt32();
4275        bool has_items = fields[5].GetBool();
4276        m->expire_time = (time_t)fields[6].GetUInt64();
4277        m->deliver_time = 0;
4278        m->COD = fields[7].GetUInt32();
4279        m->checked = fields[8].GetUInt32();
4280        m->mailTemplateId = fields[9].GetInt16();
4281
4282        Player *pl = 0;
4283        if (serverUp)
4284            pl = GetPlayer((uint64)m->receiver);
4285        if (pl && pl->m_mailsLoaded)
4286        {                                                   //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4287            //his in mailbox and he has already listed his mails )
4288            delete m;
4289            continue;
4290        }
4291        //delete or return mail:
4292        if (has_items)
4293        {
4294            QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4295            if(resultItems)
4296            {
4297                do
4298                {
4299                    Field *fields2 = resultItems->Fetch();
4300
4301                    uint32 item_guid_low = fields2[0].GetUInt32();
4302                    uint32 item_template = fields2[1].GetUInt32();
4303
4304                    m->AddItem(item_guid_low, item_template);
4305                }
4306                while (resultItems->NextRow());
4307
4308                delete resultItems;
4309            }
4310            //if it is mail from AH, it shouldn't be returned, but deleted
4311            if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4312            {
4313                // mail open and then not returned
4314                for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4315                    CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4316            }
4317            else
4318            {
4319                //mail will be returned:
4320                CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4321                delete m;
4322                continue;
4323            }
4324        }
4325
4326        if (m->itemTextId)
4327            CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4328
4329        //deletemail = true;
4330        //delmails << m->messageID << ", ";
4331        CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4332        delete m;
4333    } while (result->NextRow());
4334    delete result;
4335}
4336
4337void ObjectMgr::LoadQuestAreaTriggers()
4338{
4339    mQuestAreaTriggerMap.clear();                           // need for reload case
4340
4341    QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4342
4343    uint32 count = 0;
4344
4345    if( !result )
4346    {
4347        barGoLink bar( 1 );
4348        bar.step();
4349
4350        sLog.outString();
4351        sLog.outString( ">> Loaded %u quest trigger points", count );
4352        return;
4353    }
4354
4355    barGoLink bar( result->GetRowCount() );
4356
4357    do
4358    {
4359        ++count;
4360        bar.step();
4361
4362        Field *fields = result->Fetch();
4363
4364        uint32 trigger_ID = fields[0].GetUInt32();
4365        uint32 quest_ID   = fields[1].GetUInt32();
4366
4367        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4368        if(!atEntry)
4369        {
4370            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4371            continue;
4372        }
4373
4374        Quest const* quest = GetQuestTemplate(quest_ID);
4375
4376        if(!quest)
4377        {
4378            sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4379            continue;
4380        }
4381
4382        if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4383        {
4384            sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not quest %u, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Trigger or quest flags must be fixed, quest modified to require objective.",trigger_ID,quest_ID);
4385
4386            // this will prevent quest completing without objective
4387            const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4388
4389            // continue; - quest modified to required obkective and trigger can be allowed.
4390        }
4391
4392        mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4393
4394    } while( result->NextRow() );
4395
4396    delete result;
4397
4398    sLog.outString();
4399    sLog.outString( ">> Loaded %u quest trigger points", count );
4400}
4401
4402void ObjectMgr::LoadTavernAreaTriggers()
4403{
4404    mTavernAreaTriggerSet.clear();                          // need for reload case
4405
4406    QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4407
4408    uint32 count = 0;
4409
4410    if( !result )
4411    {
4412        barGoLink bar( 1 );
4413        bar.step();
4414
4415        sLog.outString();
4416        sLog.outString( ">> Loaded %u tavern triggers", count );
4417        return;
4418    }
4419
4420    barGoLink bar( result->GetRowCount() );
4421
4422    do
4423    {
4424        ++count;
4425        bar.step();
4426
4427        Field *fields = result->Fetch();
4428
4429        uint32 Trigger_ID      = fields[0].GetUInt32();
4430
4431        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4432        if(!atEntry)
4433        {
4434            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4435            continue;
4436        }
4437
4438        mTavernAreaTriggerSet.insert(Trigger_ID);
4439    } while( result->NextRow() );
4440
4441    delete result;
4442
4443    sLog.outString();
4444    sLog.outString( ">> Loaded %u tavern triggers", count );
4445}
4446
4447void ObjectMgr::LoadAreaTriggerScripts()
4448{
4449    mAreaTriggerScripts.clear();                            // need for reload case
4450    QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4451
4452    uint32 count = 0;
4453
4454    if( !result )
4455    {
4456        barGoLink bar( 1 );
4457        bar.step();
4458
4459        sLog.outString();
4460        sLog.outString( ">> Loaded %u areatrigger scripts", count );
4461        return;
4462    }
4463
4464    barGoLink bar( result->GetRowCount() );
4465
4466    do
4467    {
4468        ++count;
4469        bar.step();
4470
4471        Field *fields = result->Fetch();
4472
4473        uint32 Trigger_ID      = fields[0].GetUInt32();
4474        std::string scriptName = fields[1].GetCppString();
4475
4476        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4477        if(!atEntry)
4478        {
4479            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4480            continue;
4481        }
4482        mAreaTriggerScripts[Trigger_ID] = scriptName;
4483    } while( result->NextRow() );
4484
4485    delete result;
4486
4487    sLog.outString();
4488    sLog.outString( ">> Loaded %u areatrigger scripts", count );
4489}
4490uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4491{
4492    bool found = false;
4493    float dist;
4494    uint32 id = 0;
4495
4496    for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4497    {
4498        TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4499        if(node && node->map_id == mapid)
4500        {
4501            float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4502            if(found)
4503            {
4504                if(dist2 < dist)
4505                {
4506                    dist = dist2;
4507                    id = i;
4508                }
4509            }
4510            else
4511            {
4512                found = true;
4513                dist = dist2;
4514                id = i;
4515            }
4516        }
4517    }
4518
4519    return id;
4520}
4521
4522void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4523{
4524    TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4525    if(src_i==sTaxiPathSetBySource.end())
4526    {
4527        path = 0;
4528        cost = 0;
4529        return;
4530    }
4531
4532    TaxiPathSetForSource& pathSet = src_i->second;
4533
4534    TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4535    if(dest_i==pathSet.end())
4536    {
4537        path = 0;
4538        cost = 0;
4539        return;
4540    }
4541
4542    cost = dest_i->second.price;
4543    path = dest_i->second.ID;
4544}
4545
4546uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4547{
4548    uint16 mount_entry = 0;
4549    uint16 mount_id = 0;
4550
4551    TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4552    if(node)
4553    {
4554        if (team == ALLIANCE)
4555        {
4556            mount_entry = node->alliance_mount_type;
4557            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4558            if(ci)
4559                mount_id = ci->DisplayID_A;
4560        }
4561        if (team == HORDE)
4562        {
4563            mount_entry = node->horde_mount_type;
4564            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4565            if(ci)
4566                mount_id = ci->DisplayID_H;
4567        }
4568    }
4569
4570    CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4571    if(!minfo)
4572    {
4573        sLog.outErrorDb("Taxi mount (Entry: %u) for taxi node (Id: %u) for team %u has model %u not found in table `creature_model_info`, can't load. ",
4574            mount_entry,id,team,mount_id);
4575
4576        return false;
4577    }
4578    if(minfo->modelid_other_gender!=0)
4579        mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4580
4581    return mount_id;
4582}
4583
4584void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4585{
4586    if(path >= sTaxiPathNodesByPath.size())
4587        return;
4588
4589    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4590
4591    pathnodes.Resize(nodeList.size());
4592    mapIds.resize(nodeList.size());
4593
4594    for(size_t i = 0; i < nodeList.size(); ++i)
4595    {
4596        pathnodes[ i ].x = nodeList[i].x;
4597        pathnodes[ i ].y = nodeList[i].y;
4598        pathnodes[ i ].z = nodeList[i].z;
4599
4600        mapIds[i] = nodeList[i].mapid;
4601    }
4602}
4603
4604void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4605{
4606    if(path >= sTaxiPathNodesByPath.size())
4607        return;
4608
4609    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4610
4611    pathnodes.Resize(nodeList.size());
4612
4613    for(size_t i = 0; i < nodeList.size(); ++i)
4614    {
4615        pathnodes[ i ].mapid = nodeList[i].mapid;
4616        pathnodes[ i ].x = nodeList[i].x;
4617        pathnodes[ i ].y = nodeList[i].y;
4618        pathnodes[ i ].z = nodeList[i].z;
4619        pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4620        pathnodes[ i ].delay = nodeList[i].delay;
4621    }
4622}
4623
4624void ObjectMgr::LoadGraveyardZones()
4625{
4626    mGraveYardMap.clear();                                  // need for reload case
4627
4628    QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4629
4630    uint32 count = 0;
4631
4632    if( !result )
4633    {
4634        barGoLink bar( 1 );
4635        bar.step();
4636
4637        sLog.outString();
4638        sLog.outString( ">> Loaded %u graveyard-zone links", count );
4639        return;
4640    }
4641
4642    barGoLink bar( result->GetRowCount() );
4643
4644    do
4645    {
4646        ++count;
4647        bar.step();
4648
4649        Field *fields = result->Fetch();
4650
4651        uint32 safeLocId = fields[0].GetUInt32();
4652        uint32 zoneId = fields[1].GetUInt32();
4653        uint32 team   = fields[2].GetUInt32();
4654
4655        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4656        if(!entry)
4657        {
4658            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4659            continue;
4660        }
4661
4662        AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4663        if(!areaEntry)
4664        {
4665            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4666            continue;
4667        }
4668
4669        if(areaEntry->zone != 0)
4670        {
4671            sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4672            continue;
4673        }
4674
4675        if(team!=0 && team!=HORDE && team!=ALLIANCE)
4676        {
4677            sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4678            continue;
4679        }
4680
4681        if(entry->map_id != areaEntry->mapid && team != 0)
4682        {
4683            sLog.outErrorDb("Table `game_graveyard_zone` has record for ghost zone (%u) at map %u and graveyard (%u) at map %u for team %u, but in case maps are different, player faction setting is ignored. Use faction 0 instead.",zoneId,areaEntry->mapid, safeLocId, entry->map_id, team);
4684            team = 0;
4685        }
4686
4687        if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4688            sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Garveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4689    } while( result->NextRow() );
4690
4691    delete result;
4692
4693    sLog.outString();
4694    sLog.outString( ">> Loaded %u graveyard-zone links", count );
4695}
4696
4697WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4698{
4699    // search for zone associated closest graveyard
4700    uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4701
4702    // Simulate std. algorithm:
4703    //   found some graveyard associated to (ghost_zone,ghost_map)
4704    //
4705    //   if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4706    //     then check faction
4707    //   if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4708    //     then skip check faction
4709    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4710    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4711    if(graveLow==graveUp)
4712    {
4713        sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4714        return NULL;
4715    }
4716
4717    bool foundNear = false;
4718    float distNear;
4719    WorldSafeLocsEntry const* entryNear = NULL;
4720    WorldSafeLocsEntry const* entryFar = NULL;
4721
4722    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4723    {
4724        GraveYardData const& data = itr->second;
4725
4726        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4727        if(!entry)
4728        {
4729            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4730            continue;
4731        }
4732
4733        // remember first graveyard at another map and ignore other
4734        if(MapId != entry->map_id)
4735        {
4736            if(!entryFar)
4737                entryFar = entry;
4738            continue;
4739        }
4740
4741        // skip enemy faction graveyard at same map (normal area, city, or battleground)
4742        // team == 0 case can be at call from .neargrave
4743        if(data.team != 0 && team != 0 && data.team != team)
4744            continue;
4745
4746        // find now nearest graveyard at same map
4747        float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4748        if(foundNear)
4749        {
4750            if(dist2 < distNear)
4751            {
4752                distNear = dist2;
4753                entryNear = entry;
4754            }
4755        }
4756        else
4757        {
4758            foundNear = true;
4759            distNear = dist2;
4760            entryNear = entry;
4761        }
4762    }
4763
4764    if(entryNear)
4765        return entryNear;
4766
4767    return entryFar;
4768}
4769
4770GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4771{
4772    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4773    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4774
4775    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4776    {
4777        if(itr->second.safeLocId==id)
4778            return &itr->second;
4779    }
4780
4781    return NULL;
4782}
4783
4784bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4785{
4786    if(FindGraveYardData(id,zoneId))
4787        return false;
4788
4789    // add link to loaded data
4790    GraveYardData data;
4791    data.safeLocId = id;
4792    data.team = team;
4793
4794    mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4795
4796    // add link to DB
4797    if(inDB)
4798    {
4799        WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4800            "VALUES ('%u', '%u','%u')",id,zoneId,team);
4801    }
4802
4803    return true;
4804}
4805
4806void ObjectMgr::LoadAreaTriggerTeleports()
4807{
4808    mAreaTriggers.clear();                                  // need for reload case
4809
4810    uint32 count = 0;
4811
4812    //                                                0   1               2              3               4           5            6                    7                     8           9                  10                 11                 12
4813    QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
4814    if( !result )
4815    {
4816
4817        barGoLink bar( 1 );
4818
4819        bar.step();
4820
4821        sLog.outString();
4822        sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4823        return;
4824    }
4825
4826    barGoLink bar( result->GetRowCount() );
4827
4828    do
4829    {
4830        Field *fields = result->Fetch();
4831
4832        bar.step();
4833
4834        ++count;
4835
4836        uint32 Trigger_ID = fields[0].GetUInt32();
4837
4838        AreaTrigger at;
4839
4840        at.requiredLevel      = fields[1].GetUInt8();
4841        at.requiredItem       = fields[2].GetUInt32();
4842        at.requiredItem2      = fields[3].GetUInt32();
4843        at.heroicKey          = fields[4].GetUInt32();
4844        at.heroicKey2         = fields[5].GetUInt32();
4845        at.requiredQuest      = fields[6].GetUInt32();
4846        at.requiredFailedText = fields[7].GetCppString();
4847        at.target_mapId       = fields[8].GetUInt32();
4848        at.target_X           = fields[9].GetFloat();
4849        at.target_Y           = fields[10].GetFloat();
4850        at.target_Z           = fields[11].GetFloat();
4851        at.target_Orientation = fields[12].GetFloat();
4852
4853        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4854        if(!atEntry)
4855        {
4856            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4857            continue;
4858        }
4859
4860        if(at.requiredItem)
4861        {
4862            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4863            if(!pProto)
4864            {
4865                sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4866                at.requiredItem = 0;
4867            }
4868        }
4869        if(at.requiredItem2)
4870        {
4871            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4872            if(!pProto)
4873            {
4874                sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4875                at.requiredItem2 = 0;
4876            }
4877        }
4878
4879        if(at.heroicKey)
4880        {
4881            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4882            if(!pProto)
4883            {
4884                sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4885                at.heroicKey = 0;
4886            }
4887        }
4888
4889        if(at.heroicKey2)
4890        {
4891            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4892            if(!pProto)
4893            {
4894                sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4895                at.heroicKey2 = 0;
4896            }
4897        }
4898
4899        if(at.requiredQuest)
4900        {
4901            if(!mQuestTemplates[at.requiredQuest])
4902            {
4903                sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4904                at.requiredQuest = 0;
4905            }
4906        }
4907
4908        MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4909        if(!mapEntry)
4910        {
4911            sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4912            continue;
4913        }
4914
4915        if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4916        {
4917            sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4918            continue;
4919        }
4920
4921        mAreaTriggers[Trigger_ID] = at;
4922
4923    } while( result->NextRow() );
4924
4925    delete result;
4926
4927    sLog.outString();
4928    sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4929}
4930
4931AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
4932{
4933    const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
4934    if(!mapEntry) return NULL;
4935    for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
4936    {
4937        if(itr->second.target_mapId == mapEntry->parent_map)
4938        {
4939            AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
4940            if(atEntry && atEntry->mapid == Map)
4941                return &itr->second;
4942        }
4943    }
4944    return NULL;
4945}
4946
4947void ObjectMgr::SetHighestGuids()
4948{
4949    QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
4950    if( result )
4951    {
4952        m_hiCharGuid = (*result)[0].GetUInt32()+1;
4953
4954        delete result;
4955    }
4956
4957    result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
4958    if( result )
4959    {
4960        m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
4961
4962        delete result;
4963    }
4964
4965    result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
4966    if( result )
4967    {
4968        m_hiPetGuid = (*result)[0].GetUInt32()+1;
4969
4970        delete result;
4971    }
4972
4973    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
4974    if( result )
4975    {
4976        m_hiItemGuid = (*result)[0].GetUInt32()+1;
4977
4978        delete result;
4979    }
4980
4981    // Cleanup other tables from not existed guids (>=m_hiItemGuid)
4982    CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
4983    CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
4984    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
4985    CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
4986
4987    result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
4988    if( result )
4989    {
4990        m_hiGoGuid = (*result)[0].GetUInt32()+1;
4991
4992        delete result;
4993    }
4994
4995    result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
4996    if( result )
4997    {
4998        m_auctionid = (*result)[0].GetUInt32()+1;
4999
5000        delete result;
5001    }
5002    else
5003    {
5004        m_auctionid = 0;
5005    }
5006    result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5007    if( result )
5008    {
5009        m_mailid = (*result)[0].GetUInt32()+1;
5010
5011        delete result;
5012    }
5013    else
5014    {
5015        m_mailid = 0;
5016    }
5017    result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5018    if( result )
5019    {
5020        m_ItemTextId = (*result)[0].GetUInt32();
5021
5022        delete result;
5023    }
5024    else
5025        m_ItemTextId = 0;
5026
5027    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5028    if( result )
5029    {
5030        m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5031
5032        delete result;
5033    }
5034}
5035
5036uint32 ObjectMgr::GenerateAuctionID()
5037{
5038    ++m_auctionid;
5039    if(m_auctionid>=0xFFFFFFFF)
5040    {
5041        sLog.outError("Auctions ids overflow!! Can't continue, shuting down server. ");
5042        sWorld.m_stopEvent = true;
5043    }
5044    return m_auctionid;
5045}
5046
5047uint32 ObjectMgr::GenerateMailID()
5048{
5049    ++m_mailid;
5050    if(m_mailid>=0xFFFFFFFF)
5051    {
5052        sLog.outError("Mail ids overflow!! Can't continue, shuting down server. ");
5053        sWorld.m_stopEvent = true;
5054    }
5055    return m_mailid;
5056}
5057
5058uint32 ObjectMgr::GenerateItemTextID()
5059{
5060    ++m_ItemTextId;
5061    if(m_ItemTextId>=0xFFFFFFFF)
5062    {
5063        sLog.outError("Item text ids overflow!! Can't continue, shuting down server. ");
5064        sWorld.m_stopEvent = true;
5065    }
5066    return m_ItemTextId;
5067}
5068
5069uint32 ObjectMgr::CreateItemText(std::string text)
5070{
5071    uint32 newItemTextId = GenerateItemTextID();
5072    //insert new itempage to container
5073    mItemTexts[ newItemTextId ] = text;
5074    //save new itempage
5075    CharacterDatabase.escape_string(text);
5076    //any Delete query needed, itemTextId is maximum of all ids
5077    std::ostringstream query;
5078    query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5079    CharacterDatabase.Execute(query.str().c_str());         //needs to be run this way, because mail body may be more than 1024 characters
5080    return newItemTextId;
5081}
5082
5083uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5084{
5085    switch(guidhigh)
5086    {
5087        case HIGHGUID_ITEM:
5088            ++m_hiItemGuid;
5089            if(m_hiItemGuid>=0xFFFFFFFF)
5090            {
5091                sLog.outError("Item guid overflow!! Can't continue, shuting down server. ");
5092                sWorld.m_stopEvent = true;
5093            }
5094            return m_hiItemGuid;
5095        case HIGHGUID_UNIT:
5096            ++m_hiCreatureGuid;
5097            if(m_hiCreatureGuid>=0x00FFFFFF)
5098            {
5099                sLog.outError("Creature guid overflow!! Can't continue, shuting down server. ");
5100                sWorld.m_stopEvent = true;
5101            }
5102            return m_hiCreatureGuid;
5103        case HIGHGUID_PET:
5104            ++m_hiPetGuid;
5105            if(m_hiPetGuid>=0x00FFFFFF)
5106            {
5107                sLog.outError("Pet guid overflow!! Can't continue, shuting down server. ");
5108                sWorld.m_stopEvent = true;
5109            }
5110            return m_hiPetGuid;
5111        case HIGHGUID_PLAYER:
5112            ++m_hiCharGuid;
5113            if(m_hiCharGuid>=0xFFFFFFFF)
5114            {
5115                sLog.outError("Players guid overflow!! Can't continue, shuting down server. ");
5116                sWorld.m_stopEvent = true;
5117            }
5118            return m_hiCharGuid;
5119        case HIGHGUID_GAMEOBJECT:
5120            ++m_hiGoGuid;
5121            if(m_hiGoGuid>=0x00FFFFFF)
5122            {
5123                sLog.outError("Gameobject guid overflow!! Can't continue, shuting down server. ");
5124                sWorld.m_stopEvent = true;
5125            }
5126            return m_hiGoGuid;
5127        case HIGHGUID_CORPSE:
5128            ++m_hiCorpseGuid;
5129            if(m_hiCorpseGuid>=0xFFFFFFFF)
5130            {
5131                sLog.outError("Corpse guid overflow!! Can't continue, shuting down server. ");
5132                sWorld.m_stopEvent = true;
5133            }
5134            return m_hiCorpseGuid;
5135        case HIGHGUID_DYNAMICOBJECT:
5136            ++m_hiDoGuid;
5137            if(m_hiDoGuid>=0xFFFFFFFF)
5138            {
5139                sLog.outError("DynamicObject guid overflow!! Can't continue, shuting down server. ");
5140                sWorld.m_stopEvent = true;
5141            }
5142            return m_hiDoGuid;
5143        default:
5144            ASSERT(0);
5145    }
5146
5147    ASSERT(0);
5148    return 0;
5149}
5150
5151void ObjectMgr::LoadGameObjectLocales()
5152{
5153    QueryResult *result = WorldDatabase.Query("SELECT entry,"
5154        "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5155        "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5156        "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5157
5158    if(!result)
5159    {
5160        barGoLink bar(1);
5161
5162        bar.step();
5163
5164        sLog.outString("");
5165        sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5166        return;
5167    }
5168
5169    barGoLink bar(result->GetRowCount());
5170
5171    do
5172    {
5173        Field *fields = result->Fetch();
5174        bar.step();
5175
5176        uint32 entry = fields[0].GetUInt32();
5177
5178        GameObjectLocale& data = mGameObjectLocaleMap[entry];
5179
5180        for(int i = 1; i < MAX_LOCALE; ++i)
5181        {
5182            std::string str = fields[i].GetCppString();
5183            if(!str.empty())
5184            {
5185                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5186                if(idx >= 0)
5187                {
5188                    if(data.Name.size() <= idx)
5189                        data.Name.resize(idx+1);
5190
5191                    data.Name[idx] = str;
5192                }
5193            }
5194        }
5195
5196        for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5197        {
5198            std::string str = fields[i].GetCppString();
5199            if(!str.empty())
5200            {
5201                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5202                if(idx >= 0)
5203                {
5204                    if(data.CastBarCaption.size() <= idx)
5205                        data.CastBarCaption.resize(idx+1);
5206
5207                    data.CastBarCaption[idx] = str;
5208                }
5209            }
5210        }
5211
5212    } while (result->NextRow());
5213
5214    delete result;
5215
5216    sLog.outString();
5217    sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5218}
5219
5220void ObjectMgr::LoadGameobjectInfo()
5221{
5222    sGOStorage.Load();
5223
5224    // some checks
5225    for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5226    {
5227        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5228        if(!goInfo)
5229            continue;
5230
5231        switch(goInfo->type)
5232        {
5233            case GAMEOBJECT_TYPE_DOOR:                      //0
5234            {
5235                if(goInfo->door.lockId)
5236                {
5237                    if(!sLockStore.LookupEntry(goInfo->door.lockId))
5238                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5239                            id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5240                }
5241                break;
5242            }
5243            case GAMEOBJECT_TYPE_BUTTON:                    //1
5244            {
5245                if(goInfo->button.lockId)
5246                {
5247                    if(!sLockStore.LookupEntry(goInfo->button.lockId))
5248                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5249                            id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5250                }
5251                break;
5252            }
5253            case GAMEOBJECT_TYPE_CHEST:                     //3
5254            {
5255                if(goInfo->chest.lockId)
5256                {
5257                    if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5258                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5259                            id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5260                }
5261                if(goInfo->chest.linkedTrapId)              // linked trap
5262                {
5263                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5264                    {
5265                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5266                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5267                                id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5268                    }
5269                    /* disable check for while
5270                    else
5271                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5272                            id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5273                    */
5274                }
5275                break;
5276            }
5277            case GAMEOBJECT_TYPE_TRAP:                      //6
5278            {
5279                /* disable check for while
5280                if(goInfo->trap.spellId)                    // spell
5281                {
5282                    if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5283                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5284                            id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5285                }
5286                */
5287                break;
5288            }
5289            case GAMEOBJECT_TYPE_CHAIR:                     //7
5290                if(goInfo->chair.height > 2)
5291                {
5292                    sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5293                        id,goInfo->type,goInfo->chair.height);
5294
5295                    // prevent client and server unexpected work
5296                    const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5297                }
5298                break;
5299            case GAMEOBJECT_TYPE_SPELL_FOCUS:               //8
5300            {
5301                if(goInfo->spellFocus.focusId)
5302                {
5303                    if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5304                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5305                            id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5306                }
5307
5308                if(goInfo->spellFocus.linkedTrapId)         // linked trap
5309                {
5310                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5311                    {
5312                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5313                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5314                                id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5315                    }
5316                    /* disable check for while
5317                    else
5318                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5319                            id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5320                    */
5321                }
5322                break;
5323            }
5324            case GAMEOBJECT_TYPE_GOOBER:                    //10
5325            {
5326                if(goInfo->goober.pageId)                   // pageId
5327                {
5328                    if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5329                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5330                            id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5331                }
5332                /* disable check for while
5333                if(goInfo->goober.spellId)                  // spell
5334                {
5335                    if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5336                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5337                            id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5338                }
5339                */
5340                if(goInfo->goober.linkedTrapId)             // linked trap
5341                {
5342                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5343                    {
5344                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5345                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5346                                id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5347                    }
5348                    /* disable check for while
5349                    else
5350                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5351                            id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5352                    */
5353                }
5354                break;
5355            }
5356            case GAMEOBJECT_TYPE_MO_TRANSPORT:              //15
5357            {
5358                if(goInfo->moTransport.taxiPathId)
5359                {
5360                    if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5361                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5362                            id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5363                }
5364                break;
5365            }
5366            case GAMEOBJECT_TYPE_SUMMONING_RITUAL:          //18
5367            {
5368                /* disabled
5369                if(goInfo->summoningRitual.spellId)
5370                {
5371                    if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5372                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5373                            id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5374                }
5375                */
5376                break;
5377            }
5378            case GAMEOBJECT_TYPE_SPELLCASTER:               //22
5379            {
5380                if(goInfo->spellcaster.spellId)             // spell
5381                {
5382                    if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5383                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5384                            id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5385                }
5386                break;
5387            }
5388        }
5389    }
5390
5391    sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5392    sLog.outString();
5393}
5394
5395void ObjectMgr::LoadExplorationBaseXP()
5396{
5397    uint32 count = 0;
5398    QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5399
5400    if( !result )
5401    {
5402        barGoLink bar( 1 );
5403
5404        bar.step();
5405
5406        sLog.outString();
5407        sLog.outString( ">> Loaded %u BaseXP definitions", count );
5408        return;
5409    }
5410
5411    barGoLink bar( result->GetRowCount() );
5412
5413    do
5414    {
5415        bar.step();
5416
5417        Field *fields = result->Fetch();
5418        uint32 level  = fields[0].GetUInt32();
5419        uint32 basexp = fields[1].GetUInt32();
5420        mBaseXPTable[level] = basexp;
5421        ++count;
5422    }
5423    while (result->NextRow());
5424
5425    delete result;
5426
5427    sLog.outString();
5428    sLog.outString( ">> Loaded %u BaseXP definitions", count );
5429}
5430
5431uint32 ObjectMgr::GetBaseXP(uint32 level)
5432{
5433    return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5434}
5435
5436void ObjectMgr::LoadPetNames()
5437{
5438    uint32 count = 0;
5439    QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5440
5441    if( !result )
5442    {
5443        barGoLink bar( 1 );
5444
5445        bar.step();
5446
5447        sLog.outString();
5448        sLog.outString( ">> Loaded %u pet name parts", count );
5449        return;
5450    }
5451
5452    barGoLink bar( result->GetRowCount() );
5453
5454    do
5455    {
5456        bar.step();
5457
5458        Field *fields = result->Fetch();
5459        std::string word = fields[0].GetString();
5460        uint32 entry     = fields[1].GetUInt32();
5461        bool   half      = fields[2].GetBool();
5462        if(half)
5463            PetHalfName1[entry].push_back(word);
5464        else
5465            PetHalfName0[entry].push_back(word);
5466        ++count;
5467    }
5468    while (result->NextRow());
5469    delete result;
5470
5471    sLog.outString();
5472    sLog.outString( ">> Loaded %u pet name parts", count );
5473}
5474
5475void ObjectMgr::LoadPetNumber()
5476{
5477    QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5478    if(result)
5479    {
5480        Field *fields = result->Fetch();
5481        m_hiPetNumber = fields[0].GetUInt32()+1;
5482        delete result;
5483    }
5484
5485    barGoLink bar( 1 );
5486    bar.step();
5487
5488    sLog.outString();
5489    sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5490}
5491
5492std::string ObjectMgr::GeneratePetName(uint32 entry)
5493{
5494    std::vector<std::string> & list0 = PetHalfName0[entry];
5495    std::vector<std::string> & list1 = PetHalfName1[entry];
5496
5497    if(list0.empty() || list1.empty())
5498    {
5499        CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5500        char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5501        if(!petname)
5502            petname = cinfo->Name;
5503        return std::string(petname);
5504    }
5505
5506    return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5507}
5508
5509uint32 ObjectMgr::GeneratePetNumber()
5510{
5511    return ++m_hiPetNumber;
5512}
5513
5514void ObjectMgr::LoadCorpses()
5515{
5516    uint32 count = 0;
5517    //                                                     0           1           2           3            4    5     6     7            8         10
5518    QueryResult *result = CharacterDatabase.PQuery("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5519
5520    if( !result )
5521    {
5522        barGoLink bar( 1 );
5523
5524        bar.step();
5525
5526        sLog.outString();
5527        sLog.outString( ">> Loaded %u corpses", count );
5528        return;
5529    }
5530
5531    barGoLink bar( result->GetRowCount() );
5532
5533    do
5534    {
5535        bar.step();
5536
5537        Field *fields = result->Fetch();
5538
5539        uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5540
5541        Corpse *corpse = new Corpse;
5542        if(!corpse->LoadFromDB(guid,fields))
5543        {
5544            delete corpse;
5545            continue;
5546        }
5547
5548        ObjectAccessor::Instance().AddCorpse(corpse);
5549
5550        ++count;
5551    }
5552    while (result->NextRow());
5553    delete result;
5554
5555    sLog.outString();
5556    sLog.outString( ">> Loaded %u corpses", count );
5557}
5558
5559void ObjectMgr::LoadReputationOnKill()
5560{
5561    uint32 count = 0;
5562
5563    //                                                0            1                     2
5564    QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5565    //   3             4             5                   6             7             8                   9
5566        "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5567        "FROM creature_onkill_reputation");
5568
5569    if(!result)
5570    {
5571        barGoLink bar(1);
5572
5573        bar.step();
5574
5575        sLog.outString();
5576        sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5577        return;
5578    }
5579
5580    barGoLink bar(result->GetRowCount());
5581
5582    do
5583    {
5584        Field *fields = result->Fetch();
5585        bar.step();
5586
5587        uint32 creature_id = fields[0].GetUInt32();
5588
5589        ReputationOnKillEntry repOnKill;
5590        repOnKill.repfaction1          = fields[1].GetUInt32();
5591        repOnKill.repfaction2          = fields[2].GetUInt32();
5592        repOnKill.is_teamaward1        = fields[3].GetBool();
5593        repOnKill.reputation_max_cap1  = fields[4].GetUInt32();
5594        repOnKill.repvalue1            = fields[5].GetInt32();
5595        repOnKill.is_teamaward2        = fields[6].GetBool();
5596        repOnKill.reputation_max_cap2  = fields[7].GetUInt32();
5597        repOnKill.repvalue2            = fields[8].GetInt32();
5598        repOnKill.team_dependent       = fields[9].GetUInt8();
5599
5600        if(!GetCreatureTemplate(creature_id))
5601        {
5602            sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5603            continue;
5604        }
5605
5606        if(repOnKill.repfaction1)
5607        {
5608            FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5609            if(!factionEntry1)
5610            {
5611                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5612                continue;
5613            }
5614        }
5615
5616        if(repOnKill.repfaction2)
5617        {
5618            FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5619            if(!factionEntry2)
5620            {
5621                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5622                continue;
5623            }
5624        }
5625
5626        mRepOnKill[creature_id] = repOnKill;
5627
5628        ++count;
5629    } while (result->NextRow());
5630
5631    delete result;
5632
5633    sLog.outString();
5634    sLog.outString(">> Loaded %u creature award reputation definitions", count);
5635}
5636
5637void ObjectMgr::LoadWeatherZoneChances()
5638{
5639    uint32 count = 0;
5640
5641    //                                                0     1                   2                   3                    4                   5                   6                    7                 8                 9                  10                  11                  12
5642    QueryResult *result = WorldDatabase.Query("SELECT zone, spring_rain_chance, spring_snow_chance, spring_storm_chance, summer_rain_chance, summer_snow_chance, summer_storm_chance, fall_rain_chance, fall_snow_chance, fall_storm_chance, winter_rain_chance, winter_snow_chance, winter_storm_chance FROM game_weather");
5643
5644    if(!result)
5645    {
5646        barGoLink bar(1);
5647
5648        bar.step();
5649
5650        sLog.outString();
5651        sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5652        return;
5653    }
5654
5655    barGoLink bar(result->GetRowCount());
5656
5657    do
5658    {
5659        Field *fields = result->Fetch();
5660        bar.step();
5661
5662        uint32 zone_id = fields[0].GetUInt32();
5663
5664        WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5665
5666        for(int season = 0; season < WEATHER_SEASONS; ++season)
5667        {
5668            wzc.data[season].rainChance  = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5669            wzc.data[season].snowChance  = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5670            wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5671
5672            if(wzc.data[season].rainChance > 100)
5673            {
5674                wzc.data[season].rainChance = 25;
5675                sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5676            }
5677
5678            if(wzc.data[season].snowChance > 100)
5679            {
5680                wzc.data[season].snowChance = 25;
5681                sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5682            }
5683
5684            if(wzc.data[season].stormChance > 100)
5685            {
5686                wzc.data[season].stormChance = 25;
5687                sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5688            }
5689        }
5690
5691        ++count;
5692    } while (result->NextRow());
5693
5694    delete result;
5695
5696    sLog.outString();
5697    sLog.outString(">> Loaded %u weather definitions", count);
5698}
5699
5700void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5701{
5702    mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5703    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5704    if(t)
5705        WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5706}
5707
5708void ObjectMgr::DeleteCreatureData(uint32 guid)
5709{
5710    // remove mapid*cellid -> guid_set map
5711    CreatureData const* data = GetCreatureData(guid);
5712    if(data)
5713        RemoveCreatureFromGrid(guid, data);
5714
5715    mCreatureDataMap.erase(guid);
5716}
5717
5718void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5719{
5720    mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5721    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5722    if(t)
5723        WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5724}
5725
5726void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5727{
5728    RespawnTimes::iterator next;
5729
5730    for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5731    {
5732        next = itr;
5733        ++next;
5734
5735        if(GUID_HIPART(itr->first)==instance)
5736            mGORespawnTimes.erase(itr);
5737    }
5738
5739    for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5740    {
5741        next = itr;
5742        ++next;
5743
5744        if(GUID_HIPART(itr->first)==instance)
5745            mCreatureRespawnTimes.erase(itr);
5746    }
5747
5748    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5749    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5750}
5751
5752void ObjectMgr::DeleteGOData(uint32 guid)
5753{
5754    // remove mapid*cellid -> guid_set map
5755    GameObjectData const* data = GetGOData(guid);
5756    if(data)
5757        RemoveGameobjectFromGrid(guid, data);
5758
5759    mGameObjectDataMap.erase(guid);
5760}
5761
5762void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5763{
5764    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5765    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5766    cell_guids.corpses[player_guid] = instance;
5767}
5768
5769void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5770{
5771    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5772    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5773    cell_guids.corpses.erase(player_guid);
5774}
5775
5776void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5777{
5778    map.clear();                                            // need for reload case
5779
5780    uint32 count = 0;
5781
5782    QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5783
5784    if(!result)
5785    {
5786        barGoLink bar(1);
5787
5788        bar.step();
5789
5790        sLog.outString();
5791        sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5792        return;
5793    }
5794
5795    barGoLink bar(result->GetRowCount());
5796
5797    do
5798    {
5799        Field *fields = result->Fetch();
5800        bar.step();
5801
5802        uint32 id    = fields[0].GetUInt32();
5803        uint32 quest = fields[1].GetUInt32();
5804
5805        if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5806        {
5807            sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5808            continue;
5809        }
5810
5811        map.insert(QuestRelations::value_type(id,quest));
5812
5813        ++count;
5814    } while (result->NextRow());
5815
5816    delete result;
5817
5818    sLog.outString();
5819    sLog.outString(">> Loaded %u quest relations from %s", count,table);
5820}
5821
5822void ObjectMgr::LoadGameobjectQuestRelations()
5823{
5824    LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5825
5826    for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5827    {
5828        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5829        if(!goInfo)
5830            sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5831        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5832            sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5833    }
5834}
5835
5836void ObjectMgr::LoadGameobjectInvolvedRelations()
5837{
5838    LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5839
5840    for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5841    {
5842        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5843        if(!goInfo)
5844            sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5845        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5846            sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5847    }
5848}
5849
5850void ObjectMgr::LoadCreatureQuestRelations()
5851{
5852    LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5853
5854    for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5855    {
5856        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5857        if(!cInfo)
5858            sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5859        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5860            sLog.outErrorDb("Table `creature_questrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
5861    }
5862}
5863
5864void ObjectMgr::LoadCreatureInvolvedRelations()
5865{
5866    LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
5867
5868    for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
5869    {
5870        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5871        if(!cInfo)
5872            sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5873        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5874            sLog.outErrorDb("Table `creature_involvedrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
5875    }
5876}
5877
5878void ObjectMgr::LoadReservedPlayersNames()
5879{
5880    m_ReservedNames.clear();                                // need for reload case
5881
5882    QueryResult *result = WorldDatabase.PQuery("SELECT name FROM reserved_name");
5883
5884    uint32 count = 0;
5885
5886    if( !result )
5887    {
5888        barGoLink bar( 1 );
5889        bar.step();
5890
5891        sLog.outString();
5892        sLog.outString( ">> Loaded %u reserved player names", count );
5893        return;
5894    }
5895
5896    barGoLink bar( result->GetRowCount() );
5897
5898    Field* fields;
5899    do
5900    {
5901        bar.step();
5902        fields = result->Fetch();
5903        std::string name= fields[0].GetCppString();
5904        if(normalizePlayerName(name))
5905        {
5906            m_ReservedNames.insert(name);
5907            ++count;
5908        }
5909    } while ( result->NextRow() );
5910
5911    delete result;
5912
5913    sLog.outString();
5914    sLog.outString( ">> Loaded %u reserved player names", count );
5915}
5916
5917enum LanguageType
5918{
5919    LT_BASIC_LATIN    = 0x0000,
5920    LT_EXTENDEN_LATIN = 0x0001,
5921    LT_CYRILLIC       = 0x0002,
5922    LT_EAST_ASIA      = 0x0004,
5923    LT_ANY            = 0xFFFF
5924};
5925
5926static LanguageType GetRealmLanguageType(bool create)
5927{
5928    switch(sWorld.getConfig(CONFIG_REALM_ZONE))
5929    {
5930        case REALM_ZONE_UNKNOWN:                            // any language
5931        case REALM_ZONE_DEVELOPMENT:
5932        case REALM_ZONE_TEST_SERVER:
5933        case REALM_ZONE_QA_SERVER:
5934            return LT_ANY;
5935        case REALM_ZONE_UNITED_STATES:                      // extended-Latin
5936        case REALM_ZONE_OCEANIC:
5937        case REALM_ZONE_LATIN_AMERICA:
5938        case REALM_ZONE_ENGLISH:
5939        case REALM_ZONE_GERMAN:
5940        case REALM_ZONE_FRENCH:
5941        case REALM_ZONE_SPANISH:
5942            return LT_EXTENDEN_LATIN;
5943        case REALM_ZONE_KOREA:                              // East-Asian
5944        case REALM_ZONE_TAIWAN:
5945        case REALM_ZONE_CHINA:
5946            return LT_EAST_ASIA;
5947        case REALM_ZONE_RUSSIAN:                            // Cyrillic
5948            return LT_CYRILLIC;
5949        default:
5950            return create ? LT_BASIC_LATIN : LT_ANY;        // basic-Latin at create, any at login
5951    }
5952}
5953
5954bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
5955{
5956    if(strictMask==0)                                       // any language, ignore realm
5957    {
5958        if(isExtendedLatinString(wstr,numericOrSpace))
5959            return true;
5960        if(isCyrillicString(wstr,numericOrSpace))
5961            return true;
5962        if(isEastAsianString(wstr,numericOrSpace))
5963            return true;
5964        return false;
5965    }
5966
5967    if(strictMask & 0x2)                                    // realm zone specific
5968    {
5969        LanguageType lt = GetRealmLanguageType(create);
5970        if(lt & LT_EXTENDEN_LATIN)
5971            if(isExtendedLatinString(wstr,numericOrSpace))
5972                return true;
5973        if(lt & LT_CYRILLIC)
5974            if(isCyrillicString(wstr,numericOrSpace))
5975                return true;
5976        if(lt & LT_EAST_ASIA)
5977            if(isEastAsianString(wstr,numericOrSpace))
5978                return true;
5979    }
5980
5981    if(strictMask & 0x1)                                    // basic latin
5982    {
5983        if(isBasicLatinString(wstr,numericOrSpace))
5984            return true;
5985    }
5986
5987    return false;
5988}
5989
5990bool ObjectMgr::IsValidName( std::string name, bool create )
5991{
5992    std::wstring wname;
5993    if(!Utf8toWStr(name,wname))
5994        return false;
5995
5996    if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
5997        return false;
5998
5999    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6000
6001    return isValidString(wname,strictMask,false,create);
6002}
6003
6004bool ObjectMgr::IsValidCharterName( std::string name )
6005{
6006    std::wstring wname;
6007    if(!Utf8toWStr(name,wname))
6008        return false;
6009
6010    if(wname.size() < 1)
6011        return false;
6012
6013    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6014
6015    return isValidString(wname,strictMask,true);
6016}
6017
6018bool ObjectMgr::IsValidPetName( std::string name )
6019{
6020    std::wstring wname;
6021    if(!Utf8toWStr(name,wname))
6022        return false;
6023
6024    if(wname.size() < 1)
6025        return false;
6026
6027    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6028
6029    return isValidString(wname,strictMask,false);
6030}
6031
6032int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6033{
6034    if(loc==LOCALE_enUS)
6035        return -1;
6036
6037    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6038        if(m_LocalForIndex[i]==loc)
6039            return i;
6040
6041    return -1;
6042}
6043
6044LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6045{
6046    if (i<0 || i>=m_LocalForIndex.size())
6047        return LOCALE_enUS;
6048
6049    return m_LocalForIndex[i];
6050}
6051
6052int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6053{
6054    if(loc==LOCALE_enUS)
6055        return -1;
6056
6057    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6058        if(m_LocalForIndex[i]==loc)
6059            return i;
6060
6061    m_LocalForIndex.push_back(loc);
6062    return m_LocalForIndex.size()-1;
6063}
6064
6065void ObjectMgr::LoadBattleMastersEntry()
6066{
6067    mBattleMastersMap.clear();                              // need for reload case
6068
6069    QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6070
6071    uint32 count = 0;
6072
6073    if( !result )
6074    {
6075        barGoLink bar( 1 );
6076        bar.step();
6077
6078        sLog.outString();
6079        sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6080        return;
6081    }
6082
6083    barGoLink bar( result->GetRowCount() );
6084
6085    do
6086    {
6087        ++count;
6088        bar.step();
6089
6090        Field *fields = result->Fetch();
6091
6092        uint32 entry = fields[0].GetUInt32();
6093        uint32 bgTypeId  = fields[1].GetUInt32();
6094
6095        mBattleMastersMap[entry] = bgTypeId;
6096
6097    } while( result->NextRow() );
6098
6099    delete result;
6100
6101    sLog.outString();
6102    sLog.outString( ">> Loaded %u battlemaster entries", count );
6103}
6104
6105void ObjectMgr::LoadGameObjectForQuests()
6106{
6107    mGameObjectForQuestSet.clear();                         // need for reload case
6108
6109    uint32 count = 0;
6110
6111    // collect GO entries for GO that must activated
6112    for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6113    {
6114        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6115        if(!goInfo)
6116            continue;
6117
6118        switch(goInfo->type)
6119        {
6120            // scan GO chest with loot including quest items
6121            case GAMEOBJECT_TYPE_CHEST:
6122            {
6123                uint32 loot_id = GameObject::GetLootId(goInfo);
6124
6125                // find quest loot for GO
6126                if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6127                {
6128                    mGameObjectForQuestSet.insert(go_entry);
6129                    ++count;
6130                }
6131                break;
6132            }
6133            case GAMEOBJECT_TYPE_GOOBER:
6134            {
6135                if(goInfo->goober.questId)                  //quests objects
6136                {
6137                    mGameObjectForQuestSet.insert(go_entry);
6138                    count++;
6139                }
6140                break;
6141            }
6142            default:
6143                break;
6144        }
6145    }
6146
6147    sLog.outString();
6148    sLog.outString( ">> Loaded %u GameObject for quests", count );
6149}
6150
6151bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6152{
6153    // cleanup affected map part for reloading case
6154    for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6155    {
6156        if(itr->first >= min_value && itr->first <= max_value)
6157        {
6158            MangosStringLocaleMap::iterator itr2 = itr;
6159            ++itr;
6160            mMangosStringLocaleMap.erase(itr2);
6161        }
6162        else
6163            ++itr;
6164    }
6165
6166    QueryResult *result = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 FROM %s",table);
6167
6168    if(!result)
6169    {
6170        barGoLink bar(1);
6171
6172        bar.step();
6173
6174        sLog.outString("");
6175        if(min_value > 0)                                   // error only in case internal strings
6176            sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6177        else
6178            sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6179        return false;
6180    }
6181
6182    uint32 count = 0;
6183
6184    barGoLink bar(result->GetRowCount());
6185
6186    do
6187    {
6188        Field *fields = result->Fetch();
6189        bar.step();
6190
6191        int32 entry = fields[0].GetInt32();
6192
6193        if(entry==0)
6194        {
6195            sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6196            continue;
6197        }
6198        else if(entry < min_value || entry > max_value)
6199        {
6200            int32 start = min_value > 0 ? min_value : max_value;
6201            int32 end   = min_value > 0 ? max_value : min_value;
6202            sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6203            continue;
6204        }
6205
6206        MangosStringLocale& data = mMangosStringLocaleMap[entry];
6207
6208        if(data.Content.size() > 0)
6209        {
6210            sLog.outErrorDb("Table `%s` contain data for already loaded entry  %i (from another table?), ignored.",table,entry);
6211            continue;
6212        }
6213
6214        data.Content.resize(1);
6215        ++count;
6216
6217        // 0 -> default, idx in to idx+1
6218        data.Content[0] = fields[1].GetCppString();
6219
6220        for(int i = 1; i < MAX_LOCALE; ++i)
6221        {
6222            std::string str = fields[i+1].GetCppString();
6223            if(!str.empty())
6224            {
6225                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6226                if(idx >= 0)
6227                {
6228                    // 0 -> default, idx in to idx+1
6229                    if(data.Content.size() <= idx+1)
6230                        data.Content.resize(idx+2);
6231
6232                    data.Content[idx+1] = str;
6233                }
6234            }
6235        }
6236    } while (result->NextRow());
6237
6238    delete result;
6239
6240    sLog.outString();
6241    if(min_value > 0)                                       // internal mangos strings
6242        sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6243    else
6244        sLog.outString( ">> Loaded %u string templates from %s", count,table);
6245
6246    return true;
6247}
6248
6249const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6250{
6251    // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6252    // Content[0] always exist if exist MangosStringLocale
6253    if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6254    {
6255        if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6256            return msl->Content[locale_idx+1].c_str();
6257        else
6258            return msl->Content[0].c_str();
6259    }
6260
6261    if(entry > 0)
6262        sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6263    else
6264        sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6265    return "<error>";
6266}
6267
6268void ObjectMgr::LoadFishingBaseSkillLevel()
6269{
6270    mFishingBaseForArea.clear();                            // for relaod case
6271
6272    uint32 count = 0;
6273    QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6274
6275    if( !result )
6276    {
6277        barGoLink bar( 1 );
6278
6279        bar.step();
6280
6281        sLog.outString();
6282        sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6283        return;
6284    }
6285
6286    barGoLink bar( result->GetRowCount() );
6287
6288    do
6289    {
6290        bar.step();
6291
6292        Field *fields = result->Fetch();
6293        uint32 entry  = fields[0].GetUInt32();
6294        int32 skill   = fields[1].GetInt32();
6295
6296        AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6297        if(!fArea)
6298        {
6299            sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6300            continue;
6301        }
6302
6303        mFishingBaseForArea[entry] = skill;
6304        ++count;
6305    }
6306    while (result->NextRow());
6307
6308    delete result;
6309
6310    sLog.outString();
6311    sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6312}
6313
6314// Searches for the same condition already in Conditions store
6315// Returns Id if found, else adds it to Conditions and returns Id
6316uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6317{
6318    PlayerCondition lc = PlayerCondition(condition, value1, value2);
6319    for (uint16 i=0; i < mConditions.size(); ++i)
6320    {
6321        if (lc == mConditions[i])
6322            return i;
6323    }
6324
6325    mConditions.push_back(lc);
6326
6327    if(mConditions.size() > 0xFFFF)
6328    {
6329        sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6330        return 0;
6331    }
6332
6333    return mConditions.size() - 1;
6334}
6335
6336bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6337{
6338    for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6339    {
6340        std::wstring wname;
6341        if(!Utf8toWStr(names.name[i],wname))
6342            return false;
6343
6344        if(mainpart!=GetMainPartOfName(wname,i+1))
6345            return false;
6346    }
6347    return true;
6348}
6349
6350const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6351{
6352    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6353    if(i!= mAreaTriggerScripts.end())
6354        return i->second.c_str();
6355    return "";
6356}
6357
6358// Checks if player meets the condition
6359bool PlayerCondition::Meets(Player const * player) const
6360{
6361    if( !player )
6362        return false;                                       // player not present, return false
6363
6364    switch (condition)
6365    {
6366        case CONDITION_NONE:
6367            return true;                                    // empty condition, always met
6368        case CONDITION_AURA:
6369            return player->HasAura(value1, value2);
6370        case CONDITION_ITEM:
6371            return player->HasItemCount(value1, value2);
6372        case CONDITION_ITEM_EQUIPPED:
6373            return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6374        case CONDITION_ZONEID:
6375            return player->GetZoneId() == value1;
6376        case CONDITION_REPUTATION_RANK:
6377        {
6378            FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6379            return faction && player->GetReputationRank(faction) >= value2;
6380        }
6381        case CONDITION_TEAM:
6382            return player->GetTeam() == value1;
6383        case CONDITION_SKILL:
6384            return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6385        case CONDITION_QUESTREWARDED:
6386            return player->GetQuestRewardStatus(value1);
6387        case CONDITION_QUESTTAKEN:
6388        {
6389            QuestStatus status = player->GetQuestStatus(value1);
6390            return (status == QUEST_STATUS_INCOMPLETE);
6391        }
6392        case CONDITION_AD_COMMISSION_AURA:
6393        {
6394            Unit::AuraMap const& auras = player->GetAuras();
6395            for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6396                if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6397                    return true;
6398            return false;
6399        }
6400        default:
6401            return false;
6402    }
6403}
6404
6405// Verification of condition values validity
6406bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6407{
6408    if( condition >= MAX_CONDITION)                         // Wrong condition type
6409    {
6410        sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6411        return false;
6412    }
6413
6414    switch (condition)
6415    {
6416        case CONDITION_AURA:
6417        {
6418            if(!sSpellStore.LookupEntry(value1))
6419            {
6420                sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6421                return false;
6422            }
6423            if(value2 > 2)
6424            {
6425                sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6426                return false;
6427            }
6428            break;
6429        }
6430        case CONDITION_ITEM:
6431        {
6432            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6433            if(!proto)
6434            {
6435                sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6436                return false;
6437            }
6438            break;
6439        }
6440        case CONDITION_ITEM_EQUIPPED:
6441        {
6442            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6443            if(!proto)
6444            {
6445                sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6446                return false;
6447            }
6448            break;
6449        }
6450        case CONDITION_ZONEID:
6451        {
6452            AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6453            if(!areaEntry)
6454            {
6455                sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6456                return false;
6457            }
6458            if(areaEntry->zone != 0)
6459            {
6460                sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6461                return false;
6462            }
6463            break;
6464        }
6465        case CONDITION_REPUTATION_RANK:
6466        {
6467            FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6468            if(!factionEntry)
6469            {
6470                sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6471                return false;
6472            }
6473            break;
6474        }
6475        case CONDITION_TEAM:
6476        {
6477            if (value1 != ALLIANCE && value1 != HORDE)
6478            {
6479                sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6480                return false;
6481            }
6482            break;
6483        }
6484        case CONDITION_SKILL:
6485        {
6486            SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6487            if (!pSkill)
6488            {
6489                sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6490                return false;
6491            }
6492            if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6493            {
6494                sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6495                return false;
6496            }
6497            break;
6498        }
6499        case CONDITION_QUESTREWARDED:
6500        case CONDITION_QUESTTAKEN:
6501        {
6502            Quest const *Quest = objmgr.GetQuestTemplate(value1);
6503            if (!Quest)
6504            {
6505                sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6506                return false;
6507            }
6508            if(value2)
6509                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6510            break;
6511        }
6512        case CONDITION_AD_COMMISSION_AURA:
6513        {
6514            if(value1)
6515                sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6516            if(value2)
6517                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6518            break;
6519        }
6520    }
6521    return true;
6522}
6523
6524SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6525{
6526    switch(pSkill->categoryId)
6527    {
6528        case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6529        case SKILL_CATEGORY_WEAPON:
6530            if(pSkill->id!=SKILL_FIST_WEAPONS)
6531                return SKILL_RANGE_LEVEL;
6532            else
6533                return SKILL_RANGE_MONO;
6534        case SKILL_CATEGORY_ARMOR:
6535        case SKILL_CATEGORY_CLASS:
6536            if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6537                return SKILL_RANGE_MONO;
6538            else
6539                return SKILL_RANGE_LEVEL;
6540        case SKILL_CATEGORY_SECONDARY:
6541        case SKILL_CATEGORY_PROFESSION:
6542            // not set skills for professions and racial abilities
6543            if(IsProfessionSkill(pSkill->id))
6544                return SKILL_RANGE_RANK;
6545            else if(racial)
6546                return SKILL_RANGE_NONE;
6547            else
6548                return SKILL_RANGE_MONO;
6549        default:
6550        case SKILL_CATEGORY_ATTRIBUTES:                     //not found in dbc
6551        case SKILL_CATEGORY_NOT_DISPLAYED:                  //only GENEREC(DND)
6552            return SKILL_RANGE_NONE;
6553    }
6554}
6555
6556void ObjectMgr::LoadGameTele()
6557{
6558    m_GameTeleMap.clear();                                  // for relaod case
6559
6560    uint32 count = 0;
6561    QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6562
6563    if( !result )
6564    {
6565        barGoLink bar( 1 );
6566
6567        bar.step();
6568
6569        sLog.outString();
6570        sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6571        return;
6572    }
6573
6574    barGoLink bar( result->GetRowCount() );
6575
6576    do
6577    {
6578        bar.step();
6579
6580        Field *fields = result->Fetch();
6581
6582        uint32 id         = fields[0].GetUInt32();
6583
6584        GameTele gt;
6585
6586        gt.position_x     = fields[1].GetFloat();
6587        gt.position_y     = fields[2].GetFloat();
6588        gt.position_z     = fields[3].GetFloat();
6589        gt.orientation    = fields[4].GetFloat();
6590        gt.mapId          = fields[5].GetUInt32();
6591        gt.name           = fields[6].GetCppString();
6592
6593        if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6594        {
6595            sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6596            continue;
6597        }
6598
6599        if(!Utf8toWStr(gt.name,gt.wnameLow))
6600        {
6601            sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6602            continue;
6603        }
6604
6605        wstrToLower( gt.wnameLow );
6606
6607        m_GameTeleMap[id] = gt;
6608
6609        ++count;
6610    }
6611    while (result->NextRow());
6612
6613    delete result;
6614
6615    sLog.outString();
6616    sLog.outString( ">> Loaded %u game tele's", count );
6617}
6618
6619GameTele const* ObjectMgr::GetGameTele(std::string name) const
6620{
6621    // explicit name case
6622    std::wstring wname;
6623    if(!Utf8toWStr(name,wname))
6624        return false;
6625
6626    // converting string that we try to find to lower case
6627    wstrToLower( wname );
6628
6629    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6630        if(itr->second.wnameLow == wname)
6631            return &itr->second;
6632
6633    return NULL;
6634}
6635
6636bool ObjectMgr::AddGameTele(GameTele& tele)
6637{
6638    // find max id
6639    uint32 new_id = 0;
6640    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6641        if(itr->first > new_id)
6642            new_id = itr->first;
6643   
6644    // use next
6645    ++new_id;
6646
6647    if(!Utf8toWStr(tele.name,tele.wnameLow))
6648        return false;
6649
6650    wstrToLower( tele.wnameLow );
6651
6652    m_GameTeleMap[new_id] = tele;
6653
6654    return WorldDatabase.PExecuteLog("INSERT INTO game_tele (id,position_x,position_y,position_z,orientation,map,name) VALUES (%u,%f,%f,%f,%f,%d,'%s')",
6655        new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6656}
6657
6658bool ObjectMgr::DeleteGameTele(std::string name)
6659{
6660    // explicit name case
6661    std::wstring wname;
6662    if(!Utf8toWStr(name,wname))
6663        return false;
6664
6665    // converting string that we try to find to lower case
6666    wstrToLower( wname );
6667
6668    for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6669    {
6670        if(itr->second.wnameLow == wname)
6671        {
6672            WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6673            m_GameTeleMap.erase(itr);
6674            return true;
6675        }
6676    }
6677
6678    return false;
6679}
6680
6681void ObjectMgr::LoadTrainerSpell()
6682{
6683    // For reload case
6684    for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6685        itr->second.Clear();
6686    m_mCacheTrainerSpellMap.clear();
6687
6688    std::set<uint32> skip_trainers;
6689
6690    QueryResult *result = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6691
6692    if( !result )
6693    {
6694        barGoLink bar( 1 );
6695
6696        bar.step();
6697
6698        sLog.outString();
6699        sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6700        return;
6701    }
6702
6703    barGoLink bar( result->GetRowCount() );
6704
6705    uint32 count = 0;
6706    do
6707    {
6708        bar.step();
6709
6710        Field* fields = result->Fetch();
6711
6712        uint32 entry  = fields[0].GetUInt32();
6713        uint32 spell  = fields[1].GetUInt32();
6714
6715        CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6716
6717        if(!cInfo)
6718        {
6719            sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6720            continue;
6721        }
6722
6723        if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6724        {
6725            if(skip_trainers.count(entry) == 0)
6726            {
6727                sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6728                skip_trainers.insert(entry);
6729            }
6730            continue;
6731        }
6732
6733        SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6734        if(!spellinfo)
6735        {
6736            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6737            continue;
6738        }
6739
6740        if(!SpellMgr::IsSpellValid(spellinfo))
6741        {
6742            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6743            continue;
6744        }
6745
6746        TrainerSpell* pTrainerSpell = new TrainerSpell();
6747        pTrainerSpell->spell         = spell;
6748        pTrainerSpell->spellcost     = fields[2].GetUInt32();
6749        pTrainerSpell->reqskill      = fields[3].GetUInt32();
6750        pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6751        pTrainerSpell->reqlevel      = fields[5].GetUInt32();
6752
6753        if(!pTrainerSpell->reqlevel)
6754            pTrainerSpell->reqlevel = spellinfo->spellLevel;
6755
6756
6757        TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6758
6759        if(SpellMgr::IsProfessionSpell(spell))
6760            data.trainerType = 2;
6761
6762        data.spellList.push_back(pTrainerSpell);
6763        ++count;
6764
6765    } while (result->NextRow());
6766    delete result;
6767
6768    sLog.outString();
6769    sLog.outString( ">> Loaded Trainers %d", count );
6770}
6771
6772void ObjectMgr::LoadVendors()
6773{
6774    // For reload case
6775    for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6776        itr->second.Clear();
6777    m_mCacheVendorItemMap.clear();
6778
6779    std::set<uint32> skip_vendors;
6780
6781    QueryResult *result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6782    if( !result )
6783    {
6784        barGoLink bar( 1 );
6785
6786        bar.step();
6787
6788        sLog.outString();
6789        sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6790        return;
6791    }
6792
6793    barGoLink bar( result->GetRowCount() );
6794
6795    uint32 count = 0;
6796    do
6797    {
6798        bar.step();
6799        Field* fields = result->Fetch();
6800
6801        uint32 entry        = fields[0].GetUInt32();
6802        uint32 item_id      = fields[1].GetUInt32();
6803        uint32 maxcount     = fields[2].GetUInt32();
6804        uint32 incrtime     = fields[3].GetUInt32();
6805        uint32 ExtendedCost = fields[4].GetUInt32();
6806
6807        if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6808            continue;
6809
6810        VendorItemData& vList = m_mCacheVendorItemMap[entry];
6811
6812        vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
6813        ++count;
6814
6815    } while (result->NextRow());
6816    delete result;
6817
6818    sLog.outString();
6819    sLog.outString( ">> Loaded %d Vendors ", count );
6820}
6821
6822void ObjectMgr::LoadNpcTextId()
6823{
6824
6825    m_mCacheNpcTextIdMap.clear();
6826
6827    QueryResult* result = WorldDatabase.PQuery("SELECT npc_guid, textid FROM npc_gossip");
6828    if( !result )
6829    {
6830        barGoLink bar( 1 );
6831
6832        bar.step();
6833
6834        sLog.outString();
6835        sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
6836        return;
6837    }
6838
6839    barGoLink bar( result->GetRowCount() );
6840
6841    uint32 count = 0;
6842    uint32 guid,textid;
6843    do
6844    {
6845        bar.step();
6846
6847        Field* fields = result->Fetch();
6848
6849        guid   = fields[0].GetUInt32();
6850        textid = fields[1].GetUInt32();
6851
6852        if (!GetCreatureData(guid))
6853        {
6854            sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
6855            continue;
6856        }
6857        if (!GetGossipText(textid))
6858        {
6859            sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
6860            continue;
6861        }
6862
6863        m_mCacheNpcTextIdMap[guid] = textid ;
6864        ++count;
6865
6866    } while (result->NextRow());
6867    delete result;
6868
6869    sLog.outString();
6870    sLog.outString( ">> Loaded %d NpcTextId ", count );
6871}
6872
6873void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
6874{
6875    VendorItemData& vList = m_mCacheVendorItemMap[entry];
6876    vList.AddItem(item,maxcount,incrtime,extendedcost);
6877
6878    WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
6879}
6880
6881bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
6882{
6883    CacheVendorItemMap::iterator  iter = m_mCacheVendorItemMap.find(entry);
6884    if(iter == m_mCacheVendorItemMap.end())
6885        return false;
6886
6887    if(!iter->second.FindItem(item))
6888        return false;
6889
6890    iter->second.RemoveItem(item);
6891    WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
6892    return true;
6893}
6894
6895bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
6896{
6897    CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
6898    if(!cInfo)
6899    {
6900        if(pl)
6901            ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6902        else
6903            sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
6904        return false;
6905    }
6906
6907    if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
6908    {
6909        if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
6910        {
6911            if(pl)
6912                ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6913            else
6914                sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
6915
6916            if(skip_vendors)
6917                skip_vendors->insert(vendor_entry);
6918        }
6919        return false;
6920    }
6921
6922    if(!GetItemPrototype(item_id))
6923    {
6924        if(pl)
6925            ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
6926        else
6927            sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
6928        return false;
6929    }
6930
6931    if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
6932    {
6933        if(pl)
6934            ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
6935        else
6936            sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
6937        return false;
6938    }
6939
6940    if(maxcount > 0 && incrtime == 0)
6941    {
6942        if(pl)
6943            ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
6944        else
6945            sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
6946        return false;
6947    }
6948    else if(maxcount==0 && incrtime > 0)
6949    {
6950        if(pl)
6951            ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
6952        else
6953            sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
6954        return false;
6955    }
6956
6957    VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
6958    if(!vItems)
6959        return true;                                        // later checks for non-empty lists
6960
6961    if(vItems->FindItem(item_id))
6962    {
6963        if(pl)
6964            ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
6965        else
6966            sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
6967        return false;
6968    }
6969
6970    if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
6971    {
6972        if(pl)
6973            ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
6974        else
6975            sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
6976        return false;
6977    }
6978
6979    return true;
6980}
6981
6982// Functions for scripting access
6983const char* GetAreaTriggerScriptNameById(uint32 id)
6984{
6985    return objmgr.GetAreaTriggerScriptName(id);
6986}
6987
6988bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
6989{
6990    if(start_value >= 0 || start_value <= end_value)        // start/end reversed for negative values
6991    {
6992        sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), use (%d - %d) instead.",table,start_value,end_value,-1,std::numeric_limits<int32>::min());
6993        start_value = -1;
6994        end_value = std::numeric_limits<int32>::min();
6995    }
6996
6997    // for scripting localized strings allowed use _only_ negative entries
6998    return objmgr.LoadMangosStrings(db,table,end_value,start_value);
6999}
Note: See TracBrowser for help on using the browser.