[6830] Implement custom exit codes on server shutdown/restart
[getmangos.git] / src / game / ObjectMgr.cpp
blob01b20bddf15a596c8aef54a07259ae306b57634d
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
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.
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.
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
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
24 #include "Log.h"
25 #include "MapManager.h"
26 #include "ObjectMgr.h"
27 #include "SpellMgr.h"
28 #include "UpdateMask.h"
29 #include "World.h"
30 #include "WorldSession.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Policies/SingletonImp.h"
37 #include "Language.h"
38 #include "GameEvent.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
46 INSTANTIATE_SINGLETON_1(ObjectMgr);
48 ScriptMapMap sQuestEndScripts;
49 ScriptMapMap sQuestStartScripts;
50 ScriptMapMap sSpellScripts;
51 ScriptMapMap sGameObjectScripts;
52 ScriptMapMap sEventScripts;
54 bool normalizePlayerName(std::string& name)
56 if(name.empty())
57 return false;
59 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
60 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
62 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
63 return false;
65 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
66 for(size_t i = 1; i < wstr_len; ++i)
67 wstr_buf[i] = wcharToLower(wstr_buf[i]);
69 if(!WStrToUtf8(wstr_buf,wstr_len,name))
70 return false;
72 return true;
75 LanguageDesc lang_description[LANGUAGES_COUNT] =
77 { LANG_ADDON, 0, 0 },
78 { LANG_UNIVERSAL, 0, 0 },
79 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
80 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
81 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
82 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
83 { LANG_COMMON, 668, SKILL_LANG_COMMON },
84 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
85 { LANG_TITAN, 816, SKILL_LANG_TITAN },
86 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
87 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
88 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
89 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
90 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
91 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
92 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
93 { LANG_ZOMBIE, 0, 0 },
94 { LANG_GNOMISH_BINARY, 0, 0 },
95 { LANG_GOBLIN_BINARY, 0, 0 }
98 LanguageDesc const* GetLanguageDescByID(uint32 lang)
100 for(int i = 0; i < LANGUAGES_COUNT; ++i)
102 if(uint32(lang_description[i].lang_id) == lang)
103 return &lang_description[i];
106 return NULL;
109 ObjectMgr::ObjectMgr()
111 m_hiCharGuid = 1;
112 m_hiCreatureGuid = 1;
113 m_hiPetGuid = 1;
114 m_hiItemGuid = 1;
115 m_hiGoGuid = 1;
116 m_hiDoGuid = 1;
117 m_hiCorpseGuid = 1;
119 m_hiPetNumber = 1;
121 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
122 mGuildBankTabPrice[0] = 100;
123 mGuildBankTabPrice[1] = 250;
124 mGuildBankTabPrice[2] = 500;
125 mGuildBankTabPrice[3] = 1000;
126 mGuildBankTabPrice[4] = 2500;
127 mGuildBankTabPrice[5] = 5000;
129 // Only zero condition left, others will be added while loading DB tables
130 mConditions.resize(1);
133 ObjectMgr::~ObjectMgr()
135 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
137 delete i->second;
139 mQuestTemplates.clear( );
141 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
143 delete i->second;
145 mGossipText.clear( );
147 mAreaTriggers.clear();
149 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
151 delete[] i->second;
153 petInfo.clear();
155 // free only if loaded
156 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
157 delete[] playerClassInfo[class_].levelInfo;
159 for (int race = 0; race < MAX_RACES; ++race)
160 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
161 delete[] playerInfo[race][class_].levelInfo;
163 // free group and guild objects
164 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
165 delete (*itr);
166 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
167 delete (*itr);
169 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
170 delete itr->second;
172 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
173 itr->second.Clear();
175 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
176 itr->second.Clear();
179 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
181 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
182 if ((*itr)->GetLeaderGUID() == guid)
183 return *itr;
185 return NULL;
188 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
190 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
191 if ((*itr)->GetId() == GuildId)
192 return *itr;
194 return NULL;
197 Guild * ObjectMgr::GetGuildByName(std::string guildname) const
199 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
200 if ((*itr)->GetName() == guildname)
201 return *itr;
203 return NULL;
206 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
208 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
209 if ((*itr)->GetId() == GuildId)
210 return (*itr)->GetName();
212 return "";
215 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
217 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
218 if( (*itr)->GetLeader() == guid)
219 return *itr;
221 return NULL;
224 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
226 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
227 if ((*itr)->GetId() == ArenaTeamId)
228 return *itr;
230 return NULL;
233 ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
235 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
236 if ((*itr)->GetName() == arenateamname)
237 return *itr;
239 return NULL;
242 ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
244 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
245 if ((*itr)->GetCaptain() == guid)
246 return *itr;
248 return NULL;
251 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
253 switch ( location )
255 case 6: //horde
256 return & mHordeAuctions;
257 break;
258 case 2: //alliance
259 return & mAllianceAuctions;
260 break;
261 default: //neutral
262 return & mNeutralAuctions;
266 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
268 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
269 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
270 else
271 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
274 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
276 float percentance; // in 0..1
277 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
278 percentance = 0.75f;
279 else
280 percentance = 0.15f;
282 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
284 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
287 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
288 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
290 uint32 outbid = (currentBid / 100) * 5;
291 if (!outbid)
292 outbid = 1;
293 return outbid;
296 //does not clear ram
297 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
299 Item *pItem = GetAItem(auction->item_guidlow);
300 if(!pItem)
301 return;
303 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
304 Player *bidder = GetPlayer(bidder_guid);
306 uint32 bidder_accId = 0;
308 // data for gm.log
309 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
311 uint32 bidder_security = 0;
312 std::string bidder_name;
313 if (bidder)
315 bidder_accId = bidder->GetSession()->GetAccountId();
316 bidder_security = bidder->GetSession()->GetSecurity();
317 bidder_name = bidder->GetName();
319 else
321 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
322 bidder_security = accmgr.GetSecurity(bidder_accId);
324 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
326 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
327 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
331 if( bidder_security > SEC_PLAYER )
333 std::string owner_name;
334 if(!GetPlayerNameByGUID(auction->owner,owner_name))
335 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
337 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
339 sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
340 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
343 else if(!bidder)
344 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
346 // receiver exist
347 if(bidder || bidder_accId)
349 std::ostringstream msgAuctionWonSubject;
350 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
352 std::ostringstream msgAuctionWonBody;
353 msgAuctionWonBody.width(16);
354 msgAuctionWonBody << std::right << std::hex << auction->owner;
355 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
356 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
358 //prepare mail data... :
359 uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
361 // set owner to bidder (to prevent delete item with sender char deleting)
362 // owner in `data` will set at mail receive and item extracting
363 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
364 CharacterDatabase.CommitTransaction();
366 MailItemsInfo mi;
367 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
369 if (bidder)
370 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
371 else
372 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
374 // will delete item or place to receiver mail list
375 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
377 // receiver not exist
378 else
380 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
381 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
382 delete pItem;
386 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
388 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
389 Player *owner = GetPlayer(owner_guid);
391 // owner exist (online or offline)
392 if(owner || GetPlayerAccountIdByGUID(owner_guid))
394 std::ostringstream msgAuctionSalePendingSubject;
395 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
397 std::ostringstream msgAuctionSalePendingBody;
398 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
400 time_t distrTime = time(NULL) + HOUR;
402 msgAuctionSalePendingBody.width(16);
403 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
404 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
405 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
406 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
408 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
410 uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
412 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
416 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
417 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
419 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
420 Player *owner = GetPlayer(owner_guid);
422 uint32 owner_accId = 0;
423 if(!owner)
424 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
426 // owner exist
427 if(owner || owner_accId)
429 std::ostringstream msgAuctionSuccessfulSubject;
430 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
432 std::ostringstream auctionSuccessfulBody;
433 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
435 auctionSuccessfulBody.width(16);
436 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
437 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
438 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
440 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
442 uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
444 uint32 profit = auction->bid + auction->deposit - auctionCut;
446 if (owner)
448 //send auction owner notification, bidder must be current!
449 owner->GetSession()->SendAuctionOwnerNotification( auction );
452 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
456 //does not clear ram
457 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
458 { //return an item in auction to its owner by mail
459 Item *pItem = GetAItem(auction->item_guidlow);
460 if(!pItem)
462 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
463 return;
466 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
467 Player *owner = GetPlayer(owner_guid);
469 uint32 owner_accId = 0;
470 if(!owner)
471 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
473 // owner exist
474 if(owner || owner_accId)
476 std::ostringstream subject;
477 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
479 if ( owner )
480 owner->GetSession()->SendAuctionOwnerNotification( auction );
481 else
482 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
484 MailItemsInfo mi;
485 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
487 // will delete item or place to receiver mail list
488 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
490 // owner not found
491 else
493 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
494 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
495 delete pItem;
499 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
501 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
504 void ObjectMgr::LoadCreatureLocales()
506 mCreatureLocaleMap.clear(); // need for reload case
508 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");
510 if(!result)
512 barGoLink bar(1);
514 bar.step();
516 sLog.outString("");
517 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
518 return;
521 barGoLink bar(result->GetRowCount());
525 Field *fields = result->Fetch();
526 bar.step();
528 uint32 entry = fields[0].GetUInt32();
530 CreatureLocale& data = mCreatureLocaleMap[entry];
532 for(int i = 1; i < MAX_LOCALE; ++i)
534 std::string str = fields[1+2*(i-1)].GetCppString();
535 if(!str.empty())
537 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
538 if(idx >= 0)
540 if(data.Name.size() <= idx)
541 data.Name.resize(idx+1);
543 data.Name[idx] = str;
546 str = fields[1+2*(i-1)+1].GetCppString();
547 if(!str.empty())
549 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
550 if(idx >= 0)
552 if(data.SubName.size() <= idx)
553 data.SubName.resize(idx+1);
555 data.SubName[idx] = str;
559 } while (result->NextRow());
561 delete result;
563 sLog.outString();
564 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
567 void ObjectMgr::LoadNpcOptionLocales()
569 mNpcOptionLocaleMap.clear(); // need for reload case
571 QueryResult *result = WorldDatabase.Query("SELECT entry,"
572 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
573 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
574 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
575 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
576 "FROM locales_npc_option");
578 if(!result)
580 barGoLink bar(1);
582 bar.step();
584 sLog.outString("");
585 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
586 return;
589 barGoLink bar(result->GetRowCount());
593 Field *fields = result->Fetch();
594 bar.step();
596 uint32 entry = fields[0].GetUInt32();
598 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
600 for(int i = 1; i < MAX_LOCALE; ++i)
602 std::string str = fields[1+2*(i-1)].GetCppString();
603 if(!str.empty())
605 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
606 if(idx >= 0)
608 if(data.OptionText.size() <= idx)
609 data.OptionText.resize(idx+1);
611 data.OptionText[idx] = str;
614 str = fields[1+2*(i-1)+1].GetCppString();
615 if(!str.empty())
617 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
618 if(idx >= 0)
620 if(data.BoxText.size() <= idx)
621 data.BoxText.resize(idx+1);
623 data.BoxText[idx] = str;
627 } while (result->NextRow());
629 delete result;
631 sLog.outString();
632 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
635 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
637 template<class D>
638 void convert_from_str(uint32 field_pos, char *src, D &dst)
640 dst = D(objmgr.GetScriptId(src));
644 void ObjectMgr::LoadCreatureTemplates()
646 SQLCreatureLoader loader;
647 loader.Load(sCreatureStorage);
649 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
650 sLog.outString();
652 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
653 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
655 // check data correctness
656 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
658 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
659 if(!cInfo)
660 continue;
662 if(cInfo->HeroicEntry)
664 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
665 if(!heroicInfo)
667 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
668 continue;
671 if(heroicEntries.find(i)!=heroicEntries.end())
673 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
674 continue;
677 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
679 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
680 continue;
683 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
685 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
686 continue;
689 if(cInfo->npcflag != heroicInfo->npcflag)
691 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
692 continue;
695 if(cInfo->classNum != heroicInfo->classNum)
697 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
698 continue;
701 if(cInfo->race != heroicInfo->race)
703 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
704 continue;
707 if(cInfo->trainer_type != heroicInfo->trainer_type)
709 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
710 continue;
713 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
715 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
716 continue;
719 hasHeroicEntries.insert(i);
720 heroicEntries.insert(cInfo->HeroicEntry);
723 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
724 if(!factionTemplate)
725 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
727 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
728 if(!factionTemplate)
729 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
731 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
732 if (!minfo)
733 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
734 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
735 if (!minfo)
736 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
738 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
740 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
741 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
744 if(cInfo->baseattacktime == 0)
745 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
747 if(cInfo->rangeattacktime == 0)
748 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
750 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
751 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
753 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
755 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
756 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
759 if(cInfo->PetSpellDataId)
761 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
762 if(!spellDataId)
763 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
766 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
768 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
769 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
772 if(cInfo->equipmentId > 0) // 0 no equipment
774 if(!GetEquipmentInfo(cInfo->equipmentId))
776 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);
777 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
781 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
782 if(cInfo->scale <= 0.0f)
784 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
785 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
790 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
792 // Now add the auras, format "spellid effectindex spellid effectindex..."
793 char *p,*s;
794 std::vector<int> val;
795 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
796 if(p)
798 while (p[0]!=0)
800 ++p;
801 if (p[0]==' ')
803 val.push_back(atoi(s));
804 s=++p;
807 if (p!=s)
808 val.push_back(atoi(s));
810 // free char* loaded memory
811 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
813 // wrong list
814 if (val.size()%2)
816 addon->auras = NULL;
817 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
818 return;
822 // empty list
823 if(val.empty())
825 addon->auras = NULL;
826 return;
829 // replace by new structures array
830 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
832 int i=0;
833 for(int j=0;j<val.size()/2;++j)
835 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
836 cAura.spell_id = (uint32)val[2*j+0];
837 cAura.effect_idx = (uint32)val[2*j+1];
838 if ( cAura.effect_idx > 2 )
840 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);
841 continue;
843 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
844 if (!AdditionalSpellInfo)
846 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
847 continue;
850 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
852 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);
853 continue;
856 ++i;
859 // fill terminator element (after last added)
860 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
861 endAura.spell_id = 0;
862 endAura.effect_idx = 0;
865 void ObjectMgr::LoadCreatureAddons()
867 sCreatureInfoAddonStorage.Load();
869 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
870 sLog.outString();
872 // check data correctness and convert 'auras'
873 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
875 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
876 if(!addon)
877 continue;
879 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
881 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
882 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
885 sCreatureDataAddonStorage.Load();
887 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
888 sLog.outString();
890 // check data correctness and convert 'auras'
891 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
893 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
894 if(!addon)
895 continue;
897 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
899 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
900 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
904 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
906 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
909 void ObjectMgr::LoadEquipmentTemplates()
911 sEquipmentStorage.Load();
913 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
914 sLog.outString();
917 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
919 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
922 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
924 // Load creature model (display id)
925 uint32 display_id;
926 if (!data || data->displayid == 0) // use defaults from the template
928 // DisplayID_A is used if no team is given
929 if (team == HORDE)
930 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
931 else
932 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
934 else // overridden in creature data
935 display_id = data->displayid;
937 return display_id;
940 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
942 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
943 if(!minfo)
944 return NULL;
946 // If a model for another gender exists, 50% chance to use it
947 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
949 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
950 if(!minfo_tmp)
952 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
953 return minfo; // not fatal, just use the previous one
955 else
956 return minfo_tmp;
958 else
959 return minfo;
962 void ObjectMgr::LoadCreatureModelInfo()
964 sCreatureModelStorage.Load();
966 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
967 sLog.outString();
970 void ObjectMgr::LoadCreatures()
972 uint32 count = 0;
973 // 0 1 2 3
974 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
975 // 4 5 6 7 8 9 10 11
976 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
977 // 12 13 14 15 16 17
978 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
979 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
981 if(!result)
983 barGoLink bar(1);
985 bar.step();
987 sLog.outString("");
988 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
989 return;
992 // build single time for check creature data
993 std::set<uint32> heroicCreatures;
994 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
995 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
996 if(cInfo->HeroicEntry)
997 heroicCreatures.insert(cInfo->HeroicEntry);
999 barGoLink bar(result->GetRowCount());
1003 Field *fields = result->Fetch();
1004 bar.step();
1006 uint32 guid = fields[0].GetUInt32();
1008 CreatureData& data = mCreatureDataMap[guid];
1010 data.id = fields[ 1].GetUInt32();
1011 data.mapid = fields[ 2].GetUInt32();
1012 data.displayid = fields[ 3].GetUInt32();
1013 data.equipmentId = fields[ 4].GetUInt32();
1014 data.posX = fields[ 5].GetFloat();
1015 data.posY = fields[ 6].GetFloat();
1016 data.posZ = fields[ 7].GetFloat();
1017 data.orientation = fields[ 8].GetFloat();
1018 data.spawntimesecs = fields[ 9].GetUInt32();
1019 data.spawndist = fields[10].GetFloat();
1020 data.currentwaypoint= fields[11].GetUInt32();
1021 data.curhealth = fields[12].GetUInt32();
1022 data.curmana = fields[13].GetUInt32();
1023 data.is_dead = fields[14].GetBool();
1024 data.movementType = fields[15].GetUInt8();
1025 data.spawnMask = fields[16].GetUInt8();
1026 int16 gameEvent = fields[17].GetInt16();
1028 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1029 if(!cInfo)
1031 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1032 continue;
1035 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1037 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1038 continue;
1041 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1043 if(!GetEquipmentInfo(data.equipmentId))
1045 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);
1046 data.equipmentId = -1;
1050 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1052 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 );
1053 data.curhealth = cInfo->minhealth;
1056 if(data.curmana < cInfo->minmana)
1058 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 );
1059 data.curmana = cInfo->minmana;
1062 if(data.spawndist < 0.0f)
1064 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1065 data.spawndist = 0.0f;
1067 else if(data.movementType == RANDOM_MOTION_TYPE)
1069 if(data.spawndist == 0.0f)
1071 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 );
1072 data.movementType = IDLE_MOTION_TYPE;
1075 else if(data.movementType == IDLE_MOTION_TYPE)
1077 if(data.spawndist != 0.0f)
1079 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1080 data.spawndist = 0.0f;
1084 if (gameEvent==0) // if not this is to be managed by GameEvent System
1085 AddCreatureToGrid(guid, &data);
1086 ++count;
1088 } while (result->NextRow());
1090 delete result;
1092 sLog.outString();
1093 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1096 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1098 uint8 mask = data->spawnMask;
1099 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1101 if(mask & 1)
1103 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1104 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1106 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1107 cell_guids.creatures.insert(guid);
1112 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1114 uint8 mask = data->spawnMask;
1115 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1117 if(mask & 1)
1119 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1120 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1122 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1123 cell_guids.creatures.erase(guid);
1128 void ObjectMgr::LoadGameobjects()
1130 uint32 count = 0;
1132 // 0 1 2 3 4 5 6
1133 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1134 // 7 8 9 10 11 12 13 14 15
1135 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1136 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1138 if(!result)
1140 barGoLink bar(1);
1142 bar.step();
1144 sLog.outString();
1145 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1146 return;
1149 barGoLink bar(result->GetRowCount());
1153 Field *fields = result->Fetch();
1154 bar.step();
1156 uint32 guid = fields[0].GetUInt32();
1158 GameObjectData& data = mGameObjectDataMap[guid];
1160 data.id = fields[ 1].GetUInt32();
1161 data.mapid = fields[ 2].GetUInt32();
1162 data.posX = fields[ 3].GetFloat();
1163 data.posY = fields[ 4].GetFloat();
1164 data.posZ = fields[ 5].GetFloat();
1165 data.orientation = fields[ 6].GetFloat();
1166 data.rotation0 = fields[ 7].GetFloat();
1167 data.rotation1 = fields[ 8].GetFloat();
1168 data.rotation2 = fields[ 9].GetFloat();
1169 data.rotation3 = fields[10].GetFloat();
1170 data.spawntimesecs = fields[11].GetInt32();
1171 data.animprogress = fields[12].GetUInt32();
1172 data.go_state = fields[13].GetUInt32();
1173 data.spawnMask = fields[14].GetUInt8();
1174 int16 gameEvent = fields[15].GetInt16();
1176 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1177 if(!gInfo)
1179 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1180 continue;
1183 if (gameEvent==0) // if not this is to be managed by GameEvent System
1184 AddGameobjectToGrid(guid, &data);
1185 ++count;
1187 } while (result->NextRow());
1189 delete result;
1191 sLog.outString();
1192 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1195 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1197 uint8 mask = data->spawnMask;
1198 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1200 if(mask & 1)
1202 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1203 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1205 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1206 cell_guids.gameobjects.insert(guid);
1211 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1213 uint8 mask = data->spawnMask;
1214 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1216 if(mask & 1)
1218 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1219 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1221 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1222 cell_guids.gameobjects.erase(guid);
1227 void ObjectMgr::LoadCreatureRespawnTimes()
1229 // remove outdated data
1230 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1232 uint32 count = 0;
1234 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1236 if(!result)
1238 barGoLink bar(1);
1240 bar.step();
1242 sLog.outString();
1243 sLog.outString(">> Loaded 0 creature respawn time.");
1244 return;
1247 barGoLink bar(result->GetRowCount());
1251 Field *fields = result->Fetch();
1252 bar.step();
1254 uint32 loguid = fields[0].GetUInt32();
1255 uint64 respawn_time = fields[1].GetUInt64();
1256 uint32 instance = fields[2].GetUInt32();
1258 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1260 ++count;
1261 } while (result->NextRow());
1263 delete result;
1265 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1266 sLog.outString();
1269 void ObjectMgr::LoadGameobjectRespawnTimes()
1271 // remove outdated data
1272 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1274 uint32 count = 0;
1276 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1278 if(!result)
1280 barGoLink bar(1);
1282 bar.step();
1284 sLog.outString();
1285 sLog.outString(">> Loaded 0 gameobject respawn time.");
1286 return;
1289 barGoLink bar(result->GetRowCount());
1293 Field *fields = result->Fetch();
1294 bar.step();
1296 uint32 loguid = fields[0].GetUInt32();
1297 uint64 respawn_time = fields[1].GetUInt64();
1298 uint32 instance = fields[2].GetUInt32();
1300 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1302 ++count;
1303 } while (result->NextRow());
1305 delete result;
1307 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1308 sLog.outString();
1311 // name must be checked to correctness (if received) before call this function
1312 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1314 uint64 guid = 0;
1316 CharacterDatabase.escape_string(name);
1318 // Player name safe to sending to DB (checked at login) and this function using
1319 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1320 if(result)
1322 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1324 delete result;
1327 return guid;
1330 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1332 // prevent DB access for online player
1333 if(Player* player = GetPlayer(guid))
1335 name = player->GetName();
1336 return true;
1339 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1341 if(result)
1343 name = (*result)[0].GetCppString();
1344 delete result;
1345 return true;
1348 return false;
1351 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1353 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1355 if(result)
1357 uint8 race = (*result)[0].GetUInt8();
1358 delete result;
1359 return Player::TeamForRace(race);
1362 return 0;
1365 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1367 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1368 if(result)
1370 uint32 acc = (*result)[0].GetUInt32();
1371 delete result;
1372 return acc;
1375 return 0;
1378 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(std::string name) const
1380 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1381 if(result)
1383 uint32 acc = (*result)[0].GetUInt32();
1384 delete result;
1385 return acc;
1388 return 0;
1391 void ObjectMgr::LoadAuctions()
1393 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1394 if( !result )
1395 return;
1397 Field *fields = result->Fetch();
1398 uint32 AuctionCount=fields[0].GetUInt32();
1399 delete result;
1401 if(!AuctionCount)
1402 return;
1404 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1405 if( !result )
1406 return;
1408 barGoLink bar( AuctionCount );
1410 AuctionEntry *aItem;
1414 fields = result->Fetch();
1416 bar.step();
1418 aItem = new AuctionEntry;
1419 aItem->Id = fields[0].GetUInt32();
1420 aItem->auctioneer = fields[1].GetUInt32();
1421 aItem->item_guidlow = fields[2].GetUInt32();
1422 aItem->item_template = fields[3].GetUInt32();
1423 aItem->owner = fields[4].GetUInt32();
1424 aItem->buyout = fields[5].GetUInt32();
1425 aItem->time = fields[6].GetUInt32();
1426 aItem->bidder = fields[7].GetUInt32();
1427 aItem->bid = fields[8].GetUInt32();
1428 aItem->startbid = fields[9].GetUInt32();
1429 aItem->deposit = fields[10].GetUInt32();
1430 aItem->location = fields[11].GetUInt8();
1431 //check if sold item exists
1432 if ( GetAItem( aItem->item_guidlow ) )
1434 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1436 else
1438 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1439 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1440 delete aItem;
1442 } while (result->NextRow());
1443 delete result;
1445 sLog.outString();
1446 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1447 sLog.outString();
1450 void ObjectMgr::LoadItemLocales()
1452 mItemLocaleMap.clear(); // need for reload case
1454 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");
1456 if(!result)
1458 barGoLink bar(1);
1460 bar.step();
1462 sLog.outString("");
1463 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1464 return;
1467 barGoLink bar(result->GetRowCount());
1471 Field *fields = result->Fetch();
1472 bar.step();
1474 uint32 entry = fields[0].GetUInt32();
1476 ItemLocale& data = mItemLocaleMap[entry];
1478 for(int i = 1; i < MAX_LOCALE; ++i)
1480 std::string str = fields[1+2*(i-1)].GetCppString();
1481 if(!str.empty())
1483 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1484 if(idx >= 0)
1486 if(data.Name.size() <= idx)
1487 data.Name.resize(idx+1);
1489 data.Name[idx] = str;
1493 str = fields[1+2*(i-1)+1].GetCppString();
1494 if(!str.empty())
1496 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1497 if(idx >= 0)
1499 if(data.Description.size() <= idx)
1500 data.Description.resize(idx+1);
1502 data.Description[idx] = str;
1506 } while (result->NextRow());
1508 delete result;
1510 sLog.outString();
1511 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1514 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1516 template<class D>
1517 void convert_from_str(uint32 field_pos, char *src, D &dst)
1519 dst = D(objmgr.GetScriptId(src));
1523 void ObjectMgr::LoadItemPrototypes()
1525 SQLItemLoader loader;
1526 loader.Load(sItemStorage);
1527 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1528 sLog.outString();
1530 // check data correctness
1531 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1533 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1534 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1535 if(!proto)
1537 /* to many errors, and possible not all items really used in game
1538 if (dbcitem)
1539 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1541 continue;
1544 if(dbcitem)
1546 if(proto->InventoryType != dbcitem->InventoryType)
1548 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1549 // It safe let use InventoryType from DB
1552 if(proto->DisplayInfoID != dbcitem->DisplayId)
1554 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1555 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1557 if(proto->Sheath != dbcitem->Sheath)
1559 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1560 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1563 else
1565 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1568 if(proto->Class >= MAX_ITEM_CLASS)
1570 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1571 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_JUNK;
1574 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1576 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1577 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1580 if(proto->Quality >= MAX_ITEM_QUALITY)
1582 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1583 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1586 if(proto->BuyCount <= 0)
1588 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1589 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1592 if(proto->InventoryType >= MAX_INVTYPE)
1594 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1595 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1598 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1600 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1601 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1604 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1606 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1609 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1611 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1614 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1616 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1617 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1620 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1621 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1623 if(proto->RequiredReputationFaction)
1625 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1627 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1628 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1631 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1632 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1634 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1635 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1637 if(proto->Stackable==0)
1639 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1640 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1642 else if(proto->Stackable > 255)
1644 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1645 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1648 for (int j = 0; j < 10; j++)
1650 // for ItemStatValue != 0
1651 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1653 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1654 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1658 for (int j = 0; j < 5; j++)
1660 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1662 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1663 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1667 // special format
1668 if(proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN)
1670 // spell_1
1671 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1673 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);
1674 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1675 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1676 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1677 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1680 // spell_2 have learning spell
1681 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1683 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);
1684 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1685 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1686 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1688 else if(!proto->Spells[1].SpellId)
1690 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1691 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1692 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1694 else
1696 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1697 if(!spellInfo)
1699 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1700 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1701 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1702 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1704 // allowed only in special format
1705 else if(proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN)
1707 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1708 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1709 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1710 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1714 // spell_3*,spell_4*,spell_5* is empty
1715 for (int j = 2; j < 5; j++)
1717 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1719 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1720 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1721 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1723 else if(proto->Spells[j].SpellId != 0)
1725 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1726 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1730 // normal spell list
1731 else
1733 for (int j = 0; j < 5; j++)
1735 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1737 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1738 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1739 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1742 if(proto->Spells[j].SpellId)
1744 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1745 if(!spellInfo)
1747 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1748 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1750 // allowed only in special format
1751 else if(proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN)
1753 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1754 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1760 if(proto->Bonding >= MAX_BIND_TYPE)
1761 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1763 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1764 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1766 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1767 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1769 if(proto->Sheath >= MAX_SHEATHETYPE)
1771 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1772 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1775 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1777 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1778 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1781 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1783 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1784 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1787 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1789 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1790 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1793 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1794 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1796 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1797 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1799 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1800 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1802 for (int j = 0; j < 3; j++)
1804 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1806 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1807 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1811 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1812 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1814 if(proto->FoodType >= MAX_PET_DIET)
1816 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1817 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1821 // this DBC used currently only for check item templates in DB.
1822 sItemStore.Clear();
1825 void ObjectMgr::LoadAuctionItems()
1827 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1829 if( !result )
1830 return;
1832 barGoLink bar( result->GetRowCount() );
1834 uint32 count = 0;
1836 Field *fields;
1839 bar.step();
1841 fields = result->Fetch();
1842 uint32 item_guid = fields[0].GetUInt32();
1843 uint32 item_template = fields[1].GetUInt32();
1845 ItemPrototype const *proto = GetItemPrototype(item_template);
1847 if(!proto)
1849 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1850 continue;
1853 Item *item = NewItemOrBag(proto);
1855 if(!item->LoadFromDB(item_guid,0))
1857 delete item;
1858 continue;
1860 AddAItem(item);
1862 ++count;
1864 while( result->NextRow() );
1866 delete result;
1868 sLog.outString();
1869 sLog.outString( ">> Loaded %u auction items", count );
1872 void ObjectMgr::LoadPetLevelInfo()
1874 // Loading levels data
1876 // 0 1 2 3 4 5 6 7 8 9
1877 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1879 uint32 count = 0;
1881 if (!result)
1883 barGoLink bar( 1 );
1885 sLog.outString();
1886 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1887 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1888 return;
1891 barGoLink bar( result->GetRowCount() );
1895 Field* fields = result->Fetch();
1897 uint32 creature_id = fields[0].GetUInt32();
1898 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1900 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1901 continue;
1904 uint32 current_level = fields[1].GetUInt32();
1905 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1907 if(current_level > 255) // hardcoded level maximum
1908 sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1909 else
1910 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1911 continue;
1913 else if(current_level < 1)
1915 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1916 continue;
1919 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1921 if(pInfoMapEntry==NULL)
1922 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1924 // data for level 1 stored in [0] array element, ...
1925 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1927 pLevelInfo->health = fields[2].GetUInt16();
1928 pLevelInfo->mana = fields[3].GetUInt16();
1929 pLevelInfo->armor = fields[9].GetUInt16();
1931 for (int i = 0; i < MAX_STATS; i++)
1933 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1936 bar.step();
1937 ++count;
1939 while (result->NextRow());
1941 delete result;
1943 sLog.outString();
1944 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1947 // Fill gaps and check integrity
1948 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1950 PetLevelInfo* pInfo = itr->second;
1952 // fatal error if no level 1 data
1953 if(!pInfo || pInfo[0].health == 0 )
1955 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1956 exit(1);
1959 // fill level gaps
1960 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1962 if(pInfo[level].health == 0)
1964 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1965 pInfo[level] = pInfo[level-1];
1971 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1973 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1974 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1976 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1977 if(itr == petInfo.end())
1978 return NULL;
1980 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1983 void ObjectMgr::LoadPlayerInfo()
1985 // Load playercreate
1987 // 0 1 2 3 4 5 6
1988 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1990 uint32 count = 0;
1992 if (!result)
1994 barGoLink bar( 1 );
1996 sLog.outString();
1997 sLog.outString( ">> Loaded %u player create definitions", count );
1998 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1999 exit(1);
2002 barGoLink bar( result->GetRowCount() );
2006 Field* fields = result->Fetch();
2008 uint32 current_race = fields[0].GetUInt32();
2009 uint32 current_class = fields[1].GetUInt32();
2010 uint32 mapId = fields[2].GetUInt32();
2011 uint32 zoneId = fields[3].GetUInt32();
2012 float positionX = fields[4].GetFloat();
2013 float positionY = fields[5].GetFloat();
2014 float positionZ = fields[6].GetFloat();
2016 if(current_race >= MAX_RACES)
2018 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2019 continue;
2022 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2023 if(!rEntry)
2025 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2026 continue;
2029 if(current_class >= MAX_CLASSES)
2031 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2032 continue;
2035 if(!sChrClassesStore.LookupEntry(current_class))
2037 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2038 continue;
2041 // accept DB data only for valid position (and non instanceable)
2042 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2044 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2045 continue;
2048 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2050 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2051 continue;
2054 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2056 pInfo->mapId = mapId;
2057 pInfo->zoneId = zoneId;
2058 pInfo->positionX = positionX;
2059 pInfo->positionY = positionY;
2060 pInfo->positionZ = positionZ;
2062 pInfo->displayId_m = rEntry->model_m;
2063 pInfo->displayId_f = rEntry->model_f;
2065 bar.step();
2066 ++count;
2068 while (result->NextRow());
2070 delete result;
2072 sLog.outString();
2073 sLog.outString( ">> Loaded %u player create definitions", count );
2076 // Load playercreate items
2078 // 0 1 2 3
2079 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2081 uint32 count = 0;
2083 if (!result)
2085 barGoLink bar( 1 );
2087 sLog.outString();
2088 sLog.outString( ">> Loaded %u player create items", count );
2089 sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2091 else
2093 barGoLink bar( result->GetRowCount() );
2097 Field* fields = result->Fetch();
2099 uint32 current_race = fields[0].GetUInt32();
2100 if(current_race >= MAX_RACES)
2102 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2103 continue;
2106 uint32 current_class = fields[1].GetUInt32();
2107 if(current_class >= MAX_CLASSES)
2109 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2110 continue;
2113 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2115 uint32 item_id = fields[2].GetUInt32();
2117 if(!GetItemPrototype(item_id))
2119 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);
2120 continue;
2123 uint32 amount = fields[3].GetUInt32();
2125 if(!amount)
2127 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2128 continue;
2131 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2133 bar.step();
2134 ++count;
2136 while(result->NextRow());
2138 delete result;
2140 sLog.outString();
2141 sLog.outString( ">> Loaded %u player create items", count );
2145 // Load playercreate spells
2147 // 0 1 2 3
2148 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2150 uint32 count = 0;
2152 if (!result)
2154 barGoLink bar( 1 );
2156 sLog.outString();
2157 sLog.outString( ">> Loaded %u player create spells", count );
2158 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2160 else
2162 barGoLink bar( result->GetRowCount() );
2166 Field* fields = result->Fetch();
2168 uint32 current_race = fields[0].GetUInt32();
2169 if(current_race >= MAX_RACES)
2171 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2172 continue;
2175 uint32 current_class = fields[1].GetUInt32();
2176 if(current_class >= MAX_CLASSES)
2178 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2179 continue;
2182 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2183 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2185 bar.step();
2186 ++count;
2188 while( result->NextRow() );
2190 delete result;
2192 sLog.outString();
2193 sLog.outString( ">> Loaded %u player create spells", count );
2197 // Load playercreate actions
2199 // 0 1 2 3 4 5
2200 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2202 uint32 count = 0;
2204 if (!result)
2206 barGoLink bar( 1 );
2208 sLog.outString();
2209 sLog.outString( ">> Loaded %u player create actions", count );
2210 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2212 else
2214 barGoLink bar( result->GetRowCount() );
2218 Field* fields = result->Fetch();
2220 uint32 current_race = fields[0].GetUInt32();
2221 if(current_race >= MAX_RACES)
2223 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2224 continue;
2227 uint32 current_class = fields[1].GetUInt32();
2228 if(current_class >= MAX_CLASSES)
2230 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2231 continue;
2234 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2235 pInfo->action[0].push_back(fields[2].GetUInt16());
2236 pInfo->action[1].push_back(fields[3].GetUInt16());
2237 pInfo->action[2].push_back(fields[4].GetUInt16());
2238 pInfo->action[3].push_back(fields[5].GetUInt16());
2240 bar.step();
2241 ++count;
2243 while( result->NextRow() );
2245 delete result;
2247 sLog.outString();
2248 sLog.outString( ">> Loaded %u player create actions", count );
2252 // Loading levels data (class only dependent)
2254 // 0 1 2 3
2255 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2257 uint32 count = 0;
2259 if (!result)
2261 barGoLink bar( 1 );
2263 sLog.outString();
2264 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2265 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2266 exit(1);
2269 barGoLink bar( result->GetRowCount() );
2273 Field* fields = result->Fetch();
2275 uint32 current_class = fields[0].GetUInt32();
2276 if(current_class >= MAX_CLASSES)
2278 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2279 continue;
2282 uint32 current_level = fields[1].GetUInt32();
2283 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2285 if(current_level > 255) // hardcoded level maximum
2286 sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2287 else
2288 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2289 continue;
2292 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2294 if(!pClassInfo->levelInfo)
2295 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2297 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2299 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2300 pClassLevelInfo->basemana = fields[3].GetUInt16();
2302 bar.step();
2303 ++count;
2305 while (result->NextRow());
2307 delete result;
2309 sLog.outString();
2310 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2313 // Fill gaps and check integrity
2314 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2316 // skip non existed classes
2317 if(!sChrClassesStore.LookupEntry(class_))
2318 continue;
2320 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2322 // fatal error if no level 1 data
2323 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2325 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2326 exit(1);
2329 // fill level gaps
2330 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2332 if(pClassInfo->levelInfo[level].basehealth == 0)
2334 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2335 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2340 // Loading levels data (class/race dependent)
2342 // 0 1 2 3 4 5 6 7
2343 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2345 uint32 count = 0;
2347 if (!result)
2349 barGoLink bar( 1 );
2351 sLog.outString();
2352 sLog.outString( ">> Loaded %u level stats definitions", count );
2353 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2354 exit(1);
2357 barGoLink bar( result->GetRowCount() );
2361 Field* fields = result->Fetch();
2363 uint32 current_race = fields[0].GetUInt32();
2364 if(current_race >= MAX_RACES)
2366 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2367 continue;
2370 uint32 current_class = fields[1].GetUInt32();
2371 if(current_class >= MAX_CLASSES)
2373 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2374 continue;
2377 uint32 current_level = fields[2].GetUInt32();
2378 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2380 if(current_level > 255) // hardcoded level maximum
2381 sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2382 else
2383 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2384 continue;
2387 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2389 if(!pInfo->levelInfo)
2390 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2392 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2394 for (int i = 0; i < MAX_STATS; i++)
2396 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2399 bar.step();
2400 ++count;
2402 while (result->NextRow());
2404 delete result;
2406 sLog.outString();
2407 sLog.outString( ">> Loaded %u level stats definitions", count );
2410 // Fill gaps and check integrity
2411 for (int race = 0; race < MAX_RACES; ++race)
2413 // skip non existed races
2414 if(!sChrRacesStore.LookupEntry(race))
2415 continue;
2417 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2419 // skip non existed classes
2420 if(!sChrClassesStore.LookupEntry(class_))
2421 continue;
2423 PlayerInfo* pInfo = &playerInfo[race][class_];
2425 // skip non loaded combinations
2426 if(!pInfo->displayId_m || !pInfo->displayId_f)
2427 continue;
2429 // skip expansion races if not playing with expansion
2430 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2431 continue;
2433 // skip expansion classes if not playing with expansion
2434 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2435 continue;
2437 // fatal error if no level 1 data
2438 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2440 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2441 exit(1);
2444 // fill level gaps
2445 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2447 if(pInfo->levelInfo[level].stats[0] == 0)
2449 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2450 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2457 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2459 if(level < 1 || class_ >= MAX_CLASSES)
2460 return;
2462 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2464 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2465 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2467 *info = pInfo->levelInfo[level-1];
2470 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2472 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2473 return;
2475 PlayerInfo const* pInfo = &playerInfo[race][class_];
2476 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2477 return;
2479 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2480 *info = pInfo->levelInfo[level-1];
2481 else
2482 BuildPlayerLevelInfo(race,class_,level,info);
2485 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2487 // base data (last known level)
2488 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2490 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2492 switch(_class)
2494 case CLASS_WARRIOR:
2495 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2496 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2497 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2498 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2499 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2500 break;
2501 case CLASS_PALADIN:
2502 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2503 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2504 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2505 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2506 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2507 break;
2508 case CLASS_HUNTER:
2509 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2510 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2511 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2512 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2513 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2514 break;
2515 case CLASS_ROGUE:
2516 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2517 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2518 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2519 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2520 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2521 break;
2522 case CLASS_PRIEST:
2523 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2524 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2525 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2526 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2527 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2528 break;
2529 case CLASS_SHAMAN:
2530 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2531 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2532 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2533 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2534 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2535 break;
2536 case CLASS_MAGE:
2537 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2538 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2539 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2540 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2541 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2542 break;
2543 case CLASS_WARLOCK:
2544 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2545 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2546 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2547 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2548 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2549 break;
2550 case CLASS_DRUID:
2551 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2552 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2553 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2554 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2555 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2560 void ObjectMgr::LoadGuilds()
2562 Guild *newguild;
2563 uint32 count = 0;
2565 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2567 if( !result )
2570 barGoLink bar( 1 );
2572 bar.step();
2574 sLog.outString();
2575 sLog.outString( ">> Loaded %u guild definitions", count );
2576 return;
2579 barGoLink bar( result->GetRowCount() );
2583 Field *fields = result->Fetch();
2585 bar.step();
2586 ++count;
2588 newguild = new Guild;
2589 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2591 newguild->Disband();
2592 delete newguild;
2593 continue;
2595 AddGuild(newguild);
2597 }while( result->NextRow() );
2599 delete result;
2601 sLog.outString();
2602 sLog.outString( ">> Loaded %u guild definitions", count );
2605 void ObjectMgr::LoadArenaTeams()
2607 uint32 count = 0;
2609 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2611 if( !result )
2614 barGoLink bar( 1 );
2616 bar.step();
2618 sLog.outString();
2619 sLog.outString( ">> Loaded %u arenateam definitions", count );
2620 return;
2623 barGoLink bar( result->GetRowCount() );
2627 Field *fields = result->Fetch();
2629 bar.step();
2630 ++count;
2632 ArenaTeam *newarenateam = new ArenaTeam;
2633 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2635 delete newarenateam;
2636 continue;
2638 AddArenaTeam(newarenateam);
2639 }while( result->NextRow() );
2641 delete result;
2643 sLog.outString();
2644 sLog.outString( ">> Loaded %u arenateam definitions", count );
2647 void ObjectMgr::LoadGroups()
2649 // -- loading groups --
2650 Group *group = NULL;
2651 uint64 leaderGuid = 0;
2652 uint32 count = 0;
2653 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2654 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2656 if( !result )
2658 barGoLink bar( 1 );
2660 bar.step();
2662 sLog.outString();
2663 sLog.outString( ">> Loaded %u group definitions", count );
2664 return;
2667 barGoLink bar( result->GetRowCount() );
2671 bar.step();
2672 Field *fields = result->Fetch();
2673 ++count;
2674 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2676 group = new Group;
2677 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2679 group->Disband();
2680 delete group;
2681 continue;
2683 AddGroup(group);
2684 }while( result->NextRow() );
2686 delete result;
2688 sLog.outString();
2689 sLog.outString( ">> Loaded %u group definitions", count );
2691 // -- loading members --
2692 count = 0;
2693 group = NULL;
2694 leaderGuid = 0;
2695 // 0 1 2 3
2696 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2697 if(!result)
2699 barGoLink bar( 1 );
2700 bar.step();
2702 else
2704 barGoLink bar( result->GetRowCount() );
2707 bar.step();
2708 Field *fields = result->Fetch();
2709 count++;
2710 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2711 if(!group || group->GetLeaderGUID() != leaderGuid)
2713 group = GetGroupByLeader(leaderGuid);
2714 if(!group)
2716 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2717 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2718 continue;
2722 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2724 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2725 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2727 }while( result->NextRow() );
2728 delete result;
2731 // clean groups
2732 // TODO: maybe delete from the DB before loading in this case
2733 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2735 if((*itr)->GetMembersCount() < 2)
2737 (*itr)->Disband();
2738 delete *itr;
2739 mGroupSet.erase(itr++);
2741 else
2742 ++itr;
2745 // -- loading instances --
2746 count = 0;
2747 group = NULL;
2748 leaderGuid = 0;
2749 result = CharacterDatabase.Query(
2750 // 0 1 2 3 4 5
2751 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2752 // 6
2753 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2754 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2757 if(!result)
2759 barGoLink bar( 1 );
2760 bar.step();
2762 else
2764 barGoLink bar( result->GetRowCount() );
2767 bar.step();
2768 Field *fields = result->Fetch();
2769 count++;
2770 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2771 if(!group || group->GetLeaderGUID() != leaderGuid)
2773 group = GetGroupByLeader(leaderGuid);
2774 if(!group)
2776 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2777 continue;
2781 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2782 group->BindToInstance(save, fields[3].GetBool(), true);
2783 }while( result->NextRow() );
2784 delete result;
2787 sLog.outString();
2788 sLog.outString( ">> Loaded %u group-instance binds total", count );
2790 sLog.outString();
2791 sLog.outString( ">> Loaded %u group members total", count );
2794 void ObjectMgr::LoadQuests()
2796 // For reload case
2797 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2798 delete itr->second;
2799 mQuestTemplates.clear();
2801 mExclusiveQuestGroups.clear();
2803 // 0 1 2 3 4 5 6 7 8
2804 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2805 // 9 10 11 12 13 14 15 16
2806 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2807 // 17 18 19 20 21 22 23 24 25 26
2808 "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2809 // 27 28 29 30 31 32 33 34 35 36
2810 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2811 // 37 38 39 40 41 42 43 44
2812 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2813 // 45 46 47 48 49 50 51 52 53 54 54 55
2814 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2815 // 57 58 59 60 61 62 63 64
2816 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2817 // 65 66 67 68
2818 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2819 // 69 70 71 72 73 74
2820 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2821 // 75 76 77 78 79 80
2822 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2823 // 81 82 83 84 85 86 87 88
2824 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2825 // 89 90 91 92 93 94 95 96 97 98
2826 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2827 // 99 100 101 102 103 104 105 106 107 108 109
2828 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2829 // 110 111 112 113 114 115 116 117 118 119
2830 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2831 // 120 121
2832 "StartScript, CompleteScript"
2833 " FROM quest_template");
2834 if(result == NULL)
2836 barGoLink bar( 1 );
2837 bar.step();
2839 sLog.outString();
2840 sLog.outString( ">> Loaded 0 quests definitions" );
2841 sLog.outErrorDb("`quest_template` table is empty!");
2842 return;
2845 // create multimap previous quest for each existed quest
2846 // some quests can have many previous maps set by NextQuestId in previous quest
2847 // for example set of race quests can lead to single not race specific quest
2848 barGoLink bar( result->GetRowCount() );
2851 bar.step();
2852 Field *fields = result->Fetch();
2854 Quest * newQuest = new Quest(fields);
2855 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2856 } while( result->NextRow() );
2858 delete result;
2860 // Post processing
2861 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2863 Quest * qinfo = iter->second;
2865 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2867 if( qinfo->GetQuestMethod() >= 3 )
2869 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2872 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2874 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2875 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2876 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2879 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2881 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2883 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2884 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2888 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2890 // at auto-reward can be rewarded only RewChoiceItemId[0]
2891 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2893 if(uint32 id = qinfo->RewChoiceItemId[j])
2895 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2896 qinfo->GetQuestId(),j+1,id,j+1);
2897 // no changes, quest ignore this data
2902 // client quest log visual (area case)
2903 if( qinfo->ZoneOrSort > 0 )
2905 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2907 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2908 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2909 // no changes, quest not dependent from this value but can have problems at client
2912 // client quest log visual (sort case)
2913 if( qinfo->ZoneOrSort < 0 )
2915 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2916 if( !qSort )
2918 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2919 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2920 // 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)
2922 //check SkillOrClass value (class case).
2923 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2925 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2926 if(qinfo->SkillOrClass < 0)
2928 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2929 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2932 //check for proper SkillOrClass value (skill case)
2933 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2935 // skill is positive value in SkillOrClass
2936 if(qinfo->SkillOrClass != skill_id )
2938 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2939 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2940 //override, and force proper value here?
2945 // SkillOrClass (class case)
2946 if( qinfo->SkillOrClass < 0 )
2948 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2950 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2951 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2954 // SkillOrClass (skill case)
2955 if( qinfo->SkillOrClass > 0 )
2957 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2959 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2960 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2964 if( qinfo->RequiredSkillValue )
2966 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2968 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2969 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2970 // no changes, quest can't be done for this requirement
2973 if( qinfo->SkillOrClass <= 0 )
2975 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2976 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2977 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2980 // else Skill quests can have 0 skill level, this is ok
2982 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2984 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2985 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2986 // no changes, quest can't be done for this requirement
2989 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2991 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2992 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2993 // no changes, quest can't be done for this requirement
2996 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2998 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2999 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3000 // no changes, quest can't be done for this requirement
3003 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3005 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3006 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3007 // no changes, quest can't be done for this requirement
3010 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3012 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3013 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3014 // no changes, quest can't be done for this requirement
3017 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3019 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3020 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3021 // warning
3024 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3026 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3027 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3028 // warning
3031 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3033 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3034 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3035 // warning
3038 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3040 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3041 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3042 qinfo->CharTitleId = 0;
3043 // quest can't reward this title
3046 if(qinfo->SrcItemId)
3048 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3050 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3051 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3052 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3054 else if(qinfo->SrcItemCount==0)
3056 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3057 qinfo->GetQuestId(),qinfo->SrcItemId);
3058 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3061 else if(qinfo->SrcItemCount>0)
3063 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3064 qinfo->GetQuestId(),qinfo->SrcItemCount);
3065 qinfo->SrcItemCount=0; // no quest work changes in fact
3068 if(qinfo->SrcSpell)
3070 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3071 if(!spellInfo)
3073 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3074 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3075 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3077 else if(!SpellMgr::IsSpellValid(spellInfo))
3079 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3080 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3081 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3085 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3087 uint32 id = qinfo->ReqItemId[j];
3088 if(id)
3090 if(qinfo->ReqItemCount[j]==0)
3092 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3093 qinfo->GetQuestId(),j+1,id,j+1);
3094 // no changes, quest can't be done for this requirement
3097 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3099 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3101 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3102 qinfo->GetQuestId(),j+1,id,id);
3103 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3106 else if(qinfo->ReqItemCount[j]>0)
3108 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3109 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3110 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3114 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3116 uint32 id = qinfo->ReqSourceId[j];
3117 if(id)
3119 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3121 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3122 qinfo->GetQuestId(),j+1,id,id);
3123 // no changes, quest can't be done for this requirement
3126 if(!qinfo->ReqSourceCount[j])
3128 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3129 qinfo->GetQuestId(),j+1,id,j+1);
3130 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3133 if(!qinfo->ReqSourceRef[j])
3135 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3136 qinfo->GetQuestId(),j+1,id,j+1);
3137 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3140 else
3142 if(qinfo->ReqSourceCount[j]>0)
3144 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3145 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3146 // no changes, quest ignore this data
3149 if(qinfo->ReqSourceRef[j]>0)
3151 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3152 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3153 // no changes, quest ignore this data
3158 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3160 uint32 ref = qinfo->ReqSourceRef[j];
3161 if(ref)
3163 if(ref > QUEST_OBJECTIVES_COUNT)
3165 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3166 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3167 // no changes, quest can't be done for this requirement
3169 else
3170 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3172 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3173 qinfo->GetQuestId(),j+1,ref,ref,ref);
3174 // no changes, quest can't be done for this requirement
3176 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3178 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3179 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3180 // no changes, quest can't be done for this requirement
3181 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3186 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3188 uint32 id = qinfo->ReqSpell[j];
3189 if(id)
3191 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3192 if(!spellInfo)
3194 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3195 qinfo->GetQuestId(),j+1,id,id);
3196 // no changes, quest can't be done for this requirement
3199 if(!qinfo->ReqCreatureOrGOId[j])
3201 bool found = false;
3202 for(int k = 0; k < 3; ++k)
3204 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3205 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3207 found = true;
3208 break;
3212 if(found)
3214 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3216 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);
3218 // this will prevent quest completing without objective
3219 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3222 else
3224 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.",
3225 qinfo->GetQuestId(),j+1,id,j+1,id);
3226 // no changes, quest can't be done for this requirement
3232 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3234 int32 id = qinfo->ReqCreatureOrGOId[j];
3235 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3237 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3238 qinfo->GetQuestId(),j+1,id,uint32(-id));
3239 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3242 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3244 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3245 qinfo->GetQuestId(),j+1,id,uint32(id));
3246 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3249 if(id)
3251 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3253 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3255 if(!qinfo->ReqCreatureOrGOCount[j])
3257 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3258 qinfo->GetQuestId(),j+1,id,j+1);
3259 // no changes, quest can be incorrectly done, but we already report this
3262 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3264 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3265 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3266 // no changes, quest ignore this data
3270 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3272 uint32 id = qinfo->RewChoiceItemId[j];
3273 if(id)
3275 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3277 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3278 qinfo->GetQuestId(),j+1,id,id);
3279 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3282 if(!qinfo->RewChoiceItemCount[j])
3284 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3285 qinfo->GetQuestId(),j+1,id,j+1);
3286 // no changes, quest can't be done
3289 else if(qinfo->RewChoiceItemCount[j]>0)
3291 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3292 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3293 // no changes, quest ignore this data
3297 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3299 uint32 id = qinfo->RewItemId[j];
3300 if(id)
3302 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3304 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3305 qinfo->GetQuestId(),j+1,id,id);
3306 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3309 if(!qinfo->RewItemCount[j])
3311 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3312 qinfo->GetQuestId(),j+1,id,j+1);
3313 // no changes
3316 else if(qinfo->RewItemCount[j]>0)
3318 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3319 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3320 // no changes, quest ignore this data
3324 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3326 if(qinfo->RewRepFaction[j])
3328 if(!qinfo->RewRepValue[j])
3330 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3331 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3332 // no changes
3335 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3337 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.",
3338 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3339 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3342 else if(qinfo->RewRepValue[j]!=0)
3344 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3345 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3346 // no changes, quest ignore this data
3350 if(qinfo->RewSpell)
3352 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3354 if(!spellInfo)
3356 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3357 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3358 qinfo->RewSpell = 0; // no spell reward will display for this quest
3361 else if(!SpellMgr::IsSpellValid(spellInfo))
3363 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3364 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3365 qinfo->RewSpell = 0; // no spell reward will display for this quest
3370 if(qinfo->RewSpellCast)
3372 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3374 if(!spellInfo)
3376 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3377 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3378 qinfo->RewSpellCast = 0; // no spell will be casted on player
3381 else if(!SpellMgr::IsSpellValid(spellInfo))
3383 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3384 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3385 qinfo->RewSpellCast = 0; // no spell will be casted on player
3390 if(qinfo->RewMailTemplateId)
3392 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3394 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3395 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3396 qinfo->RewMailTemplateId = 0; // no mail will send to player
3397 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3401 if(qinfo->NextQuestInChain)
3403 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3405 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3406 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3407 qinfo->NextQuestInChain = 0;
3409 else
3410 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3413 // fill additional data stores
3414 if(qinfo->PrevQuestId)
3416 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3418 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3420 else
3422 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3426 if(qinfo->NextQuestId)
3428 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3430 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3432 else
3434 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3435 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3439 if(qinfo->ExclusiveGroup)
3440 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3441 if(qinfo->LimitTime)
3442 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3445 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3446 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3448 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3449 if(!spellInfo)
3450 continue;
3452 for(int j = 0; j < 3; ++j)
3454 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3455 continue;
3457 uint32 quest_id = spellInfo->EffectMiscValue[j];
3459 Quest const* quest = GetQuestTemplate(quest_id);
3461 // some quest referenced in spells not exist (outdated spells)
3462 if(!quest)
3463 continue;
3465 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3467 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);
3469 // this will prevent quest completing without objective
3470 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3475 sLog.outString();
3476 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3479 void ObjectMgr::LoadQuestLocales()
3481 mQuestLocaleMap.clear(); // need for reload case
3483 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3484 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3485 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3486 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3487 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3488 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3489 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3490 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3491 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3492 " FROM locales_quest"
3495 if(!result)
3497 barGoLink bar(1);
3499 bar.step();
3501 sLog.outString("");
3502 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3503 return;
3506 barGoLink bar(result->GetRowCount());
3510 Field *fields = result->Fetch();
3511 bar.step();
3513 uint32 entry = fields[0].GetUInt32();
3515 QuestLocale& data = mQuestLocaleMap[entry];
3517 for(int i = 1; i < MAX_LOCALE; ++i)
3519 std::string str = fields[1+10*(i-1)].GetCppString();
3520 if(!str.empty())
3522 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3523 if(idx >= 0)
3525 if(data.Title.size() <= idx)
3526 data.Title.resize(idx+1);
3528 data.Title[idx] = str;
3531 str = fields[1+10*(i-1)+1].GetCppString();
3532 if(!str.empty())
3534 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3535 if(idx >= 0)
3537 if(data.Details.size() <= idx)
3538 data.Details.resize(idx+1);
3540 data.Details[idx] = str;
3543 str = fields[1+10*(i-1)+2].GetCppString();
3544 if(!str.empty())
3546 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3547 if(idx >= 0)
3549 if(data.Objectives.size() <= idx)
3550 data.Objectives.resize(idx+1);
3552 data.Objectives[idx] = str;
3555 str = fields[1+10*(i-1)+3].GetCppString();
3556 if(!str.empty())
3558 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3559 if(idx >= 0)
3561 if(data.OfferRewardText.size() <= idx)
3562 data.OfferRewardText.resize(idx+1);
3564 data.OfferRewardText[idx] = str;
3567 str = fields[1+10*(i-1)+4].GetCppString();
3568 if(!str.empty())
3570 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3571 if(idx >= 0)
3573 if(data.RequestItemsText.size() <= idx)
3574 data.RequestItemsText.resize(idx+1);
3576 data.RequestItemsText[idx] = str;
3579 str = fields[1+10*(i-1)+5].GetCppString();
3580 if(!str.empty())
3582 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3583 if(idx >= 0)
3585 if(data.EndText.size() <= idx)
3586 data.EndText.resize(idx+1);
3588 data.EndText[idx] = str;
3591 for(int k = 0; k < 4; ++k)
3593 str = fields[1+10*(i-1)+6+k].GetCppString();
3594 if(!str.empty())
3596 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3597 if(idx >= 0)
3599 if(data.ObjectiveText[k].size() <= idx)
3600 data.ObjectiveText[k].resize(idx+1);
3602 data.ObjectiveText[k][idx] = str;
3607 } while (result->NextRow());
3609 delete result;
3611 sLog.outString();
3612 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3615 void ObjectMgr::LoadPetCreateSpells()
3617 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3618 if(!result)
3620 barGoLink bar( 1 );
3621 bar.step();
3623 sLog.outString();
3624 sLog.outString( ">> Loaded 0 pet create spells" );
3625 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3626 return;
3629 uint32 count = 0;
3631 barGoLink bar( result->GetRowCount() );
3633 mPetCreateSpell.clear();
3637 Field *fields = result->Fetch();
3638 bar.step();
3640 uint32 creature_id = fields[0].GetUInt32();
3642 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3643 continue;
3645 PetCreateSpellEntry PetCreateSpell;
3646 for(int i = 0; i < 4; i++)
3648 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3650 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3651 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3654 mPetCreateSpell[creature_id] = PetCreateSpell;
3656 ++count;
3658 while (result->NextRow());
3660 delete result;
3662 sLog.outString();
3663 sLog.outString( ">> Loaded %u pet create spells", count );
3666 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3668 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3669 return;
3671 sLog.outString( "%s :", tablename);
3673 scripts.clear(); // need for reload support
3675 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3677 uint32 count = 0;
3679 if( !result )
3681 barGoLink bar( 1 );
3682 bar.step();
3684 sLog.outString();
3685 sLog.outString( ">> Loaded %u script definitions", count );
3686 return;
3689 barGoLink bar( result->GetRowCount() );
3693 bar.step();
3695 Field *fields = result->Fetch();
3696 ScriptInfo tmp;
3697 tmp.id = fields[0].GetUInt32();
3698 tmp.delay = fields[1].GetUInt32();
3699 tmp.command = fields[2].GetUInt32();
3700 tmp.datalong = fields[3].GetUInt32();
3701 tmp.datalong2 = fields[4].GetUInt32();
3702 tmp.dataint = fields[5].GetInt32();
3703 tmp.x = fields[6].GetFloat();
3704 tmp.y = fields[7].GetFloat();
3705 tmp.z = fields[8].GetFloat();
3706 tmp.o = fields[9].GetFloat();
3708 // generic command args check
3709 switch(tmp.command)
3711 case SCRIPT_COMMAND_TALK:
3713 if(tmp.datalong > 3)
3715 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3716 continue;
3718 if(tmp.dataint==0)
3720 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3721 continue;
3723 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3725 sLog.outErrorDb("Table `%s` has out of range text id (dataint = %i expected %u-%u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID,tmp.id);
3726 continue;
3729 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3730 break;
3733 case SCRIPT_COMMAND_TELEPORT_TO:
3735 if(!sMapStore.LookupEntry(tmp.datalong))
3737 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3738 continue;
3741 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3743 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);
3744 continue;
3746 break;
3749 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3751 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3753 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);
3754 continue;
3757 if(!GetCreatureTemplate(tmp.datalong))
3759 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3760 continue;
3762 break;
3765 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3767 GameObjectData const* data = GetGOData(tmp.datalong);
3768 if(!data)
3770 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3771 continue;
3774 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3775 if(!info)
3777 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);
3778 continue;
3781 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3782 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3783 info->type==GAMEOBJECT_TYPE_DOOR ||
3784 info->type==GAMEOBJECT_TYPE_BUTTON ||
3785 info->type==GAMEOBJECT_TYPE_TRAP )
3787 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3788 continue;
3790 break;
3792 case SCRIPT_COMMAND_OPEN_DOOR:
3793 case SCRIPT_COMMAND_CLOSE_DOOR:
3795 GameObjectData const* data = GetGOData(tmp.datalong);
3796 if(!data)
3798 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);
3799 continue;
3802 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3803 if(!info)
3805 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);
3806 continue;
3809 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3811 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);
3812 continue;
3815 break;
3817 case SCRIPT_COMMAND_QUEST_EXPLORED:
3819 Quest const* quest = GetQuestTemplate(tmp.datalong);
3820 if(!quest)
3822 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);
3823 continue;
3826 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3828 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);
3830 // this will prevent quest completing without objective
3831 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3833 // continue; - quest objective requirement set and command can be allowed
3836 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3838 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",
3839 tablename,tmp.datalong2,tmp.id);
3840 continue;
3843 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3845 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 %f or 0 for disable distance check",
3846 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3847 continue;
3850 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3852 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 %f or 0 for disable distance check",
3853 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3854 continue;
3857 break;
3860 case SCRIPT_COMMAND_REMOVE_AURA:
3861 case SCRIPT_COMMAND_CAST_SPELL:
3863 if(!sSpellStore.LookupEntry(tmp.datalong))
3865 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3866 tablename,tmp.datalong,tmp.id);
3867 continue;
3869 break;
3873 if (scripts.find(tmp.id) == scripts.end())
3875 ScriptMap emptyMap;
3876 scripts[tmp.id] = emptyMap;
3878 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3880 ++count;
3881 } while( result->NextRow() );
3883 delete result;
3885 sLog.outString();
3886 sLog.outString( ">> Loaded %u script definitions", count );
3889 void ObjectMgr::LoadGameObjectScripts()
3891 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3893 // check ids
3894 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3896 if(!GetGOData(itr->first))
3897 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3901 void ObjectMgr::LoadQuestEndScripts()
3903 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3905 // check ids
3906 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3908 if(!GetQuestTemplate(itr->first))
3909 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3913 void ObjectMgr::LoadQuestStartScripts()
3915 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3917 // check ids
3918 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3920 if(!GetQuestTemplate(itr->first))
3921 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3925 void ObjectMgr::LoadSpellScripts()
3927 LoadScripts(sSpellScripts, "spell_scripts");
3929 // check ids
3930 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3932 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3934 if(!spellInfo)
3936 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3937 continue;
3940 //check for correct spellEffect
3941 bool found = false;
3942 for(int i=0; i<3; ++i)
3944 // skip empty effects
3945 if( !spellInfo->Effect[i] )
3946 continue;
3948 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3950 found = true;
3951 break;
3955 if(!found)
3956 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3960 void ObjectMgr::LoadEventScripts()
3962 LoadScripts(sEventScripts, "event_scripts");
3964 std::set<uint32> evt_scripts;
3965 // Load all possible script entries from gameobjects
3966 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3968 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3969 if (goInfo)
3971 switch(goInfo->type)
3973 case GAMEOBJECT_TYPE_GOOBER:
3974 if(goInfo->goober.eventId)
3975 evt_scripts.insert(goInfo->goober.eventId);
3976 break;
3977 case GAMEOBJECT_TYPE_CHEST:
3978 if(goInfo->chest.eventId)
3979 evt_scripts.insert(goInfo->chest.eventId);
3980 break;
3981 default:
3982 break;
3986 // Load all possible script entries from spells
3987 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3989 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3990 if (spell)
3992 for(int j=0; j<3; ++j)
3994 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3996 if (spell->EffectMiscValue[j])
3997 evt_scripts.insert(spell->EffectMiscValue[j]);
4002 // Then check if all scripts are in above list of possible script entries
4003 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4005 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4006 if (itr2 == evt_scripts.end())
4007 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
4011 void ObjectMgr::LoadItemTexts()
4013 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4015 uint32 count = 0;
4017 if( !result )
4019 barGoLink bar( 1 );
4020 bar.step();
4022 sLog.outString();
4023 sLog.outString( ">> Loaded %u item pages", count );
4024 return;
4027 barGoLink bar( result->GetRowCount() );
4029 Field* fields;
4032 bar.step();
4034 fields = result->Fetch();
4036 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4038 ++count;
4040 } while ( result->NextRow() );
4042 delete result;
4044 sLog.outString();
4045 sLog.outString( ">> Loaded %u item texts", count );
4048 void ObjectMgr::LoadPageTexts()
4050 sPageTextStore.Free(); // for reload case
4052 sPageTextStore.Load();
4053 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4054 sLog.outString();
4056 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4058 // check data correctness
4059 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4060 if(!page)
4061 continue;
4063 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4065 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4066 continue;
4069 // detect circular reference
4070 std::set<uint32> checkedPages;
4071 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4073 if(!pageItr->Next_Page)
4074 break;
4075 checkedPages.insert(pageItr->Page_ID);
4076 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4078 std::ostringstream ss;
4079 ss<< "The text page(s) ";
4080 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
4081 ss << *itr << " ";
4082 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4083 << pageItr->Page_ID <<" to 0";
4084 sLog.outErrorDb(ss.str().c_str());
4085 const_cast<PageText*>(pageItr)->Next_Page = 0;
4086 break;
4092 void ObjectMgr::LoadPageTextLocales()
4094 mPageTextLocaleMap.clear(); // need for reload case
4096 QueryResult *result = WorldDatabase.Query("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4098 if(!result)
4100 barGoLink bar(1);
4102 bar.step();
4104 sLog.outString("");
4105 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4106 return;
4109 barGoLink bar(result->GetRowCount());
4113 Field *fields = result->Fetch();
4114 bar.step();
4116 uint32 entry = fields[0].GetUInt32();
4118 PageTextLocale& data = mPageTextLocaleMap[entry];
4120 for(int i = 1; i < MAX_LOCALE; ++i)
4122 std::string str = fields[i].GetCppString();
4123 if(str.empty())
4124 continue;
4126 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4127 if(idx >= 0)
4129 if(data.Text.size() <= idx)
4130 data.Text.resize(idx+1);
4132 data.Text[idx] = str;
4136 } while (result->NextRow());
4138 delete result;
4140 sLog.outString();
4141 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4144 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4146 template<class D>
4147 void convert_from_str(uint32 field_pos, char *src, D &dst)
4149 dst = D(objmgr.GetScriptId(src));
4153 void ObjectMgr::LoadInstanceTemplate()
4155 SQLInstanceLoader loader;
4156 loader.Load(sInstanceTemplate);
4158 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4160 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4161 if(!temp) continue;
4162 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4163 if(!entry)
4165 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4166 continue;
4168 else if(!entry->HasResetTime())
4169 continue;
4171 if(temp->reset_delay == 0)
4173 // use defaults from the DBC
4174 if(entry->SupportsHeroicMode())
4176 temp->reset_delay = entry->resetTimeHeroic / DAY;
4178 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4180 temp->reset_delay = entry->resetTimeRaid / DAY;
4184 // the reset_delay must be at least one day
4185 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4188 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4189 sLog.outString();
4192 void ObjectMgr::AddGossipText(GossipText *pGText)
4194 ASSERT( pGText->Text_ID );
4195 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4196 mGossipText[pGText->Text_ID] = pGText;
4199 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4201 GossipTextMap::const_iterator itr;
4202 for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4204 if(itr->second->Text_ID == Text_ID)
4205 return itr->second;
4207 return NULL;
4210 void ObjectMgr::LoadGossipText()
4212 GossipText *pGText;
4213 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4215 int count = 0;
4216 if( !result )
4218 barGoLink bar( 1 );
4219 bar.step();
4221 sLog.outString();
4222 sLog.outString( ">> Loaded %u npc texts", count );
4223 return;
4226 int cic;
4228 barGoLink bar( result->GetRowCount() );
4232 ++count;
4233 cic = 0;
4235 Field *fields = result->Fetch();
4237 bar.step();
4239 pGText = new GossipText;
4240 pGText->Text_ID = fields[cic++].GetUInt32();
4242 for (int i=0; i< 8; i++)
4244 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4245 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4247 pGText->Options[i].Language = fields[cic++].GetUInt32();
4248 pGText->Options[i].Probability = fields[cic++].GetFloat();
4250 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4251 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4253 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4254 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4256 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4257 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4260 if ( !pGText->Text_ID ) continue;
4261 AddGossipText( pGText );
4263 } while( result->NextRow() );
4265 sLog.outString();
4266 sLog.outString( ">> Loaded %u npc texts", count );
4267 delete result;
4270 void ObjectMgr::LoadNpcTextLocales()
4272 mNpcTextLocaleMap.clear(); // need for reload case
4274 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4275 "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,"
4276 "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,"
4277 "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,"
4278 "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,"
4279 "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,"
4280 "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,"
4281 "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, "
4282 "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 "
4283 " FROM locales_npc_text");
4285 if(!result)
4287 barGoLink bar(1);
4289 bar.step();
4291 sLog.outString("");
4292 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4293 return;
4296 barGoLink bar(result->GetRowCount());
4300 Field *fields = result->Fetch();
4301 bar.step();
4303 uint32 entry = fields[0].GetUInt32();
4305 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4307 for(int i=1; i<MAX_LOCALE; ++i)
4309 for(int j=0; j<8; ++j)
4311 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4312 if(!str0.empty())
4314 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4315 if(idx >= 0)
4317 if(data.Text_0[j].size() <= idx)
4318 data.Text_0[j].resize(idx+1);
4320 data.Text_0[j][idx] = str0;
4323 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4324 if(!str1.empty())
4326 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4327 if(idx >= 0)
4329 if(data.Text_1[j].size() <= idx)
4330 data.Text_1[j].resize(idx+1);
4332 data.Text_1[j][idx] = str1;
4337 } while (result->NextRow());
4339 delete result;
4341 sLog.outString();
4342 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4345 //not very fast function but it is called only once a day, or on starting-up
4346 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4348 time_t basetime = time(NULL);
4349 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4350 //delete all old mails without item and without body immediately, if starting server
4351 if (!serverUp)
4352 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4353 // 0 1 2 3 4 5 6 7 8 9
4354 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);
4355 if ( !result )
4356 return; // any mails need to be returned or deleted
4357 Field *fields;
4358 //std::ostringstream delitems, delmails; //will be here for optimization
4359 //bool deletemail = false, deleteitem = false;
4360 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4361 //delmails << "DELETE FROM mail WHERE id IN ( "
4364 fields = result->Fetch();
4365 Mail *m = new Mail;
4366 m->messageID = fields[0].GetUInt32();
4367 m->messageType = fields[1].GetUInt8();
4368 m->sender = fields[2].GetUInt32();
4369 m->receiver = fields[3].GetUInt32();
4370 m->itemTextId = fields[4].GetUInt32();
4371 bool has_items = fields[5].GetBool();
4372 m->expire_time = (time_t)fields[6].GetUInt64();
4373 m->deliver_time = 0;
4374 m->COD = fields[7].GetUInt32();
4375 m->checked = fields[8].GetUInt32();
4376 m->mailTemplateId = fields[9].GetInt16();
4378 Player *pl = 0;
4379 if (serverUp)
4380 pl = GetPlayer((uint64)m->receiver);
4381 if (pl && pl->m_mailsLoaded)
4382 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4383 //his in mailbox and he has already listed his mails )
4384 delete m;
4385 continue;
4387 //delete or return mail:
4388 if (has_items)
4390 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4391 if(resultItems)
4395 Field *fields2 = resultItems->Fetch();
4397 uint32 item_guid_low = fields2[0].GetUInt32();
4398 uint32 item_template = fields2[1].GetUInt32();
4400 m->AddItem(item_guid_low, item_template);
4402 while (resultItems->NextRow());
4404 delete resultItems;
4406 //if it is mail from AH, it shouldn't be returned, but deleted
4407 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4409 // mail open and then not returned
4410 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4411 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4413 else
4415 //mail will be returned:
4416 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);
4417 delete m;
4418 continue;
4422 if (m->itemTextId)
4423 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4425 //deletemail = true;
4426 //delmails << m->messageID << ", ";
4427 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4428 delete m;
4429 } while (result->NextRow());
4430 delete result;
4433 void ObjectMgr::LoadQuestAreaTriggers()
4435 mQuestAreaTriggerMap.clear(); // need for reload case
4437 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4439 uint32 count = 0;
4441 if( !result )
4443 barGoLink bar( 1 );
4444 bar.step();
4446 sLog.outString();
4447 sLog.outString( ">> Loaded %u quest trigger points", count );
4448 return;
4451 barGoLink bar( result->GetRowCount() );
4455 ++count;
4456 bar.step();
4458 Field *fields = result->Fetch();
4460 uint32 trigger_ID = fields[0].GetUInt32();
4461 uint32 quest_ID = fields[1].GetUInt32();
4463 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4464 if(!atEntry)
4466 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4467 continue;
4470 Quest const* quest = GetQuestTemplate(quest_ID);
4472 if(!quest)
4474 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4475 continue;
4478 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4480 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);
4482 // this will prevent quest completing without objective
4483 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4485 // continue; - quest modified to required objective and trigger can be allowed.
4488 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4490 } while( result->NextRow() );
4492 delete result;
4494 sLog.outString();
4495 sLog.outString( ">> Loaded %u quest trigger points", count );
4498 void ObjectMgr::LoadTavernAreaTriggers()
4500 mTavernAreaTriggerSet.clear(); // need for reload case
4502 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4504 uint32 count = 0;
4506 if( !result )
4508 barGoLink bar( 1 );
4509 bar.step();
4511 sLog.outString();
4512 sLog.outString( ">> Loaded %u tavern triggers", count );
4513 return;
4516 barGoLink bar( result->GetRowCount() );
4520 ++count;
4521 bar.step();
4523 Field *fields = result->Fetch();
4525 uint32 Trigger_ID = fields[0].GetUInt32();
4527 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4528 if(!atEntry)
4530 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4531 continue;
4534 mTavernAreaTriggerSet.insert(Trigger_ID);
4535 } while( result->NextRow() );
4537 delete result;
4539 sLog.outString();
4540 sLog.outString( ">> Loaded %u tavern triggers", count );
4543 void ObjectMgr::LoadAreaTriggerScripts()
4545 mAreaTriggerScripts.clear(); // need for reload case
4546 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4548 uint32 count = 0;
4550 if( !result )
4552 barGoLink bar( 1 );
4553 bar.step();
4555 sLog.outString();
4556 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4557 return;
4560 barGoLink bar( result->GetRowCount() );
4564 ++count;
4565 bar.step();
4567 Field *fields = result->Fetch();
4569 uint32 Trigger_ID = fields[0].GetUInt32();
4570 const char *scriptName = fields[1].GetString();
4572 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4573 if(!atEntry)
4575 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4576 continue;
4578 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4579 } while( result->NextRow() );
4581 delete result;
4583 sLog.outString();
4584 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4587 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4589 bool found = false;
4590 float dist;
4591 uint32 id = 0;
4593 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4595 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4596 if(node && node->map_id == mapid)
4598 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4599 if(found)
4601 if(dist2 < dist)
4603 dist = dist2;
4604 id = i;
4607 else
4609 found = true;
4610 dist = dist2;
4611 id = i;
4616 return id;
4619 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4621 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4622 if(src_i==sTaxiPathSetBySource.end())
4624 path = 0;
4625 cost = 0;
4626 return;
4629 TaxiPathSetForSource& pathSet = src_i->second;
4631 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4632 if(dest_i==pathSet.end())
4634 path = 0;
4635 cost = 0;
4636 return;
4639 cost = dest_i->second.price;
4640 path = dest_i->second.ID;
4643 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4645 uint16 mount_entry = 0;
4646 uint16 mount_id = 0;
4648 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4649 if(node)
4651 if (team == ALLIANCE)
4653 mount_entry = node->alliance_mount_type;
4654 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4655 if(ci)
4656 mount_id = ci->DisplayID_A;
4658 if (team == HORDE)
4660 mount_entry = node->horde_mount_type;
4661 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4662 if(ci)
4663 mount_id = ci->DisplayID_H;
4667 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4668 if(!minfo)
4670 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. ",
4671 mount_entry,id,team,mount_id);
4673 return false;
4675 if(minfo->modelid_other_gender!=0)
4676 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4678 return mount_id;
4681 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4683 if(path >= sTaxiPathNodesByPath.size())
4684 return;
4686 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4688 pathnodes.Resize(nodeList.size());
4689 mapIds.resize(nodeList.size());
4691 for(size_t i = 0; i < nodeList.size(); ++i)
4693 pathnodes[ i ].x = nodeList[i].x;
4694 pathnodes[ i ].y = nodeList[i].y;
4695 pathnodes[ i ].z = nodeList[i].z;
4697 mapIds[i] = nodeList[i].mapid;
4701 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4703 if(path >= sTaxiPathNodesByPath.size())
4704 return;
4706 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4708 pathnodes.Resize(nodeList.size());
4710 for(size_t i = 0; i < nodeList.size(); ++i)
4712 pathnodes[ i ].mapid = nodeList[i].mapid;
4713 pathnodes[ i ].x = nodeList[i].x;
4714 pathnodes[ i ].y = nodeList[i].y;
4715 pathnodes[ i ].z = nodeList[i].z;
4716 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4717 pathnodes[ i ].delay = nodeList[i].delay;
4721 void ObjectMgr::LoadGraveyardZones()
4723 mGraveYardMap.clear(); // need for reload case
4725 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4727 uint32 count = 0;
4729 if( !result )
4731 barGoLink bar( 1 );
4732 bar.step();
4734 sLog.outString();
4735 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4736 return;
4739 barGoLink bar( result->GetRowCount() );
4743 ++count;
4744 bar.step();
4746 Field *fields = result->Fetch();
4748 uint32 safeLocId = fields[0].GetUInt32();
4749 uint32 zoneId = fields[1].GetUInt32();
4750 uint32 team = fields[2].GetUInt32();
4752 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4753 if(!entry)
4755 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4756 continue;
4759 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4760 if(!areaEntry)
4762 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4763 continue;
4766 if(areaEntry->zone != 0)
4768 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4769 continue;
4772 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4774 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4775 continue;
4778 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4779 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4780 } while( result->NextRow() );
4782 delete result;
4784 sLog.outString();
4785 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4788 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4790 // search for zone associated closest graveyard
4791 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4793 // Simulate std. algorithm:
4794 // found some graveyard associated to (ghost_zone,ghost_map)
4796 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4797 // then check faction
4798 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4799 // then check faction
4800 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4801 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4802 if(graveLow==graveUp)
4804 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4805 return NULL;
4808 // at corpse map
4809 bool foundNear = false;
4810 float distNear;
4811 WorldSafeLocsEntry const* entryNear = NULL;
4813 // at entrance map for corpse map
4814 bool foundEntr = false;
4815 float distEntr;
4816 WorldSafeLocsEntry const* entryEntr = NULL;
4818 // some where other
4819 WorldSafeLocsEntry const* entryFar = NULL;
4821 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4823 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4825 GraveYardData const& data = itr->second;
4827 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4828 if(!entry)
4830 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4831 continue;
4834 // skip enemy faction graveyard
4835 // team == 0 case can be at call from .neargrave
4836 if(data.team != 0 && team != 0 && data.team != team)
4837 continue;
4839 // find now nearest graveyard at other map
4840 if(MapId != entry->map_id)
4842 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4843 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4844 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4846 // not have any corrdinates for check distance anyway
4847 entryFar = entry;
4848 continue;
4851 // at entrance map calculate distance (2D);
4852 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4853 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4854 if(foundEntr)
4856 if(dist2 < distEntr)
4858 distEntr = dist2;
4859 entryEntr = entry;
4862 else
4864 foundEntr = true;
4865 distEntr = dist2;
4866 entryEntr = entry;
4869 // find now nearest graveyard at same map
4870 else
4872 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4873 if(foundNear)
4875 if(dist2 < distNear)
4877 distNear = dist2;
4878 entryNear = entry;
4881 else
4883 foundNear = true;
4884 distNear = dist2;
4885 entryNear = entry;
4890 if(entryNear)
4891 return entryNear;
4893 if(entryEntr)
4894 return entryEntr;
4896 return entryFar;
4899 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4901 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4902 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4904 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4906 if(itr->second.safeLocId==id)
4907 return &itr->second;
4910 return NULL;
4913 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4915 if(FindGraveYardData(id,zoneId))
4916 return false;
4918 // add link to loaded data
4919 GraveYardData data;
4920 data.safeLocId = id;
4921 data.team = team;
4923 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4925 // add link to DB
4926 if(inDB)
4928 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4929 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4932 return true;
4935 void ObjectMgr::LoadAreaTriggerTeleports()
4937 mAreaTriggers.clear(); // need for reload case
4939 uint32 count = 0;
4941 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4942 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");
4943 if( !result )
4946 barGoLink bar( 1 );
4948 bar.step();
4950 sLog.outString();
4951 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4952 return;
4955 barGoLink bar( result->GetRowCount() );
4959 Field *fields = result->Fetch();
4961 bar.step();
4963 ++count;
4965 uint32 Trigger_ID = fields[0].GetUInt32();
4967 AreaTrigger at;
4969 at.requiredLevel = fields[1].GetUInt8();
4970 at.requiredItem = fields[2].GetUInt32();
4971 at.requiredItem2 = fields[3].GetUInt32();
4972 at.heroicKey = fields[4].GetUInt32();
4973 at.heroicKey2 = fields[5].GetUInt32();
4974 at.requiredQuest = fields[6].GetUInt32();
4975 at.requiredFailedText = fields[7].GetCppString();
4976 at.target_mapId = fields[8].GetUInt32();
4977 at.target_X = fields[9].GetFloat();
4978 at.target_Y = fields[10].GetFloat();
4979 at.target_Z = fields[11].GetFloat();
4980 at.target_Orientation = fields[12].GetFloat();
4982 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4983 if(!atEntry)
4985 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4986 continue;
4989 if(at.requiredItem)
4991 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4992 if(!pProto)
4994 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4995 at.requiredItem = 0;
4998 if(at.requiredItem2)
5000 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5001 if(!pProto)
5003 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5004 at.requiredItem2 = 0;
5008 if(at.heroicKey)
5010 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5011 if(!pProto)
5013 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5014 at.heroicKey = 0;
5018 if(at.heroicKey2)
5020 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5021 if(!pProto)
5023 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5024 at.heroicKey2 = 0;
5028 if(at.requiredQuest)
5030 if(!mQuestTemplates[at.requiredQuest])
5032 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5033 at.requiredQuest = 0;
5037 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5038 if(!mapEntry)
5040 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5041 continue;
5044 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5046 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5047 continue;
5050 mAreaTriggers[Trigger_ID] = at;
5052 } while( result->NextRow() );
5054 delete result;
5056 sLog.outString();
5057 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5060 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5062 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5063 if(!mapEntry) return NULL;
5064 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
5066 if(itr->second.target_mapId == mapEntry->entrance_map)
5068 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5069 if(atEntry && atEntry->mapid == Map)
5070 return &itr->second;
5073 return NULL;
5076 void ObjectMgr::SetHighestGuids()
5078 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5079 if( result )
5081 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5083 delete result;
5086 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5087 if( result )
5089 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5091 delete result;
5094 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5095 m_hiPetGuid = 0;
5097 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5098 if( result )
5100 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5102 delete result;
5105 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5106 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5107 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5108 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5109 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5111 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5112 if( result )
5114 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5116 delete result;
5119 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5120 if( result )
5122 m_auctionid = (*result)[0].GetUInt32()+1;
5124 delete result;
5126 else
5128 m_auctionid = 0;
5130 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5131 if( result )
5133 m_mailid = (*result)[0].GetUInt32()+1;
5135 delete result;
5137 else
5139 m_mailid = 0;
5141 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5142 if( result )
5144 m_ItemTextId = (*result)[0].GetUInt32();
5146 delete result;
5148 else
5149 m_ItemTextId = 0;
5151 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5152 if( result )
5154 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5156 delete result;
5159 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5160 if (result)
5162 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5164 delete result;
5167 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5168 if (result)
5170 m_guildId = (*result)[0].GetUInt32()+1;
5172 delete result;
5176 uint32 ObjectMgr::GenerateArenaTeamId()
5178 ++m_arenaTeamId;
5179 if(m_arenaTeamId>=0xFFFFFFFF)
5181 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5182 World::StopNow(ERROR_EXIT_CODE);
5184 return m_arenaTeamId;
5187 uint32 ObjectMgr::GenerateGuildId()
5189 ++m_guildId;
5190 if(m_guildId>=0xFFFFFFFF)
5192 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5193 World::StopNow(ERROR_EXIT_CODE);
5195 return m_guildId;
5198 uint32 ObjectMgr::GenerateAuctionID()
5200 ++m_auctionid;
5201 if(m_auctionid>=0xFFFFFFFF)
5203 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5204 World::StopNow(ERROR_EXIT_CODE);
5206 return m_auctionid;
5209 uint32 ObjectMgr::GenerateMailID()
5211 ++m_mailid;
5212 if(m_mailid>=0xFFFFFFFF)
5214 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5215 World::StopNow(ERROR_EXIT_CODE);
5217 return m_mailid;
5220 uint32 ObjectMgr::GenerateItemTextID()
5222 ++m_ItemTextId;
5223 if(m_ItemTextId>=0xFFFFFFFF)
5225 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5226 World::StopNow(ERROR_EXIT_CODE);
5228 return m_ItemTextId;
5231 uint32 ObjectMgr::CreateItemText(std::string text)
5233 uint32 newItemTextId = GenerateItemTextID();
5234 //insert new itempage to container
5235 mItemTexts[ newItemTextId ] = text;
5236 //save new itempage
5237 CharacterDatabase.escape_string(text);
5238 //any Delete query needed, itemTextId is maximum of all ids
5239 std::ostringstream query;
5240 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5241 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5242 return newItemTextId;
5245 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5247 switch(guidhigh)
5249 case HIGHGUID_ITEM:
5250 ++m_hiItemGuid;
5251 if(m_hiItemGuid>=0xFFFFFFFF)
5253 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5254 World::StopNow(ERROR_EXIT_CODE);
5256 return m_hiItemGuid;
5257 case HIGHGUID_UNIT:
5258 ++m_hiCreatureGuid;
5259 if(m_hiCreatureGuid>=0x00FFFFFF)
5261 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5262 World::StopNow(ERROR_EXIT_CODE);
5264 return m_hiCreatureGuid;
5265 case HIGHGUID_PET:
5266 ++m_hiPetGuid;
5267 if(m_hiPetGuid>=0x00FFFFFF)
5269 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5270 World::StopNow(ERROR_EXIT_CODE);
5272 return m_hiPetGuid;
5273 case HIGHGUID_PLAYER:
5274 ++m_hiCharGuid;
5275 if(m_hiCharGuid>=0xFFFFFFFF)
5277 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5278 World::StopNow(ERROR_EXIT_CODE);
5280 return m_hiCharGuid;
5281 case HIGHGUID_GAMEOBJECT:
5282 ++m_hiGoGuid;
5283 if(m_hiGoGuid>=0x00FFFFFF)
5285 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5286 World::StopNow(ERROR_EXIT_CODE);
5288 return m_hiGoGuid;
5289 case HIGHGUID_CORPSE:
5290 ++m_hiCorpseGuid;
5291 if(m_hiCorpseGuid>=0xFFFFFFFF)
5293 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5294 World::StopNow(ERROR_EXIT_CODE);
5296 return m_hiCorpseGuid;
5297 case HIGHGUID_DYNAMICOBJECT:
5298 ++m_hiDoGuid;
5299 if(m_hiDoGuid>=0xFFFFFFFF)
5301 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5302 World::StopNow(ERROR_EXIT_CODE);
5304 return m_hiDoGuid;
5305 default:
5306 ASSERT(0);
5309 ASSERT(0);
5310 return 0;
5313 void ObjectMgr::LoadGameObjectLocales()
5315 mGameObjectLocaleMap.clear(); // need for reload case
5317 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5318 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5319 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5320 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5322 if(!result)
5324 barGoLink bar(1);
5326 bar.step();
5328 sLog.outString("");
5329 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5330 return;
5333 barGoLink bar(result->GetRowCount());
5337 Field *fields = result->Fetch();
5338 bar.step();
5340 uint32 entry = fields[0].GetUInt32();
5342 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5344 for(int i = 1; i < MAX_LOCALE; ++i)
5346 std::string str = fields[i].GetCppString();
5347 if(!str.empty())
5349 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5350 if(idx >= 0)
5352 if(data.Name.size() <= idx)
5353 data.Name.resize(idx+1);
5355 data.Name[idx] = str;
5360 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5362 std::string str = fields[i].GetCppString();
5363 if(!str.empty())
5365 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5366 if(idx >= 0)
5368 if(data.CastBarCaption.size() <= idx)
5369 data.CastBarCaption.resize(idx+1);
5371 data.CastBarCaption[idx] = str;
5376 } while (result->NextRow());
5378 delete result;
5380 sLog.outString();
5381 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5384 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5386 template<class D>
5387 void convert_from_str(uint32 field_pos, char *src, D &dst)
5389 dst = D(objmgr.GetScriptId(src));
5393 void ObjectMgr::LoadGameobjectInfo()
5395 SQLGameObjectLoader loader;
5396 loader.Load(sGOStorage);
5398 // some checks
5399 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5401 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5402 if(!goInfo)
5403 continue;
5405 switch(goInfo->type)
5407 case GAMEOBJECT_TYPE_DOOR: //0
5409 if(goInfo->door.lockId)
5411 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5412 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5413 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5415 break;
5417 case GAMEOBJECT_TYPE_BUTTON: //1
5419 if(goInfo->button.lockId)
5421 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5422 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5423 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5425 break;
5427 case GAMEOBJECT_TYPE_CHEST: //3
5429 if(goInfo->chest.lockId)
5431 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5432 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5433 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5435 if(goInfo->chest.linkedTrapId) // linked trap
5437 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5439 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5440 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5441 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5443 /* disable check for while
5444 else
5445 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5446 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5449 break;
5451 case GAMEOBJECT_TYPE_TRAP: //6
5453 /* disable check for while
5454 if(goInfo->trap.spellId) // spell
5456 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5457 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5458 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5461 break;
5463 case GAMEOBJECT_TYPE_CHAIR: //7
5464 if(goInfo->chair.height > 2)
5466 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5467 id,goInfo->type,goInfo->chair.height);
5469 // prevent client and server unexpected work
5470 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5472 break;
5473 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5475 if(goInfo->spellFocus.focusId)
5477 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5478 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5479 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5482 if(goInfo->spellFocus.linkedTrapId) // linked trap
5484 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5486 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5487 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5488 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5490 /* disable check for while
5491 else
5492 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5493 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5496 break;
5498 case GAMEOBJECT_TYPE_GOOBER: //10
5500 if(goInfo->goober.pageId) // pageId
5502 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5503 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5504 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5506 /* disable check for while
5507 if(goInfo->goober.spellId) // spell
5509 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5510 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5511 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5514 if(goInfo->goober.linkedTrapId) // linked trap
5516 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5518 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5519 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5520 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5522 /* disable check for while
5523 else
5524 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5525 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5528 break;
5530 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5532 if(goInfo->moTransport.taxiPathId)
5534 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5535 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5536 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5538 break;
5540 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5542 /* disabled
5543 if(goInfo->summoningRitual.spellId)
5545 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5546 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5547 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5550 break;
5552 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5554 if(goInfo->spellcaster.spellId) // spell
5556 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5557 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5558 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5560 break;
5565 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5566 sLog.outString();
5569 void ObjectMgr::LoadExplorationBaseXP()
5571 uint32 count = 0;
5572 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5574 if( !result )
5576 barGoLink bar( 1 );
5578 bar.step();
5580 sLog.outString();
5581 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5582 return;
5585 barGoLink bar( result->GetRowCount() );
5589 bar.step();
5591 Field *fields = result->Fetch();
5592 uint32 level = fields[0].GetUInt32();
5593 uint32 basexp = fields[1].GetUInt32();
5594 mBaseXPTable[level] = basexp;
5595 ++count;
5597 while (result->NextRow());
5599 delete result;
5601 sLog.outString();
5602 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5605 uint32 ObjectMgr::GetBaseXP(uint32 level)
5607 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5610 void ObjectMgr::LoadPetNames()
5612 uint32 count = 0;
5613 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5615 if( !result )
5617 barGoLink bar( 1 );
5619 bar.step();
5621 sLog.outString();
5622 sLog.outString( ">> Loaded %u pet name parts", count );
5623 return;
5626 barGoLink bar( result->GetRowCount() );
5630 bar.step();
5632 Field *fields = result->Fetch();
5633 std::string word = fields[0].GetString();
5634 uint32 entry = fields[1].GetUInt32();
5635 bool half = fields[2].GetBool();
5636 if(half)
5637 PetHalfName1[entry].push_back(word);
5638 else
5639 PetHalfName0[entry].push_back(word);
5640 ++count;
5642 while (result->NextRow());
5643 delete result;
5645 sLog.outString();
5646 sLog.outString( ">> Loaded %u pet name parts", count );
5649 void ObjectMgr::LoadPetNumber()
5651 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5652 if(result)
5654 Field *fields = result->Fetch();
5655 m_hiPetNumber = fields[0].GetUInt32()+1;
5656 delete result;
5659 barGoLink bar( 1 );
5660 bar.step();
5662 sLog.outString();
5663 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5666 std::string ObjectMgr::GeneratePetName(uint32 entry)
5668 std::vector<std::string> & list0 = PetHalfName0[entry];
5669 std::vector<std::string> & list1 = PetHalfName1[entry];
5671 if(list0.empty() || list1.empty())
5673 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5674 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5675 if(!petname)
5676 petname = cinfo->Name;
5677 return std::string(petname);
5680 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5683 uint32 ObjectMgr::GeneratePetNumber()
5685 return ++m_hiPetNumber;
5688 void ObjectMgr::LoadCorpses()
5690 uint32 count = 0;
5691 // 0 1 2 3 4 5 6 7 8 10
5692 QueryResult *result = CharacterDatabase.Query("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5694 if( !result )
5696 barGoLink bar( 1 );
5698 bar.step();
5700 sLog.outString();
5701 sLog.outString( ">> Loaded %u corpses", count );
5702 return;
5705 barGoLink bar( result->GetRowCount() );
5709 bar.step();
5711 Field *fields = result->Fetch();
5713 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5715 Corpse *corpse = new Corpse;
5716 if(!corpse->LoadFromDB(guid,fields))
5718 delete corpse;
5719 continue;
5722 ObjectAccessor::Instance().AddCorpse(corpse);
5724 ++count;
5726 while (result->NextRow());
5727 delete result;
5729 sLog.outString();
5730 sLog.outString( ">> Loaded %u corpses", count );
5733 void ObjectMgr::LoadReputationOnKill()
5735 uint32 count = 0;
5737 // 0 1 2
5738 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5739 // 3 4 5 6 7 8 9
5740 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5741 "FROM creature_onkill_reputation");
5743 if(!result)
5745 barGoLink bar(1);
5747 bar.step();
5749 sLog.outString();
5750 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5751 return;
5754 barGoLink bar(result->GetRowCount());
5758 Field *fields = result->Fetch();
5759 bar.step();
5761 uint32 creature_id = fields[0].GetUInt32();
5763 ReputationOnKillEntry repOnKill;
5764 repOnKill.repfaction1 = fields[1].GetUInt32();
5765 repOnKill.repfaction2 = fields[2].GetUInt32();
5766 repOnKill.is_teamaward1 = fields[3].GetBool();
5767 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5768 repOnKill.repvalue1 = fields[5].GetInt32();
5769 repOnKill.is_teamaward2 = fields[6].GetBool();
5770 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5771 repOnKill.repvalue2 = fields[8].GetInt32();
5772 repOnKill.team_dependent = fields[9].GetUInt8();
5774 if(!GetCreatureTemplate(creature_id))
5776 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5777 continue;
5780 if(repOnKill.repfaction1)
5782 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5783 if(!factionEntry1)
5785 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5786 continue;
5790 if(repOnKill.repfaction2)
5792 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5793 if(!factionEntry2)
5795 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5796 continue;
5800 mRepOnKill[creature_id] = repOnKill;
5802 ++count;
5803 } while (result->NextRow());
5805 delete result;
5807 sLog.outString();
5808 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5811 void ObjectMgr::LoadWeatherZoneChances()
5813 uint32 count = 0;
5815 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5816 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");
5818 if(!result)
5820 barGoLink bar(1);
5822 bar.step();
5824 sLog.outString();
5825 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5826 return;
5829 barGoLink bar(result->GetRowCount());
5833 Field *fields = result->Fetch();
5834 bar.step();
5836 uint32 zone_id = fields[0].GetUInt32();
5838 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5840 for(int season = 0; season < WEATHER_SEASONS; ++season)
5842 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5843 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5844 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5846 if(wzc.data[season].rainChance > 100)
5848 wzc.data[season].rainChance = 25;
5849 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5852 if(wzc.data[season].snowChance > 100)
5854 wzc.data[season].snowChance = 25;
5855 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5858 if(wzc.data[season].stormChance > 100)
5860 wzc.data[season].stormChance = 25;
5861 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5865 ++count;
5866 } while (result->NextRow());
5868 delete result;
5870 sLog.outString();
5871 sLog.outString(">> Loaded %u weather definitions", count);
5874 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5876 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5877 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5878 if(t)
5879 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5882 void ObjectMgr::DeleteCreatureData(uint32 guid)
5884 // remove mapid*cellid -> guid_set map
5885 CreatureData const* data = GetCreatureData(guid);
5886 if(data)
5887 RemoveCreatureFromGrid(guid, data);
5889 mCreatureDataMap.erase(guid);
5892 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5894 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5895 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5896 if(t)
5897 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5900 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5902 RespawnTimes::iterator next;
5904 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5906 next = itr;
5907 ++next;
5909 if(GUID_HIPART(itr->first)==instance)
5910 mGORespawnTimes.erase(itr);
5913 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5915 next = itr;
5916 ++next;
5918 if(GUID_HIPART(itr->first)==instance)
5919 mCreatureRespawnTimes.erase(itr);
5922 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5923 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5926 void ObjectMgr::DeleteGOData(uint32 guid)
5928 // remove mapid*cellid -> guid_set map
5929 GameObjectData const* data = GetGOData(guid);
5930 if(data)
5931 RemoveGameobjectFromGrid(guid, data);
5933 mGameObjectDataMap.erase(guid);
5936 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5938 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5939 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5940 cell_guids.corpses[player_guid] = instance;
5943 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5945 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5946 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5947 cell_guids.corpses.erase(player_guid);
5950 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5952 map.clear(); // need for reload case
5954 uint32 count = 0;
5956 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5958 if(!result)
5960 barGoLink bar(1);
5962 bar.step();
5964 sLog.outString();
5965 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5966 return;
5969 barGoLink bar(result->GetRowCount());
5973 Field *fields = result->Fetch();
5974 bar.step();
5976 uint32 id = fields[0].GetUInt32();
5977 uint32 quest = fields[1].GetUInt32();
5979 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5981 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5982 continue;
5985 map.insert(QuestRelations::value_type(id,quest));
5987 ++count;
5988 } while (result->NextRow());
5990 delete result;
5992 sLog.outString();
5993 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5996 void ObjectMgr::LoadGameobjectQuestRelations()
5998 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6000 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6002 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6003 if(!goInfo)
6004 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6005 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6006 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6010 void ObjectMgr::LoadGameobjectInvolvedRelations()
6012 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6014 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6016 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6017 if(!goInfo)
6018 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6019 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6020 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6024 void ObjectMgr::LoadCreatureQuestRelations()
6026 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6028 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6030 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6031 if(!cInfo)
6032 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6033 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6034 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);
6038 void ObjectMgr::LoadCreatureInvolvedRelations()
6040 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6042 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6044 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6045 if(!cInfo)
6046 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6047 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6048 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);
6052 void ObjectMgr::LoadReservedPlayersNames()
6054 m_ReservedNames.clear(); // need for reload case
6056 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6058 uint32 count = 0;
6060 if( !result )
6062 barGoLink bar( 1 );
6063 bar.step();
6065 sLog.outString();
6066 sLog.outString( ">> Loaded %u reserved player names", count );
6067 return;
6070 barGoLink bar( result->GetRowCount() );
6072 Field* fields;
6075 bar.step();
6076 fields = result->Fetch();
6077 std::string name= fields[0].GetCppString();
6078 if(normalizePlayerName(name))
6080 m_ReservedNames.insert(name);
6081 ++count;
6083 } while ( result->NextRow() );
6085 delete result;
6087 sLog.outString();
6088 sLog.outString( ">> Loaded %u reserved player names", count );
6091 enum LanguageType
6093 LT_BASIC_LATIN = 0x0000,
6094 LT_EXTENDEN_LATIN = 0x0001,
6095 LT_CYRILLIC = 0x0002,
6096 LT_EAST_ASIA = 0x0004,
6097 LT_ANY = 0xFFFF
6100 static LanguageType GetRealmLanguageType(bool create)
6102 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6104 case REALM_ZONE_UNKNOWN: // any language
6105 case REALM_ZONE_DEVELOPMENT:
6106 case REALM_ZONE_TEST_SERVER:
6107 case REALM_ZONE_QA_SERVER:
6108 return LT_ANY;
6109 case REALM_ZONE_UNITED_STATES: // extended-Latin
6110 case REALM_ZONE_OCEANIC:
6111 case REALM_ZONE_LATIN_AMERICA:
6112 case REALM_ZONE_ENGLISH:
6113 case REALM_ZONE_GERMAN:
6114 case REALM_ZONE_FRENCH:
6115 case REALM_ZONE_SPANISH:
6116 return LT_EXTENDEN_LATIN;
6117 case REALM_ZONE_KOREA: // East-Asian
6118 case REALM_ZONE_TAIWAN:
6119 case REALM_ZONE_CHINA:
6120 return LT_EAST_ASIA;
6121 case REALM_ZONE_RUSSIAN: // Cyrillic
6122 return LT_CYRILLIC;
6123 default:
6124 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6128 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6130 if(strictMask==0) // any language, ignore realm
6132 if(isExtendedLatinString(wstr,numericOrSpace))
6133 return true;
6134 if(isCyrillicString(wstr,numericOrSpace))
6135 return true;
6136 if(isEastAsianString(wstr,numericOrSpace))
6137 return true;
6138 return false;
6141 if(strictMask & 0x2) // realm zone specific
6143 LanguageType lt = GetRealmLanguageType(create);
6144 if(lt & LT_EXTENDEN_LATIN)
6145 if(isExtendedLatinString(wstr,numericOrSpace))
6146 return true;
6147 if(lt & LT_CYRILLIC)
6148 if(isCyrillicString(wstr,numericOrSpace))
6149 return true;
6150 if(lt & LT_EAST_ASIA)
6151 if(isEastAsianString(wstr,numericOrSpace))
6152 return true;
6155 if(strictMask & 0x1) // basic Latin
6157 if(isBasicLatinString(wstr,numericOrSpace))
6158 return true;
6161 return false;
6164 bool ObjectMgr::IsValidName( std::string name, bool create )
6166 std::wstring wname;
6167 if(!Utf8toWStr(name,wname))
6168 return false;
6170 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6171 return false;
6173 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6175 return isValidString(wname,strictMask,false,create);
6178 bool ObjectMgr::IsValidCharterName( std::string name )
6180 std::wstring wname;
6181 if(!Utf8toWStr(name,wname))
6182 return false;
6184 if(wname.size() < 1)
6185 return false;
6187 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6189 return isValidString(wname,strictMask,true);
6192 bool ObjectMgr::IsValidPetName( std::string name )
6194 std::wstring wname;
6195 if(!Utf8toWStr(name,wname))
6196 return false;
6198 if(wname.size() < 1)
6199 return false;
6201 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6203 return isValidString(wname,strictMask,false);
6206 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6208 if(loc==LOCALE_enUS)
6209 return -1;
6211 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6212 if(m_LocalForIndex[i]==loc)
6213 return i;
6215 return -1;
6218 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6220 if (i<0 || i>=m_LocalForIndex.size())
6221 return LOCALE_enUS;
6223 return m_LocalForIndex[i];
6226 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6228 if(loc==LOCALE_enUS)
6229 return -1;
6231 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6232 if(m_LocalForIndex[i]==loc)
6233 return i;
6235 m_LocalForIndex.push_back(loc);
6236 return m_LocalForIndex.size()-1;
6239 void ObjectMgr::LoadBattleMastersEntry()
6241 mBattleMastersMap.clear(); // need for reload case
6243 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6245 uint32 count = 0;
6247 if( !result )
6249 barGoLink bar( 1 );
6250 bar.step();
6252 sLog.outString();
6253 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6254 return;
6257 barGoLink bar( result->GetRowCount() );
6261 ++count;
6262 bar.step();
6264 Field *fields = result->Fetch();
6266 uint32 entry = fields[0].GetUInt32();
6267 uint32 bgTypeId = fields[1].GetUInt32();
6269 mBattleMastersMap[entry] = bgTypeId;
6271 } while( result->NextRow() );
6273 delete result;
6275 sLog.outString();
6276 sLog.outString( ">> Loaded %u battlemaster entries", count );
6279 void ObjectMgr::LoadGameObjectForQuests()
6281 mGameObjectForQuestSet.clear(); // need for reload case
6283 uint32 count = 0;
6285 // collect GO entries for GO that must activated
6286 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6288 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6289 if(!goInfo)
6290 continue;
6292 switch(goInfo->type)
6294 // scan GO chest with loot including quest items
6295 case GAMEOBJECT_TYPE_CHEST:
6297 uint32 loot_id = GameObject::GetLootId(goInfo);
6299 // find quest loot for GO
6300 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6302 mGameObjectForQuestSet.insert(go_entry);
6303 ++count;
6305 break;
6307 case GAMEOBJECT_TYPE_GOOBER:
6309 if(goInfo->goober.questId) //quests objects
6311 mGameObjectForQuestSet.insert(go_entry);
6312 count++;
6314 break;
6316 default:
6317 break;
6321 sLog.outString();
6322 sLog.outString( ">> Loaded %u GameObject for quests", count );
6325 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6327 // cleanup affected map part for reloading case
6328 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6330 if(itr->first >= min_value && itr->first <= max_value)
6332 MangosStringLocaleMap::iterator itr2 = itr;
6333 ++itr;
6334 mMangosStringLocaleMap.erase(itr2);
6336 else
6337 ++itr;
6340 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);
6342 if(!result)
6344 barGoLink bar(1);
6346 bar.step();
6348 sLog.outString("");
6349 if(min_value > 0) // error only in case internal strings
6350 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6351 else
6352 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6353 return false;
6356 uint32 count = 0;
6358 barGoLink bar(result->GetRowCount());
6362 Field *fields = result->Fetch();
6363 bar.step();
6365 int32 entry = fields[0].GetInt32();
6367 if(entry==0)
6369 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6370 continue;
6372 else if(entry < min_value || entry > max_value)
6374 int32 start = min_value > 0 ? min_value : max_value;
6375 int32 end = min_value > 0 ? max_value : min_value;
6376 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6377 continue;
6380 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6382 if(data.Content.size() > 0)
6384 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6385 continue;
6388 data.Content.resize(1);
6389 ++count;
6391 // 0 -> default, idx in to idx+1
6392 data.Content[0] = fields[1].GetCppString();
6394 for(int i = 1; i < MAX_LOCALE; ++i)
6396 std::string str = fields[i+1].GetCppString();
6397 if(!str.empty())
6399 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6400 if(idx >= 0)
6402 // 0 -> default, idx in to idx+1
6403 if(data.Content.size() <= idx+1)
6404 data.Content.resize(idx+2);
6406 data.Content[idx+1] = str;
6410 } while (result->NextRow());
6412 delete result;
6414 sLog.outString();
6415 if(min_value > 0) // internal mangos strings
6416 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6417 else
6418 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6420 return true;
6423 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6425 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6426 // Content[0] always exist if exist MangosStringLocale
6427 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6429 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6430 return msl->Content[locale_idx+1].c_str();
6431 else
6432 return msl->Content[0].c_str();
6435 if(entry > 0)
6436 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6437 else
6438 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6439 return "<error>";
6442 void ObjectMgr::LoadFishingBaseSkillLevel()
6444 mFishingBaseForArea.clear(); // for reload case
6446 uint32 count = 0;
6447 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6449 if( !result )
6451 barGoLink bar( 1 );
6453 bar.step();
6455 sLog.outString();
6456 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6457 return;
6460 barGoLink bar( result->GetRowCount() );
6464 bar.step();
6466 Field *fields = result->Fetch();
6467 uint32 entry = fields[0].GetUInt32();
6468 int32 skill = fields[1].GetInt32();
6470 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6471 if(!fArea)
6473 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6474 continue;
6477 mFishingBaseForArea[entry] = skill;
6478 ++count;
6480 while (result->NextRow());
6482 delete result;
6484 sLog.outString();
6485 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6488 // Searches for the same condition already in Conditions store
6489 // Returns Id if found, else adds it to Conditions and returns Id
6490 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6492 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6493 for (uint16 i=0; i < mConditions.size(); ++i)
6495 if (lc == mConditions[i])
6496 return i;
6499 mConditions.push_back(lc);
6501 if(mConditions.size() > 0xFFFF)
6503 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6504 return 0;
6507 return mConditions.size() - 1;
6510 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6512 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6514 std::wstring wname;
6515 if(!Utf8toWStr(names.name[i],wname))
6516 return false;
6518 if(mainpart!=GetMainPartOfName(wname,i+1))
6519 return false;
6521 return true;
6524 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6526 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6527 if(i!= mAreaTriggerScripts.end())
6528 return i->second;
6529 return 0;
6532 // Checks if player meets the condition
6533 bool PlayerCondition::Meets(Player const * player) const
6535 if( !player )
6536 return false; // player not present, return false
6538 switch (condition)
6540 case CONDITION_NONE:
6541 return true; // empty condition, always met
6542 case CONDITION_AURA:
6543 return player->HasAura(value1, value2);
6544 case CONDITION_ITEM:
6545 return player->HasItemCount(value1, value2);
6546 case CONDITION_ITEM_EQUIPPED:
6547 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6548 case CONDITION_ZONEID:
6549 return player->GetZoneId() == value1;
6550 case CONDITION_REPUTATION_RANK:
6552 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6553 return faction && player->GetReputationRank(faction) >= value2;
6555 case CONDITION_TEAM:
6556 return player->GetTeam() == value1;
6557 case CONDITION_SKILL:
6558 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6559 case CONDITION_QUESTREWARDED:
6560 return player->GetQuestRewardStatus(value1);
6561 case CONDITION_QUESTTAKEN:
6563 QuestStatus status = player->GetQuestStatus(value1);
6564 return (status == QUEST_STATUS_INCOMPLETE);
6566 case CONDITION_AD_COMMISSION_AURA:
6568 Unit::AuraMap const& auras = player->GetAuras();
6569 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6570 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6571 return true;
6572 return false;
6574 case CONDITION_NO_AURA:
6575 return !player->HasAura(value1, value2);
6576 case CONDITION_ACTIVE_EVENT:
6577 return gameeventmgr.IsActiveEvent(value1);
6578 default:
6579 return false;
6583 // Verification of condition values validity
6584 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6586 if( condition >= MAX_CONDITION) // Wrong condition type
6588 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6589 return false;
6592 switch (condition)
6594 case CONDITION_AURA:
6596 if(!sSpellStore.LookupEntry(value1))
6598 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6599 return false;
6601 if(value2 > 2)
6603 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6604 return false;
6606 break;
6608 case CONDITION_ITEM:
6610 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6611 if(!proto)
6613 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6614 return false;
6616 break;
6618 case CONDITION_ITEM_EQUIPPED:
6620 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6621 if(!proto)
6623 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6624 return false;
6626 break;
6628 case CONDITION_ZONEID:
6630 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6631 if(!areaEntry)
6633 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6634 return false;
6636 if(areaEntry->zone != 0)
6638 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6639 return false;
6641 break;
6643 case CONDITION_REPUTATION_RANK:
6645 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6646 if(!factionEntry)
6648 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6649 return false;
6651 break;
6653 case CONDITION_TEAM:
6655 if (value1 != ALLIANCE && value1 != HORDE)
6657 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6658 return false;
6660 break;
6662 case CONDITION_SKILL:
6664 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6665 if (!pSkill)
6667 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6668 return false;
6670 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6672 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6673 return false;
6675 break;
6677 case CONDITION_QUESTREWARDED:
6678 case CONDITION_QUESTTAKEN:
6680 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6681 if (!Quest)
6683 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6684 return false;
6686 if(value2)
6687 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6688 break;
6690 case CONDITION_AD_COMMISSION_AURA:
6692 if(value1)
6693 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6694 if(value2)
6695 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6696 break;
6698 case CONDITION_NO_AURA:
6700 if(!sSpellStore.LookupEntry(value1))
6702 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6703 return false;
6705 if(value2 > 2)
6707 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6708 return false;
6710 break;
6712 case CONDITION_ACTIVE_EVENT:
6714 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6715 if(value1 >=events.size() || !events[value1].isValid())
6717 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6718 return false;
6720 break;
6723 return true;
6726 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6728 switch(pSkill->categoryId)
6730 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6731 case SKILL_CATEGORY_WEAPON:
6732 if(pSkill->id!=SKILL_FIST_WEAPONS)
6733 return SKILL_RANGE_LEVEL;
6734 else
6735 return SKILL_RANGE_MONO;
6736 case SKILL_CATEGORY_ARMOR:
6737 case SKILL_CATEGORY_CLASS:
6738 if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6739 return SKILL_RANGE_MONO;
6740 else
6741 return SKILL_RANGE_LEVEL;
6742 case SKILL_CATEGORY_SECONDARY:
6743 case SKILL_CATEGORY_PROFESSION:
6744 // not set skills for professions and racial abilities
6745 if(IsProfessionSkill(pSkill->id))
6746 return SKILL_RANGE_RANK;
6747 else if(racial)
6748 return SKILL_RANGE_NONE;
6749 else
6750 return SKILL_RANGE_MONO;
6751 default:
6752 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6753 case SKILL_CATEGORY_NOT_DISPLAYED: //only GENEREC(DND)
6754 return SKILL_RANGE_NONE;
6758 void ObjectMgr::LoadGameTele()
6760 m_GameTeleMap.clear(); // for reload case
6762 uint32 count = 0;
6763 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6765 if( !result )
6767 barGoLink bar( 1 );
6769 bar.step();
6771 sLog.outString();
6772 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6773 return;
6776 barGoLink bar( result->GetRowCount() );
6780 bar.step();
6782 Field *fields = result->Fetch();
6784 uint32 id = fields[0].GetUInt32();
6786 GameTele gt;
6788 gt.position_x = fields[1].GetFloat();
6789 gt.position_y = fields[2].GetFloat();
6790 gt.position_z = fields[3].GetFloat();
6791 gt.orientation = fields[4].GetFloat();
6792 gt.mapId = fields[5].GetUInt32();
6793 gt.name = fields[6].GetCppString();
6795 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6797 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6798 continue;
6801 if(!Utf8toWStr(gt.name,gt.wnameLow))
6803 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6804 continue;
6807 wstrToLower( gt.wnameLow );
6809 m_GameTeleMap[id] = gt;
6811 ++count;
6813 while (result->NextRow());
6815 delete result;
6817 sLog.outString();
6818 sLog.outString( ">> Loaded %u game tele's", count );
6821 GameTele const* ObjectMgr::GetGameTele(std::string name) const
6823 // explicit name case
6824 std::wstring wname;
6825 if(!Utf8toWStr(name,wname))
6826 return false;
6828 // converting string that we try to find to lower case
6829 wstrToLower( wname );
6831 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6832 const GameTele* alt = NULL;
6833 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6834 if(itr->second.wnameLow == wname)
6835 return &itr->second;
6836 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6837 alt = &itr->second;
6839 return alt;
6842 bool ObjectMgr::AddGameTele(GameTele& tele)
6844 // find max id
6845 uint32 new_id = 0;
6846 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6847 if(itr->first > new_id)
6848 new_id = itr->first;
6850 // use next
6851 ++new_id;
6853 if(!Utf8toWStr(tele.name,tele.wnameLow))
6854 return false;
6856 wstrToLower( tele.wnameLow );
6858 m_GameTeleMap[new_id] = tele;
6860 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')",
6861 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6864 bool ObjectMgr::DeleteGameTele(std::string name)
6866 // explicit name case
6867 std::wstring wname;
6868 if(!Utf8toWStr(name,wname))
6869 return false;
6871 // converting string that we try to find to lower case
6872 wstrToLower( wname );
6874 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6876 if(itr->second.wnameLow == wname)
6878 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6879 m_GameTeleMap.erase(itr);
6880 return true;
6884 return false;
6887 void ObjectMgr::LoadTrainerSpell()
6889 // For reload case
6890 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6891 itr->second.Clear();
6892 m_mCacheTrainerSpellMap.clear();
6894 std::set<uint32> skip_trainers;
6896 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6898 if( !result )
6900 barGoLink bar( 1 );
6902 bar.step();
6904 sLog.outString();
6905 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6906 return;
6909 barGoLink bar( result->GetRowCount() );
6911 uint32 count = 0;
6914 bar.step();
6916 Field* fields = result->Fetch();
6918 uint32 entry = fields[0].GetUInt32();
6919 uint32 spell = fields[1].GetUInt32();
6921 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6923 if(!cInfo)
6925 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6926 continue;
6929 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6931 if(skip_trainers.count(entry) == 0)
6933 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6934 skip_trainers.insert(entry);
6936 continue;
6939 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6940 if(!spellinfo)
6942 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6943 continue;
6946 if(!SpellMgr::IsSpellValid(spellinfo))
6948 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6949 continue;
6952 TrainerSpell* pTrainerSpell = new TrainerSpell();
6953 pTrainerSpell->spell = spell;
6954 pTrainerSpell->spellcost = fields[2].GetUInt32();
6955 pTrainerSpell->reqskill = fields[3].GetUInt32();
6956 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6957 pTrainerSpell->reqlevel = fields[5].GetUInt32();
6959 if(!pTrainerSpell->reqlevel)
6960 pTrainerSpell->reqlevel = spellinfo->spellLevel;
6963 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6965 if(SpellMgr::IsProfessionSpell(spell))
6966 data.trainerType = 2;
6968 data.spellList.push_back(pTrainerSpell);
6969 ++count;
6971 } while (result->NextRow());
6972 delete result;
6974 sLog.outString();
6975 sLog.outString( ">> Loaded Trainers %d", count );
6978 void ObjectMgr::LoadVendors()
6980 // For reload case
6981 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6982 itr->second.Clear();
6983 m_mCacheVendorItemMap.clear();
6985 std::set<uint32> skip_vendors;
6987 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6988 if( !result )
6990 barGoLink bar( 1 );
6992 bar.step();
6994 sLog.outString();
6995 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6996 return;
6999 barGoLink bar( result->GetRowCount() );
7001 uint32 count = 0;
7004 bar.step();
7005 Field* fields = result->Fetch();
7007 uint32 entry = fields[0].GetUInt32();
7008 uint32 item_id = fields[1].GetUInt32();
7009 uint32 maxcount = fields[2].GetUInt32();
7010 uint32 incrtime = fields[3].GetUInt32();
7011 uint32 ExtendedCost = fields[4].GetUInt32();
7013 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7014 continue;
7016 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7018 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7019 ++count;
7021 } while (result->NextRow());
7022 delete result;
7024 sLog.outString();
7025 sLog.outString( ">> Loaded %d Vendors ", count );
7028 void ObjectMgr::LoadNpcTextId()
7031 m_mCacheNpcTextIdMap.clear();
7033 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7034 if( !result )
7036 barGoLink bar( 1 );
7038 bar.step();
7040 sLog.outString();
7041 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7042 return;
7045 barGoLink bar( result->GetRowCount() );
7047 uint32 count = 0;
7048 uint32 guid,textid;
7051 bar.step();
7053 Field* fields = result->Fetch();
7055 guid = fields[0].GetUInt32();
7056 textid = fields[1].GetUInt32();
7058 if (!GetCreatureData(guid))
7060 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7061 continue;
7063 if (!GetGossipText(textid))
7065 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7066 continue;
7069 m_mCacheNpcTextIdMap[guid] = textid ;
7070 ++count;
7072 } while (result->NextRow());
7073 delete result;
7075 sLog.outString();
7076 sLog.outString( ">> Loaded %d NpcTextId ", count );
7079 void ObjectMgr::LoadNpcOptions()
7081 m_mCacheNpcOptionList.clear(); // For reload case
7083 QueryResult *result = WorldDatabase.Query(
7084 // 0 1 2 3 4 5 6 7 8
7085 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7086 "FROM npc_option");
7088 if( !result )
7090 barGoLink bar( 1 );
7092 bar.step();
7094 sLog.outString();
7095 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7096 return;
7099 barGoLink bar( result->GetRowCount() );
7101 uint32 count = 0;
7105 bar.step();
7107 Field* fields = result->Fetch();
7109 GossipOption go;
7110 go.Id = fields[0].GetUInt32();
7111 go.GossipId = fields[1].GetUInt32();
7112 go.NpcFlag = fields[2].GetUInt32();
7113 go.Icon = fields[3].GetUInt32();
7114 go.Action = fields[4].GetUInt32();
7115 go.BoxMoney = fields[5].GetUInt32();
7116 go.Coded = fields[6].GetUInt8()!=0;
7117 go.OptionText = fields[7].GetCppString();
7118 go.BoxText = fields[8].GetCppString();
7120 m_mCacheNpcOptionList.push_back(go);
7122 ++count;
7124 } while (result->NextRow());
7125 delete result;
7127 sLog.outString();
7128 sLog.outString( ">> Loaded %d npc_option entries", count );
7131 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7133 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7134 vList.AddItem(item,maxcount,incrtime,extendedcost);
7136 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7139 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7141 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7142 if(iter == m_mCacheVendorItemMap.end())
7143 return false;
7145 if(!iter->second.FindItem(item))
7146 return false;
7148 iter->second.RemoveItem(item);
7149 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7150 return true;
7153 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7155 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7156 if(!cInfo)
7158 if(pl)
7159 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7160 else
7161 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7162 return false;
7165 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7167 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7169 if(pl)
7170 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7171 else
7172 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7174 if(skip_vendors)
7175 skip_vendors->insert(vendor_entry);
7177 return false;
7180 if(!GetItemPrototype(item_id))
7182 if(pl)
7183 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7184 else
7185 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7186 return false;
7189 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7191 if(pl)
7192 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7193 else
7194 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7195 return false;
7198 if(maxcount > 0 && incrtime == 0)
7200 if(pl)
7201 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7202 else
7203 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7204 return false;
7206 else if(maxcount==0 && incrtime > 0)
7208 if(pl)
7209 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7210 else
7211 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7212 return false;
7215 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7216 if(!vItems)
7217 return true; // later checks for non-empty lists
7219 if(vItems->FindItem(item_id))
7221 if(pl)
7222 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7223 else
7224 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7225 return false;
7228 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7230 if(pl)
7231 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7232 else
7233 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7234 return false;
7237 return true;
7240 void ObjectMgr::LoadScriptNames()
7242 m_scriptNames.push_back("");
7243 QueryResult *result = WorldDatabase.Query(
7244 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7245 "UNION "
7246 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7247 "UNION "
7248 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7249 "UNION "
7250 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7251 "UNION "
7252 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7253 if(result)
7257 m_scriptNames.push_back((*result)[0].GetString());
7258 } while (result->NextRow());
7259 delete result;
7262 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7265 uint32 ObjectMgr::GetScriptId(const char *name)
7267 // use binary search to find the script name in the sorted vector
7268 // assume "" is the first element
7269 if(!name) return 0;
7270 ScriptNameMap::const_iterator itr =
7271 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7272 if(itr == m_scriptNames.end()) return 0;
7273 return itr - m_scriptNames.begin();
7276 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7278 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7280 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7282 if(itrM->second.dataint)
7284 if(!GetMangosStringLocale (itrM->second.dataint))
7285 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", *itrM);
7287 if(ids.count(itrM->second.dataint))
7288 ids.erase(itrM->second.dataint);
7294 void ObjectMgr::LoadDbScriptStrings()
7296 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7298 std::set<int32> ids;
7300 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7301 if(GetMangosStringLocale(i))
7302 ids.insert(i);
7304 CheckScripts(sQuestEndScripts,ids);
7305 CheckScripts(sQuestStartScripts,ids);
7306 CheckScripts(sSpellScripts,ids);
7307 CheckScripts(sGameObjectScripts,ids);
7308 CheckScripts(sEventScripts,ids);
7310 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7311 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7314 // Functions for scripting access
7315 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7317 return objmgr.GetAreaTriggerScriptId(trigger_id);
7320 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7322 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7324 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());
7325 start_value = -1;
7326 end_value = std::numeric_limits<int32>::min();
7329 // for scripting localized strings allowed use _only_ negative entries
7330 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7333 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7335 return objmgr.GetScriptId(name);
7338 ObjectMgr::ScriptNameMap & GetScriptNames()
7340 return objmgr.GetScriptNames();