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

Revision 37, 247.0 kB (checked in by yumileroy, 17 years ago)

[svn] * svn:eol-style native set on all files that need it

Original author: Neo2003
Date: 2008-10-11 14:16:25-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
2082        QueryResult *result = NULL;
2083        if(sWorld.getConfig(CONFIG_START_ALL_SPELLS))
2084                result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell_custom");
2085        else
2086                result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2087
2088        uint32 count = 0;
2089
2090        if (!result)
2091        {
2092            barGoLink bar( 1 );
2093
2094            sLog.outString();
2095            sLog.outString( ">> Loaded %u player create spells", count );
2096            sLog.outErrorDb( "Error loading player starting spells or empty table.");
2097        }
2098        else
2099        {
2100            barGoLink bar( result->GetRowCount() );
2101
2102            do
2103            {
2104                Field* fields = result->Fetch();
2105
2106                uint32 current_race = fields[0].GetUInt32();
2107                if(current_race >= MAX_RACES)
2108                {
2109                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2110                    continue;
2111                }
2112
2113                uint32 current_class = fields[1].GetUInt32();
2114                if(current_class >= MAX_CLASSES)
2115                {
2116                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2117                    continue;
2118                }
2119
2120                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2121                pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2122
2123                bar.step();
2124                ++count;
2125            }
2126            while( result->NextRow() );
2127
2128            delete result;
2129
2130            sLog.outString();
2131            sLog.outString( ">> Loaded %u player create spells", count );
2132        }
2133    }
2134
2135    // Load playercreate actions
2136    {
2137        //                                                0     1      2       3       4     5
2138        QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2139
2140        uint32 count = 0;
2141
2142        if (!result)
2143        {
2144            barGoLink bar( 1 );
2145
2146            sLog.outString();
2147            sLog.outString( ">> Loaded %u player create actions", count );
2148            sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2149        }
2150        else
2151        {
2152            barGoLink bar( result->GetRowCount() );
2153
2154            do
2155            {
2156                Field* fields = result->Fetch();
2157
2158                uint32 current_race = fields[0].GetUInt32();
2159                if(current_race >= MAX_RACES)
2160                {
2161                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2162                    continue;
2163                }
2164
2165                uint32 current_class = fields[1].GetUInt32();
2166                if(current_class >= MAX_CLASSES)
2167                {
2168                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2169                    continue;
2170                }
2171
2172                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2173                pInfo->action[0].push_back(fields[2].GetUInt16());
2174                pInfo->action[1].push_back(fields[3].GetUInt16());
2175                pInfo->action[2].push_back(fields[4].GetUInt16());
2176                pInfo->action[3].push_back(fields[5].GetUInt16());
2177
2178                bar.step();
2179                ++count;
2180            }
2181            while( result->NextRow() );
2182
2183            delete result;
2184
2185            sLog.outString();
2186            sLog.outString( ">> Loaded %u player create actions", count );
2187        }
2188    }
2189
2190    // Loading levels data (class only dependent)
2191    {
2192        //                                                 0      1      2       3
2193        QueryResult *result  = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2194
2195        uint32 count = 0;
2196
2197        if (!result)
2198        {
2199            barGoLink bar( 1 );
2200
2201            sLog.outString();
2202            sLog.outString( ">> Loaded %u level health/mana definitions", count );
2203            sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2204            exit(1);
2205        }
2206
2207        barGoLink bar( result->GetRowCount() );
2208
2209        do
2210        {
2211            Field* fields = result->Fetch();
2212
2213            uint32 current_class = fields[0].GetUInt32();
2214            if(current_class >= MAX_CLASSES)
2215            {
2216                sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2217                continue;
2218            }
2219
2220            uint32 current_level = fields[1].GetUInt32();
2221            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2222            {
2223                if(current_level > 255)                     // hardcoded level maximum
2224                    sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2225                else
2226                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2227                continue;
2228            }
2229
2230            PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2231
2232            if(!pClassInfo->levelInfo)
2233                pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2234
2235            PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2236
2237            pClassLevelInfo->basehealth = fields[2].GetUInt16();
2238            pClassLevelInfo->basemana   = fields[3].GetUInt16();
2239
2240            bar.step();
2241            ++count;
2242        }
2243        while (result->NextRow());
2244
2245        delete result;
2246
2247        sLog.outString();
2248        sLog.outString( ">> Loaded %u level health/mana definitions", count );
2249    }
2250
2251    // Fill gaps and check integrity
2252    for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2253    {
2254        // skip non existed classes
2255        if(!sChrClassesStore.LookupEntry(class_))
2256            continue;
2257
2258        PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2259
2260        // fatal error if no level 1 data
2261        if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2262        {
2263            sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2264            exit(1);
2265        }
2266
2267        // fill level gaps
2268        for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2269        {
2270            if(pClassInfo->levelInfo[level].basehealth == 0)
2271            {
2272                sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2273                pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2274            }
2275        }
2276    }
2277
2278    // Loading levels data (class/race dependent)
2279    {
2280        //                                                 0     1      2      3    4    5    6    7
2281        QueryResult *result  = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2282
2283        uint32 count = 0;
2284
2285        if (!result)
2286        {
2287            barGoLink bar( 1 );
2288
2289            sLog.outString();
2290            sLog.outString( ">> Loaded %u level stats definitions", count );
2291            sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2292            exit(1);
2293        }
2294
2295        barGoLink bar( result->GetRowCount() );
2296
2297        do
2298        {
2299            Field* fields = result->Fetch();
2300
2301            uint32 current_race = fields[0].GetUInt32();
2302            if(current_race >= MAX_RACES)
2303            {
2304                sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2305                continue;
2306            }
2307
2308            uint32 current_class = fields[1].GetUInt32();
2309            if(current_class >= MAX_CLASSES)
2310            {
2311                sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2312                continue;
2313            }
2314
2315            uint32 current_level = fields[2].GetUInt32();
2316            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2317            {
2318                if(current_level > 255)                     // hardcoded level maximum
2319                    sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2320                else
2321                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2322                continue;
2323            }
2324
2325            PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2326
2327            if(!pInfo->levelInfo)
2328                pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2329
2330            PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2331
2332            for (int i = 0; i < MAX_STATS; i++)
2333            {
2334                pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2335            }
2336
2337            bar.step();
2338            ++count;
2339        }
2340        while (result->NextRow());
2341
2342        delete result;
2343
2344        sLog.outString();
2345        sLog.outString( ">> Loaded %u level stats definitions", count );
2346    }
2347
2348    // Fill gaps and check integrity
2349    for (int race = 0; race < MAX_RACES; ++race)
2350    {
2351        // skip non existed races
2352        if(!sChrRacesStore.LookupEntry(race))
2353            continue;
2354
2355        for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2356        {
2357            // skip non existed classes
2358            if(!sChrClassesStore.LookupEntry(class_))
2359                continue;
2360
2361            PlayerInfo* pInfo = &playerInfo[race][class_];
2362
2363            // skip non loaded combinations
2364            if(!pInfo->displayId_m || !pInfo->displayId_f)
2365                continue;
2366
2367            // skip expansion races if not playing with expansion
2368            if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2369                continue;
2370
2371            // fatal error if no level 1 data
2372            if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2373            {
2374                sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2375                exit(1);
2376            }
2377
2378            // fill level gaps
2379            for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2380            {
2381                if(pInfo->levelInfo[level].stats[0] == 0)
2382                {
2383                    sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2384                    pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2385                }
2386            }
2387        }
2388    }
2389}
2390
2391void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2392{
2393    if(level < 1 || class_ >= MAX_CLASSES)
2394        return;
2395
2396    PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2397
2398    if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2399        level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2400
2401    *info = pInfo->levelInfo[level-1];
2402}
2403
2404void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2405{
2406    if(level < 1 || race   >= MAX_RACES || class_ >= MAX_CLASSES)
2407        return;
2408
2409    PlayerInfo const* pInfo = &playerInfo[race][class_];
2410    if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2411        return;
2412
2413    if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2414        *info = pInfo->levelInfo[level-1];
2415    else
2416        BuildPlayerLevelInfo(race,class_,level,info);
2417}
2418
2419void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2420{
2421    // base data (last known level)
2422    *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2423
2424    for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2425    {
2426        switch(_class)
2427        {
2428            case CLASS_WARRIOR:
2429                info->stats[STAT_STRENGTH]  += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2430                info->stats[STAT_STAMINA]   += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2431                info->stats[STAT_AGILITY]   += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2432                info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2433                info->stats[STAT_SPIRIT]    += (lvl > 9 && !(lvl%2) ? 1: 0);
2434                break;
2435            case CLASS_PALADIN:
2436                info->stats[STAT_STRENGTH]  += (lvl > 3  ? 1: 0);
2437                info->stats[STAT_STAMINA]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2438                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2439                info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2440                info->stats[STAT_SPIRIT]    += (lvl > 7 ? 1: 0);
2441                break;
2442            case CLASS_HUNTER:
2443                info->stats[STAT_STRENGTH]  += (lvl > 4  ? 1: 0);
2444                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2445                info->stats[STAT_AGILITY]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2446                info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2447                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2448                break;
2449            case CLASS_ROGUE:
2450                info->stats[STAT_STRENGTH]  += (lvl > 5  ? 1: 0);
2451                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2452                info->stats[STAT_AGILITY]   += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2453                info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2454                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2455                break;
2456            case CLASS_PRIEST:
2457                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2458                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2459                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2460                info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2461                info->stats[STAT_SPIRIT]    += (lvl > 3  ? 1: 0);
2462                break;
2463            case CLASS_SHAMAN:
2464                info->stats[STAT_STRENGTH]  += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2465                info->stats[STAT_STAMINA]   += (lvl > 4 ? 1: 0);
2466                info->stats[STAT_AGILITY]   += (lvl > 7 && !(lvl%2) ? 1: 0);
2467                info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2468                info->stats[STAT_SPIRIT]    += (lvl > 4 ? 1: 0);
2469                break;
2470            case CLASS_MAGE:
2471                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2472                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2473                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2474                info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2475                info->stats[STAT_SPIRIT]    += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2476                break;
2477            case CLASS_WARLOCK:
2478                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2479                info->stats[STAT_STAMINA]   += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2480                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2481                info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2482                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2483                break;
2484            case CLASS_DRUID:
2485                info->stats[STAT_STRENGTH]  += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2486                info->stats[STAT_STAMINA]   += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2487                info->stats[STAT_AGILITY]   += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2488                info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2489                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2490        }
2491    }
2492}
2493
2494void ObjectMgr::LoadGuilds()
2495{
2496    Guild *newguild;
2497    uint32 count = 0;
2498
2499    QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2500
2501    if( !result )
2502    {
2503
2504        barGoLink bar( 1 );
2505
2506        bar.step();
2507
2508        sLog.outString();
2509        sLog.outString( ">> Loaded %u guild definitions", count );
2510        return;
2511    }
2512
2513    barGoLink bar( result->GetRowCount() );
2514
2515    do
2516    {
2517        Field *fields = result->Fetch();
2518
2519        bar.step();
2520        ++count;
2521
2522        newguild = new Guild;
2523        if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2524        {
2525            newguild->Disband();
2526            delete newguild;
2527            continue;
2528        }
2529        AddGuild(newguild);
2530
2531    }while( result->NextRow() );
2532
2533    delete result;
2534
2535    sLog.outString();
2536    sLog.outString( ">> Loaded %u guild definitions", count );
2537}
2538
2539void ObjectMgr::LoadArenaTeams()
2540{
2541    uint32 count = 0;
2542
2543    QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2544
2545    if( !result )
2546    {
2547
2548        barGoLink bar( 1 );
2549
2550        bar.step();
2551
2552        sLog.outString();
2553        sLog.outString( ">> Loaded %u arenateam definitions", count );
2554        return;
2555    }
2556
2557    barGoLink bar( result->GetRowCount() );
2558
2559    do
2560    {
2561        Field *fields = result->Fetch();
2562
2563        bar.step();
2564        ++count;
2565
2566        ArenaTeam *newarenateam = new ArenaTeam;
2567        if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2568        {
2569            delete newarenateam;
2570            continue;
2571        }
2572        AddArenaTeam(newarenateam);
2573    }while( result->NextRow() );
2574
2575    delete result;
2576
2577    sLog.outString();
2578    sLog.outString( ">> Loaded %u arenateam definitions", count );
2579}
2580
2581void ObjectMgr::LoadGroups()
2582{
2583    // -- loading groups --
2584    Group *group = NULL;
2585    uint64 leaderGuid = 0;
2586    uint32 count = 0;
2587    //                                                     0         1              2           3           4              5      6      7      8      9      10     11     12     13      14          15
2588    QueryResult *result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2589
2590    if( !result )
2591    {
2592        barGoLink bar( 1 );
2593
2594        bar.step();
2595
2596        sLog.outString();
2597        sLog.outString( ">> Loaded %u group definitions", count );
2598        return;
2599    }
2600
2601    barGoLink bar( result->GetRowCount() );
2602
2603    do
2604    {
2605        bar.step();
2606        Field *fields = result->Fetch();
2607        ++count;
2608        leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2609
2610        group = new Group;
2611        if(!group->LoadGroupFromDB(leaderGuid, result, false))
2612        {
2613            group->Disband();
2614            delete group;
2615            continue;
2616        }
2617        AddGroup(group);
2618    }while( result->NextRow() );
2619
2620    delete result;
2621
2622    sLog.outString();
2623    sLog.outString( ">> Loaded %u group definitions", count );
2624
2625    // -- loading members --
2626    count = 0;
2627    group = NULL;
2628    leaderGuid = 0;
2629    //                                        0           1          2         3
2630    result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2631    if(!result)
2632    {
2633        barGoLink bar( 1 );
2634        bar.step();
2635    }
2636    else
2637    {
2638        barGoLink bar( result->GetRowCount() );
2639        do
2640        {
2641            bar.step();
2642            Field *fields = result->Fetch();
2643            count++;
2644            leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2645            if(!group || group->GetLeaderGUID() != leaderGuid)
2646            {
2647                group = GetGroupByLeader(leaderGuid);
2648                if(!group)
2649                {
2650                    sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2651                    CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2652                    continue;
2653                }
2654            }
2655
2656            if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2657            {
2658                sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2659                CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2660            }
2661        }while( result->NextRow() );
2662        delete result;
2663    }
2664
2665    // clean groups
2666    // TODO: maybe delete from the DB before loading in this case
2667    for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2668    {
2669        if((*itr)->GetMembersCount() < 2)
2670        {
2671            (*itr)->Disband();
2672            delete *itr;
2673            mGroupSet.erase(itr++);
2674        }
2675        else
2676            ++itr;
2677    }
2678
2679    // -- loading instances --
2680    count = 0;
2681    group = NULL;
2682    leaderGuid = 0;
2683    result = CharacterDatabase.PQuery(
2684        //      0           1    2         3          4           5
2685        "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2686        // 6
2687        "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2688        "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2689    );
2690
2691    if(!result)
2692    {
2693        barGoLink bar( 1 );
2694        bar.step();
2695    }
2696    else
2697    {
2698        barGoLink bar( result->GetRowCount() );
2699        do
2700        {
2701            bar.step();
2702            Field *fields = result->Fetch();
2703            count++;
2704            leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2705            if(!group || group->GetLeaderGUID() != leaderGuid)
2706            {
2707                group = GetGroupByLeader(leaderGuid);
2708                if(!group)
2709                {
2710                    sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2711                    continue;
2712                }
2713            }
2714
2715            InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2716            group->BindToInstance(save, fields[3].GetBool(), true);
2717        }while( result->NextRow() );
2718        delete result;
2719    }
2720
2721    sLog.outString();
2722    sLog.outString( ">> Loaded %u group-instance binds total", count );
2723
2724    sLog.outString();
2725    sLog.outString( ">> Loaded %u group members total", count );
2726}
2727
2728void ObjectMgr::LoadQuests()
2729{
2730    // For reload case
2731    for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2732        delete itr->second;
2733    mQuestTemplates.clear();
2734
2735    mExclusiveQuestGroups.clear();
2736
2737    //                                                0      1       2           3             4         5           6     7              8
2738    QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2739    //   9                    10                 11                     12                   13                     14                   15                16
2740        "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2741    //   17          18            19           20           21           22              23                24         25            26
2742        "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2743    //   27     28       29          30               31                32       33              34              35              36
2744        "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2745    //   37          38          39          40          41             42             43             44
2746        "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2747    //   45            46            47            48            49               50               51               52               53             54             54             55
2748        "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2749    //   57                  58                  59                  60                  61                     62                     63                     64
2750        "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2751    //   65             66             67             68
2752        "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2753    //   69                70                71                72                73                74
2754        "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2755    //   75                   76                   77                   78                   79                   80
2756        "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2757    //   81          82          83          84          85             86             87             88
2758        "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2759    //   89              90              91              92              93              94            95            96            97            98
2760        "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2761    //   99             100               101       102           103                104               105         106     107     108
2762        "RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2763    //   109            110            111            112           113              114            115                116                117                118
2764        "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2765    //   119          120
2766        "StartScript, CompleteScript"
2767        " FROM quest_template");
2768    if(result == NULL)
2769    {
2770        barGoLink bar( 1 );
2771        bar.step();
2772
2773        sLog.outString();
2774        sLog.outString( ">> Loaded 0 quests definitions" );
2775        sLog.outErrorDb("`quest_template` table is empty!");
2776        return;
2777    }
2778
2779    // create multimap previous quest for each existed quest
2780    // some quests can have many previous maps set by NextQuestId in previous quest
2781    // for example set of race quests can lead to single not race specific quest
2782    barGoLink bar( result->GetRowCount() );
2783    do
2784    {
2785        bar.step();
2786        Field *fields = result->Fetch();
2787
2788        Quest * newQuest = new Quest(fields);
2789        mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2790    } while( result->NextRow() );
2791
2792    delete result;
2793
2794    // Post processing
2795    for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2796    {
2797        Quest * qinfo = iter->second;
2798
2799        // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2800
2801        if( qinfo->GetQuestMethod() >= 3 )
2802        {
2803            sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2804        }
2805
2806        if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2807        {
2808            sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2809                qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2810            qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2811        }
2812
2813        if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2814        {
2815            if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2816            {
2817                sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2818                qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2819            }
2820        }
2821
2822        if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2823        {
2824            // at auto-reward can be rewarded only RewChoiceItemId[0]
2825            for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2826            {
2827                if(uint32 id = qinfo->RewChoiceItemId[j])
2828                {
2829                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2830                        qinfo->GetQuestId(),j+1,id,j+1);
2831                    // no changes, quest ignore this data
2832                }
2833            }
2834        }
2835
2836        // client quest log visual (area case)
2837        if( qinfo->ZoneOrSort > 0 )
2838        {
2839            if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2840            {
2841                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2842                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2843                // no changes, quest not dependent from this value but can have problems at client
2844            }
2845        }
2846        // client quest log visual (sort case)
2847        if( qinfo->ZoneOrSort < 0 )
2848        {
2849            QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2850            if( !qSort )
2851            {
2852                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2853                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2854                // 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)
2855            }
2856            //check SkillOrClass value (class case).
2857            if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2858            {
2859                // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2860                if(qinfo->SkillOrClass < 0)
2861                {
2862                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2863                        qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2864                }
2865            }
2866            //check for proper SkillOrClass value (skill case)
2867            if(int32 skill_id =  SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2868            {
2869                // skill is positive value in SkillOrClass
2870                if(qinfo->SkillOrClass != skill_id )
2871                {
2872                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2873                        qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2874                    //override, and force proper value here?
2875                }
2876            }
2877        }
2878
2879        // SkillOrClass (class case)
2880        if( qinfo->SkillOrClass < 0 )
2881        {
2882            if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2883            {
2884                sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2885                    qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2886            }
2887        }
2888        // SkillOrClass (skill case)
2889        if( qinfo->SkillOrClass > 0 )
2890        {
2891            if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2892            {
2893                sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2894                    qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2895            }
2896        }
2897
2898        if( qinfo->RequiredSkillValue )
2899        {
2900            if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2901            {
2902                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2903                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2904                // no changes, quest can't be done for this requirement
2905            }
2906
2907            if( qinfo->SkillOrClass <= 0 )
2908            {
2909                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2910                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2911                // no changes, quest can't be done for this requirement (fail at wrong skill id)
2912            }
2913        }
2914        // else Skill quests can have 0 skill level, this is ok
2915
2916        if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2917        {
2918            sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2919                qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2920            // no changes, quest can't be done for this requirement
2921        }
2922
2923        if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2924        {
2925            sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2926                qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2927            // no changes, quest can't be done for this requirement
2928        }
2929
2930        if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2931        {
2932            sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2933                qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2934            // no changes, quest can't be done for this requirement
2935        }
2936
2937        if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2938        {
2939            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2940                qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2941            // no changes, quest can't be done for this requirement
2942        }
2943
2944        if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2945        {
2946            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2947                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2948            // no changes, quest can't be done for this requirement
2949        }
2950
2951        if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2952        {
2953            sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2954                qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2955            // warning
2956        }
2957
2958        if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2959        {
2960            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2961                qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2962            // warning
2963        }
2964
2965        if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2966        {
2967            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2968                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2969            // warning
2970        }
2971
2972        if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2973        {
2974            sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2975                qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2976            qinfo->CharTitleId = 0;
2977            // quest can't reward this title
2978        }
2979
2980        if(qinfo->SrcItemId)
2981        {
2982            if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2983            {
2984                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2985                    qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2986                qinfo->SrcItemId = 0;                       // quest can't be done for this requirement
2987            }
2988            else if(qinfo->SrcItemCount==0)
2989            {
2990                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2991                    qinfo->GetQuestId(),qinfo->SrcItemId);
2992                qinfo->SrcItemCount = 1;                    // update to 1 for allow quest work for backward comptibility with DB
2993            }
2994        }
2995        else if(qinfo->SrcItemCount>0)
2996        {
2997            sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
2998                qinfo->GetQuestId(),qinfo->SrcItemCount);
2999            qinfo->SrcItemCount=0;                          // no quest work changes in fact
3000        }
3001
3002        if(qinfo->SrcSpell)
3003        {
3004            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3005            if(!spellInfo)
3006            {
3007                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3008                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3009                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
3010            }
3011            else if(!SpellMgr::IsSpellValid(spellInfo))
3012            {
3013                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3014                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3015                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
3016            }
3017        }
3018
3019        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3020        {
3021            uint32 id = qinfo->ReqItemId[j];
3022            if(id)
3023            {
3024                if(qinfo->ReqItemCount[j]==0)
3025                {
3026                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3027                        qinfo->GetQuestId(),j+1,id,j+1);
3028                    // no changes, quest can't be done for this requirement
3029                }
3030
3031                qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3032
3033                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3034                {
3035                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3036                        qinfo->GetQuestId(),j+1,id,id);
3037                    qinfo->ReqItemCount[j] = 0;             // prevent incorrect work of quest
3038                }
3039            }
3040            else if(qinfo->ReqItemCount[j]>0)
3041            {
3042                sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3043                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3044                qinfo->ReqItemCount[j] = 0;                 // prevent incorrect work of quest
3045            }
3046        }
3047
3048        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3049        {
3050            uint32 id = qinfo->ReqSourceId[j];
3051            if(id)
3052            {
3053                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3054                {
3055                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3056                        qinfo->GetQuestId(),j+1,id,id);
3057                    // no changes, quest can't be done for this requirement
3058                }
3059
3060                if(!qinfo->ReqSourceCount[j])
3061                {
3062                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3063                        qinfo->GetQuestId(),j+1,id,j+1);
3064                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3065                }
3066
3067                if(!qinfo->ReqSourceRef[j])
3068                {
3069                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3070                        qinfo->GetQuestId(),j+1,id,j+1);
3071                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3072                }
3073            }
3074            else
3075            {
3076                if(qinfo->ReqSourceCount[j]>0)
3077                {
3078                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3079                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3080                    // no changes, quest ignore this data
3081                }
3082
3083                if(qinfo->ReqSourceRef[j]>0)
3084                {
3085                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3086                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3087                    // no changes, quest ignore this data
3088                }
3089            }
3090        }
3091
3092        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3093        {
3094            uint32 ref = qinfo->ReqSourceRef[j];
3095            if(ref)
3096            {
3097                if(ref > QUEST_OBJECTIVES_COUNT)
3098                {
3099                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3100                        qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3101                    // no changes, quest can't be done for this requirement
3102                }
3103                else
3104                if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3105                {
3106                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3107                        qinfo->GetQuestId(),j+1,ref,ref,ref);
3108                    // no changes, quest can't be done for this requirement
3109                }
3110                else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3111                {
3112                    sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3113                        qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3114                    // no changes, quest can't be done for this requirement
3115                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3116                }
3117            }
3118        }
3119
3120        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3121        {
3122            uint32 id = qinfo->ReqSpell[j];
3123            if(id)
3124            {
3125                SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3126                if(!spellInfo)
3127                {
3128                    sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3129                        qinfo->GetQuestId(),j+1,id,id);
3130                    // no changes, quest can't be done for this requirement
3131                }
3132
3133                if(!qinfo->ReqCreatureOrGOId[j])
3134                {
3135                    bool found = false;
3136                    for(int k = 0; k < 3; ++k)
3137                    {
3138                        if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3139                            spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3140                        {
3141                            found = true;
3142                            break;
3143                        }
3144                    }
3145
3146                    if(found)
3147                    {
3148                        if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3149                        {
3150                            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);
3151
3152                            // this will prevent quest completing without objective
3153                            const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3154                        }
3155                    }
3156                    else
3157                    {
3158                        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.",
3159                            qinfo->GetQuestId(),j+1,id,j+1,id);
3160                        // no changes, quest can't be done for this requirement
3161                    }
3162                }
3163            }
3164        }
3165
3166        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3167        {
3168            int32 id = qinfo->ReqCreatureOrGOId[j];
3169            if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3170            {
3171                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3172                    qinfo->GetQuestId(),j+1,id,uint32(-id));
3173                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3174            }
3175
3176            if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3177            {
3178                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3179                    qinfo->GetQuestId(),j+1,id,uint32(id));
3180                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3181            }
3182
3183            if(id)
3184            {
3185                // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3186
3187                qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3188
3189                if(!qinfo->ReqCreatureOrGOCount[j])
3190                {
3191                    sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3192                        qinfo->GetQuestId(),j+1,id,j+1);
3193                    // no changes, quest can be incorrectly done, but we already report this
3194                }
3195            }
3196            else if(qinfo->ReqCreatureOrGOCount[j]>0)
3197            {
3198                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3199                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3200                // no changes, quest ignore this data
3201            }
3202        }
3203
3204        for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3205        {
3206            uint32 id = qinfo->RewChoiceItemId[j];
3207            if(id)
3208            {
3209                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3210                {
3211                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3212                        qinfo->GetQuestId(),j+1,id,id);
3213                    qinfo->RewChoiceItemId[j] = 0;          // no changes, quest will not reward this
3214                }
3215
3216                if(!qinfo->RewChoiceItemCount[j])
3217                {
3218                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3219                        qinfo->GetQuestId(),j+1,id,j+1);
3220                    // no changes, quest can't be done
3221                }
3222            }
3223            else if(qinfo->RewChoiceItemCount[j]>0)
3224            {
3225                sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3226                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3227                // no changes, quest ignore this data
3228            }
3229        }
3230
3231        for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3232        {
3233            uint32 id = qinfo->RewItemId[j];
3234            if(id)
3235            {
3236                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3237                {
3238                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3239                        qinfo->GetQuestId(),j+1,id,id);
3240                    qinfo->RewItemId[j] = 0;                // no changes, quest will not reward this item
3241                }
3242
3243                if(!qinfo->RewItemCount[j])
3244                {
3245                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3246                        qinfo->GetQuestId(),j+1,id,j+1);
3247                    // no changes
3248                }
3249            }
3250            else if(qinfo->RewItemCount[j]>0)
3251            {
3252                sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3253                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3254                // no changes, quest ignore this data
3255            }
3256        }
3257
3258        for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3259        {
3260            if(qinfo->RewRepFaction[j])
3261            {
3262                if(!qinfo->RewRepValue[j])
3263                {
3264                    sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3265                        qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3266                    // no changes
3267                }
3268
3269                if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3270                {
3271                    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.",
3272                        qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3273                    qinfo->RewRepFaction[j] = 0;            // quest will not reward this
3274                }
3275            }
3276            else if(qinfo->RewRepValue[j]!=0)
3277            {
3278                sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3279                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3280                // no changes, quest ignore this data
3281            }
3282        }
3283
3284        if(qinfo->RewSpell)
3285        {
3286            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3287
3288            if(!spellInfo)
3289            {
3290                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3291                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3292                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3293            }
3294
3295            else if(!SpellMgr::IsSpellValid(spellInfo))
3296            {
3297                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3298                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3299                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3300            }
3301
3302        }
3303
3304        if(qinfo->RewSpellCast)
3305        {
3306            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3307
3308            if(!spellInfo)
3309            {
3310                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3311                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3312                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3313            }
3314
3315            else if(!SpellMgr::IsSpellValid(spellInfo))
3316            {
3317                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3318                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3319                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3320            }
3321
3322        }
3323
3324        if(qinfo->RewMailTemplateId)
3325        {
3326            if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3327            {
3328                sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template  %u does not exist, quest will not have a mail reward.",
3329                    qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3330                qinfo->RewMailTemplateId = 0;               // no mail will send to player
3331                qinfo->RewMailDelaySecs = 0;                // no mail will send to player
3332            }
3333        }
3334
3335        if(qinfo->NextQuestInChain)
3336        {
3337            if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3338            {
3339                sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3340                    qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3341                qinfo->NextQuestInChain = 0;
3342            }
3343            else
3344                mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3345        }
3346
3347        // fill additional data stores
3348        if(qinfo->PrevQuestId)
3349        {
3350            if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3351            {
3352                sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3353            }
3354            else
3355            {
3356                qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3357            }
3358        }
3359
3360        if(qinfo->NextQuestId)
3361        {
3362            if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3363            {
3364                sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3365            }
3366            else
3367            {
3368                int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3369                mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3370            }
3371        }
3372
3373        if(qinfo->ExclusiveGroup)
3374            mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3375        if(qinfo->LimitTime)
3376            qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3377    }
3378
3379    // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3380    for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3381    {
3382        SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3383        if(!spellInfo)
3384            continue;
3385
3386        for(int j = 0; j < 3; ++j)
3387        {
3388            if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3389                continue;
3390
3391            uint32 quest_id = spellInfo->EffectMiscValue[j];
3392
3393            Quest const* quest = GetQuestTemplate(quest_id);
3394
3395            // some quest referenced in spells not exist (outdataed spells)
3396            if(!quest)
3397                continue;
3398
3399            if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3400            {
3401                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);
3402
3403                // this will prevent quest completing without objective
3404                const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3405            }
3406        }
3407    }
3408
3409    sLog.outString();
3410    sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3411}
3412
3413void ObjectMgr::LoadQuestLocales()
3414{
3415    QueryResult *result = WorldDatabase.Query("SELECT entry,"
3416        "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3417        "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3418        "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3419        "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3420        "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3421        "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3422        "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3423        "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3424        " FROM locales_quest"
3425        );
3426
3427    if(!result)
3428    {
3429        barGoLink bar(1);
3430
3431        bar.step();
3432
3433        sLog.outString("");
3434        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3435        return;
3436    }
3437
3438    barGoLink bar(result->GetRowCount());
3439
3440    do
3441    {
3442        Field *fields = result->Fetch();
3443        bar.step();
3444
3445        uint32 entry = fields[0].GetUInt32();
3446
3447        QuestLocale& data = mQuestLocaleMap[entry];
3448
3449        for(int i = 1; i < MAX_LOCALE; ++i)
3450        {
3451            std::string str = fields[1+10*(i-1)].GetCppString();
3452            if(!str.empty())
3453            {
3454                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3455                if(idx >= 0)
3456                {
3457                    if(data.Title.size() <= idx)
3458                        data.Title.resize(idx+1);
3459
3460                    data.Title[idx] = str;
3461                }
3462            }
3463            str = fields[1+10*(i-1)+1].GetCppString();
3464            if(!str.empty())
3465            {
3466                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3467                if(idx >= 0)
3468                {
3469                    if(data.Details.size() <= idx)
3470                        data.Details.resize(idx+1);
3471
3472                    data.Details[idx] = str;
3473                }
3474            }
3475            str = fields[1+10*(i-1)+2].GetCppString();
3476            if(!str.empty())
3477            {
3478                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3479                if(idx >= 0)
3480                {
3481                    if(data.Objectives.size() <= idx)
3482                        data.Objectives.resize(idx+1);
3483
3484                    data.Objectives[idx] = str;
3485                }
3486            }
3487            str = fields[1+10*(i-1)+3].GetCppString();
3488            if(!str.empty())
3489            {
3490                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3491                if(idx >= 0)
3492                {
3493                    if(data.OfferRewardText.size() <= idx)
3494                        data.OfferRewardText.resize(idx+1);
3495
3496                    data.OfferRewardText[idx] = str;
3497                }
3498            }
3499            str = fields[1+10*(i-1)+4].GetCppString();
3500            if(!str.empty())
3501            {
3502                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3503                if(idx >= 0)
3504                {
3505                    if(data.RequestItemsText.size() <= idx)
3506                        data.RequestItemsText.resize(idx+1);
3507
3508                    data.RequestItemsText[idx] = str;
3509                }
3510            }
3511            str = fields[1+10*(i-1)+5].GetCppString();
3512            if(!str.empty())
3513            {
3514                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3515                if(idx >= 0)
3516                {
3517                    if(data.EndText.size() <= idx)
3518                        data.EndText.resize(idx+1);
3519
3520                    data.EndText[idx] = str;
3521                }
3522            }
3523            for(int k = 0; k < 4; ++k)
3524            {
3525                str = fields[1+10*(i-1)+6+k].GetCppString();
3526                if(!str.empty())
3527                {
3528                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3529                    if(idx >= 0)
3530                    {
3531                        if(data.ObjectiveText[k].size() <= idx)
3532                            data.ObjectiveText[k].resize(idx+1);
3533
3534                        data.ObjectiveText[k][idx] = str;
3535                    }
3536                }
3537            }
3538        }
3539    } while (result->NextRow());
3540
3541    delete result;
3542
3543    sLog.outString();
3544    sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3545}
3546
3547void ObjectMgr::LoadPetCreateSpells()
3548{
3549    QueryResult *result = WorldDatabase.PQuery("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3550    if(!result)
3551    {
3552        barGoLink bar( 1 );
3553        bar.step();
3554
3555        sLog.outString();
3556        sLog.outString( ">> Loaded 0 pet create spells" );
3557        sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3558        return;
3559    }
3560
3561    uint32 count = 0;
3562
3563    barGoLink bar( result->GetRowCount() );
3564
3565    mPetCreateSpell.clear();
3566
3567    do
3568    {
3569        Field *fields = result->Fetch();
3570        bar.step();
3571
3572        uint32 creature_id = fields[0].GetUInt32();
3573
3574        if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3575            continue;
3576
3577        PetCreateSpellEntry PetCreateSpell;
3578        for(int i = 0; i < 4; i++)
3579        {
3580            PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3581
3582            if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3583                sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3584        }
3585
3586        mPetCreateSpell[creature_id] = PetCreateSpell;
3587
3588        ++count;
3589    }
3590    while (result->NextRow());
3591
3592    delete result;
3593
3594    sLog.outString();
3595    sLog.outString( ">> Loaded %u pet create spells", count );
3596}
3597
3598void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3599{
3600    if(sWorld.IsScriptScheduled())                          // function don't must be called in time scripts use.
3601        return;
3602
3603    sLog.outString( "%s :", tablename);
3604
3605    scripts.clear();                                        // need for reload support
3606
3607    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3608
3609    uint32 count = 0;
3610
3611    if( !result )
3612    {
3613        barGoLink bar( 1 );
3614        bar.step();
3615
3616        sLog.outString();
3617        sLog.outString( ">> Loaded %u script definitions", count );
3618        return;
3619    }
3620
3621    barGoLink bar( result->GetRowCount() );
3622
3623    do
3624    {
3625        bar.step();
3626
3627        Field *fields = result->Fetch();
3628        ScriptInfo tmp;
3629        tmp.id = fields[0].GetUInt32();
3630        tmp.delay = fields[1].GetUInt32();
3631        tmp.command = fields[2].GetUInt32();
3632        tmp.datalong = fields[3].GetUInt32();
3633        tmp.datalong2 = fields[4].GetUInt32();
3634        tmp.datatext = fields[5].GetCppString();
3635        tmp.x = fields[6].GetFloat();
3636        tmp.y = fields[7].GetFloat();
3637        tmp.z = fields[8].GetFloat();
3638        tmp.o = fields[9].GetFloat();
3639
3640        // generic command args check
3641        switch(tmp.command)
3642        {
3643            case SCRIPT_COMMAND_TALK:
3644            {
3645                if(tmp.datalong > 3)
3646                {
3647                    sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3648                    continue;
3649                }
3650                break;
3651            }
3652
3653            case SCRIPT_COMMAND_TELEPORT_TO:
3654            {
3655                if(!sMapStore.LookupEntry(tmp.datalong))
3656                {
3657                    sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3658                    continue;
3659                }
3660
3661                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3662                {
3663                    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);
3664                    continue;
3665                }
3666                break;
3667            }
3668
3669            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3670            {
3671                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3672                {
3673                    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);
3674                    continue;
3675                }
3676
3677                if(!GetCreatureTemplate(tmp.datalong))
3678                {
3679                    sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3680                    continue;
3681                }
3682                break;
3683            }
3684
3685            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3686            {
3687                GameObjectData const* data = GetGOData(tmp.datalong);
3688                if(!data)
3689                {
3690                    sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3691                    continue;
3692                }
3693
3694                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3695                if(!info)
3696                {
3697                    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);
3698                    continue;
3699                }
3700
3701                if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3702                    info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3703                    info->type==GAMEOBJECT_TYPE_DOOR        ||
3704                    info->type==GAMEOBJECT_TYPE_BUTTON      ||
3705                    info->type==GAMEOBJECT_TYPE_TRAP )
3706                {
3707                    sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3708                    continue;
3709                }
3710                break;
3711            }
3712            case SCRIPT_COMMAND_OPEN_DOOR:
3713            case SCRIPT_COMMAND_CLOSE_DOOR:
3714            {
3715                GameObjectData const* data = GetGOData(tmp.datalong);
3716                if(!data)
3717                {
3718                    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);
3719                    continue;
3720                }
3721
3722                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3723                if(!info)
3724                {
3725                    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);
3726                    continue;
3727                }
3728
3729                if( info->type!=GAMEOBJECT_TYPE_DOOR)
3730                {
3731                    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);
3732                    continue;
3733                }
3734
3735                break;
3736            }
3737            case SCRIPT_COMMAND_QUEST_EXPLORED:
3738            {
3739                Quest const* quest = GetQuestTemplate(tmp.datalong);
3740                if(!quest)
3741                {
3742                    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);
3743                    continue;
3744                }
3745
3746                if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3747                {
3748                    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);
3749
3750                    // this will prevent quest completing without objective
3751                    const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3752
3753                    // continue; - quest objective requiremet set and command can be allowed
3754                }
3755
3756                if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3757                {
3758                    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);
3759                    continue;
3760                }
3761
3762                if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3763                {
3764                    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));
3765                    continue;
3766                }
3767
3768                if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3769                {
3770                    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));
3771                    continue;
3772                }
3773
3774                break;
3775            }
3776
3777            case SCRIPT_COMMAND_REMOVE_AURA:
3778            case SCRIPT_COMMAND_CAST_SPELL:
3779            {
3780                if(!sSpellStore.LookupEntry(tmp.datalong))
3781                {
3782                    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);
3783                    continue;
3784                }
3785                break;
3786            }
3787        }
3788
3789        if (scripts.find(tmp.id) == scripts.end())
3790        {
3791            ScriptMap emptyMap;
3792            scripts[tmp.id] = emptyMap;
3793        }
3794        scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3795
3796        ++count;
3797    } while( result->NextRow() );
3798
3799    delete result;
3800
3801    sLog.outString();
3802    sLog.outString( ">> Loaded %u script definitions", count );
3803}
3804
3805void ObjectMgr::LoadGameObjectScripts()
3806{
3807    LoadScripts(sGameObjectScripts,    "gameobject_scripts");
3808
3809    // check ids
3810    for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3811    {
3812        if(!GetGOData(itr->first))
3813            sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3814    }
3815}
3816
3817void ObjectMgr::LoadQuestEndScripts()
3818{
3819    LoadScripts(sQuestEndScripts,  "quest_end_scripts");
3820
3821    // check ids
3822    for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3823    {
3824        if(!GetQuestTemplate(itr->first))
3825            sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3826    }
3827}
3828
3829void ObjectMgr::LoadQuestStartScripts()
3830{
3831    LoadScripts(sQuestStartScripts,"quest_start_scripts");
3832
3833    // check ids
3834    for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3835    {
3836        if(!GetQuestTemplate(itr->first))
3837            sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3838    }
3839}
3840
3841void ObjectMgr::LoadSpellScripts()
3842{
3843    LoadScripts(sSpellScripts, "spell_scripts");
3844
3845    // check ids
3846    for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3847    {
3848        SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3849
3850        if(!spellInfo)
3851        {
3852            sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3853            continue;
3854        }
3855
3856        //check for correct spellEffect
3857        bool found = false;
3858        for(int i=0; i<3; ++i)
3859        {
3860            // skip empty effects
3861            if( !spellInfo->Effect[i] )
3862                continue;
3863
3864            if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3865            {
3866                found =  true;
3867                break;
3868            }
3869        }
3870
3871        if(!found)
3872            sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3873    }
3874}
3875
3876void ObjectMgr::LoadEventScripts()
3877{
3878    LoadScripts(sEventScripts, "event_scripts");
3879
3880    std::set<uint32> evt_scripts;
3881    // Load all possible script entries from gameobjects
3882    for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3883    {
3884        GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3885        if (goInfo)
3886        {
3887            switch(goInfo->type)
3888            {
3889                case GAMEOBJECT_TYPE_GOOBER:
3890                    if(goInfo->goober.eventId)
3891                        evt_scripts.insert(goInfo->goober.eventId);
3892                    break;
3893                case GAMEOBJECT_TYPE_CHEST:
3894                    if(goInfo->chest.eventId)
3895                        evt_scripts.insert(goInfo->chest.eventId);
3896                    break;
3897                default:
3898                    break;
3899            }
3900        }
3901    }
3902    // Load all possible script entries from spells
3903    for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3904    {
3905        SpellEntry const * spell = sSpellStore.LookupEntry(i);
3906        if (spell)
3907        {
3908            for(int j=0; j<3; ++j)
3909            {
3910                if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3911                {
3912                    if (spell->EffectMiscValue[j])
3913                        evt_scripts.insert(spell->EffectMiscValue[j]);
3914                }
3915            }
3916        }
3917    }
3918    // Then check if all scripts are in above list of possible script entries
3919    for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3920    {
3921        std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3922        if (itr2 == evt_scripts.end())
3923            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);
3924    }
3925}
3926
3927void ObjectMgr::LoadItemTexts()
3928{
3929    QueryResult *result = CharacterDatabase.PQuery("SELECT id, text FROM item_text");
3930
3931    uint32 count = 0;
3932
3933    if( !result )
3934    {
3935        barGoLink bar( 1 );
3936        bar.step();
3937
3938        sLog.outString();
3939        sLog.outString( ">> Loaded %u item pages", count );
3940        return;
3941    }
3942
3943    barGoLink bar( result->GetRowCount() );
3944
3945    Field* fields;
3946    do
3947    {
3948        bar.step();
3949
3950        fields = result->Fetch();
3951
3952        mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3953
3954        ++count;
3955
3956    } while ( result->NextRow() );
3957
3958    delete result;
3959
3960    sLog.outString();
3961    sLog.outString( ">> Loaded %u item texts", count );
3962}
3963
3964void ObjectMgr::LoadPageTexts()
3965{
3966    sPageTextStore.Free();                                  // for reload case
3967
3968    sPageTextStore.Load();
3969    sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3970    sLog.outString();
3971
3972    for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3973    {
3974        // check data correctness
3975        PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3976        if(!page)
3977            continue;
3978
3979        if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3980        {
3981            sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3982            continue;
3983        }
3984
3985        // detect circular reference
3986        std::set<uint32> checkedPages;
3987        for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
3988        {
3989            if(!pageItr->Next_Page)
3990                break;
3991            checkedPages.insert(pageItr->Page_ID);
3992            if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
3993            {
3994                std::ostringstream ss;
3995                ss<< "The text page(s) ";
3996                for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
3997                    ss << *itr << " ";
3998                ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
3999                    << pageItr->Page_ID <<" to 0";
4000                sLog.outErrorDb(ss.str().c_str());
4001                const_cast<PageText*>(pageItr)->Next_Page = 0;
4002                break;
4003            }
4004        }
4005    }
4006}
4007
4008void ObjectMgr::LoadPageTextLocales()
4009{
4010    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");
4011
4012    if(!result)
4013    {
4014        barGoLink bar(1);
4015
4016        bar.step();
4017
4018        sLog.outString("");
4019        sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4020        return;
4021    }
4022
4023    barGoLink bar(result->GetRowCount());
4024
4025    do
4026    {
4027        Field *fields = result->Fetch();
4028        bar.step();
4029
4030        uint32 entry = fields[0].GetUInt32();
4031
4032        PageTextLocale& data = mPageTextLocaleMap[entry];
4033
4034        for(int i = 1; i < MAX_LOCALE; ++i)
4035        {
4036            std::string str = fields[i].GetCppString();
4037            if(str.empty())
4038                continue;
4039
4040            int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4041            if(idx >= 0)
4042            {
4043                if(data.Text.size() <= idx)
4044                    data.Text.resize(idx+1);
4045
4046                data.Text[idx] = str;
4047            }
4048        }
4049
4050    } while (result->NextRow());
4051
4052    delete result;
4053
4054    sLog.outString();
4055    sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4056}
4057
4058void ObjectMgr::LoadInstanceTemplate()
4059{
4060    sInstanceTemplate.Load();
4061
4062    for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4063    {
4064        InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4065        if(!temp) continue;
4066        const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4067        if(!entry)
4068        {
4069            sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4070            continue;
4071        }
4072        else if(!entry->HasResetTime())
4073            continue;
4074
4075        if(temp->reset_delay == 0)
4076        {
4077            // use defaults from the DBC
4078            if(entry->SupportsHeroicMode())
4079            {
4080                temp->reset_delay = entry->resetTimeHeroic / DAY;
4081            }
4082            else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4083            {
4084                temp->reset_delay = entry->resetTimeRaid / DAY;
4085            }
4086        }
4087
4088        // the reset_delay must be atleast one day
4089        temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4090    }
4091
4092    sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4093    sLog.outString();
4094}
4095
4096void ObjectMgr::AddGossipText(GossipText *pGText)
4097{
4098    ASSERT( pGText->Text_ID );
4099    ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4100    mGossipText[pGText->Text_ID] = pGText;
4101}
4102
4103GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4104{
4105    GossipTextMap::const_iterator itr;
4106    for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4107    {
4108        if(itr->second->Text_ID == Text_ID)
4109            return itr->second;
4110    }
4111    return NULL;
4112}
4113
4114void ObjectMgr::LoadGossipText()
4115{
4116    GossipText *pGText;
4117    QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4118
4119    int count = 0;
4120    if( !result )
4121    {
4122        barGoLink bar( 1 );
4123        bar.step();
4124
4125        sLog.outString();
4126        sLog.outString( ">> Loaded %u npc texts", count );
4127        return;
4128    }
4129
4130    int cic;
4131
4132    barGoLink bar( result->GetRowCount() );
4133
4134    do
4135    {
4136        ++count;
4137        cic = 0;
4138
4139        Field *fields = result->Fetch();
4140
4141        bar.step();
4142
4143        pGText = new GossipText;
4144        pGText->Text_ID    = fields[cic++].GetUInt32();
4145
4146        for (int i=0; i< 8; i++)
4147        {
4148            pGText->Options[i].Text_0           = fields[cic++].GetCppString();
4149            pGText->Options[i].Text_1           = fields[cic++].GetCppString();
4150
4151            pGText->Options[i].Language         = fields[cic++].GetUInt32();
4152            pGText->Options[i].Probability      = fields[cic++].GetFloat();
4153
4154            pGText->Options[i].Emotes[0]._Delay  = fields[cic++].GetUInt32();
4155            pGText->Options[i].Emotes[0]._Emote  = fields[cic++].GetUInt32();
4156
4157            pGText->Options[i].Emotes[1]._Delay  = fields[cic++].GetUInt32();
4158            pGText->Options[i].Emotes[1]._Emote  = fields[cic++].GetUInt32();
4159
4160            pGText->Options[i].Emotes[2]._Delay  = fields[cic++].GetUInt32();
4161            pGText->Options[i].Emotes[2]._Emote  = fields[cic++].GetUInt32();
4162        }
4163
4164        if ( !pGText->Text_ID ) continue;
4165        AddGossipText( pGText );
4166
4167    } while( result->NextRow() );
4168
4169    sLog.outString();
4170    sLog.outString( ">> Loaded %u npc texts", count );
4171    delete result;
4172}
4173
4174void ObjectMgr::LoadNpcTextLocales()
4175{
4176    QueryResult *result = WorldDatabase.Query("SELECT entry,"
4177        "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,"
4178        "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,"
4179        "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,"
4180        "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,"
4181        "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,"
4182        "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,"
4183        "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, "
4184        "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 "
4185        " FROM locales_npc_text");
4186
4187    if(!result)
4188    {
4189        barGoLink bar(1);
4190
4191        bar.step();
4192
4193        sLog.outString("");
4194        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4195        return;
4196    }
4197
4198    barGoLink bar(result->GetRowCount());
4199
4200    do
4201    {
4202        Field *fields = result->Fetch();
4203        bar.step();
4204
4205        uint32 entry = fields[0].GetUInt32();
4206
4207        NpcTextLocale& data = mNpcTextLocaleMap[entry];
4208
4209        for(int i=1; i<MAX_LOCALE; ++i)
4210        {
4211            for(int j=0; j<8; ++j)
4212            {
4213                std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4214                if(!str0.empty())
4215                {
4216                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4217                    if(idx >= 0)
4218                    {
4219                        if(data.Text_0[j].size() <= idx)
4220                            data.Text_0[j].resize(idx+1);
4221
4222                        data.Text_0[j][idx] = str0;
4223                    }
4224                }
4225                std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4226                if(!str1.empty())
4227                {
4228                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4229                    if(idx >= 0)
4230                    {
4231                        if(data.Text_1[j].size() <= idx)
4232                            data.Text_1[j].resize(idx+1);
4233
4234                        data.Text_1[j][idx] = str1;
4235                    }
4236                }
4237            }
4238        }
4239    } while (result->NextRow());
4240
4241    delete result;
4242
4243    sLog.outString();
4244    sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4245}
4246
4247//not very fast function but it is called only once a day, or on starting-up
4248void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4249{
4250    time_t basetime = time(NULL);
4251    sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4252    //delete all old mails without item and without body immediately, if starting server
4253    if (!serverUp)
4254        CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4255    //                                                     0  1           2      3        4          5         6           7   8       9
4256    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);
4257    if ( !result )
4258        return;                                             // any mails need to be returned or deleted
4259    Field *fields;
4260    //std::ostringstream delitems, delmails; //will be here for optimization
4261    //bool deletemail = false, deleteitem = false;
4262    //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4263    //delmails << "DELETE FROM mail WHERE id IN ( "
4264    do
4265    {
4266        fields = result->Fetch();
4267        Mail *m = new Mail;
4268        m->messageID = fields[0].GetUInt32();
4269        m->messageType = fields[1].GetUInt8();
4270        m->sender = fields[2].GetUInt32();
4271        m->receiver = fields[3].GetUInt32();
4272        m->itemTextId = fields[4].GetUInt32();
4273        bool has_items = fields[5].GetBool();
4274        m->expire_time = (time_t)fields[6].GetUInt64();
4275        m->deliver_time = 0;
4276        m->COD = fields[7].GetUInt32();
4277        m->checked = fields[8].GetUInt32();
4278        m->mailTemplateId = fields[9].GetInt16();
4279
4280        Player *pl = 0;
4281        if (serverUp)
4282            pl = GetPlayer((uint64)m->receiver);
4283        if (pl && pl->m_mailsLoaded)
4284        {                                                   //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4285            //his in mailbox and he has already listed his mails )
4286            delete m;
4287            continue;
4288        }
4289        //delete or return mail:
4290        if (has_items)
4291        {
4292            QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4293            if(resultItems)
4294            {
4295                do
4296                {
4297                    Field *fields2 = resultItems->Fetch();
4298
4299                    uint32 item_guid_low = fields2[0].GetUInt32();
4300                    uint32 item_template = fields2[1].GetUInt32();
4301
4302                    m->AddItem(item_guid_low, item_template);
4303                }
4304                while (resultItems->NextRow());
4305
4306                delete resultItems;
4307            }
4308            //if it is mail from AH, it shouldn't be returned, but deleted
4309            if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4310            {
4311                // mail open and then not returned
4312                for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4313                    CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4314            }
4315            else
4316            {
4317                //mail will be returned:
4318                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);
4319                delete m;
4320                continue;
4321            }
4322        }
4323
4324        if (m->itemTextId)
4325            CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4326
4327        //deletemail = true;
4328        //delmails << m->messageID << ", ";
4329        CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4330        delete m;
4331    } while (result->NextRow());
4332    delete result;
4333}
4334
4335void ObjectMgr::LoadQuestAreaTriggers()
4336{
4337    mQuestAreaTriggerMap.clear();                           // need for reload case
4338
4339    QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4340
4341    uint32 count = 0;
4342
4343    if( !result )
4344    {
4345        barGoLink bar( 1 );
4346        bar.step();
4347
4348        sLog.outString();
4349        sLog.outString( ">> Loaded %u quest trigger points", count );
4350        return;
4351    }
4352
4353    barGoLink bar( result->GetRowCount() );
4354
4355    do
4356    {
4357        ++count;
4358        bar.step();
4359
4360        Field *fields = result->Fetch();
4361
4362        uint32 trigger_ID = fields[0].GetUInt32();
4363        uint32 quest_ID   = fields[1].GetUInt32();
4364
4365        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4366        if(!atEntry)
4367        {
4368            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4369            continue;
4370        }
4371
4372        Quest const* quest = GetQuestTemplate(quest_ID);
4373
4374        if(!quest)
4375        {
4376            sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4377            continue;
4378        }
4379
4380        if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4381        {
4382            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);
4383
4384            // this will prevent quest completing without objective
4385            const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4386
4387            // continue; - quest modified to required obkective and trigger can be allowed.
4388        }
4389
4390        mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4391
4392    } while( result->NextRow() );
4393
4394    delete result;
4395
4396    sLog.outString();
4397    sLog.outString( ">> Loaded %u quest trigger points", count );
4398}
4399
4400void ObjectMgr::LoadTavernAreaTriggers()
4401{
4402    mTavernAreaTriggerSet.clear();                          // need for reload case
4403
4404    QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4405
4406    uint32 count = 0;
4407
4408    if( !result )
4409    {
4410        barGoLink bar( 1 );
4411        bar.step();
4412
4413        sLog.outString();
4414        sLog.outString( ">> Loaded %u tavern triggers", count );
4415        return;
4416    }
4417
4418    barGoLink bar( result->GetRowCount() );
4419
4420    do
4421    {
4422        ++count;
4423        bar.step();
4424
4425        Field *fields = result->Fetch();
4426
4427        uint32 Trigger_ID      = fields[0].GetUInt32();
4428
4429        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4430        if(!atEntry)
4431        {
4432            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4433            continue;
4434        }
4435
4436        mTavernAreaTriggerSet.insert(Trigger_ID);
4437    } while( result->NextRow() );
4438
4439    delete result;
4440
4441    sLog.outString();
4442    sLog.outString( ">> Loaded %u tavern triggers", count );
4443}
4444
4445void ObjectMgr::LoadAreaTriggerScripts()
4446{
4447    mAreaTriggerScripts.clear();                            // need for reload case
4448    QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4449
4450    uint32 count = 0;
4451
4452    if( !result )
4453    {
4454        barGoLink bar( 1 );
4455        bar.step();
4456
4457        sLog.outString();
4458        sLog.outString( ">> Loaded %u areatrigger scripts", count );
4459        return;
4460    }
4461
4462    barGoLink bar( result->GetRowCount() );
4463
4464    do
4465    {
4466        ++count;
4467        bar.step();
4468
4469        Field *fields = result->Fetch();
4470
4471        uint32 Trigger_ID      = fields[0].GetUInt32();
4472        std::string scriptName = fields[1].GetCppString();
4473
4474        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4475        if(!atEntry)
4476        {
4477            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4478            continue;
4479        }
4480        mAreaTriggerScripts[Trigger_ID] = scriptName;
4481    } while( result->NextRow() );
4482
4483    delete result;
4484
4485    sLog.outString();
4486    sLog.outString( ">> Loaded %u areatrigger scripts", count );
4487}
4488uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4489{
4490    bool found = false;
4491    float dist;
4492    uint32 id = 0;
4493
4494    for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4495    {
4496        TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4497        if(node && node->map_id == mapid)
4498        {
4499            float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4500            if(found)
4501            {
4502                if(dist2 < dist)
4503                {
4504                    dist = dist2;
4505                    id = i;
4506                }
4507            }
4508            else
4509            {
4510                found = true;
4511                dist = dist2;
4512                id = i;
4513            }
4514        }
4515    }
4516
4517    return id;
4518}
4519
4520void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4521{
4522    TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4523    if(src_i==sTaxiPathSetBySource.end())
4524    {
4525        path = 0;
4526        cost = 0;
4527        return;
4528    }
4529
4530    TaxiPathSetForSource& pathSet = src_i->second;
4531
4532    TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4533    if(dest_i==pathSet.end())
4534    {
4535        path = 0;
4536        cost = 0;
4537        return;
4538    }
4539
4540    cost = dest_i->second.price;
4541    path = dest_i->second.ID;
4542}
4543
4544uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4545{
4546    uint16 mount_entry = 0;
4547    uint16 mount_id = 0;
4548
4549    TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4550    if(node)
4551    {
4552        if (team == ALLIANCE)
4553        {
4554            mount_entry = node->alliance_mount_type;
4555            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4556            if(ci)
4557                mount_id = ci->DisplayID_A;
4558        }
4559        if (team == HORDE)
4560        {
4561            mount_entry = node->horde_mount_type;
4562            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4563            if(ci)
4564                mount_id = ci->DisplayID_H;
4565        }
4566    }
4567
4568    CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4569    if(!minfo)
4570    {
4571        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. ",
4572            mount_entry,id,team,mount_id);
4573
4574        return false;
4575    }
4576    if(minfo->modelid_other_gender!=0)
4577        mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4578
4579    return mount_id;
4580}
4581
4582void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4583{
4584    if(path >= sTaxiPathNodesByPath.size())
4585        return;
4586
4587    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4588
4589    pathnodes.Resize(nodeList.size());
4590    mapIds.resize(nodeList.size());
4591
4592    for(size_t i = 0; i < nodeList.size(); ++i)
4593    {
4594        pathnodes[ i ].x = nodeList[i].x;
4595        pathnodes[ i ].y = nodeList[i].y;
4596        pathnodes[ i ].z = nodeList[i].z;
4597
4598        mapIds[i] = nodeList[i].mapid;
4599    }
4600}
4601
4602void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4603{
4604    if(path >= sTaxiPathNodesByPath.size())
4605        return;
4606
4607    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4608
4609    pathnodes.Resize(nodeList.size());
4610
4611    for(size_t i = 0; i < nodeList.size(); ++i)
4612    {
4613        pathnodes[ i ].mapid = nodeList[i].mapid;
4614        pathnodes[ i ].x = nodeList[i].x;
4615        pathnodes[ i ].y = nodeList[i].y;
4616        pathnodes[ i ].z = nodeList[i].z;
4617        pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4618        pathnodes[ i ].delay = nodeList[i].delay;
4619    }
4620}
4621
4622void ObjectMgr::LoadGraveyardZones()
4623{
4624    mGraveYardMap.clear();                                  // need for reload case
4625
4626    QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4627
4628    uint32 count = 0;
4629
4630    if( !result )
4631    {
4632        barGoLink bar( 1 );
4633        bar.step();
4634
4635        sLog.outString();
4636        sLog.outString( ">> Loaded %u graveyard-zone links", count );
4637        return;
4638    }
4639
4640    barGoLink bar( result->GetRowCount() );
4641
4642    do
4643    {
4644        ++count;
4645        bar.step();
4646
4647        Field *fields = result->Fetch();
4648
4649        uint32 safeLocId = fields[0].GetUInt32();
4650        uint32 zoneId = fields[1].GetUInt32();
4651        uint32 team   = fields[2].GetUInt32();
4652
4653        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4654        if(!entry)
4655        {
4656            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4657            continue;
4658        }
4659
4660        AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4661        if(!areaEntry)
4662        {
4663            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4664            continue;
4665        }
4666
4667        if(areaEntry->zone != 0)
4668        {
4669            sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4670            continue;
4671        }
4672
4673        if(team!=0 && team!=HORDE && team!=ALLIANCE)
4674        {
4675            sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4676            continue;
4677        }
4678
4679        if(entry->map_id != areaEntry->mapid && team != 0)
4680        {
4681            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);
4682            team = 0;
4683        }
4684
4685        if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4686            sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Garveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4687    } while( result->NextRow() );
4688
4689    delete result;
4690
4691    sLog.outString();
4692    sLog.outString( ">> Loaded %u graveyard-zone links", count );
4693}
4694
4695WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4696{
4697    // search for zone associated closest graveyard
4698    uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4699
4700    // Simulate std. algorithm:
4701    //   found some graveyard associated to (ghost_zone,ghost_map)
4702    //
4703    //   if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4704    //     then check faction
4705    //   if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4706    //     then skip check faction
4707    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4708    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4709    if(graveLow==graveUp)
4710    {
4711        sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4712        return NULL;
4713    }
4714
4715    bool foundNear = false;
4716    float distNear;
4717    WorldSafeLocsEntry const* entryNear = NULL;
4718    WorldSafeLocsEntry const* entryFar = NULL;
4719
4720    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4721    {
4722        GraveYardData const& data = itr->second;
4723
4724        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4725        if(!entry)
4726        {
4727            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4728            continue;
4729        }
4730
4731        // remember first graveyard at another map and ignore other
4732        if(MapId != entry->map_id)
4733        {
4734            if(!entryFar)
4735                entryFar = entry;
4736            continue;
4737        }
4738
4739        // skip enemy faction graveyard at same map (normal area, city, or battleground)
4740        // team == 0 case can be at call from .neargrave
4741        if(data.team != 0 && team != 0 && data.team != team)
4742            continue;
4743
4744        // find now nearest graveyard at same map
4745        float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4746        if(foundNear)
4747        {
4748            if(dist2 < distNear)
4749            {
4750                distNear = dist2;
4751                entryNear = entry;
4752            }
4753        }
4754        else
4755        {
4756            foundNear = true;
4757            distNear = dist2;
4758            entryNear = entry;
4759        }
4760    }
4761
4762    if(entryNear)
4763        return entryNear;
4764
4765    return entryFar;
4766}
4767
4768GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4769{
4770    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4771    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4772
4773    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4774    {
4775        if(itr->second.safeLocId==id)
4776            return &itr->second;
4777    }
4778
4779    return NULL;
4780}
4781
4782bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4783{
4784    if(FindGraveYardData(id,zoneId))
4785        return false;
4786
4787    // add link to loaded data
4788    GraveYardData data;
4789    data.safeLocId = id;
4790    data.team = team;
4791
4792    mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4793
4794    // add link to DB
4795    if(inDB)
4796    {
4797        WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4798            "VALUES ('%u', '%u','%u')",id,zoneId,team);
4799    }
4800
4801    return true;
4802}
4803
4804void ObjectMgr::LoadAreaTriggerTeleports()
4805{
4806    mAreaTriggers.clear();                                  // need for reload case
4807
4808    uint32 count = 0;
4809
4810    //                                                0   1               2              3               4           5            6                    7                     8           9                  10                 11                 12
4811    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");
4812    if( !result )
4813    {
4814
4815        barGoLink bar( 1 );
4816
4817        bar.step();
4818
4819        sLog.outString();
4820        sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4821        return;
4822    }
4823
4824    barGoLink bar( result->GetRowCount() );
4825
4826    do
4827    {
4828        Field *fields = result->Fetch();
4829
4830        bar.step();
4831
4832        ++count;
4833
4834        uint32 Trigger_ID = fields[0].GetUInt32();
4835
4836        AreaTrigger at;
4837
4838        at.requiredLevel      = fields[1].GetUInt8();
4839        at.requiredItem       = fields[2].GetUInt32();
4840        at.requiredItem2      = fields[3].GetUInt32();
4841        at.heroicKey          = fields[4].GetUInt32();
4842        at.heroicKey2         = fields[5].GetUInt32();
4843        at.requiredQuest      = fields[6].GetUInt32();
4844        at.requiredFailedText = fields[7].GetCppString();
4845        at.target_mapId       = fields[8].GetUInt32();
4846        at.target_X           = fields[9].GetFloat();
4847        at.target_Y           = fields[10].GetFloat();
4848        at.target_Z           = fields[11].GetFloat();
4849        at.target_Orientation = fields[12].GetFloat();
4850
4851        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4852        if(!atEntry)
4853        {
4854            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4855            continue;
4856        }
4857
4858        if(at.requiredItem)
4859        {
4860            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4861            if(!pProto)
4862            {
4863                sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4864                at.requiredItem = 0;
4865            }
4866        }
4867        if(at.requiredItem2)
4868        {
4869            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4870            if(!pProto)
4871            {
4872                sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4873                at.requiredItem2 = 0;
4874            }
4875        }
4876
4877        if(at.heroicKey)
4878        {
4879            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4880            if(!pProto)
4881            {
4882                sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4883                at.heroicKey = 0;
4884            }
4885        }
4886
4887        if(at.heroicKey2)
4888        {
4889            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4890            if(!pProto)
4891            {
4892                sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4893                at.heroicKey2 = 0;
4894            }
4895        }
4896
4897        if(at.requiredQuest)
4898        {
4899            if(!mQuestTemplates[at.requiredQuest])
4900            {
4901                sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4902                at.requiredQuest = 0;
4903            }
4904        }
4905
4906        MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4907        if(!mapEntry)
4908        {
4909            sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4910            continue;
4911        }
4912
4913        if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4914        {
4915            sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4916            continue;
4917        }
4918
4919        mAreaTriggers[Trigger_ID] = at;
4920
4921    } while( result->NextRow() );
4922
4923    delete result;
4924
4925    sLog.outString();
4926    sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4927}
4928
4929AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
4930{
4931    const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
4932    if(!mapEntry) return NULL;
4933    for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
4934    {
4935        if(itr->second.target_mapId == mapEntry->parent_map)
4936        {
4937            AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
4938            if(atEntry && atEntry->mapid == Map)
4939                return &itr->second;
4940        }
4941    }
4942    return NULL;
4943}
4944
4945void ObjectMgr::SetHighestGuids()
4946{
4947    QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
4948    if( result )
4949    {
4950        m_hiCharGuid = (*result)[0].GetUInt32()+1;
4951
4952        delete result;
4953    }
4954
4955    result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
4956    if( result )
4957    {
4958        m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
4959
4960        delete result;
4961    }
4962
4963    result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
4964    if( result )
4965    {
4966        m_hiPetGuid = (*result)[0].GetUInt32()+1;
4967
4968        delete result;
4969    }
4970
4971    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
4972    if( result )
4973    {
4974        m_hiItemGuid = (*result)[0].GetUInt32()+1;
4975
4976        delete result;
4977    }
4978
4979    // Cleanup other tables from not existed guids (>=m_hiItemGuid)
4980    CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
4981    CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
4982    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
4983    CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
4984
4985    result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
4986    if( result )
4987    {
4988        m_hiGoGuid = (*result)[0].GetUInt32()+1;
4989
4990        delete result;
4991    }
4992
4993    result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
4994    if( result )
4995    {
4996        m_auctionid = (*result)[0].GetUInt32()+1;
4997
4998        delete result;
4999    }
5000    else
5001    {
5002        m_auctionid = 0;
5003    }
5004    result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5005    if( result )
5006    {
5007        m_mailid = (*result)[0].GetUInt32()+1;
5008
5009        delete result;
5010    }
5011    else
5012    {
5013        m_mailid = 0;
5014    }
5015    result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5016    if( result )
5017    {
5018        m_ItemTextId = (*result)[0].GetUInt32();
5019
5020        delete result;
5021    }
5022    else
5023        m_ItemTextId = 0;
5024
5025    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5026    if( result )
5027    {
5028        m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5029
5030        delete result;
5031    }
5032}
5033
5034uint32 ObjectMgr::GenerateAuctionID()
5035{
5036    ++m_auctionid;
5037    if(m_auctionid>=0xFFFFFFFF)
5038    {
5039        sLog.outError("Auctions ids overflow!! Can't continue, shuting down server. ");
5040        sWorld.m_stopEvent = true;
5041    }
5042    return m_auctionid;
5043}
5044
5045uint32 ObjectMgr::GenerateMailID()
5046{
5047    ++m_mailid;
5048    if(m_mailid>=0xFFFFFFFF)
5049    {
5050        sLog.outError("Mail ids overflow!! Can't continue, shuting down server. ");
5051        sWorld.m_stopEvent = true;
5052    }
5053    return m_mailid;
5054}
5055
5056uint32 ObjectMgr::GenerateItemTextID()
5057{
5058    ++m_ItemTextId;
5059    if(m_ItemTextId>=0xFFFFFFFF)
5060    {
5061        sLog.outError("Item text ids overflow!! Can't continue, shuting down server. ");
5062        sWorld.m_stopEvent = true;
5063    }
5064    return m_ItemTextId;
5065}
5066
5067uint32 ObjectMgr::CreateItemText(std::string text)
5068{
5069    uint32 newItemTextId = GenerateItemTextID();
5070    //insert new itempage to container
5071    mItemTexts[ newItemTextId ] = text;
5072    //save new itempage
5073    CharacterDatabase.escape_string(text);
5074    //any Delete query needed, itemTextId is maximum of all ids
5075    std::ostringstream query;
5076    query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5077    CharacterDatabase.Execute(query.str().c_str());         //needs to be run this way, because mail body may be more than 1024 characters
5078    return newItemTextId;
5079}
5080
5081uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5082{
5083    switch(guidhigh)
5084    {
5085        case HIGHGUID_ITEM:
5086            ++m_hiItemGuid;
5087            if(m_hiItemGuid>=0xFFFFFFFF)
5088            {
5089                sLog.outError("Item guid overflow!! Can't continue, shuting down server. ");
5090                sWorld.m_stopEvent = true;
5091            }
5092            return m_hiItemGuid;
5093        case HIGHGUID_UNIT:
5094            ++m_hiCreatureGuid;
5095            if(m_hiCreatureGuid>=0x00FFFFFF)
5096            {
5097                sLog.outError("Creature guid overflow!! Can't continue, shuting down server. ");
5098                sWorld.m_stopEvent = true;
5099            }
5100            return m_hiCreatureGuid;
5101        case HIGHGUID_PET:
5102            ++m_hiPetGuid;
5103            if(m_hiPetGuid>=0x00FFFFFF)
5104            {
5105                sLog.outError("Pet guid overflow!! Can't continue, shuting down server. ");
5106                sWorld.m_stopEvent = true;
5107            }
5108            return m_hiPetGuid;
5109        case HIGHGUID_PLAYER:
5110            ++m_hiCharGuid;
5111            if(m_hiCharGuid>=0xFFFFFFFF)
5112            {
5113                sLog.outError("Players guid overflow!! Can't continue, shuting down server. ");
5114                sWorld.m_stopEvent = true;
5115            }
5116            return m_hiCharGuid;
5117        case HIGHGUID_GAMEOBJECT:
5118            ++m_hiGoGuid;
5119            if(m_hiGoGuid>=0x00FFFFFF)
5120            {
5121                sLog.outError("Gameobject guid overflow!! Can't continue, shuting down server. ");
5122                sWorld.m_stopEvent = true;
5123            }
5124            return m_hiGoGuid;
5125        case HIGHGUID_CORPSE:
5126            ++m_hiCorpseGuid;
5127            if(m_hiCorpseGuid>=0xFFFFFFFF)
5128            {
5129                sLog.outError("Corpse guid overflow!! Can't continue, shuting down server. ");
5130                sWorld.m_stopEvent = true;
5131            }
5132            return m_hiCorpseGuid;
5133        case HIGHGUID_DYNAMICOBJECT:
5134            ++m_hiDoGuid;
5135            if(m_hiDoGuid>=0xFFFFFFFF)
5136            {
5137                sLog.outError("DynamicObject guid overflow!! Can't continue, shuting down server. ");
5138                sWorld.m_stopEvent = true;
5139            }
5140            return m_hiDoGuid;
5141        default:
5142            ASSERT(0);
5143    }
5144
5145    ASSERT(0);
5146    return 0;
5147}
5148
5149void ObjectMgr::LoadGameObjectLocales()
5150{
5151    QueryResult *result = WorldDatabase.Query("SELECT entry,"
5152        "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5153        "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5154        "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5155
5156    if(!result)
5157    {
5158        barGoLink bar(1);
5159
5160        bar.step();
5161
5162        sLog.outString("");
5163        sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5164        return;
5165    }
5166
5167    barGoLink bar(result->GetRowCount());
5168
5169    do
5170    {
5171        Field *fields = result->Fetch();
5172        bar.step();
5173
5174        uint32 entry = fields[0].GetUInt32();
5175
5176        GameObjectLocale& data = mGameObjectLocaleMap[entry];
5177
5178        for(int i = 1; i < MAX_LOCALE; ++i)
5179        {
5180            std::string str = fields[i].GetCppString();
5181            if(!str.empty())
5182            {
5183                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5184                if(idx >= 0)
5185                {
5186                    if(data.Name.size() <= idx)
5187                        data.Name.resize(idx+1);
5188
5189                    data.Name[idx] = str;
5190                }
5191            }
5192        }
5193
5194        for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5195        {
5196            std::string str = fields[i].GetCppString();
5197            if(!str.empty())
5198            {
5199                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5200                if(idx >= 0)
5201                {
5202                    if(data.CastBarCaption.size() <= idx)
5203                        data.CastBarCaption.resize(idx+1);
5204
5205                    data.CastBarCaption[idx] = str;
5206                }
5207            }
5208        }
5209
5210    } while (result->NextRow());
5211
5212    delete result;
5213
5214    sLog.outString();
5215    sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5216}
5217
5218void ObjectMgr::LoadGameobjectInfo()
5219{
5220    sGOStorage.Load();
5221
5222    // some checks
5223    for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5224    {
5225        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5226        if(!goInfo)
5227            continue;
5228
5229        switch(goInfo->type)
5230        {
5231            case GAMEOBJECT_TYPE_DOOR:                      //0
5232            {
5233                if(goInfo->door.lockId)
5234                {
5235                    if(!sLockStore.LookupEntry(goInfo->door.lockId))
5236                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5237                            id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5238                }
5239                break;
5240            }
5241            case GAMEOBJECT_TYPE_BUTTON:                    //1
5242            {
5243                if(goInfo->button.lockId)
5244                {
5245                    if(!sLockStore.LookupEntry(goInfo->button.lockId))
5246                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5247                            id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5248                }
5249                break;
5250            }
5251            case GAMEOBJECT_TYPE_CHEST:                     //3
5252            {
5253                if(goInfo->chest.lockId)
5254                {
5255                    if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5256                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5257                            id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5258                }
5259                if(goInfo->chest.linkedTrapId)              // linked trap
5260                {
5261                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5262                    {
5263                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5264                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5265                                id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5266                    }
5267                    /* disable check for while
5268                    else
5269                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5270                            id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5271                    */
5272                }
5273                break;
5274            }
5275            case GAMEOBJECT_TYPE_TRAP:                      //6
5276            {
5277                /* disable check for while
5278                if(goInfo->trap.spellId)                    // spell
5279                {
5280                    if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5281                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5282                            id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5283                }
5284                */
5285                break;
5286            }
5287            case GAMEOBJECT_TYPE_CHAIR:                     //7
5288                if(goInfo->chair.height > 2)
5289                {
5290                    sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5291                        id,goInfo->type,goInfo->chair.height);
5292
5293                    // prevent client and server unexpected work
5294                    const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5295                }
5296                break;
5297            case GAMEOBJECT_TYPE_SPELL_FOCUS:               //8
5298            {
5299                if(goInfo->spellFocus.focusId)
5300                {
5301                    if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5302                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5303                            id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5304                }
5305
5306                if(goInfo->spellFocus.linkedTrapId)         // linked trap
5307                {
5308                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5309                    {
5310                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5311                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5312                                id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5313                    }
5314                    /* disable check for while
5315                    else
5316                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5317                            id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5318                    */
5319                }
5320                break;
5321            }
5322            case GAMEOBJECT_TYPE_GOOBER:                    //10
5323            {
5324                if(goInfo->goober.pageId)                   // pageId
5325                {
5326                    if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5327                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5328                            id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5329                }
5330                /* disable check for while
5331                if(goInfo->goober.spellId)                  // spell
5332                {
5333                    if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5334                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5335                            id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5336                }
5337                */
5338                if(goInfo->goober.linkedTrapId)             // linked trap
5339                {
5340                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5341                    {
5342                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5343                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5344                                id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5345                    }
5346                    /* disable check for while
5347                    else
5348                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5349                            id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5350                    */
5351                }
5352                break;
5353            }
5354            case GAMEOBJECT_TYPE_MO_TRANSPORT:              //15
5355            {
5356                if(goInfo->moTransport.taxiPathId)
5357                {
5358                    if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5359                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5360                            id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5361                }
5362                break;
5363            }
5364            case GAMEOBJECT_TYPE_SUMMONING_RITUAL:          //18
5365            {
5366                /* disabled
5367                if(goInfo->summoningRitual.spellId)
5368                {
5369                    if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5370                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5371                            id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5372                }
5373                */
5374                break;
5375            }
5376            case GAMEOBJECT_TYPE_SPELLCASTER:               //22
5377            {
5378                if(goInfo->spellcaster.spellId)             // spell
5379                {
5380                    if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5381                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5382                            id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5383                }
5384                break;
5385            }
5386        }
5387    }
5388
5389    sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5390    sLog.outString();
5391}
5392
5393void ObjectMgr::LoadExplorationBaseXP()
5394{
5395    uint32 count = 0;
5396    QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5397
5398    if( !result )
5399    {
5400        barGoLink bar( 1 );
5401
5402        bar.step();
5403
5404        sLog.outString();
5405        sLog.outString( ">> Loaded %u BaseXP definitions", count );
5406        return;
5407    }
5408
5409    barGoLink bar( result->GetRowCount() );
5410
5411    do
5412    {
5413        bar.step();
5414
5415        Field *fields = result->Fetch();
5416        uint32 level  = fields[0].GetUInt32();
5417        uint32 basexp = fields[1].GetUInt32();
5418        mBaseXPTable[level] = basexp;
5419        ++count;
5420    }
5421    while (result->NextRow());
5422
5423    delete result;
5424
5425    sLog.outString();
5426    sLog.outString( ">> Loaded %u BaseXP definitions", count );
5427}
5428
5429uint32 ObjectMgr::GetBaseXP(uint32 level)
5430{
5431    return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5432}
5433
5434void ObjectMgr::LoadPetNames()
5435{
5436    uint32 count = 0;
5437    QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5438
5439    if( !result )
5440    {
5441        barGoLink bar( 1 );
5442
5443        bar.step();
5444
5445        sLog.outString();
5446        sLog.outString( ">> Loaded %u pet name parts", count );
5447        return;
5448    }
5449
5450    barGoLink bar( result->GetRowCount() );
5451
5452    do
5453    {
5454        bar.step();
5455
5456        Field *fields = result->Fetch();
5457        std::string word = fields[0].GetString();
5458        uint32 entry     = fields[1].GetUInt32();
5459        bool   half      = fields[2].GetBool();
5460        if(half)
5461            PetHalfName1[entry].push_back(word);
5462        else
5463            PetHalfName0[entry].push_back(word);
5464        ++count;
5465    }
5466    while (result->NextRow());
5467    delete result;
5468
5469    sLog.outString();
5470    sLog.outString( ">> Loaded %u pet name parts", count );
5471}
5472
5473void ObjectMgr::LoadPetNumber()
5474{
5475    QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5476    if(result)
5477    {
5478        Field *fields = result->Fetch();
5479        m_hiPetNumber = fields[0].GetUInt32()+1;
5480        delete result;
5481    }
5482
5483    barGoLink bar( 1 );
5484    bar.step();
5485
5486    sLog.outString();
5487    sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5488}
5489
5490std::string ObjectMgr::GeneratePetName(uint32 entry)
5491{
5492    std::vector<std::string> & list0 = PetHalfName0[entry];
5493    std::vector<std::string> & list1 = PetHalfName1[entry];
5494
5495    if(list0.empty() || list1.empty())
5496    {
5497        CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5498        char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5499        if(!petname)
5500            petname = cinfo->Name;
5501        return std::string(petname);
5502    }
5503
5504    return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5505}
5506
5507uint32 ObjectMgr::GeneratePetNumber()
5508{
5509    return ++m_hiPetNumber;
5510}
5511
5512void ObjectMgr::LoadCorpses()
5513{
5514    uint32 count = 0;
5515    //                                                     0           1           2           3            4    5     6     7            8         10
5516    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");
5517
5518    if( !result )
5519    {
5520        barGoLink bar( 1 );
5521
5522        bar.step();
5523
5524        sLog.outString();
5525        sLog.outString( ">> Loaded %u corpses", count );
5526        return;
5527    }
5528
5529    barGoLink bar( result->GetRowCount() );
5530
5531    do
5532    {
5533        bar.step();
5534
5535        Field *fields = result->Fetch();
5536
5537        uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5538
5539        Corpse *corpse = new Corpse;
5540        if(!corpse->LoadFromDB(guid,fields))
5541        {
5542            delete corpse;
5543            continue;
5544        }
5545
5546        ObjectAccessor::Instance().AddCorpse(corpse);
5547
5548        ++count;
5549    }
5550    while (result->NextRow());
5551    delete result;
5552
5553    sLog.outString();
5554    sLog.outString( ">> Loaded %u corpses", count );
5555}
5556
5557void ObjectMgr::LoadReputationOnKill()
5558{
5559    uint32 count = 0;
5560
5561    //                                                0            1                     2
5562    QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5563    //   3             4             5                   6             7             8                   9
5564        "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5565        "FROM creature_onkill_reputation");
5566
5567    if(!result)
5568    {
5569        barGoLink bar(1);
5570
5571        bar.step();
5572
5573        sLog.outString();
5574        sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5575        return;
5576    }
5577
5578    barGoLink bar(result->GetRowCount());
5579
5580    do
5581    {
5582        Field *fields = result->Fetch();
5583        bar.step();
5584
5585        uint32 creature_id = fields[0].GetUInt32();
5586
5587        ReputationOnKillEntry repOnKill;
5588        repOnKill.repfaction1          = fields[1].GetUInt32();
5589        repOnKill.repfaction2          = fields[2].GetUInt32();
5590        repOnKill.is_teamaward1        = fields[3].GetBool();
5591        repOnKill.reputation_max_cap1  = fields[4].GetUInt32();
5592        repOnKill.repvalue1            = fields[5].GetInt32();
5593        repOnKill.is_teamaward2        = fields[6].GetBool();
5594        repOnKill.reputation_max_cap2  = fields[7].GetUInt32();
5595        repOnKill.repvalue2            = fields[8].GetInt32();
5596        repOnKill.team_dependent       = fields[9].GetUInt8();
5597
5598        if(!GetCreatureTemplate(creature_id))
5599        {
5600            sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5601            continue;
5602        }
5603
5604        if(repOnKill.repfaction1)
5605        {
5606            FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5607            if(!factionEntry1)
5608            {
5609                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5610                continue;
5611            }
5612        }
5613
5614        if(repOnKill.repfaction2)
5615        {
5616            FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5617            if(!factionEntry2)
5618            {
5619                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5620                continue;
5621            }
5622        }
5623
5624        mRepOnKill[creature_id] = repOnKill;
5625
5626        ++count;
5627    } while (result->NextRow());
5628
5629    delete result;
5630
5631    sLog.outString();
5632    sLog.outString(">> Loaded %u creature award reputation definitions", count);
5633}
5634
5635void ObjectMgr::LoadWeatherZoneChances()
5636{
5637    uint32 count = 0;
5638
5639    //                                                0     1                   2                   3                    4                   5                   6                    7                 8                 9                  10                  11                  12
5640    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");
5641
5642    if(!result)
5643    {
5644        barGoLink bar(1);
5645
5646        bar.step();
5647
5648        sLog.outString();
5649        sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5650        return;
5651    }
5652
5653    barGoLink bar(result->GetRowCount());
5654
5655    do
5656    {
5657        Field *fields = result->Fetch();
5658        bar.step();
5659
5660        uint32 zone_id = fields[0].GetUInt32();
5661
5662        WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5663
5664        for(int season = 0; season < WEATHER_SEASONS; ++season)
5665        {
5666            wzc.data[season].rainChance  = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5667            wzc.data[season].snowChance  = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5668            wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5669
5670            if(wzc.data[season].rainChance > 100)
5671            {
5672                wzc.data[season].rainChance = 25;
5673                sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5674            }
5675
5676            if(wzc.data[season].snowChance > 100)
5677            {
5678                wzc.data[season].snowChance = 25;
5679                sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5680            }
5681
5682            if(wzc.data[season].stormChance > 100)
5683            {
5684                wzc.data[season].stormChance = 25;
5685                sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5686            }
5687        }
5688
5689        ++count;
5690    } while (result->NextRow());
5691
5692    delete result;
5693
5694    sLog.outString();
5695    sLog.outString(">> Loaded %u weather definitions", count);
5696}
5697
5698void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5699{
5700    mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5701    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5702    if(t)
5703        WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5704}
5705
5706void ObjectMgr::DeleteCreatureData(uint32 guid)
5707{
5708    // remove mapid*cellid -> guid_set map
5709    CreatureData const* data = GetCreatureData(guid);
5710    if(data)
5711        RemoveCreatureFromGrid(guid, data);
5712
5713    mCreatureDataMap.erase(guid);
5714}
5715
5716void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5717{
5718    mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5719    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5720    if(t)
5721        WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5722}
5723
5724void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5725{
5726    RespawnTimes::iterator next;
5727
5728    for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5729    {
5730        next = itr;
5731        ++next;
5732
5733        if(GUID_HIPART(itr->first)==instance)
5734            mGORespawnTimes.erase(itr);
5735    }
5736
5737    for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5738    {
5739        next = itr;
5740        ++next;
5741
5742        if(GUID_HIPART(itr->first)==instance)
5743            mCreatureRespawnTimes.erase(itr);
5744    }
5745
5746    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5747    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5748}
5749
5750void ObjectMgr::DeleteGOData(uint32 guid)
5751{
5752    // remove mapid*cellid -> guid_set map
5753    GameObjectData const* data = GetGOData(guid);
5754    if(data)
5755        RemoveGameobjectFromGrid(guid, data);
5756
5757    mGameObjectDataMap.erase(guid);
5758}
5759
5760void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5761{
5762    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5763    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5764    cell_guids.corpses[player_guid] = instance;
5765}
5766
5767void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5768{
5769    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5770    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5771    cell_guids.corpses.erase(player_guid);
5772}
5773
5774void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5775{
5776    map.clear();                                            // need for reload case
5777
5778    uint32 count = 0;
5779
5780    QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5781
5782    if(!result)
5783    {
5784        barGoLink bar(1);
5785
5786        bar.step();
5787
5788        sLog.outString();
5789        sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5790        return;
5791    }
5792
5793    barGoLink bar(result->GetRowCount());
5794
5795    do
5796    {
5797        Field *fields = result->Fetch();
5798        bar.step();
5799
5800        uint32 id    = fields[0].GetUInt32();
5801        uint32 quest = fields[1].GetUInt32();
5802
5803        if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5804        {
5805            sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5806            continue;
5807        }
5808
5809        map.insert(QuestRelations::value_type(id,quest));
5810
5811        ++count;
5812    } while (result->NextRow());
5813
5814    delete result;
5815
5816    sLog.outString();
5817    sLog.outString(">> Loaded %u quest relations from %s", count,table);
5818}
5819
5820void ObjectMgr::LoadGameobjectQuestRelations()
5821{
5822    LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5823
5824    for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5825    {
5826        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5827        if(!goInfo)
5828            sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5829        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5830            sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5831    }
5832}
5833
5834void ObjectMgr::LoadGameobjectInvolvedRelations()
5835{
5836    LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5837
5838    for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5839    {
5840        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5841        if(!goInfo)
5842            sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5843        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5844            sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5845    }
5846}
5847
5848void ObjectMgr::LoadCreatureQuestRelations()
5849{
5850    LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5851
5852    for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5853    {
5854        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5855        if(!cInfo)
5856            sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5857        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5858            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);
5859    }
5860}
5861
5862void ObjectMgr::LoadCreatureInvolvedRelations()
5863{
5864    LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
5865
5866    for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
5867    {
5868        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5869        if(!cInfo)
5870            sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5871        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5872            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);
5873    }
5874}
5875
5876void ObjectMgr::LoadReservedPlayersNames()
5877{
5878    m_ReservedNames.clear();                                // need for reload case
5879
5880    QueryResult *result = WorldDatabase.PQuery("SELECT name FROM reserved_name");
5881
5882    uint32 count = 0;
5883
5884    if( !result )
5885    {
5886        barGoLink bar( 1 );
5887        bar.step();
5888
5889        sLog.outString();
5890        sLog.outString( ">> Loaded %u reserved player names", count );
5891        return;
5892    }
5893
5894    barGoLink bar( result->GetRowCount() );
5895
5896    Field* fields;
5897    do
5898    {
5899        bar.step();
5900        fields = result->Fetch();
5901        std::string name= fields[0].GetCppString();
5902        if(normalizePlayerName(name))
5903        {
5904            m_ReservedNames.insert(name);
5905            ++count;
5906        }
5907    } while ( result->NextRow() );
5908
5909    delete result;
5910
5911    sLog.outString();
5912    sLog.outString( ">> Loaded %u reserved player names", count );
5913}
5914
5915enum LanguageType
5916{
5917    LT_BASIC_LATIN    = 0x0000,
5918    LT_EXTENDEN_LATIN = 0x0001,
5919    LT_CYRILLIC       = 0x0002,
5920    LT_EAST_ASIA      = 0x0004,
5921    LT_ANY            = 0xFFFF
5922};
5923
5924static LanguageType GetRealmLanguageType(bool create)
5925{
5926    switch(sWorld.getConfig(CONFIG_REALM_ZONE))
5927    {
5928        case REALM_ZONE_UNKNOWN:                            // any language
5929        case REALM_ZONE_DEVELOPMENT:
5930        case REALM_ZONE_TEST_SERVER:
5931        case REALM_ZONE_QA_SERVER:
5932            return LT_ANY;
5933        case REALM_ZONE_UNITED_STATES:                      // extended-Latin
5934        case REALM_ZONE_OCEANIC:
5935        case REALM_ZONE_LATIN_AMERICA:
5936        case REALM_ZONE_ENGLISH:
5937        case REALM_ZONE_GERMAN:
5938        case REALM_ZONE_FRENCH:
5939        case REALM_ZONE_SPANISH:
5940            return LT_EXTENDEN_LATIN;
5941        case REALM_ZONE_KOREA:                              // East-Asian
5942        case REALM_ZONE_TAIWAN:
5943        case REALM_ZONE_CHINA:
5944            return LT_EAST_ASIA;
5945        case REALM_ZONE_RUSSIAN:                            // Cyrillic
5946            return LT_CYRILLIC;
5947        default:
5948            return create ? LT_BASIC_LATIN : LT_ANY;        // basic-Latin at create, any at login
5949    }
5950}
5951
5952bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
5953{
5954    if(strictMask==0)                                       // any language, ignore realm
5955    {
5956        if(isExtendedLatinString(wstr,numericOrSpace))
5957            return true;
5958        if(isCyrillicString(wstr,numericOrSpace))
5959            return true;
5960        if(isEastAsianString(wstr,numericOrSpace))
5961            return true;
5962        return false;
5963    }
5964
5965    if(strictMask & 0x2)                                    // realm zone specific
5966    {
5967        LanguageType lt = GetRealmLanguageType(create);
5968        if(lt & LT_EXTENDEN_LATIN)
5969            if(isExtendedLatinString(wstr,numericOrSpace))
5970                return true;
5971        if(lt & LT_CYRILLIC)
5972            if(isCyrillicString(wstr,numericOrSpace))
5973                return true;
5974        if(lt & LT_EAST_ASIA)
5975            if(isEastAsianString(wstr,numericOrSpace))
5976                return true;
5977    }
5978
5979    if(strictMask & 0x1)                                    // basic latin
5980    {
5981        if(isBasicLatinString(wstr,numericOrSpace))
5982            return true;
5983    }
5984
5985    return false;
5986}
5987
5988bool ObjectMgr::IsValidName( std::string name, bool create )
5989{
5990    std::wstring wname;
5991    if(!Utf8toWStr(name,wname))
5992        return false;
5993
5994    if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
5995        return false;
5996
5997    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
5998
5999    return isValidString(wname,strictMask,false,create);
6000}
6001
6002bool ObjectMgr::IsValidCharterName( std::string name )
6003{
6004    std::wstring wname;
6005    if(!Utf8toWStr(name,wname))
6006        return false;
6007
6008    if(wname.size() < 1)
6009        return false;
6010
6011    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6012
6013    return isValidString(wname,strictMask,true);
6014}
6015
6016bool ObjectMgr::IsValidPetName( std::string name )
6017{
6018    std::wstring wname;
6019    if(!Utf8toWStr(name,wname))
6020        return false;
6021
6022    if(wname.size() < 1)
6023        return false;
6024
6025    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6026
6027    return isValidString(wname,strictMask,false);
6028}
6029
6030int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6031{
6032    if(loc==LOCALE_enUS)
6033        return -1;
6034
6035    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6036        if(m_LocalForIndex[i]==loc)
6037            return i;
6038
6039    return -1;
6040}
6041
6042LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6043{
6044    if (i<0 || i>=m_LocalForIndex.size())
6045        return LOCALE_enUS;
6046
6047    return m_LocalForIndex[i];
6048}
6049
6050int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6051{
6052    if(loc==LOCALE_enUS)
6053        return -1;
6054
6055    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6056        if(m_LocalForIndex[i]==loc)
6057            return i;
6058
6059    m_LocalForIndex.push_back(loc);
6060    return m_LocalForIndex.size()-1;
6061}
6062
6063void ObjectMgr::LoadBattleMastersEntry()
6064{
6065    mBattleMastersMap.clear();                              // need for reload case
6066
6067    QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6068
6069    uint32 count = 0;
6070
6071    if( !result )
6072    {
6073        barGoLink bar( 1 );
6074        bar.step();
6075
6076        sLog.outString();
6077        sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6078        return;
6079    }
6080
6081    barGoLink bar( result->GetRowCount() );
6082
6083    do
6084    {
6085        ++count;
6086        bar.step();
6087
6088        Field *fields = result->Fetch();
6089
6090        uint32 entry = fields[0].GetUInt32();
6091        uint32 bgTypeId  = fields[1].GetUInt32();
6092
6093        mBattleMastersMap[entry] = bgTypeId;
6094
6095    } while( result->NextRow() );
6096
6097    delete result;
6098
6099    sLog.outString();
6100    sLog.outString( ">> Loaded %u battlemaster entries", count );
6101}
6102
6103void ObjectMgr::LoadGameObjectForQuests()
6104{
6105    mGameObjectForQuestSet.clear();                         // need for reload case
6106
6107    uint32 count = 0;
6108
6109    // collect GO entries for GO that must activated
6110    for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6111    {
6112        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6113        if(!goInfo)
6114            continue;
6115
6116        switch(goInfo->type)
6117        {
6118            // scan GO chest with loot including quest items
6119            case GAMEOBJECT_TYPE_CHEST:
6120            {
6121                uint32 loot_id = GameObject::GetLootId(goInfo);
6122
6123                // find quest loot for GO
6124                if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6125                {
6126                    mGameObjectForQuestSet.insert(go_entry);
6127                    ++count;
6128                }
6129                break;
6130            }
6131            case GAMEOBJECT_TYPE_GOOBER:
6132            {
6133                if(goInfo->goober.questId)                  //quests objects
6134                {
6135                    mGameObjectForQuestSet.insert(go_entry);
6136                    count++;
6137                }
6138                break;
6139            }
6140            default:
6141                break;
6142        }
6143    }
6144
6145    sLog.outString();
6146    sLog.outString( ">> Loaded %u GameObject for quests", count );
6147}
6148
6149bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6150{
6151    // cleanup affected map part for reloading case
6152    for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6153    {
6154        if(itr->first >= min_value && itr->first <= max_value)
6155        {
6156            MangosStringLocaleMap::iterator itr2 = itr;
6157            ++itr;
6158            mMangosStringLocaleMap.erase(itr2);
6159        }
6160        else
6161            ++itr;
6162    }
6163
6164    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);
6165
6166    if(!result)
6167    {
6168        barGoLink bar(1);
6169
6170        bar.step();
6171
6172        sLog.outString("");
6173        if(min_value > 0)                                   // error only in case internal strings
6174            sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6175        else
6176            sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6177        return false;
6178    }
6179
6180    uint32 count = 0;
6181
6182    barGoLink bar(result->GetRowCount());
6183
6184    do
6185    {
6186        Field *fields = result->Fetch();
6187        bar.step();
6188
6189        int32 entry = fields[0].GetInt32();
6190
6191        if(entry==0)
6192        {
6193            sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6194            continue;
6195        }
6196        else if(entry < min_value || entry > max_value)
6197        {
6198            int32 start = min_value > 0 ? min_value : max_value;
6199            int32 end   = min_value > 0 ? max_value : min_value;
6200            sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6201            continue;
6202        }
6203
6204        MangosStringLocale& data = mMangosStringLocaleMap[entry];
6205
6206        if(data.Content.size() > 0)
6207        {
6208            sLog.outErrorDb("Table `%s` contain data for already loaded entry  %i (from another table?), ignored.",table,entry);
6209            continue;
6210        }
6211
6212        data.Content.resize(1);
6213        ++count;
6214
6215        // 0 -> default, idx in to idx+1
6216        data.Content[0] = fields[1].GetCppString();
6217
6218        for(int i = 1; i < MAX_LOCALE; ++i)
6219        {
6220            std::string str = fields[i+1].GetCppString();
6221            if(!str.empty())
6222            {
6223                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6224                if(idx >= 0)
6225                {
6226                    // 0 -> default, idx in to idx+1
6227                    if(data.Content.size() <= idx+1)
6228                        data.Content.resize(idx+2);
6229
6230                    data.Content[idx+1] = str;
6231                }
6232            }
6233        }
6234    } while (result->NextRow());
6235
6236    delete result;
6237
6238    sLog.outString();
6239    if(min_value > 0)                                       // internal mangos strings
6240        sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6241    else
6242        sLog.outString( ">> Loaded %u string templates from %s", count,table);
6243
6244    return true;
6245}
6246
6247const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6248{
6249    // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6250    // Content[0] always exist if exist MangosStringLocale
6251    if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6252    {
6253        if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6254            return msl->Content[locale_idx+1].c_str();
6255        else
6256            return msl->Content[0].c_str();
6257    }
6258
6259    if(entry > 0)
6260        sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6261    else
6262        sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6263    return "<error>";
6264}
6265
6266void ObjectMgr::LoadFishingBaseSkillLevel()
6267{
6268    mFishingBaseForArea.clear();                            // for relaod case
6269
6270    uint32 count = 0;
6271    QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6272
6273    if( !result )
6274    {
6275        barGoLink bar( 1 );
6276
6277        bar.step();
6278
6279        sLog.outString();
6280        sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6281        return;
6282    }
6283
6284    barGoLink bar( result->GetRowCount() );
6285
6286    do
6287    {
6288        bar.step();
6289
6290        Field *fields = result->Fetch();
6291        uint32 entry  = fields[0].GetUInt32();
6292        int32 skill   = fields[1].GetInt32();
6293
6294        AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6295        if(!fArea)
6296        {
6297            sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6298            continue;
6299        }
6300
6301        mFishingBaseForArea[entry] = skill;
6302        ++count;
6303    }
6304    while (result->NextRow());
6305
6306    delete result;
6307
6308    sLog.outString();
6309    sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6310}
6311
6312// Searches for the same condition already in Conditions store
6313// Returns Id if found, else adds it to Conditions and returns Id
6314uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6315{
6316    PlayerCondition lc = PlayerCondition(condition, value1, value2);
6317    for (uint16 i=0; i < mConditions.size(); ++i)
6318    {
6319        if (lc == mConditions[i])
6320            return i;
6321    }
6322
6323    mConditions.push_back(lc);
6324
6325    if(mConditions.size() > 0xFFFF)
6326    {
6327        sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6328        return 0;
6329    }
6330
6331    return mConditions.size() - 1;
6332}
6333
6334bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6335{
6336    for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6337    {
6338        std::wstring wname;
6339        if(!Utf8toWStr(names.name[i],wname))
6340            return false;
6341
6342        if(mainpart!=GetMainPartOfName(wname,i+1))
6343            return false;
6344    }
6345    return true;
6346}
6347
6348const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6349{
6350    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6351    if(i!= mAreaTriggerScripts.end())
6352        return i->second.c_str();
6353    return "";
6354}
6355
6356// Checks if player meets the condition
6357bool PlayerCondition::Meets(Player const * player) const
6358{
6359    if( !player )
6360        return false;                                       // player not present, return false
6361
6362    switch (condition)
6363    {
6364        case CONDITION_NONE:
6365            return true;                                    // empty condition, always met
6366        case CONDITION_AURA:
6367            return player->HasAura(value1, value2);
6368        case CONDITION_ITEM:
6369            return player->HasItemCount(value1, value2);
6370        case CONDITION_ITEM_EQUIPPED:
6371            return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6372        case CONDITION_ZONEID:
6373            return player->GetZoneId() == value1;
6374        case CONDITION_REPUTATION_RANK:
6375        {
6376            FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6377            return faction && player->GetReputationRank(faction) >= value2;
6378        }
6379        case CONDITION_TEAM:
6380            return player->GetTeam() == value1;
6381        case CONDITION_SKILL:
6382            return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6383        case CONDITION_QUESTREWARDED:
6384            return player->GetQuestRewardStatus(value1);
6385        case CONDITION_QUESTTAKEN:
6386        {
6387            QuestStatus status = player->GetQuestStatus(value1);
6388            return (status == QUEST_STATUS_INCOMPLETE);
6389        }
6390        case CONDITION_AD_COMMISSION_AURA:
6391        {
6392            Unit::AuraMap const& auras = player->GetAuras();
6393            for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6394                if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6395                    return true;
6396            return false;
6397        }
6398        default:
6399            return false;
6400    }
6401}
6402
6403// Verification of condition values validity
6404bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6405{
6406    if( condition >= MAX_CONDITION)                         // Wrong condition type
6407    {
6408        sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6409        return false;
6410    }
6411
6412    switch (condition)
6413    {
6414        case CONDITION_AURA:
6415        {
6416            if(!sSpellStore.LookupEntry(value1))
6417            {
6418                sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6419                return false;
6420            }
6421            if(value2 > 2)
6422            {
6423                sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6424                return false;
6425            }
6426            break;
6427        }
6428        case CONDITION_ITEM:
6429        {
6430            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6431            if(!proto)
6432            {
6433                sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6434                return false;
6435            }
6436            break;
6437        }
6438        case CONDITION_ITEM_EQUIPPED:
6439        {
6440            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6441            if(!proto)
6442            {
6443                sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6444                return false;
6445            }
6446            break;
6447        }
6448        case CONDITION_ZONEID:
6449        {
6450            AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6451            if(!areaEntry)
6452            {
6453                sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6454                return false;
6455            }
6456            if(areaEntry->zone != 0)
6457            {
6458                sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6459                return false;
6460            }
6461            break;
6462        }
6463        case CONDITION_REPUTATION_RANK:
6464        {
6465            FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6466            if(!factionEntry)
6467            {
6468                sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6469                return false;
6470            }
6471            break;
6472        }
6473        case CONDITION_TEAM:
6474        {
6475            if (value1 != ALLIANCE && value1 != HORDE)
6476            {
6477                sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6478                return false;
6479            }
6480            break;
6481        }
6482        case CONDITION_SKILL:
6483        {
6484            SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6485            if (!pSkill)
6486            {
6487                sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6488                return false;
6489            }
6490            if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6491            {
6492                sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6493                return false;
6494            }
6495            break;
6496        }
6497        case CONDITION_QUESTREWARDED:
6498        case CONDITION_QUESTTAKEN:
6499        {
6500            Quest const *Quest = objmgr.GetQuestTemplate(value1);
6501            if (!Quest)
6502            {
6503                sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6504                return false;
6505            }
6506            if(value2)
6507                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6508            break;
6509        }
6510        case CONDITION_AD_COMMISSION_AURA:
6511        {
6512            if(value1)
6513                sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6514            if(value2)
6515                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6516            break;
6517        }
6518    }
6519    return true;
6520}
6521
6522SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6523{
6524    switch(pSkill->categoryId)
6525    {
6526        case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6527        case SKILL_CATEGORY_WEAPON:
6528            if(pSkill->id!=SKILL_FIST_WEAPONS)
6529                return SKILL_RANGE_LEVEL;
6530            else
6531                return SKILL_RANGE_MONO;
6532        case SKILL_CATEGORY_ARMOR:
6533        case SKILL_CATEGORY_CLASS:
6534            if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6535                return SKILL_RANGE_MONO;
6536            else
6537                return SKILL_RANGE_LEVEL;
6538        case SKILL_CATEGORY_SECONDARY:
6539        case SKILL_CATEGORY_PROFESSION:
6540            // not set skills for professions and racial abilities
6541            if(IsProfessionSkill(pSkill->id))
6542                return SKILL_RANGE_RANK;
6543            else if(racial)
6544                return SKILL_RANGE_NONE;
6545            else
6546                return SKILL_RANGE_MONO;
6547        default:
6548        case SKILL_CATEGORY_ATTRIBUTES:                     //not found in dbc
6549        case SKILL_CATEGORY_NOT_DISPLAYED:                  //only GENEREC(DND)
6550            return SKILL_RANGE_NONE;
6551    }
6552}
6553
6554void ObjectMgr::LoadGameTele()
6555{
6556    m_GameTeleMap.clear();                                  // for relaod case
6557
6558    uint32 count = 0;
6559    QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6560
6561    if( !result )
6562    {
6563        barGoLink bar( 1 );
6564
6565        bar.step();
6566
6567        sLog.outString();
6568        sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6569        return;
6570    }
6571
6572    barGoLink bar( result->GetRowCount() );
6573
6574    do
6575    {
6576        bar.step();
6577
6578        Field *fields = result->Fetch();
6579
6580        uint32 id         = fields[0].GetUInt32();
6581
6582        GameTele gt;
6583
6584        gt.position_x     = fields[1].GetFloat();
6585        gt.position_y     = fields[2].GetFloat();
6586        gt.position_z     = fields[3].GetFloat();
6587        gt.orientation    = fields[4].GetFloat();
6588        gt.mapId          = fields[5].GetUInt32();
6589        gt.name           = fields[6].GetCppString();
6590
6591        if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6592        {
6593            sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6594            continue;
6595        }
6596
6597        if(!Utf8toWStr(gt.name,gt.wnameLow))
6598        {
6599            sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6600            continue;
6601        }
6602
6603        wstrToLower( gt.wnameLow );
6604
6605        m_GameTeleMap[id] = gt;
6606
6607        ++count;
6608    }
6609    while (result->NextRow());
6610
6611    delete result;
6612
6613    sLog.outString();
6614    sLog.outString( ">> Loaded %u game tele's", count );
6615}
6616
6617GameTele const* ObjectMgr::GetGameTele(std::string name) const
6618{
6619    // explicit name case
6620    std::wstring wname;
6621    if(!Utf8toWStr(name,wname))
6622        return false;
6623
6624    // converting string that we try to find to lower case
6625    wstrToLower( wname );
6626
6627    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6628        if(itr->second.wnameLow == wname)
6629            return &itr->second;
6630
6631    return NULL;
6632}
6633
6634bool ObjectMgr::AddGameTele(GameTele& tele)
6635{
6636    // find max id
6637    uint32 new_id = 0;
6638    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6639        if(itr->first > new_id)
6640            new_id = itr->first;
6641   
6642    // use next
6643    ++new_id;
6644
6645    if(!Utf8toWStr(tele.name,tele.wnameLow))
6646        return false;
6647
6648    wstrToLower( tele.wnameLow );
6649
6650    m_GameTeleMap[new_id] = tele;
6651
6652    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')",
6653        new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6654}
6655
6656bool ObjectMgr::DeleteGameTele(std::string name)
6657{
6658    // explicit name case
6659    std::wstring wname;
6660    if(!Utf8toWStr(name,wname))
6661        return false;
6662
6663    // converting string that we try to find to lower case
6664    wstrToLower( wname );
6665
6666    for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6667    {
6668        if(itr->second.wnameLow == wname)
6669        {
6670            WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6671            m_GameTeleMap.erase(itr);
6672            return true;
6673        }
6674    }
6675
6676    return false;
6677}
6678
6679void ObjectMgr::LoadTrainerSpell()
6680{
6681    // For reload case
6682    for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6683        itr->second.Clear();
6684    m_mCacheTrainerSpellMap.clear();
6685
6686    std::set<uint32> skip_trainers;
6687
6688    QueryResult *result = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6689
6690    if( !result )
6691    {
6692        barGoLink bar( 1 );
6693
6694        bar.step();
6695
6696        sLog.outString();
6697        sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6698        return;
6699    }
6700
6701    barGoLink bar( result->GetRowCount() );
6702
6703    uint32 count = 0;
6704    do
6705    {
6706        bar.step();
6707
6708        Field* fields = result->Fetch();
6709
6710        uint32 entry  = fields[0].GetUInt32();
6711        uint32 spell  = fields[1].GetUInt32();
6712
6713        CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6714
6715        if(!cInfo)
6716        {
6717            sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6718            continue;
6719        }
6720
6721        if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6722        {
6723            if(skip_trainers.count(entry) == 0)
6724            {
6725                sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6726                skip_trainers.insert(entry);
6727            }
6728            continue;
6729        }
6730
6731        SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6732        if(!spellinfo)
6733        {
6734            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6735            continue;
6736        }
6737
6738        if(!SpellMgr::IsSpellValid(spellinfo))
6739        {
6740            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6741            continue;
6742        }
6743
6744        TrainerSpell* pTrainerSpell = new TrainerSpell();
6745        pTrainerSpell->spell         = spell;
6746        pTrainerSpell->spellcost     = fields[2].GetUInt32();
6747        pTrainerSpell->reqskill      = fields[3].GetUInt32();
6748        pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6749        pTrainerSpell->reqlevel      = fields[5].GetUInt32();
6750
6751        if(!pTrainerSpell->reqlevel)
6752            pTrainerSpell->reqlevel = spellinfo->spellLevel;
6753
6754
6755        TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6756
6757        if(SpellMgr::IsProfessionSpell(spell))
6758            data.trainerType = 2;
6759
6760        data.spellList.push_back(pTrainerSpell);
6761        ++count;
6762
6763    } while (result->NextRow());
6764    delete result;
6765
6766    sLog.outString();
6767    sLog.outString( ">> Loaded Trainers %d", count );
6768}
6769
6770void ObjectMgr::LoadVendors()
6771{
6772    // For reload case
6773    for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6774        itr->second.Clear();
6775    m_mCacheVendorItemMap.clear();
6776
6777    std::set<uint32> skip_vendors;
6778
6779    QueryResult *result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6780    if( !result )
6781    {
6782        barGoLink bar( 1 );
6783
6784        bar.step();
6785
6786        sLog.outString();
6787        sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6788        return;
6789    }
6790
6791    barGoLink bar( result->GetRowCount() );
6792
6793    uint32 count = 0;
6794    do
6795    {
6796        bar.step();
6797        Field* fields = result->Fetch();
6798
6799        uint32 entry        = fields[0].GetUInt32();
6800        uint32 item_id      = fields[1].GetUInt32();
6801        uint32 maxcount     = fields[2].GetUInt32();
6802        uint32 incrtime     = fields[3].GetUInt32();
6803        uint32 ExtendedCost = fields[4].GetUInt32();
6804
6805        if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6806            continue;
6807
6808        VendorItemData& vList = m_mCacheVendorItemMap[entry];
6809
6810        vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
6811        ++count;
6812
6813    } while (result->NextRow());
6814    delete result;
6815
6816    sLog.outString();
6817    sLog.outString( ">> Loaded %d Vendors ", count );
6818}
6819
6820void ObjectMgr::LoadNpcTextId()
6821{
6822
6823    m_mCacheNpcTextIdMap.clear();
6824
6825    QueryResult* result = WorldDatabase.PQuery("SELECT npc_guid, textid FROM npc_gossip");
6826    if( !result )
6827    {
6828        barGoLink bar( 1 );
6829
6830        bar.step();
6831
6832        sLog.outString();
6833        sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
6834        return;
6835    }
6836
6837    barGoLink bar( result->GetRowCount() );
6838
6839    uint32 count = 0;
6840    uint32 guid,textid;
6841    do
6842    {
6843        bar.step();
6844
6845        Field* fields = result->Fetch();
6846
6847        guid   = fields[0].GetUInt32();
6848        textid = fields[1].GetUInt32();
6849
6850        if (!GetCreatureData(guid))
6851        {
6852            sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
6853            continue;
6854        }
6855        if (!GetGossipText(textid))
6856        {
6857            sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
6858            continue;
6859        }
6860
6861        m_mCacheNpcTextIdMap[guid] = textid ;
6862        ++count;
6863
6864    } while (result->NextRow());
6865    delete result;
6866
6867    sLog.outString();
6868    sLog.outString( ">> Loaded %d NpcTextId ", count );
6869}
6870
6871void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
6872{
6873    VendorItemData& vList = m_mCacheVendorItemMap[entry];
6874    vList.AddItem(item,maxcount,incrtime,extendedcost);
6875
6876    WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
6877}
6878
6879bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
6880{
6881    CacheVendorItemMap::iterator  iter = m_mCacheVendorItemMap.find(entry);
6882    if(iter == m_mCacheVendorItemMap.end())
6883        return false;
6884
6885    if(!iter->second.FindItem(item))
6886        return false;
6887
6888    iter->second.RemoveItem(item);
6889    WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
6890    return true;
6891}
6892
6893bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
6894{
6895    CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
6896    if(!cInfo)
6897    {
6898        if(pl)
6899            ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6900        else
6901            sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
6902        return false;
6903    }
6904
6905    if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
6906    {
6907        if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
6908        {
6909            if(pl)
6910                ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6911            else
6912                sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
6913
6914            if(skip_vendors)
6915                skip_vendors->insert(vendor_entry);
6916        }
6917        return false;
6918    }
6919
6920    if(!GetItemPrototype(item_id))
6921    {
6922        if(pl)
6923            ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
6924        else
6925            sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
6926        return false;
6927    }
6928
6929    if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
6930    {
6931        if(pl)
6932            ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
6933        else
6934            sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
6935        return false;
6936    }
6937
6938    if(maxcount > 0 && incrtime == 0)
6939    {
6940        if(pl)
6941            ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
6942        else
6943            sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
6944        return false;
6945    }
6946    else if(maxcount==0 && incrtime > 0)
6947    {
6948        if(pl)
6949            ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
6950        else
6951            sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
6952        return false;
6953    }
6954
6955    VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
6956    if(!vItems)
6957        return true;                                        // later checks for non-empty lists
6958
6959    if(vItems->FindItem(item_id))
6960    {
6961        if(pl)
6962            ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
6963        else
6964            sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
6965        return false;
6966    }
6967
6968    if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
6969    {
6970        if(pl)
6971            ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
6972        else
6973            sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
6974        return false;
6975    }
6976
6977    return true;
6978}
6979
6980// Functions for scripting access
6981const char* GetAreaTriggerScriptNameById(uint32 id)
6982{
6983    return objmgr.GetAreaTriggerScriptName(id);
6984}
6985
6986bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
6987{
6988    if(start_value >= 0 || start_value <= end_value)        // start/end reversed for negative values
6989    {
6990        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());
6991        start_value = -1;
6992        end_value = std::numeric_limits<int32>::min();
6993    }
6994
6995    // for scripting localized strings allowed use _only_ negative entries
6996    return objmgr.LoadMangosStrings(db,table,end_value,start_value);
6997}
Note: See TracBrowser for help on using the browser.