[sql/updates/2008_11_11_01_mangos_db_script_string.sql sql/updates/2008_11_11_02_mang...
[auctionmangos.git] / src / game / ObjectMgr.cpp
blob635077035def48ee05c88e3c369876e8dd36188a
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"
23 #include "Log.h"
24 #include "MapManager.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "WorldSession.h"
30 #include "Group.h"
31 #include "Guild.h"
32 #include "ArenaTeam.h"
33 #include "Transports.h"
34 #include "ProgressBar.h"
35 #include "Policies/SingletonImp.h"
36 #include "Language.h"
37 #include "GameEvent.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
45 INSTANTIATE_SINGLETON_1(ObjectMgr);
47 ScriptMapMap sQuestEndScripts;
48 ScriptMapMap sQuestStartScripts;
49 ScriptMapMap sSpellScripts;
50 ScriptMapMap sGameObjectScripts;
51 ScriptMapMap sEventScripts;
53 bool normalizePlayerName(std::string& name)
55 if(name.empty())
56 return false;
58 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
59 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
61 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
62 return false;
64 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
65 for(size_t i = 1; i < wstr_len; ++i)
66 wstr_buf[i] = wcharToLower(wstr_buf[i]);
68 if(!WStrToUtf8(wstr_buf,wstr_len,name))
69 return false;
71 return true;
74 LanguageDesc lang_description[LANGUAGES_COUNT] =
76 { LANG_ADDON, 0, 0 },
77 { LANG_UNIVERSAL, 0, 0 },
78 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
79 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
80 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
81 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
82 { LANG_COMMON, 668, SKILL_LANG_COMMON },
83 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
84 { LANG_TITAN, 816, SKILL_LANG_TITAN },
85 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
86 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
87 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
88 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
89 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
90 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
91 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
92 { LANG_ZOMBIE, 0, 0 },
93 { LANG_GNOMISH_BINARY, 0, 0 },
94 { LANG_GOBLIN_BINARY, 0, 0 }
97 LanguageDesc const* GetLanguageDescByID(uint32 lang)
99 for(int i = 0; i < LANGUAGES_COUNT; ++i)
101 if(uint32(lang_description[i].lang_id) == lang)
102 return &lang_description[i];
105 return NULL;
108 ObjectMgr::ObjectMgr()
110 m_hiCharGuid = 1;
111 m_hiCreatureGuid = 1;
112 m_hiPetGuid = 1;
113 m_hiItemGuid = 1;
114 m_hiGoGuid = 1;
115 m_hiDoGuid = 1;
116 m_hiCorpseGuid = 1;
118 m_hiPetNumber = 1;
120 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
121 mGuildBankTabPrice[0] = 100;
122 mGuildBankTabPrice[1] = 250;
123 mGuildBankTabPrice[2] = 500;
124 mGuildBankTabPrice[3] = 1000;
125 mGuildBankTabPrice[4] = 2500;
126 mGuildBankTabPrice[5] = 5000;
128 // Only zero condition left, others will be added while loading DB tables
129 mConditions.resize(1);
132 ObjectMgr::~ObjectMgr()
134 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
136 delete i->second;
138 mQuestTemplates.clear( );
140 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
142 delete i->second;
144 mGossipText.clear( );
146 mAreaTriggers.clear();
148 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
150 delete[] i->second;
152 petInfo.clear();
154 // free only if loaded
155 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
156 delete[] playerClassInfo[class_].levelInfo;
158 for (int race = 0; race < MAX_RACES; ++race)
159 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
160 delete[] playerInfo[race][class_].levelInfo;
162 // free group and guild objects
163 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
164 delete (*itr);
165 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
166 delete (*itr);
168 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
169 delete itr->second;
171 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
172 itr->second.Clear();
174 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
175 itr->second.Clear();
178 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
180 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
181 if ((*itr)->GetLeaderGUID() == guid)
182 return *itr;
184 return NULL;
187 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
189 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
190 if ((*itr)->GetId() == GuildId)
191 return *itr;
193 return NULL;
196 Guild * ObjectMgr::GetGuildByName(std::string guildname) const
198 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
199 if ((*itr)->GetName() == guildname)
200 return *itr;
202 return NULL;
205 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
207 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
208 if ((*itr)->GetId() == GuildId)
209 return (*itr)->GetName();
211 return "";
214 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
216 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
217 if( (*itr)->GetLeader() == guid)
218 return *itr;
220 return NULL;
223 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
225 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
226 if ((*itr)->GetId() == ArenaTeamId)
227 return *itr;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
234 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
235 if ((*itr)->GetName() == arenateamname)
236 return *itr;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
243 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
244 if ((*itr)->GetCaptain() == guid)
245 return *itr;
247 return NULL;
250 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
252 switch ( location )
254 case 6: //horde
255 return & mHordeAuctions;
256 break;
257 case 2: //alliance
258 return & mAllianceAuctions;
259 break;
260 default: //neutral
261 return & mNeutralAuctions;
265 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
267 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
268 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
269 else
270 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
273 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
275 float percentance; // in 0..1
276 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
277 percentance = 0.75f;
278 else
279 percentance = 0.15f;
281 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
283 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
286 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
287 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
289 uint32 outbid = (currentBid / 100) * 5;
290 if (!outbid)
291 outbid = 1;
292 return outbid;
295 //does not clear ram
296 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
298 Item *pItem = GetAItem(auction->item_guidlow);
299 if(!pItem)
300 return;
302 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
303 Player *bidder = GetPlayer(bidder_guid);
305 uint32 bidder_accId = 0;
307 // data for gm.log
308 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
310 uint32 bidder_security = 0;
311 std::string bidder_name;
312 if (bidder)
314 bidder_accId = bidder->GetSession()->GetAccountId();
315 bidder_security = bidder->GetSession()->GetSecurity();
316 bidder_name = bidder->GetName();
318 else
320 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
321 bidder_security = accmgr.GetSecurity(bidder_accId);
323 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
325 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
326 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
330 if( bidder_security > SEC_PLAYER )
332 std::string owner_name;
333 if(!GetPlayerNameByGUID(auction->owner,owner_name))
334 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
336 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
338 sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
339 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
342 else if(!bidder)
343 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
345 // receiver exist
346 if(bidder || bidder_accId)
348 std::ostringstream msgAuctionWonSubject;
349 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
351 std::ostringstream msgAuctionWonBody;
352 msgAuctionWonBody.width(16);
353 msgAuctionWonBody << std::right << std::hex << auction->owner;
354 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
355 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
357 //prepare mail data... :
358 uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
360 // set owner to bidder (to prevent delete item with sender char deleting)
361 // owner in `data` will set at mail receive and item extracting
362 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
363 CharacterDatabase.CommitTransaction();
365 MailItemsInfo mi;
366 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
368 if (bidder)
369 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
370 else
371 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
373 // will delete item or place to receiver mail list
374 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
376 // receiver not exist
377 else
379 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
380 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
381 delete pItem;
385 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
387 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
388 Player *owner = GetPlayer(owner_guid);
390 // owner exist (online or offline)
391 if(owner || GetPlayerAccountIdByGUID(owner_guid))
393 std::ostringstream msgAuctionSalePendingSubject;
394 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
396 std::ostringstream msgAuctionSalePendingBody;
397 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
399 time_t distrTime = time(NULL) + HOUR;
401 msgAuctionSalePendingBody.width(16);
402 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
403 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
404 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
405 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
407 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
409 uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
411 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
415 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
416 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
418 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
419 Player *owner = GetPlayer(owner_guid);
421 uint32 owner_accId = 0;
422 if(!owner)
423 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
425 // owner exist
426 if(owner || owner_accId)
428 std::ostringstream msgAuctionSuccessfulSubject;
429 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
431 std::ostringstream auctionSuccessfulBody;
432 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
434 auctionSuccessfulBody.width(16);
435 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
436 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
437 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
439 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
441 uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
443 uint32 profit = auction->bid + auction->deposit - auctionCut;
445 if (owner)
447 //send auction owner notification, bidder must be current!
448 owner->GetSession()->SendAuctionOwnerNotification( auction );
451 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
455 //does not clear ram
456 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
457 { //return an item in auction to its owner by mail
458 Item *pItem = GetAItem(auction->item_guidlow);
459 if(!pItem)
461 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
462 return;
465 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
466 Player *owner = GetPlayer(owner_guid);
468 uint32 owner_accId = 0;
469 if(!owner)
470 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
472 // owner exist
473 if(owner || owner_accId)
475 std::ostringstream subject;
476 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
478 if ( owner )
479 owner->GetSession()->SendAuctionOwnerNotification( auction );
480 else
481 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
483 MailItemsInfo mi;
484 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
486 // will delete item or place to receiver mail list
487 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
489 // owner not found
490 else
492 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
493 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
494 delete pItem;
498 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
500 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
503 void ObjectMgr::LoadCreatureLocales()
505 mCreatureLocaleMap.clear(); // need for reload case
507 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");
509 if(!result)
511 barGoLink bar(1);
513 bar.step();
515 sLog.outString("");
516 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
517 return;
520 barGoLink bar(result->GetRowCount());
524 Field *fields = result->Fetch();
525 bar.step();
527 uint32 entry = fields[0].GetUInt32();
529 CreatureLocale& data = mCreatureLocaleMap[entry];
531 for(int i = 1; i < MAX_LOCALE; ++i)
533 std::string str = fields[1+2*(i-1)].GetCppString();
534 if(!str.empty())
536 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
537 if(idx >= 0)
539 if(data.Name.size() <= idx)
540 data.Name.resize(idx+1);
542 data.Name[idx] = str;
545 str = fields[1+2*(i-1)+1].GetCppString();
546 if(!str.empty())
548 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
549 if(idx >= 0)
551 if(data.SubName.size() <= idx)
552 data.SubName.resize(idx+1);
554 data.SubName[idx] = str;
558 } while (result->NextRow());
560 delete result;
562 sLog.outString();
563 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
566 void ObjectMgr::LoadNpcOptionLocales()
568 mNpcOptionLocaleMap.clear(); // need for reload case
570 QueryResult *result = WorldDatabase.Query("SELECT entry,"
571 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
572 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
573 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
574 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
575 "FROM locales_npc_option");
577 if(!result)
579 barGoLink bar(1);
581 bar.step();
583 sLog.outString("");
584 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
585 return;
588 barGoLink bar(result->GetRowCount());
592 Field *fields = result->Fetch();
593 bar.step();
595 uint32 entry = fields[0].GetUInt32();
597 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
599 for(int i = 1; i < MAX_LOCALE; ++i)
601 std::string str = fields[1+2*(i-1)].GetCppString();
602 if(!str.empty())
604 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
605 if(idx >= 0)
607 if(data.OptionText.size() <= idx)
608 data.OptionText.resize(idx+1);
610 data.OptionText[idx] = str;
613 str = fields[1+2*(i-1)+1].GetCppString();
614 if(!str.empty())
616 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
617 if(idx >= 0)
619 if(data.BoxText.size() <= idx)
620 data.BoxText.resize(idx+1);
622 data.BoxText[idx] = str;
626 } while (result->NextRow());
628 delete result;
630 sLog.outString();
631 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
634 void ObjectMgr::LoadCreatureTemplates()
636 sCreatureStorage.Load();
638 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
639 sLog.outString();
641 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
642 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
644 // check data correctness
645 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
647 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
648 if(!cInfo)
649 continue;
651 if(cInfo->HeroicEntry)
653 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
654 if(!heroicInfo)
656 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
657 continue;
660 if(heroicEntries.find(i)!=heroicEntries.end())
662 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
663 continue;
666 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
668 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
669 continue;
672 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
674 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
675 continue;
678 if(cInfo->npcflag != heroicInfo->npcflag)
680 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
681 continue;
684 if(cInfo->classNum != heroicInfo->classNum)
686 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
687 continue;
690 if(cInfo->race != heroicInfo->race)
692 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
693 continue;
696 if(cInfo->trainer_type != heroicInfo->trainer_type)
698 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
699 continue;
702 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
704 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
705 continue;
708 hasHeroicEntries.insert(i);
709 heroicEntries.insert(cInfo->HeroicEntry);
712 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
713 if(!factionTemplate)
714 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
716 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
717 if(!factionTemplate)
718 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
720 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
721 if (!minfo)
722 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
723 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
724 if (!minfo)
725 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
727 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
729 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
730 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
733 if(cInfo->baseattacktime == 0)
734 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
736 if(cInfo->rangeattacktime == 0)
737 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
739 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
740 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
742 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
744 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
745 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
748 if(cInfo->PetSpellDataId)
750 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
751 if(!spellDataId)
752 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
755 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
757 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
758 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
761 if(cInfo->equipmentId > 0) // 0 no equipment
763 if(!GetEquipmentInfo(cInfo->equipmentId))
765 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);
766 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
770 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
771 if(cInfo->scale <= 0.0f)
773 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
774 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
779 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
781 // Now add the auras, format "spellid effectindex spellid effectindex..."
782 char *p,*s;
783 std::vector<int> val;
784 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
785 if(p)
787 while (p[0]!=0)
789 ++p;
790 if (p[0]==' ')
792 val.push_back(atoi(s));
793 s=++p;
796 if (p!=s)
797 val.push_back(atoi(s));
799 // free char* loaded memory
800 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
802 // wrong list
803 if (val.size()%2)
805 addon->auras = NULL;
806 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
807 return;
811 // empty list
812 if(val.empty())
814 addon->auras = NULL;
815 return;
818 // replace by new structures array
819 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
821 int i=0;
822 for(int j=0;j<val.size()/2;++j)
824 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
825 cAura.spell_id = (uint32)val[2*j+0];
826 cAura.effect_idx = (uint32)val[2*j+1];
827 if ( cAura.effect_idx > 2 )
829 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);
830 continue;
832 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
833 if (!AdditionalSpellInfo)
835 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
836 continue;
839 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
841 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);
842 continue;
845 ++i;
848 // fill terminator element (after last added)
849 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
850 endAura.spell_id = 0;
851 endAura.effect_idx = 0;
854 void ObjectMgr::LoadCreatureAddons()
856 sCreatureInfoAddonStorage.Load();
858 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
859 sLog.outString();
861 // check data correctness and convert 'auras'
862 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
864 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
865 if(!addon)
866 continue;
868 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
870 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
871 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
874 sCreatureDataAddonStorage.Load();
876 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
877 sLog.outString();
879 // check data correctness and convert 'auras'
880 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
882 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
883 if(!addon)
884 continue;
886 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
888 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
889 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
893 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
895 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
898 void ObjectMgr::LoadEquipmentTemplates()
900 sEquipmentStorage.Load();
902 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
903 sLog.outString();
906 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
908 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
911 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
913 // Load creature model (display id)
914 uint32 display_id;
915 if (!data || data->displayid == 0) // use defaults from the template
917 // DisplayID_A is used if no team is given
918 if (team == HORDE)
919 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
920 else
921 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
923 else // overridden in creature data
924 display_id = data->displayid;
926 return display_id;
929 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
931 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
932 if(!minfo)
933 return NULL;
935 // If a model for another gender exists, 50% chance to use it
936 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
938 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
939 if(!minfo_tmp)
941 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
942 return minfo; // not fatal, just use the previous one
944 else
945 return minfo_tmp;
947 else
948 return minfo;
951 void ObjectMgr::LoadCreatureModelInfo()
953 sCreatureModelStorage.Load();
955 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
956 sLog.outString();
959 void ObjectMgr::LoadCreatures()
961 uint32 count = 0;
962 // 0 1 2 3
963 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
964 // 4 5 6 7 8 9 10 11
965 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
966 // 12 13 14 15 16 17
967 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
968 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
970 if(!result)
972 barGoLink bar(1);
974 bar.step();
976 sLog.outString("");
977 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
978 return;
981 // build single time for check creature data
982 std::set<uint32> heroicCreatures;
983 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
984 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
985 if(cInfo->HeroicEntry)
986 heroicCreatures.insert(cInfo->HeroicEntry);
988 barGoLink bar(result->GetRowCount());
992 Field *fields = result->Fetch();
993 bar.step();
995 uint32 guid = fields[0].GetUInt32();
997 CreatureData& data = mCreatureDataMap[guid];
999 data.id = fields[ 1].GetUInt32();
1000 data.mapid = fields[ 2].GetUInt32();
1001 data.displayid = fields[ 3].GetUInt32();
1002 data.equipmentId = fields[ 4].GetUInt32();
1003 data.posX = fields[ 5].GetFloat();
1004 data.posY = fields[ 6].GetFloat();
1005 data.posZ = fields[ 7].GetFloat();
1006 data.orientation = fields[ 8].GetFloat();
1007 data.spawntimesecs = fields[ 9].GetUInt32();
1008 data.spawndist = fields[10].GetFloat();
1009 data.currentwaypoint= fields[11].GetUInt32();
1010 data.curhealth = fields[12].GetUInt32();
1011 data.curmana = fields[13].GetUInt32();
1012 data.is_dead = fields[14].GetBool();
1013 data.movementType = fields[15].GetUInt8();
1014 data.spawnMask = fields[16].GetUInt8();
1015 int16 gameEvent = fields[17].GetInt16();
1017 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1018 if(!cInfo)
1020 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1021 continue;
1024 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1026 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1027 continue;
1030 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1032 if(!GetEquipmentInfo(data.equipmentId))
1034 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);
1035 data.equipmentId = -1;
1039 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1041 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 );
1042 data.curhealth = cInfo->minhealth;
1045 if(data.curmana < cInfo->minmana)
1047 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 );
1048 data.curmana = cInfo->minmana;
1051 if(data.spawndist < 0.0f)
1053 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1054 data.spawndist = 0.0f;
1056 else if(data.movementType == RANDOM_MOTION_TYPE)
1058 if(data.spawndist == 0.0f)
1060 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 );
1061 data.movementType = IDLE_MOTION_TYPE;
1064 else if(data.movementType == IDLE_MOTION_TYPE)
1066 if(data.spawndist != 0.0f)
1068 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1069 data.spawndist = 0.0f;
1073 if (gameEvent==0) // if not this is to be managed by GameEvent System
1074 AddCreatureToGrid(guid, &data);
1075 ++count;
1077 } while (result->NextRow());
1079 delete result;
1081 sLog.outString();
1082 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1085 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1087 uint8 mask = data->spawnMask;
1088 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1090 if(mask & 1)
1092 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1093 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1095 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1096 cell_guids.creatures.insert(guid);
1101 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1103 uint8 mask = data->spawnMask;
1104 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1106 if(mask & 1)
1108 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1109 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1111 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1112 cell_guids.creatures.erase(guid);
1117 void ObjectMgr::LoadGameobjects()
1119 uint32 count = 0;
1121 // 0 1 2 3 4 5 6
1122 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1123 // 7 8 9 10 11 12 13 14 15
1124 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1125 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1127 if(!result)
1129 barGoLink bar(1);
1131 bar.step();
1133 sLog.outString();
1134 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1135 return;
1138 barGoLink bar(result->GetRowCount());
1142 Field *fields = result->Fetch();
1143 bar.step();
1145 uint32 guid = fields[0].GetUInt32();
1147 GameObjectData& data = mGameObjectDataMap[guid];
1149 data.id = fields[ 1].GetUInt32();
1150 data.mapid = fields[ 2].GetUInt32();
1151 data.posX = fields[ 3].GetFloat();
1152 data.posY = fields[ 4].GetFloat();
1153 data.posZ = fields[ 5].GetFloat();
1154 data.orientation = fields[ 6].GetFloat();
1155 data.rotation0 = fields[ 7].GetFloat();
1156 data.rotation1 = fields[ 8].GetFloat();
1157 data.rotation2 = fields[ 9].GetFloat();
1158 data.rotation3 = fields[10].GetFloat();
1159 data.spawntimesecs = fields[11].GetInt32();
1160 data.animprogress = fields[12].GetUInt32();
1161 data.go_state = fields[13].GetUInt32();
1162 data.spawnMask = fields[14].GetUInt8();
1163 int16 gameEvent = fields[15].GetInt16();
1165 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1166 if(!gInfo)
1168 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1169 continue;
1172 if (gameEvent==0) // if not this is to be managed by GameEvent System
1173 AddGameobjectToGrid(guid, &data);
1174 ++count;
1176 } while (result->NextRow());
1178 delete result;
1180 sLog.outString();
1181 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1184 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1186 uint8 mask = data->spawnMask;
1187 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1189 if(mask & 1)
1191 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1192 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1194 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1195 cell_guids.gameobjects.insert(guid);
1200 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1202 uint8 mask = data->spawnMask;
1203 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1205 if(mask & 1)
1207 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1208 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1210 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1211 cell_guids.gameobjects.erase(guid);
1216 void ObjectMgr::LoadCreatureRespawnTimes()
1218 // remove outdated data
1219 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1221 uint32 count = 0;
1223 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1225 if(!result)
1227 barGoLink bar(1);
1229 bar.step();
1231 sLog.outString();
1232 sLog.outString(">> Loaded 0 creature respawn time.");
1233 return;
1236 barGoLink bar(result->GetRowCount());
1240 Field *fields = result->Fetch();
1241 bar.step();
1243 uint32 loguid = fields[0].GetUInt32();
1244 uint64 respawn_time = fields[1].GetUInt64();
1245 uint32 instance = fields[2].GetUInt32();
1247 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1249 ++count;
1250 } while (result->NextRow());
1252 delete result;
1254 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1255 sLog.outString();
1258 void ObjectMgr::LoadGameobjectRespawnTimes()
1260 // remove outdated data
1261 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1263 uint32 count = 0;
1265 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1267 if(!result)
1269 barGoLink bar(1);
1271 bar.step();
1273 sLog.outString();
1274 sLog.outString(">> Loaded 0 gameobject respawn time.");
1275 return;
1278 barGoLink bar(result->GetRowCount());
1282 Field *fields = result->Fetch();
1283 bar.step();
1285 uint32 loguid = fields[0].GetUInt32();
1286 uint64 respawn_time = fields[1].GetUInt64();
1287 uint32 instance = fields[2].GetUInt32();
1289 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1291 ++count;
1292 } while (result->NextRow());
1294 delete result;
1296 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1297 sLog.outString();
1300 // name must be checked to correctness (if received) before call this function
1301 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1303 uint64 guid = 0;
1305 CharacterDatabase.escape_string(name);
1307 // Player name safe to sending to DB (checked at login) and this function using
1308 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1309 if(result)
1311 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1313 delete result;
1316 return guid;
1319 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1321 // prevent DB access for online player
1322 if(Player* player = GetPlayer(guid))
1324 name = player->GetName();
1325 return true;
1328 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1330 if(result)
1332 name = (*result)[0].GetCppString();
1333 delete result;
1334 return true;
1337 return false;
1340 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1342 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1344 if(result)
1346 uint8 race = (*result)[0].GetUInt8();
1347 delete result;
1348 return Player::TeamForRace(race);
1351 return 0;
1354 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1356 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1357 if(result)
1359 uint32 acc = (*result)[0].GetUInt32();
1360 delete result;
1361 return acc;
1364 return 0;
1367 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(std::string name) const
1369 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1370 if(result)
1372 uint32 acc = (*result)[0].GetUInt32();
1373 delete result;
1374 return acc;
1377 return 0;
1380 void ObjectMgr::LoadAuctions()
1382 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1383 if( !result )
1384 return;
1386 Field *fields = result->Fetch();
1387 uint32 AuctionCount=fields[0].GetUInt32();
1388 delete result;
1390 if(!AuctionCount)
1391 return;
1393 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1394 if( !result )
1395 return;
1397 barGoLink bar( AuctionCount );
1399 AuctionEntry *aItem;
1403 fields = result->Fetch();
1405 bar.step();
1407 aItem = new AuctionEntry;
1408 aItem->Id = fields[0].GetUInt32();
1409 aItem->auctioneer = fields[1].GetUInt32();
1410 aItem->item_guidlow = fields[2].GetUInt32();
1411 aItem->item_template = fields[3].GetUInt32();
1412 aItem->owner = fields[4].GetUInt32();
1413 aItem->buyout = fields[5].GetUInt32();
1414 aItem->time = fields[6].GetUInt32();
1415 aItem->bidder = fields[7].GetUInt32();
1416 aItem->bid = fields[8].GetUInt32();
1417 aItem->startbid = fields[9].GetUInt32();
1418 aItem->deposit = fields[10].GetUInt32();
1419 aItem->location = fields[11].GetUInt8();
1420 //check if sold item exists
1421 if ( GetAItem( aItem->item_guidlow ) )
1423 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1425 else
1427 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1428 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1429 delete aItem;
1431 } while (result->NextRow());
1432 delete result;
1434 sLog.outString();
1435 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1436 sLog.outString();
1439 void ObjectMgr::LoadItemLocales()
1441 mItemLocaleMap.clear(); // need for reload case
1443 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");
1445 if(!result)
1447 barGoLink bar(1);
1449 bar.step();
1451 sLog.outString("");
1452 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1453 return;
1456 barGoLink bar(result->GetRowCount());
1460 Field *fields = result->Fetch();
1461 bar.step();
1463 uint32 entry = fields[0].GetUInt32();
1465 ItemLocale& data = mItemLocaleMap[entry];
1467 for(int i = 1; i < MAX_LOCALE; ++i)
1469 std::string str = fields[1+2*(i-1)].GetCppString();
1470 if(!str.empty())
1472 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1473 if(idx >= 0)
1475 if(data.Name.size() <= idx)
1476 data.Name.resize(idx+1);
1478 data.Name[idx] = str;
1482 str = fields[1+2*(i-1)+1].GetCppString();
1483 if(!str.empty())
1485 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1486 if(idx >= 0)
1488 if(data.Description.size() <= idx)
1489 data.Description.resize(idx+1);
1491 data.Description[idx] = str;
1495 } while (result->NextRow());
1497 delete result;
1499 sLog.outString();
1500 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1503 void ObjectMgr::LoadItemPrototypes()
1505 sItemStorage.Load ();
1506 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1507 sLog.outString();
1509 // check data correctness
1510 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1512 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1513 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1514 if(!proto)
1516 /* to many errors, and possible not all items really used in game
1517 if (dbcitem)
1518 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1520 continue;
1523 if(dbcitem)
1525 if(proto->InventoryType != dbcitem->InventoryType)
1527 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1528 // It safe let use InventoryType from DB
1531 if(proto->DisplayInfoID != dbcitem->DisplayId)
1533 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1534 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1536 if(proto->Sheath != dbcitem->Sheath)
1538 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1539 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1542 else
1544 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1547 if(proto->Class >= MAX_ITEM_CLASS)
1549 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1550 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_JUNK;
1553 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1555 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1556 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1559 if(proto->Quality >= MAX_ITEM_QUALITY)
1561 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1562 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1565 if(proto->BuyCount <= 0)
1567 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1568 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1571 if(proto->InventoryType >= MAX_INVTYPE)
1573 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1574 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1577 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1579 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1580 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1583 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1585 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1588 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1590 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1593 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1595 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1596 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1599 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1600 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1602 if(proto->RequiredReputationFaction)
1604 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1606 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1607 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1610 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1611 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1613 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1614 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1616 if(proto->Stackable==0)
1618 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1619 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1621 else if(proto->Stackable > 255)
1623 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1624 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1627 for (int j = 0; j < 10; j++)
1629 // for ItemStatValue != 0
1630 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1632 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1633 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1637 for (int j = 0; j < 5; j++)
1639 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1641 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1642 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1646 // special format
1647 if(proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN)
1649 // spell_1
1650 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1652 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);
1653 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1654 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1655 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1656 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1659 // spell_2 have learning spell
1660 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1662 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);
1663 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1664 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1665 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1667 else if(!proto->Spells[1].SpellId)
1669 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1670 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1671 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1673 else
1675 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1676 if(!spellInfo)
1678 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1679 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1680 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1681 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1683 // allowed only in special format
1684 else if(proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN)
1686 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1687 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1688 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1689 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1693 // spell_3*,spell_4*,spell_5* is empty
1694 for (int j = 2; j < 5; j++)
1696 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1698 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1699 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1700 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1702 else if(proto->Spells[j].SpellId != 0)
1704 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1705 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1709 // normal spell list
1710 else
1712 for (int j = 0; j < 5; j++)
1714 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1716 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1717 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1718 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1721 if(proto->Spells[j].SpellId)
1723 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1724 if(!spellInfo)
1726 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1727 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1729 // allowed only in special format
1730 else if(proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN)
1732 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1733 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1739 if(proto->Bonding >= MAX_BIND_TYPE)
1740 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1742 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1743 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1745 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1746 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1748 if(proto->Sheath >= MAX_SHEATHETYPE)
1750 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1751 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1754 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1756 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1757 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1760 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1762 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1763 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1766 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1768 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1769 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1772 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1773 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1775 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1776 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1778 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1779 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1781 for (int j = 0; j < 3; j++)
1783 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1785 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1786 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1790 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1791 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1793 if(proto->FoodType >= MAX_PET_DIET)
1795 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1796 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1800 // this DBC used currently only for check item templates in DB.
1801 sItemStore.Clear();
1804 void ObjectMgr::LoadAuctionItems()
1806 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1808 if( !result )
1809 return;
1811 barGoLink bar( result->GetRowCount() );
1813 uint32 count = 0;
1815 Field *fields;
1818 bar.step();
1820 fields = result->Fetch();
1821 uint32 item_guid = fields[0].GetUInt32();
1822 uint32 item_template = fields[1].GetUInt32();
1824 ItemPrototype const *proto = GetItemPrototype(item_template);
1826 if(!proto)
1828 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1829 continue;
1832 Item *item = NewItemOrBag(proto);
1834 if(!item->LoadFromDB(item_guid,0))
1836 delete item;
1837 continue;
1839 AddAItem(item);
1841 ++count;
1843 while( result->NextRow() );
1845 delete result;
1847 sLog.outString();
1848 sLog.outString( ">> Loaded %u auction items", count );
1851 void ObjectMgr::LoadPetLevelInfo()
1853 // Loading levels data
1855 // 0 1 2 3 4 5 6 7 8 9
1856 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1858 uint32 count = 0;
1860 if (!result)
1862 barGoLink bar( 1 );
1864 sLog.outString();
1865 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1866 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1867 return;
1870 barGoLink bar( result->GetRowCount() );
1874 Field* fields = result->Fetch();
1876 uint32 creature_id = fields[0].GetUInt32();
1877 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1879 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1880 continue;
1883 uint32 current_level = fields[1].GetUInt32();
1884 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1886 if(current_level > 255) // hardcoded level maximum
1887 sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1888 else
1889 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1890 continue;
1892 else if(current_level < 1)
1894 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1895 continue;
1898 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1900 if(pInfoMapEntry==NULL)
1901 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1903 // data for level 1 stored in [0] array element, ...
1904 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1906 pLevelInfo->health = fields[2].GetUInt16();
1907 pLevelInfo->mana = fields[3].GetUInt16();
1908 pLevelInfo->armor = fields[9].GetUInt16();
1910 for (int i = 0; i < MAX_STATS; i++)
1912 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1915 bar.step();
1916 ++count;
1918 while (result->NextRow());
1920 delete result;
1922 sLog.outString();
1923 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1926 // Fill gaps and check integrity
1927 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1929 PetLevelInfo* pInfo = itr->second;
1931 // fatal error if no level 1 data
1932 if(!pInfo || pInfo[0].health == 0 )
1934 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1935 exit(1);
1938 // fill level gaps
1939 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1941 if(pInfo[level].health == 0)
1943 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1944 pInfo[level] = pInfo[level-1];
1950 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1952 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1953 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1955 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1956 if(itr == petInfo.end())
1957 return NULL;
1959 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1962 void ObjectMgr::LoadPlayerInfo()
1964 // Load playercreate
1966 // 0 1 2 3 4 5 6
1967 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1969 uint32 count = 0;
1971 if (!result)
1973 barGoLink bar( 1 );
1975 sLog.outString();
1976 sLog.outString( ">> Loaded %u player create definitions", count );
1977 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1978 exit(1);
1981 barGoLink bar( result->GetRowCount() );
1985 Field* fields = result->Fetch();
1987 uint32 current_race = fields[0].GetUInt32();
1988 uint32 current_class = fields[1].GetUInt32();
1989 uint32 mapId = fields[2].GetUInt32();
1990 uint32 zoneId = fields[3].GetUInt32();
1991 float positionX = fields[4].GetFloat();
1992 float positionY = fields[5].GetFloat();
1993 float positionZ = fields[6].GetFloat();
1995 if(current_race >= MAX_RACES)
1997 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1998 continue;
2001 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2002 if(!rEntry)
2004 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2005 continue;
2008 if(current_class >= MAX_CLASSES)
2010 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2011 continue;
2014 if(!sChrClassesStore.LookupEntry(current_class))
2016 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2017 continue;
2020 // accept DB data only for valid position (and non instanceable)
2021 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2023 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2024 continue;
2027 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2029 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2030 continue;
2033 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2035 pInfo->mapId = mapId;
2036 pInfo->zoneId = zoneId;
2037 pInfo->positionX = positionX;
2038 pInfo->positionY = positionY;
2039 pInfo->positionZ = positionZ;
2041 pInfo->displayId_m = rEntry->model_m;
2042 pInfo->displayId_f = rEntry->model_f;
2044 bar.step();
2045 ++count;
2047 while (result->NextRow());
2049 delete result;
2051 sLog.outString();
2052 sLog.outString( ">> Loaded %u player create definitions", count );
2055 // Load playercreate items
2057 // 0 1 2 3
2058 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2060 uint32 count = 0;
2062 if (!result)
2064 barGoLink bar( 1 );
2066 sLog.outString();
2067 sLog.outString( ">> Loaded %u player create items", count );
2068 sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2070 else
2072 barGoLink bar( result->GetRowCount() );
2076 Field* fields = result->Fetch();
2078 uint32 current_race = fields[0].GetUInt32();
2079 if(current_race >= MAX_RACES)
2081 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2082 continue;
2085 uint32 current_class = fields[1].GetUInt32();
2086 if(current_class >= MAX_CLASSES)
2088 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2089 continue;
2092 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2094 uint32 item_id = fields[2].GetUInt32();
2096 if(!GetItemPrototype(item_id))
2098 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);
2099 continue;
2102 uint32 amount = fields[3].GetUInt32();
2104 if(!amount)
2106 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2107 continue;
2110 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2112 bar.step();
2113 ++count;
2115 while(result->NextRow());
2117 delete result;
2119 sLog.outString();
2120 sLog.outString( ">> Loaded %u player create items", count );
2124 // Load playercreate spells
2126 // 0 1 2 3
2127 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2129 uint32 count = 0;
2131 if (!result)
2133 barGoLink bar( 1 );
2135 sLog.outString();
2136 sLog.outString( ">> Loaded %u player create spells", count );
2137 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2139 else
2141 barGoLink bar( result->GetRowCount() );
2145 Field* fields = result->Fetch();
2147 uint32 current_race = fields[0].GetUInt32();
2148 if(current_race >= MAX_RACES)
2150 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2151 continue;
2154 uint32 current_class = fields[1].GetUInt32();
2155 if(current_class >= MAX_CLASSES)
2157 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2158 continue;
2161 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2162 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2164 bar.step();
2165 ++count;
2167 while( result->NextRow() );
2169 delete result;
2171 sLog.outString();
2172 sLog.outString( ">> Loaded %u player create spells", count );
2176 // Load playercreate actions
2178 // 0 1 2 3 4 5
2179 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2181 uint32 count = 0;
2183 if (!result)
2185 barGoLink bar( 1 );
2187 sLog.outString();
2188 sLog.outString( ">> Loaded %u player create actions", count );
2189 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2191 else
2193 barGoLink bar( result->GetRowCount() );
2197 Field* fields = result->Fetch();
2199 uint32 current_race = fields[0].GetUInt32();
2200 if(current_race >= MAX_RACES)
2202 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2203 continue;
2206 uint32 current_class = fields[1].GetUInt32();
2207 if(current_class >= MAX_CLASSES)
2209 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2210 continue;
2213 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2214 pInfo->action[0].push_back(fields[2].GetUInt16());
2215 pInfo->action[1].push_back(fields[3].GetUInt16());
2216 pInfo->action[2].push_back(fields[4].GetUInt16());
2217 pInfo->action[3].push_back(fields[5].GetUInt16());
2219 bar.step();
2220 ++count;
2222 while( result->NextRow() );
2224 delete result;
2226 sLog.outString();
2227 sLog.outString( ">> Loaded %u player create actions", count );
2231 // Loading levels data (class only dependent)
2233 // 0 1 2 3
2234 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2236 uint32 count = 0;
2238 if (!result)
2240 barGoLink bar( 1 );
2242 sLog.outString();
2243 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2244 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2245 exit(1);
2248 barGoLink bar( result->GetRowCount() );
2252 Field* fields = result->Fetch();
2254 uint32 current_class = fields[0].GetUInt32();
2255 if(current_class >= MAX_CLASSES)
2257 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2258 continue;
2261 uint32 current_level = fields[1].GetUInt32();
2262 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2264 if(current_level > 255) // hardcoded level maximum
2265 sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2266 else
2267 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2268 continue;
2271 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2273 if(!pClassInfo->levelInfo)
2274 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2276 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2278 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2279 pClassLevelInfo->basemana = fields[3].GetUInt16();
2281 bar.step();
2282 ++count;
2284 while (result->NextRow());
2286 delete result;
2288 sLog.outString();
2289 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2292 // Fill gaps and check integrity
2293 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2295 // skip non existed classes
2296 if(!sChrClassesStore.LookupEntry(class_))
2297 continue;
2299 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2301 // fatal error if no level 1 data
2302 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2304 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2305 exit(1);
2308 // fill level gaps
2309 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2311 if(pClassInfo->levelInfo[level].basehealth == 0)
2313 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2314 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2319 // Loading levels data (class/race dependent)
2321 // 0 1 2 3 4 5 6 7
2322 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2324 uint32 count = 0;
2326 if (!result)
2328 barGoLink bar( 1 );
2330 sLog.outString();
2331 sLog.outString( ">> Loaded %u level stats definitions", count );
2332 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2333 exit(1);
2336 barGoLink bar( result->GetRowCount() );
2340 Field* fields = result->Fetch();
2342 uint32 current_race = fields[0].GetUInt32();
2343 if(current_race >= MAX_RACES)
2345 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2346 continue;
2349 uint32 current_class = fields[1].GetUInt32();
2350 if(current_class >= MAX_CLASSES)
2352 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2353 continue;
2356 uint32 current_level = fields[2].GetUInt32();
2357 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2359 if(current_level > 255) // hardcoded level maximum
2360 sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2361 else
2362 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2363 continue;
2366 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2368 if(!pInfo->levelInfo)
2369 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2371 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2373 for (int i = 0; i < MAX_STATS; i++)
2375 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2378 bar.step();
2379 ++count;
2381 while (result->NextRow());
2383 delete result;
2385 sLog.outString();
2386 sLog.outString( ">> Loaded %u level stats definitions", count );
2389 // Fill gaps and check integrity
2390 for (int race = 0; race < MAX_RACES; ++race)
2392 // skip non existed races
2393 if(!sChrRacesStore.LookupEntry(race))
2394 continue;
2396 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2398 // skip non existed classes
2399 if(!sChrClassesStore.LookupEntry(class_))
2400 continue;
2402 PlayerInfo* pInfo = &playerInfo[race][class_];
2404 // skip non loaded combinations
2405 if(!pInfo->displayId_m || !pInfo->displayId_f)
2406 continue;
2408 // skip expansion races if not playing with expansion
2409 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2410 continue;
2412 // skip expansion classes if not playing with expansion
2413 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2414 continue;
2416 // fatal error if no level 1 data
2417 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2419 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2420 exit(1);
2423 // fill level gaps
2424 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2426 if(pInfo->levelInfo[level].stats[0] == 0)
2428 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2429 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2436 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2438 if(level < 1 || class_ >= MAX_CLASSES)
2439 return;
2441 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2443 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2444 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2446 *info = pInfo->levelInfo[level-1];
2449 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2451 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2452 return;
2454 PlayerInfo const* pInfo = &playerInfo[race][class_];
2455 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2456 return;
2458 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2459 *info = pInfo->levelInfo[level-1];
2460 else
2461 BuildPlayerLevelInfo(race,class_,level,info);
2464 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2466 // base data (last known level)
2467 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2469 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2471 switch(_class)
2473 case CLASS_WARRIOR:
2474 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2475 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2476 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2477 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2478 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2479 break;
2480 case CLASS_PALADIN:
2481 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2482 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2483 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2484 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2485 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2486 break;
2487 case CLASS_HUNTER:
2488 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2489 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2490 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2491 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2492 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2493 break;
2494 case CLASS_ROGUE:
2495 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2496 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2497 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2498 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2499 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2500 break;
2501 case CLASS_PRIEST:
2502 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2503 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2504 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2505 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2506 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2507 break;
2508 case CLASS_SHAMAN:
2509 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2510 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2511 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2512 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2513 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2514 break;
2515 case CLASS_MAGE:
2516 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2517 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2518 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2519 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2520 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2521 break;
2522 case CLASS_WARLOCK:
2523 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2524 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2525 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2526 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2527 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2528 break;
2529 case CLASS_DRUID:
2530 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2531 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2532 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2533 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2534 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2539 void ObjectMgr::LoadGuilds()
2541 Guild *newguild;
2542 uint32 count = 0;
2544 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2546 if( !result )
2549 barGoLink bar( 1 );
2551 bar.step();
2553 sLog.outString();
2554 sLog.outString( ">> Loaded %u guild definitions", count );
2555 return;
2558 barGoLink bar( result->GetRowCount() );
2562 Field *fields = result->Fetch();
2564 bar.step();
2565 ++count;
2567 newguild = new Guild;
2568 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2570 newguild->Disband();
2571 delete newguild;
2572 continue;
2574 AddGuild(newguild);
2576 }while( result->NextRow() );
2578 delete result;
2580 sLog.outString();
2581 sLog.outString( ">> Loaded %u guild definitions", count );
2584 void ObjectMgr::LoadArenaTeams()
2586 uint32 count = 0;
2588 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2590 if( !result )
2593 barGoLink bar( 1 );
2595 bar.step();
2597 sLog.outString();
2598 sLog.outString( ">> Loaded %u arenateam definitions", count );
2599 return;
2602 barGoLink bar( result->GetRowCount() );
2606 Field *fields = result->Fetch();
2608 bar.step();
2609 ++count;
2611 ArenaTeam *newarenateam = new ArenaTeam;
2612 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2614 delete newarenateam;
2615 continue;
2617 AddArenaTeam(newarenateam);
2618 }while( result->NextRow() );
2620 delete result;
2622 sLog.outString();
2623 sLog.outString( ">> Loaded %u arenateam definitions", count );
2626 void ObjectMgr::LoadGroups()
2628 // -- loading groups --
2629 Group *group = NULL;
2630 uint64 leaderGuid = 0;
2631 uint32 count = 0;
2632 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2633 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2635 if( !result )
2637 barGoLink bar( 1 );
2639 bar.step();
2641 sLog.outString();
2642 sLog.outString( ">> Loaded %u group definitions", count );
2643 return;
2646 barGoLink bar( result->GetRowCount() );
2650 bar.step();
2651 Field *fields = result->Fetch();
2652 ++count;
2653 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2655 group = new Group;
2656 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2658 group->Disband();
2659 delete group;
2660 continue;
2662 AddGroup(group);
2663 }while( result->NextRow() );
2665 delete result;
2667 sLog.outString();
2668 sLog.outString( ">> Loaded %u group definitions", count );
2670 // -- loading members --
2671 count = 0;
2672 group = NULL;
2673 leaderGuid = 0;
2674 // 0 1 2 3
2675 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2676 if(!result)
2678 barGoLink bar( 1 );
2679 bar.step();
2681 else
2683 barGoLink bar( result->GetRowCount() );
2686 bar.step();
2687 Field *fields = result->Fetch();
2688 count++;
2689 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2690 if(!group || group->GetLeaderGUID() != leaderGuid)
2692 group = GetGroupByLeader(leaderGuid);
2693 if(!group)
2695 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2696 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2697 continue;
2701 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2703 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2704 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2706 }while( result->NextRow() );
2707 delete result;
2710 // clean groups
2711 // TODO: maybe delete from the DB before loading in this case
2712 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2714 if((*itr)->GetMembersCount() < 2)
2716 (*itr)->Disband();
2717 delete *itr;
2718 mGroupSet.erase(itr++);
2720 else
2721 ++itr;
2724 // -- loading instances --
2725 count = 0;
2726 group = NULL;
2727 leaderGuid = 0;
2728 result = CharacterDatabase.Query(
2729 // 0 1 2 3 4 5
2730 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2731 // 6
2732 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2733 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2736 if(!result)
2738 barGoLink bar( 1 );
2739 bar.step();
2741 else
2743 barGoLink bar( result->GetRowCount() );
2746 bar.step();
2747 Field *fields = result->Fetch();
2748 count++;
2749 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2750 if(!group || group->GetLeaderGUID() != leaderGuid)
2752 group = GetGroupByLeader(leaderGuid);
2753 if(!group)
2755 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2756 continue;
2760 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2761 group->BindToInstance(save, fields[3].GetBool(), true);
2762 }while( result->NextRow() );
2763 delete result;
2766 sLog.outString();
2767 sLog.outString( ">> Loaded %u group-instance binds total", count );
2769 sLog.outString();
2770 sLog.outString( ">> Loaded %u group members total", count );
2773 void ObjectMgr::LoadQuests()
2775 // For reload case
2776 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2777 delete itr->second;
2778 mQuestTemplates.clear();
2780 mExclusiveQuestGroups.clear();
2782 // 0 1 2 3 4 5 6 7 8
2783 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2784 // 9 10 11 12 13 14 15 16
2785 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2786 // 17 18 19 20 21 22 23 24 25 26
2787 "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2788 // 27 28 29 30 31 32 33 34 35 36
2789 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2790 // 37 38 39 40 41 42 43 44
2791 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2792 // 45 46 47 48 49 50 51 52 53 54 54 55
2793 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2794 // 57 58 59 60 61 62 63 64
2795 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2796 // 65 66 67 68
2797 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2798 // 69 70 71 72 73 74
2799 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2800 // 75 76 77 78 79 80
2801 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2802 // 81 82 83 84 85 86 87 88
2803 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2804 // 89 90 91 92 93 94 95 96 97 98
2805 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2806 // 99 100 101 102 103 104 105 106 107 108 109
2807 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2808 // 110 111 112 113 114 115 116 117 118 119
2809 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2810 // 120 121
2811 "StartScript, CompleteScript"
2812 " FROM quest_template");
2813 if(result == NULL)
2815 barGoLink bar( 1 );
2816 bar.step();
2818 sLog.outString();
2819 sLog.outString( ">> Loaded 0 quests definitions" );
2820 sLog.outErrorDb("`quest_template` table is empty!");
2821 return;
2824 // create multimap previous quest for each existed quest
2825 // some quests can have many previous maps set by NextQuestId in previous quest
2826 // for example set of race quests can lead to single not race specific quest
2827 barGoLink bar( result->GetRowCount() );
2830 bar.step();
2831 Field *fields = result->Fetch();
2833 Quest * newQuest = new Quest(fields);
2834 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2835 } while( result->NextRow() );
2837 delete result;
2839 // Post processing
2840 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2842 Quest * qinfo = iter->second;
2844 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2846 if( qinfo->GetQuestMethod() >= 3 )
2848 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2851 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2853 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2854 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2855 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2858 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2860 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2862 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2863 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2867 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2869 // at auto-reward can be rewarded only RewChoiceItemId[0]
2870 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2872 if(uint32 id = qinfo->RewChoiceItemId[j])
2874 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2875 qinfo->GetQuestId(),j+1,id,j+1);
2876 // no changes, quest ignore this data
2881 // client quest log visual (area case)
2882 if( qinfo->ZoneOrSort > 0 )
2884 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2886 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2887 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2888 // no changes, quest not dependent from this value but can have problems at client
2891 // client quest log visual (sort case)
2892 if( qinfo->ZoneOrSort < 0 )
2894 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2895 if( !qSort )
2897 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2898 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2899 // 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)
2901 //check SkillOrClass value (class case).
2902 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2904 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2905 if(qinfo->SkillOrClass < 0)
2907 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2908 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2911 //check for proper SkillOrClass value (skill case)
2912 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2914 // skill is positive value in SkillOrClass
2915 if(qinfo->SkillOrClass != skill_id )
2917 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2918 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2919 //override, and force proper value here?
2924 // SkillOrClass (class case)
2925 if( qinfo->SkillOrClass < 0 )
2927 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2929 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2930 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2933 // SkillOrClass (skill case)
2934 if( qinfo->SkillOrClass > 0 )
2936 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2938 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2939 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2943 if( qinfo->RequiredSkillValue )
2945 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2947 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2948 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2949 // no changes, quest can't be done for this requirement
2952 if( qinfo->SkillOrClass <= 0 )
2954 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2955 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2956 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2959 // else Skill quests can have 0 skill level, this is ok
2961 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2963 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2964 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2965 // no changes, quest can't be done for this requirement
2968 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2970 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2971 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2972 // no changes, quest can't be done for this requirement
2975 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2977 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2978 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2979 // no changes, quest can't be done for this requirement
2982 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2984 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2985 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2986 // no changes, quest can't be done for this requirement
2989 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2991 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2992 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2993 // no changes, quest can't be done for this requirement
2996 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2998 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2999 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3000 // warning
3003 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3005 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3006 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3007 // warning
3010 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3012 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3013 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3014 // warning
3017 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3019 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3020 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3021 qinfo->CharTitleId = 0;
3022 // quest can't reward this title
3025 if(qinfo->SrcItemId)
3027 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3029 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3030 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3031 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3033 else if(qinfo->SrcItemCount==0)
3035 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3036 qinfo->GetQuestId(),qinfo->SrcItemId);
3037 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3040 else if(qinfo->SrcItemCount>0)
3042 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3043 qinfo->GetQuestId(),qinfo->SrcItemCount);
3044 qinfo->SrcItemCount=0; // no quest work changes in fact
3047 if(qinfo->SrcSpell)
3049 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3050 if(!spellInfo)
3052 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3053 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3054 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3056 else if(!SpellMgr::IsSpellValid(spellInfo))
3058 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3059 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3060 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3064 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3066 uint32 id = qinfo->ReqItemId[j];
3067 if(id)
3069 if(qinfo->ReqItemCount[j]==0)
3071 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3072 qinfo->GetQuestId(),j+1,id,j+1);
3073 // no changes, quest can't be done for this requirement
3076 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3078 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3080 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3081 qinfo->GetQuestId(),j+1,id,id);
3082 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3085 else if(qinfo->ReqItemCount[j]>0)
3087 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3088 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3089 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3093 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3095 uint32 id = qinfo->ReqSourceId[j];
3096 if(id)
3098 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3100 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3101 qinfo->GetQuestId(),j+1,id,id);
3102 // no changes, quest can't be done for this requirement
3105 if(!qinfo->ReqSourceCount[j])
3107 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3108 qinfo->GetQuestId(),j+1,id,j+1);
3109 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3112 if(!qinfo->ReqSourceRef[j])
3114 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3115 qinfo->GetQuestId(),j+1,id,j+1);
3116 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3119 else
3121 if(qinfo->ReqSourceCount[j]>0)
3123 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3124 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3125 // no changes, quest ignore this data
3128 if(qinfo->ReqSourceRef[j]>0)
3130 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3131 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3132 // no changes, quest ignore this data
3137 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3139 uint32 ref = qinfo->ReqSourceRef[j];
3140 if(ref)
3142 if(ref > QUEST_OBJECTIVES_COUNT)
3144 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3145 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3146 // no changes, quest can't be done for this requirement
3148 else
3149 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3151 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3152 qinfo->GetQuestId(),j+1,ref,ref,ref);
3153 // no changes, quest can't be done for this requirement
3155 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3157 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3158 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3159 // no changes, quest can't be done for this requirement
3160 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3165 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3167 uint32 id = qinfo->ReqSpell[j];
3168 if(id)
3170 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3171 if(!spellInfo)
3173 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3174 qinfo->GetQuestId(),j+1,id,id);
3175 // no changes, quest can't be done for this requirement
3178 if(!qinfo->ReqCreatureOrGOId[j])
3180 bool found = false;
3181 for(int k = 0; k < 3; ++k)
3183 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3184 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3186 found = true;
3187 break;
3191 if(found)
3193 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3195 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);
3197 // this will prevent quest completing without objective
3198 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3201 else
3203 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.",
3204 qinfo->GetQuestId(),j+1,id,j+1,id);
3205 // no changes, quest can't be done for this requirement
3211 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3213 int32 id = qinfo->ReqCreatureOrGOId[j];
3214 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3216 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3217 qinfo->GetQuestId(),j+1,id,uint32(-id));
3218 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3221 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3223 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3224 qinfo->GetQuestId(),j+1,id,uint32(id));
3225 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3228 if(id)
3230 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3232 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3234 if(!qinfo->ReqCreatureOrGOCount[j])
3236 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3237 qinfo->GetQuestId(),j+1,id,j+1);
3238 // no changes, quest can be incorrectly done, but we already report this
3241 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3243 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3244 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3245 // no changes, quest ignore this data
3249 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3251 uint32 id = qinfo->RewChoiceItemId[j];
3252 if(id)
3254 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3256 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3257 qinfo->GetQuestId(),j+1,id,id);
3258 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3261 if(!qinfo->RewChoiceItemCount[j])
3263 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3264 qinfo->GetQuestId(),j+1,id,j+1);
3265 // no changes, quest can't be done
3268 else if(qinfo->RewChoiceItemCount[j]>0)
3270 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3271 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3272 // no changes, quest ignore this data
3276 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3278 uint32 id = qinfo->RewItemId[j];
3279 if(id)
3281 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3283 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3284 qinfo->GetQuestId(),j+1,id,id);
3285 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3288 if(!qinfo->RewItemCount[j])
3290 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3291 qinfo->GetQuestId(),j+1,id,j+1);
3292 // no changes
3295 else if(qinfo->RewItemCount[j]>0)
3297 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3298 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3299 // no changes, quest ignore this data
3303 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3305 if(qinfo->RewRepFaction[j])
3307 if(!qinfo->RewRepValue[j])
3309 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3310 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3311 // no changes
3314 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3316 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.",
3317 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3318 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3321 else if(qinfo->RewRepValue[j]!=0)
3323 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3324 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3325 // no changes, quest ignore this data
3329 if(qinfo->RewSpell)
3331 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3333 if(!spellInfo)
3335 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3336 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3337 qinfo->RewSpell = 0; // no spell reward will display for this quest
3340 else if(!SpellMgr::IsSpellValid(spellInfo))
3342 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3343 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3344 qinfo->RewSpell = 0; // no spell reward will display for this quest
3349 if(qinfo->RewSpellCast)
3351 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3353 if(!spellInfo)
3355 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3356 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3357 qinfo->RewSpellCast = 0; // no spell will be casted on player
3360 else if(!SpellMgr::IsSpellValid(spellInfo))
3362 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3363 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3364 qinfo->RewSpellCast = 0; // no spell will be casted on player
3369 if(qinfo->RewMailTemplateId)
3371 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3373 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3374 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3375 qinfo->RewMailTemplateId = 0; // no mail will send to player
3376 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3380 if(qinfo->NextQuestInChain)
3382 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3384 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3385 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3386 qinfo->NextQuestInChain = 0;
3388 else
3389 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3392 // fill additional data stores
3393 if(qinfo->PrevQuestId)
3395 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3397 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3399 else
3401 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3405 if(qinfo->NextQuestId)
3407 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3409 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3411 else
3413 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3414 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3418 if(qinfo->ExclusiveGroup)
3419 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3420 if(qinfo->LimitTime)
3421 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3424 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3425 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3427 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3428 if(!spellInfo)
3429 continue;
3431 for(int j = 0; j < 3; ++j)
3433 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3434 continue;
3436 uint32 quest_id = spellInfo->EffectMiscValue[j];
3438 Quest const* quest = GetQuestTemplate(quest_id);
3440 // some quest referenced in spells not exist (outdated spells)
3441 if(!quest)
3442 continue;
3444 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3446 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);
3448 // this will prevent quest completing without objective
3449 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3454 sLog.outString();
3455 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3458 void ObjectMgr::LoadQuestLocales()
3460 mQuestLocaleMap.clear(); // need for reload case
3462 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3463 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3464 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3465 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3466 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3467 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3468 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3469 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3470 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3471 " FROM locales_quest"
3474 if(!result)
3476 barGoLink bar(1);
3478 bar.step();
3480 sLog.outString("");
3481 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3482 return;
3485 barGoLink bar(result->GetRowCount());
3489 Field *fields = result->Fetch();
3490 bar.step();
3492 uint32 entry = fields[0].GetUInt32();
3494 QuestLocale& data = mQuestLocaleMap[entry];
3496 for(int i = 1; i < MAX_LOCALE; ++i)
3498 std::string str = fields[1+10*(i-1)].GetCppString();
3499 if(!str.empty())
3501 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3502 if(idx >= 0)
3504 if(data.Title.size() <= idx)
3505 data.Title.resize(idx+1);
3507 data.Title[idx] = str;
3510 str = fields[1+10*(i-1)+1].GetCppString();
3511 if(!str.empty())
3513 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3514 if(idx >= 0)
3516 if(data.Details.size() <= idx)
3517 data.Details.resize(idx+1);
3519 data.Details[idx] = str;
3522 str = fields[1+10*(i-1)+2].GetCppString();
3523 if(!str.empty())
3525 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3526 if(idx >= 0)
3528 if(data.Objectives.size() <= idx)
3529 data.Objectives.resize(idx+1);
3531 data.Objectives[idx] = str;
3534 str = fields[1+10*(i-1)+3].GetCppString();
3535 if(!str.empty())
3537 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3538 if(idx >= 0)
3540 if(data.OfferRewardText.size() <= idx)
3541 data.OfferRewardText.resize(idx+1);
3543 data.OfferRewardText[idx] = str;
3546 str = fields[1+10*(i-1)+4].GetCppString();
3547 if(!str.empty())
3549 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3550 if(idx >= 0)
3552 if(data.RequestItemsText.size() <= idx)
3553 data.RequestItemsText.resize(idx+1);
3555 data.RequestItemsText[idx] = str;
3558 str = fields[1+10*(i-1)+5].GetCppString();
3559 if(!str.empty())
3561 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3562 if(idx >= 0)
3564 if(data.EndText.size() <= idx)
3565 data.EndText.resize(idx+1);
3567 data.EndText[idx] = str;
3570 for(int k = 0; k < 4; ++k)
3572 str = fields[1+10*(i-1)+6+k].GetCppString();
3573 if(!str.empty())
3575 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3576 if(idx >= 0)
3578 if(data.ObjectiveText[k].size() <= idx)
3579 data.ObjectiveText[k].resize(idx+1);
3581 data.ObjectiveText[k][idx] = str;
3586 } while (result->NextRow());
3588 delete result;
3590 sLog.outString();
3591 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3594 void ObjectMgr::LoadPetCreateSpells()
3596 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3597 if(!result)
3599 barGoLink bar( 1 );
3600 bar.step();
3602 sLog.outString();
3603 sLog.outString( ">> Loaded 0 pet create spells" );
3604 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3605 return;
3608 uint32 count = 0;
3610 barGoLink bar( result->GetRowCount() );
3612 mPetCreateSpell.clear();
3616 Field *fields = result->Fetch();
3617 bar.step();
3619 uint32 creature_id = fields[0].GetUInt32();
3621 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3622 continue;
3624 PetCreateSpellEntry PetCreateSpell;
3625 for(int i = 0; i < 4; i++)
3627 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3629 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3630 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3633 mPetCreateSpell[creature_id] = PetCreateSpell;
3635 ++count;
3637 while (result->NextRow());
3639 delete result;
3641 sLog.outString();
3642 sLog.outString( ">> Loaded %u pet create spells", count );
3645 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3647 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3648 return;
3650 sLog.outString( "%s :", tablename);
3652 scripts.clear(); // need for reload support
3654 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3656 uint32 count = 0;
3658 if( !result )
3660 barGoLink bar( 1 );
3661 bar.step();
3663 sLog.outString();
3664 sLog.outString( ">> Loaded %u script definitions", count );
3665 return;
3668 barGoLink bar( result->GetRowCount() );
3672 bar.step();
3674 Field *fields = result->Fetch();
3675 ScriptInfo tmp;
3676 tmp.id = fields[0].GetUInt32();
3677 tmp.delay = fields[1].GetUInt32();
3678 tmp.command = fields[2].GetUInt32();
3679 tmp.datalong = fields[3].GetUInt32();
3680 tmp.datalong2 = fields[4].GetUInt32();
3681 tmp.dataint = fields[5].GetInt32();
3682 tmp.x = fields[6].GetFloat();
3683 tmp.y = fields[7].GetFloat();
3684 tmp.z = fields[8].GetFloat();
3685 tmp.o = fields[9].GetFloat();
3687 // generic command args check
3688 switch(tmp.command)
3690 case SCRIPT_COMMAND_TALK:
3692 if(tmp.datalong > 3)
3694 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3695 continue;
3697 if(tmp.dataint==0)
3699 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3700 continue;
3702 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3704 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);
3705 continue;
3707 if(!objmgr.GetMangosStringLocale(tmp.dataint))
3709 sLog.outErrorDb("Table `%s` has not existed text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3710 continue;
3712 break;
3715 case SCRIPT_COMMAND_TELEPORT_TO:
3717 if(!sMapStore.LookupEntry(tmp.datalong))
3719 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3720 continue;
3723 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3725 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);
3726 continue;
3728 break;
3731 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3733 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3735 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);
3736 continue;
3739 if(!GetCreatureTemplate(tmp.datalong))
3741 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3742 continue;
3744 break;
3747 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3749 GameObjectData const* data = GetGOData(tmp.datalong);
3750 if(!data)
3752 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3753 continue;
3756 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3757 if(!info)
3759 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);
3760 continue;
3763 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3764 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3765 info->type==GAMEOBJECT_TYPE_DOOR ||
3766 info->type==GAMEOBJECT_TYPE_BUTTON ||
3767 info->type==GAMEOBJECT_TYPE_TRAP )
3769 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3770 continue;
3772 break;
3774 case SCRIPT_COMMAND_OPEN_DOOR:
3775 case SCRIPT_COMMAND_CLOSE_DOOR:
3777 GameObjectData const* data = GetGOData(tmp.datalong);
3778 if(!data)
3780 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);
3781 continue;
3784 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3785 if(!info)
3787 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);
3788 continue;
3791 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3793 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);
3794 continue;
3797 break;
3799 case SCRIPT_COMMAND_QUEST_EXPLORED:
3801 Quest const* quest = GetQuestTemplate(tmp.datalong);
3802 if(!quest)
3804 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);
3805 continue;
3808 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3810 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);
3812 // this will prevent quest completing without objective
3813 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3815 // continue; - quest objective requirement set and command can be allowed
3818 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3820 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",
3821 tablename,tmp.datalong2,tmp.id);
3822 continue;
3825 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3827 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",
3828 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3829 continue;
3832 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3834 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",
3835 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3836 continue;
3839 break;
3842 case SCRIPT_COMMAND_REMOVE_AURA:
3843 case SCRIPT_COMMAND_CAST_SPELL:
3845 if(!sSpellStore.LookupEntry(tmp.datalong))
3847 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3848 tablename,tmp.datalong,tmp.id);
3849 continue;
3851 break;
3855 if (scripts.find(tmp.id) == scripts.end())
3857 ScriptMap emptyMap;
3858 scripts[tmp.id] = emptyMap;
3860 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3862 ++count;
3863 } while( result->NextRow() );
3865 delete result;
3867 sLog.outString();
3868 sLog.outString( ">> Loaded %u script definitions", count );
3871 void ObjectMgr::LoadGameObjectScripts()
3873 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3875 // check ids
3876 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3878 if(!GetGOData(itr->first))
3879 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3883 void ObjectMgr::LoadQuestEndScripts()
3885 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3887 // check ids
3888 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3890 if(!GetQuestTemplate(itr->first))
3891 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3895 void ObjectMgr::LoadQuestStartScripts()
3897 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3899 // check ids
3900 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3902 if(!GetQuestTemplate(itr->first))
3903 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3907 void ObjectMgr::LoadSpellScripts()
3909 LoadScripts(sSpellScripts, "spell_scripts");
3911 // check ids
3912 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3914 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3916 if(!spellInfo)
3918 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3919 continue;
3922 //check for correct spellEffect
3923 bool found = false;
3924 for(int i=0; i<3; ++i)
3926 // skip empty effects
3927 if( !spellInfo->Effect[i] )
3928 continue;
3930 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3932 found = true;
3933 break;
3937 if(!found)
3938 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3942 void ObjectMgr::LoadEventScripts()
3944 LoadScripts(sEventScripts, "event_scripts");
3946 std::set<uint32> evt_scripts;
3947 // Load all possible script entries from gameobjects
3948 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3950 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3951 if (goInfo)
3953 switch(goInfo->type)
3955 case GAMEOBJECT_TYPE_GOOBER:
3956 if(goInfo->goober.eventId)
3957 evt_scripts.insert(goInfo->goober.eventId);
3958 break;
3959 case GAMEOBJECT_TYPE_CHEST:
3960 if(goInfo->chest.eventId)
3961 evt_scripts.insert(goInfo->chest.eventId);
3962 break;
3963 default:
3964 break;
3968 // Load all possible script entries from spells
3969 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3971 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3972 if (spell)
3974 for(int j=0; j<3; ++j)
3976 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3978 if (spell->EffectMiscValue[j])
3979 evt_scripts.insert(spell->EffectMiscValue[j]);
3984 // Then check if all scripts are in above list of possible script entries
3985 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3987 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3988 if (itr2 == evt_scripts.end())
3989 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);
3993 void ObjectMgr::LoadItemTexts()
3995 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3997 uint32 count = 0;
3999 if( !result )
4001 barGoLink bar( 1 );
4002 bar.step();
4004 sLog.outString();
4005 sLog.outString( ">> Loaded %u item pages", count );
4006 return;
4009 barGoLink bar( result->GetRowCount() );
4011 Field* fields;
4014 bar.step();
4016 fields = result->Fetch();
4018 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4020 ++count;
4022 } while ( result->NextRow() );
4024 delete result;
4026 sLog.outString();
4027 sLog.outString( ">> Loaded %u item texts", count );
4030 void ObjectMgr::LoadPageTexts()
4032 sPageTextStore.Free(); // for reload case
4034 sPageTextStore.Load();
4035 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4036 sLog.outString();
4038 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4040 // check data correctness
4041 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4042 if(!page)
4043 continue;
4045 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4047 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4048 continue;
4051 // detect circular reference
4052 std::set<uint32> checkedPages;
4053 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4055 if(!pageItr->Next_Page)
4056 break;
4057 checkedPages.insert(pageItr->Page_ID);
4058 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4060 std::ostringstream ss;
4061 ss<< "The text page(s) ";
4062 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
4063 ss << *itr << " ";
4064 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4065 << pageItr->Page_ID <<" to 0";
4066 sLog.outErrorDb(ss.str().c_str());
4067 const_cast<PageText*>(pageItr)->Next_Page = 0;
4068 break;
4074 void ObjectMgr::LoadPageTextLocales()
4076 mPageTextLocaleMap.clear(); // need for reload case
4078 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");
4080 if(!result)
4082 barGoLink bar(1);
4084 bar.step();
4086 sLog.outString("");
4087 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4088 return;
4091 barGoLink bar(result->GetRowCount());
4095 Field *fields = result->Fetch();
4096 bar.step();
4098 uint32 entry = fields[0].GetUInt32();
4100 PageTextLocale& data = mPageTextLocaleMap[entry];
4102 for(int i = 1; i < MAX_LOCALE; ++i)
4104 std::string str = fields[i].GetCppString();
4105 if(str.empty())
4106 continue;
4108 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4109 if(idx >= 0)
4111 if(data.Text.size() <= idx)
4112 data.Text.resize(idx+1);
4114 data.Text[idx] = str;
4118 } while (result->NextRow());
4120 delete result;
4122 sLog.outString();
4123 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4126 void ObjectMgr::LoadInstanceTemplate()
4128 sInstanceTemplate.Load();
4130 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4132 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4133 if(!temp) continue;
4134 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4135 if(!entry)
4137 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4138 continue;
4140 else if(!entry->HasResetTime())
4141 continue;
4143 if(temp->reset_delay == 0)
4145 // use defaults from the DBC
4146 if(entry->SupportsHeroicMode())
4148 temp->reset_delay = entry->resetTimeHeroic / DAY;
4150 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4152 temp->reset_delay = entry->resetTimeRaid / DAY;
4156 // the reset_delay must be at least one day
4157 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4160 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4161 sLog.outString();
4164 void ObjectMgr::AddGossipText(GossipText *pGText)
4166 ASSERT( pGText->Text_ID );
4167 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4168 mGossipText[pGText->Text_ID] = pGText;
4171 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4173 GossipTextMap::const_iterator itr;
4174 for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4176 if(itr->second->Text_ID == Text_ID)
4177 return itr->second;
4179 return NULL;
4182 void ObjectMgr::LoadGossipText()
4184 GossipText *pGText;
4185 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4187 int count = 0;
4188 if( !result )
4190 barGoLink bar( 1 );
4191 bar.step();
4193 sLog.outString();
4194 sLog.outString( ">> Loaded %u npc texts", count );
4195 return;
4198 int cic;
4200 barGoLink bar( result->GetRowCount() );
4204 ++count;
4205 cic = 0;
4207 Field *fields = result->Fetch();
4209 bar.step();
4211 pGText = new GossipText;
4212 pGText->Text_ID = fields[cic++].GetUInt32();
4214 for (int i=0; i< 8; i++)
4216 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4217 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4219 pGText->Options[i].Language = fields[cic++].GetUInt32();
4220 pGText->Options[i].Probability = fields[cic++].GetFloat();
4222 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4223 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4225 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4226 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4228 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4229 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4232 if ( !pGText->Text_ID ) continue;
4233 AddGossipText( pGText );
4235 } while( result->NextRow() );
4237 sLog.outString();
4238 sLog.outString( ">> Loaded %u npc texts", count );
4239 delete result;
4242 void ObjectMgr::LoadNpcTextLocales()
4244 mNpcTextLocaleMap.clear(); // need for reload case
4246 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4247 "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,"
4248 "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,"
4249 "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,"
4250 "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,"
4251 "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,"
4252 "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,"
4253 "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, "
4254 "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 "
4255 " FROM locales_npc_text");
4257 if(!result)
4259 barGoLink bar(1);
4261 bar.step();
4263 sLog.outString("");
4264 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4265 return;
4268 barGoLink bar(result->GetRowCount());
4272 Field *fields = result->Fetch();
4273 bar.step();
4275 uint32 entry = fields[0].GetUInt32();
4277 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4279 for(int i=1; i<MAX_LOCALE; ++i)
4281 for(int j=0; j<8; ++j)
4283 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4284 if(!str0.empty())
4286 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4287 if(idx >= 0)
4289 if(data.Text_0[j].size() <= idx)
4290 data.Text_0[j].resize(idx+1);
4292 data.Text_0[j][idx] = str0;
4295 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4296 if(!str1.empty())
4298 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4299 if(idx >= 0)
4301 if(data.Text_1[j].size() <= idx)
4302 data.Text_1[j].resize(idx+1);
4304 data.Text_1[j][idx] = str1;
4309 } while (result->NextRow());
4311 delete result;
4313 sLog.outString();
4314 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4317 //not very fast function but it is called only once a day, or on starting-up
4318 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4320 time_t basetime = time(NULL);
4321 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4322 //delete all old mails without item and without body immediately, if starting server
4323 if (!serverUp)
4324 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4325 // 0 1 2 3 4 5 6 7 8 9
4326 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);
4327 if ( !result )
4328 return; // any mails need to be returned or deleted
4329 Field *fields;
4330 //std::ostringstream delitems, delmails; //will be here for optimization
4331 //bool deletemail = false, deleteitem = false;
4332 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4333 //delmails << "DELETE FROM mail WHERE id IN ( "
4336 fields = result->Fetch();
4337 Mail *m = new Mail;
4338 m->messageID = fields[0].GetUInt32();
4339 m->messageType = fields[1].GetUInt8();
4340 m->sender = fields[2].GetUInt32();
4341 m->receiver = fields[3].GetUInt32();
4342 m->itemTextId = fields[4].GetUInt32();
4343 bool has_items = fields[5].GetBool();
4344 m->expire_time = (time_t)fields[6].GetUInt64();
4345 m->deliver_time = 0;
4346 m->COD = fields[7].GetUInt32();
4347 m->checked = fields[8].GetUInt32();
4348 m->mailTemplateId = fields[9].GetInt16();
4350 Player *pl = 0;
4351 if (serverUp)
4352 pl = GetPlayer((uint64)m->receiver);
4353 if (pl && pl->m_mailsLoaded)
4354 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4355 //his in mailbox and he has already listed his mails )
4356 delete m;
4357 continue;
4359 //delete or return mail:
4360 if (has_items)
4362 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4363 if(resultItems)
4367 Field *fields2 = resultItems->Fetch();
4369 uint32 item_guid_low = fields2[0].GetUInt32();
4370 uint32 item_template = fields2[1].GetUInt32();
4372 m->AddItem(item_guid_low, item_template);
4374 while (resultItems->NextRow());
4376 delete resultItems;
4378 //if it is mail from AH, it shouldn't be returned, but deleted
4379 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4381 // mail open and then not returned
4382 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4383 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4385 else
4387 //mail will be returned:
4388 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);
4389 delete m;
4390 continue;
4394 if (m->itemTextId)
4395 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4397 //deletemail = true;
4398 //delmails << m->messageID << ", ";
4399 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4400 delete m;
4401 } while (result->NextRow());
4402 delete result;
4405 void ObjectMgr::LoadQuestAreaTriggers()
4407 mQuestAreaTriggerMap.clear(); // need for reload case
4409 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4411 uint32 count = 0;
4413 if( !result )
4415 barGoLink bar( 1 );
4416 bar.step();
4418 sLog.outString();
4419 sLog.outString( ">> Loaded %u quest trigger points", count );
4420 return;
4423 barGoLink bar( result->GetRowCount() );
4427 ++count;
4428 bar.step();
4430 Field *fields = result->Fetch();
4432 uint32 trigger_ID = fields[0].GetUInt32();
4433 uint32 quest_ID = fields[1].GetUInt32();
4435 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4436 if(!atEntry)
4438 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4439 continue;
4442 Quest const* quest = GetQuestTemplate(quest_ID);
4444 if(!quest)
4446 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4447 continue;
4450 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4452 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);
4454 // this will prevent quest completing without objective
4455 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4457 // continue; - quest modified to required objective and trigger can be allowed.
4460 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4462 } while( result->NextRow() );
4464 delete result;
4466 sLog.outString();
4467 sLog.outString( ">> Loaded %u quest trigger points", count );
4470 void ObjectMgr::LoadTavernAreaTriggers()
4472 mTavernAreaTriggerSet.clear(); // need for reload case
4474 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4476 uint32 count = 0;
4478 if( !result )
4480 barGoLink bar( 1 );
4481 bar.step();
4483 sLog.outString();
4484 sLog.outString( ">> Loaded %u tavern triggers", count );
4485 return;
4488 barGoLink bar( result->GetRowCount() );
4492 ++count;
4493 bar.step();
4495 Field *fields = result->Fetch();
4497 uint32 Trigger_ID = fields[0].GetUInt32();
4499 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4500 if(!atEntry)
4502 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4503 continue;
4506 mTavernAreaTriggerSet.insert(Trigger_ID);
4507 } while( result->NextRow() );
4509 delete result;
4511 sLog.outString();
4512 sLog.outString( ">> Loaded %u tavern triggers", count );
4515 void ObjectMgr::LoadAreaTriggerScripts()
4517 mAreaTriggerScripts.clear(); // need for reload case
4518 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4520 uint32 count = 0;
4522 if( !result )
4524 barGoLink bar( 1 );
4525 bar.step();
4527 sLog.outString();
4528 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4529 return;
4532 barGoLink bar( result->GetRowCount() );
4536 ++count;
4537 bar.step();
4539 Field *fields = result->Fetch();
4541 uint32 Trigger_ID = fields[0].GetUInt32();
4542 std::string scriptName = fields[1].GetCppString();
4544 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4545 if(!atEntry)
4547 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4548 continue;
4550 mAreaTriggerScripts[Trigger_ID] = scriptName;
4551 } while( result->NextRow() );
4553 delete result;
4555 sLog.outString();
4556 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4559 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4561 bool found = false;
4562 float dist;
4563 uint32 id = 0;
4565 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4567 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4568 if(node && node->map_id == mapid)
4570 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4571 if(found)
4573 if(dist2 < dist)
4575 dist = dist2;
4576 id = i;
4579 else
4581 found = true;
4582 dist = dist2;
4583 id = i;
4588 return id;
4591 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4593 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4594 if(src_i==sTaxiPathSetBySource.end())
4596 path = 0;
4597 cost = 0;
4598 return;
4601 TaxiPathSetForSource& pathSet = src_i->second;
4603 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4604 if(dest_i==pathSet.end())
4606 path = 0;
4607 cost = 0;
4608 return;
4611 cost = dest_i->second.price;
4612 path = dest_i->second.ID;
4615 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4617 uint16 mount_entry = 0;
4618 uint16 mount_id = 0;
4620 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4621 if(node)
4623 if (team == ALLIANCE)
4625 mount_entry = node->alliance_mount_type;
4626 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4627 if(ci)
4628 mount_id = ci->DisplayID_A;
4630 if (team == HORDE)
4632 mount_entry = node->horde_mount_type;
4633 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4634 if(ci)
4635 mount_id = ci->DisplayID_H;
4639 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4640 if(!minfo)
4642 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. ",
4643 mount_entry,id,team,mount_id);
4645 return false;
4647 if(minfo->modelid_other_gender!=0)
4648 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4650 return mount_id;
4653 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4655 if(path >= sTaxiPathNodesByPath.size())
4656 return;
4658 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4660 pathnodes.Resize(nodeList.size());
4661 mapIds.resize(nodeList.size());
4663 for(size_t i = 0; i < nodeList.size(); ++i)
4665 pathnodes[ i ].x = nodeList[i].x;
4666 pathnodes[ i ].y = nodeList[i].y;
4667 pathnodes[ i ].z = nodeList[i].z;
4669 mapIds[i] = nodeList[i].mapid;
4673 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4675 if(path >= sTaxiPathNodesByPath.size())
4676 return;
4678 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4680 pathnodes.Resize(nodeList.size());
4682 for(size_t i = 0; i < nodeList.size(); ++i)
4684 pathnodes[ i ].mapid = nodeList[i].mapid;
4685 pathnodes[ i ].x = nodeList[i].x;
4686 pathnodes[ i ].y = nodeList[i].y;
4687 pathnodes[ i ].z = nodeList[i].z;
4688 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4689 pathnodes[ i ].delay = nodeList[i].delay;
4693 void ObjectMgr::LoadGraveyardZones()
4695 mGraveYardMap.clear(); // need for reload case
4697 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4699 uint32 count = 0;
4701 if( !result )
4703 barGoLink bar( 1 );
4704 bar.step();
4706 sLog.outString();
4707 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4708 return;
4711 barGoLink bar( result->GetRowCount() );
4715 ++count;
4716 bar.step();
4718 Field *fields = result->Fetch();
4720 uint32 safeLocId = fields[0].GetUInt32();
4721 uint32 zoneId = fields[1].GetUInt32();
4722 uint32 team = fields[2].GetUInt32();
4724 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4725 if(!entry)
4727 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4728 continue;
4731 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4732 if(!areaEntry)
4734 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4735 continue;
4738 if(areaEntry->zone != 0)
4740 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4741 continue;
4744 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4746 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4747 continue;
4750 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4751 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4752 } while( result->NextRow() );
4754 delete result;
4756 sLog.outString();
4757 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4760 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4762 // search for zone associated closest graveyard
4763 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4765 // Simulate std. algorithm:
4766 // found some graveyard associated to (ghost_zone,ghost_map)
4768 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4769 // then check faction
4770 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4771 // then check faction
4772 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4773 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4774 if(graveLow==graveUp)
4776 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4777 return NULL;
4780 // at corpse map
4781 bool foundNear = false;
4782 float distNear;
4783 WorldSafeLocsEntry const* entryNear = NULL;
4785 // at entrance map for corpse map
4786 bool foundEntr = false;
4787 float distEntr;
4788 WorldSafeLocsEntry const* entryEntr = NULL;
4790 // some where other
4791 WorldSafeLocsEntry const* entryFar = NULL;
4793 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4795 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4797 GraveYardData const& data = itr->second;
4799 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4800 if(!entry)
4802 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4803 continue;
4806 // skip enemy faction graveyard
4807 // team == 0 case can be at call from .neargrave
4808 if(data.team != 0 && team != 0 && data.team != team)
4809 continue;
4811 // find now nearest graveyard at other map
4812 if(MapId != entry->map_id)
4814 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4815 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4816 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4818 // not have any corrdinates for check distance anyway
4819 entryFar = entry;
4820 continue;
4823 // at entrance map calculate distance (2D);
4824 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4825 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4826 if(foundEntr)
4828 if(dist2 < distEntr)
4830 distEntr = dist2;
4831 entryEntr = entry;
4834 else
4836 foundEntr = true;
4837 distEntr = dist2;
4838 entryEntr = entry;
4841 // find now nearest graveyard at same map
4842 else
4844 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4845 if(foundNear)
4847 if(dist2 < distNear)
4849 distNear = dist2;
4850 entryNear = entry;
4853 else
4855 foundNear = true;
4856 distNear = dist2;
4857 entryNear = entry;
4862 if(entryNear)
4863 return entryNear;
4865 if(entryEntr)
4866 return entryEntr;
4868 return entryFar;
4871 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4873 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4874 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4876 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4878 if(itr->second.safeLocId==id)
4879 return &itr->second;
4882 return NULL;
4885 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4887 if(FindGraveYardData(id,zoneId))
4888 return false;
4890 // add link to loaded data
4891 GraveYardData data;
4892 data.safeLocId = id;
4893 data.team = team;
4895 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4897 // add link to DB
4898 if(inDB)
4900 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4901 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4904 return true;
4907 void ObjectMgr::LoadAreaTriggerTeleports()
4909 mAreaTriggers.clear(); // need for reload case
4911 uint32 count = 0;
4913 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4914 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");
4915 if( !result )
4918 barGoLink bar( 1 );
4920 bar.step();
4922 sLog.outString();
4923 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4924 return;
4927 barGoLink bar( result->GetRowCount() );
4931 Field *fields = result->Fetch();
4933 bar.step();
4935 ++count;
4937 uint32 Trigger_ID = fields[0].GetUInt32();
4939 AreaTrigger at;
4941 at.requiredLevel = fields[1].GetUInt8();
4942 at.requiredItem = fields[2].GetUInt32();
4943 at.requiredItem2 = fields[3].GetUInt32();
4944 at.heroicKey = fields[4].GetUInt32();
4945 at.heroicKey2 = fields[5].GetUInt32();
4946 at.requiredQuest = fields[6].GetUInt32();
4947 at.requiredFailedText = fields[7].GetCppString();
4948 at.target_mapId = fields[8].GetUInt32();
4949 at.target_X = fields[9].GetFloat();
4950 at.target_Y = fields[10].GetFloat();
4951 at.target_Z = fields[11].GetFloat();
4952 at.target_Orientation = fields[12].GetFloat();
4954 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4955 if(!atEntry)
4957 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4958 continue;
4961 if(at.requiredItem)
4963 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4964 if(!pProto)
4966 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4967 at.requiredItem = 0;
4970 if(at.requiredItem2)
4972 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4973 if(!pProto)
4975 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4976 at.requiredItem2 = 0;
4980 if(at.heroicKey)
4982 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4983 if(!pProto)
4985 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4986 at.heroicKey = 0;
4990 if(at.heroicKey2)
4992 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4993 if(!pProto)
4995 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4996 at.heroicKey2 = 0;
5000 if(at.requiredQuest)
5002 if(!mQuestTemplates[at.requiredQuest])
5004 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5005 at.requiredQuest = 0;
5009 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5010 if(!mapEntry)
5012 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5013 continue;
5016 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5018 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5019 continue;
5022 mAreaTriggers[Trigger_ID] = at;
5024 } while( result->NextRow() );
5026 delete result;
5028 sLog.outString();
5029 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5032 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5034 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5035 if(!mapEntry) return NULL;
5036 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
5038 if(itr->second.target_mapId == mapEntry->entrance_map)
5040 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5041 if(atEntry && atEntry->mapid == Map)
5042 return &itr->second;
5045 return NULL;
5048 void ObjectMgr::SetHighestGuids()
5050 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5051 if( result )
5053 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5055 delete result;
5058 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5059 if( result )
5061 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5063 delete result;
5066 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5067 m_hiPetGuid = 0;
5069 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5070 if( result )
5072 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5074 delete result;
5077 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5078 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5079 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5080 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5081 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5083 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5084 if( result )
5086 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5088 delete result;
5091 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5092 if( result )
5094 m_auctionid = (*result)[0].GetUInt32()+1;
5096 delete result;
5098 else
5100 m_auctionid = 0;
5102 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5103 if( result )
5105 m_mailid = (*result)[0].GetUInt32()+1;
5107 delete result;
5109 else
5111 m_mailid = 0;
5113 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5114 if( result )
5116 m_ItemTextId = (*result)[0].GetUInt32();
5118 delete result;
5120 else
5121 m_ItemTextId = 0;
5123 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5124 if( result )
5126 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5128 delete result;
5131 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5132 if (result)
5134 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5136 delete result;
5139 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5140 if (result)
5142 m_guildId = (*result)[0].GetUInt32()+1;
5144 delete result;
5148 uint32 ObjectMgr::GenerateArenaTeamId()
5150 ++m_arenaTeamId;
5151 if(m_arenaTeamId>=0xFFFFFFFF)
5153 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5154 sWorld.m_stopEvent = true;
5156 return m_arenaTeamId;
5159 uint32 ObjectMgr::GenerateGuildId()
5161 ++m_guildId;
5162 if(m_guildId>=0xFFFFFFFF)
5164 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5165 sWorld.m_stopEvent = true;
5167 return m_guildId;
5170 uint32 ObjectMgr::GenerateAuctionID()
5172 ++m_auctionid;
5173 if(m_auctionid>=0xFFFFFFFF)
5175 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5176 sWorld.m_stopEvent = true;
5178 return m_auctionid;
5181 uint32 ObjectMgr::GenerateMailID()
5183 ++m_mailid;
5184 if(m_mailid>=0xFFFFFFFF)
5186 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5187 sWorld.m_stopEvent = true;
5189 return m_mailid;
5192 uint32 ObjectMgr::GenerateItemTextID()
5194 ++m_ItemTextId;
5195 if(m_ItemTextId>=0xFFFFFFFF)
5197 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5198 sWorld.m_stopEvent = true;
5200 return m_ItemTextId;
5203 uint32 ObjectMgr::CreateItemText(std::string text)
5205 uint32 newItemTextId = GenerateItemTextID();
5206 //insert new itempage to container
5207 mItemTexts[ newItemTextId ] = text;
5208 //save new itempage
5209 CharacterDatabase.escape_string(text);
5210 //any Delete query needed, itemTextId is maximum of all ids
5211 std::ostringstream query;
5212 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5213 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5214 return newItemTextId;
5217 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5219 switch(guidhigh)
5221 case HIGHGUID_ITEM:
5222 ++m_hiItemGuid;
5223 if(m_hiItemGuid>=0xFFFFFFFF)
5225 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5226 sWorld.m_stopEvent = true;
5228 return m_hiItemGuid;
5229 case HIGHGUID_UNIT:
5230 ++m_hiCreatureGuid;
5231 if(m_hiCreatureGuid>=0x00FFFFFF)
5233 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5234 sWorld.m_stopEvent = true;
5236 return m_hiCreatureGuid;
5237 case HIGHGUID_PET:
5238 ++m_hiPetGuid;
5239 if(m_hiPetGuid>=0x00FFFFFF)
5241 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5242 sWorld.m_stopEvent = true;
5244 return m_hiPetGuid;
5245 case HIGHGUID_PLAYER:
5246 ++m_hiCharGuid;
5247 if(m_hiCharGuid>=0xFFFFFFFF)
5249 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5250 sWorld.m_stopEvent = true;
5252 return m_hiCharGuid;
5253 case HIGHGUID_GAMEOBJECT:
5254 ++m_hiGoGuid;
5255 if(m_hiGoGuid>=0x00FFFFFF)
5257 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5258 sWorld.m_stopEvent = true;
5260 return m_hiGoGuid;
5261 case HIGHGUID_CORPSE:
5262 ++m_hiCorpseGuid;
5263 if(m_hiCorpseGuid>=0xFFFFFFFF)
5265 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5266 sWorld.m_stopEvent = true;
5268 return m_hiCorpseGuid;
5269 case HIGHGUID_DYNAMICOBJECT:
5270 ++m_hiDoGuid;
5271 if(m_hiDoGuid>=0xFFFFFFFF)
5273 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5274 sWorld.m_stopEvent = true;
5276 return m_hiDoGuid;
5277 default:
5278 ASSERT(0);
5281 ASSERT(0);
5282 return 0;
5285 void ObjectMgr::LoadGameObjectLocales()
5287 mGameObjectLocaleMap.clear(); // need for reload case
5289 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5290 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5291 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5292 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5294 if(!result)
5296 barGoLink bar(1);
5298 bar.step();
5300 sLog.outString("");
5301 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5302 return;
5305 barGoLink bar(result->GetRowCount());
5309 Field *fields = result->Fetch();
5310 bar.step();
5312 uint32 entry = fields[0].GetUInt32();
5314 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5316 for(int i = 1; i < MAX_LOCALE; ++i)
5318 std::string str = fields[i].GetCppString();
5319 if(!str.empty())
5321 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5322 if(idx >= 0)
5324 if(data.Name.size() <= idx)
5325 data.Name.resize(idx+1);
5327 data.Name[idx] = str;
5332 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5334 std::string str = fields[i].GetCppString();
5335 if(!str.empty())
5337 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5338 if(idx >= 0)
5340 if(data.CastBarCaption.size() <= idx)
5341 data.CastBarCaption.resize(idx+1);
5343 data.CastBarCaption[idx] = str;
5348 } while (result->NextRow());
5350 delete result;
5352 sLog.outString();
5353 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5356 void ObjectMgr::LoadGameobjectInfo()
5358 sGOStorage.Load();
5360 // some checks
5361 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5363 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5364 if(!goInfo)
5365 continue;
5367 switch(goInfo->type)
5369 case GAMEOBJECT_TYPE_DOOR: //0
5371 if(goInfo->door.lockId)
5373 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5374 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5375 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5377 break;
5379 case GAMEOBJECT_TYPE_BUTTON: //1
5381 if(goInfo->button.lockId)
5383 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5384 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5385 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5387 break;
5389 case GAMEOBJECT_TYPE_CHEST: //3
5391 if(goInfo->chest.lockId)
5393 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5394 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5395 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5397 if(goInfo->chest.linkedTrapId) // linked trap
5399 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5401 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5402 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5403 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5405 /* disable check for while
5406 else
5407 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5408 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5411 break;
5413 case GAMEOBJECT_TYPE_TRAP: //6
5415 /* disable check for while
5416 if(goInfo->trap.spellId) // spell
5418 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5419 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5420 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5423 break;
5425 case GAMEOBJECT_TYPE_CHAIR: //7
5426 if(goInfo->chair.height > 2)
5428 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5429 id,goInfo->type,goInfo->chair.height);
5431 // prevent client and server unexpected work
5432 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5434 break;
5435 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5437 if(goInfo->spellFocus.focusId)
5439 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5440 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5441 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5444 if(goInfo->spellFocus.linkedTrapId) // linked trap
5446 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5448 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5449 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5450 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5452 /* disable check for while
5453 else
5454 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5455 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5458 break;
5460 case GAMEOBJECT_TYPE_GOOBER: //10
5462 if(goInfo->goober.pageId) // pageId
5464 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5465 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5466 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5468 /* disable check for while
5469 if(goInfo->goober.spellId) // spell
5471 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5472 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5473 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5476 if(goInfo->goober.linkedTrapId) // linked trap
5478 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5480 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5481 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5482 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5484 /* disable check for while
5485 else
5486 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5487 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5490 break;
5492 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5494 if(goInfo->moTransport.taxiPathId)
5496 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5497 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5498 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5500 break;
5502 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5504 /* disabled
5505 if(goInfo->summoningRitual.spellId)
5507 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5508 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5509 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5512 break;
5514 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5516 if(goInfo->spellcaster.spellId) // spell
5518 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5519 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5520 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5522 break;
5527 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5528 sLog.outString();
5531 void ObjectMgr::LoadExplorationBaseXP()
5533 uint32 count = 0;
5534 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5536 if( !result )
5538 barGoLink bar( 1 );
5540 bar.step();
5542 sLog.outString();
5543 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5544 return;
5547 barGoLink bar( result->GetRowCount() );
5551 bar.step();
5553 Field *fields = result->Fetch();
5554 uint32 level = fields[0].GetUInt32();
5555 uint32 basexp = fields[1].GetUInt32();
5556 mBaseXPTable[level] = basexp;
5557 ++count;
5559 while (result->NextRow());
5561 delete result;
5563 sLog.outString();
5564 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5567 uint32 ObjectMgr::GetBaseXP(uint32 level)
5569 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5572 void ObjectMgr::LoadPetNames()
5574 uint32 count = 0;
5575 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5577 if( !result )
5579 barGoLink bar( 1 );
5581 bar.step();
5583 sLog.outString();
5584 sLog.outString( ">> Loaded %u pet name parts", count );
5585 return;
5588 barGoLink bar( result->GetRowCount() );
5592 bar.step();
5594 Field *fields = result->Fetch();
5595 std::string word = fields[0].GetString();
5596 uint32 entry = fields[1].GetUInt32();
5597 bool half = fields[2].GetBool();
5598 if(half)
5599 PetHalfName1[entry].push_back(word);
5600 else
5601 PetHalfName0[entry].push_back(word);
5602 ++count;
5604 while (result->NextRow());
5605 delete result;
5607 sLog.outString();
5608 sLog.outString( ">> Loaded %u pet name parts", count );
5611 void ObjectMgr::LoadPetNumber()
5613 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5614 if(result)
5616 Field *fields = result->Fetch();
5617 m_hiPetNumber = fields[0].GetUInt32()+1;
5618 delete result;
5621 barGoLink bar( 1 );
5622 bar.step();
5624 sLog.outString();
5625 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5628 std::string ObjectMgr::GeneratePetName(uint32 entry)
5630 std::vector<std::string> & list0 = PetHalfName0[entry];
5631 std::vector<std::string> & list1 = PetHalfName1[entry];
5633 if(list0.empty() || list1.empty())
5635 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5636 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5637 if(!petname)
5638 petname = cinfo->Name;
5639 return std::string(petname);
5642 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5645 uint32 ObjectMgr::GeneratePetNumber()
5647 return ++m_hiPetNumber;
5650 void ObjectMgr::LoadCorpses()
5652 uint32 count = 0;
5653 // 0 1 2 3 4 5 6 7 8 10
5654 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");
5656 if( !result )
5658 barGoLink bar( 1 );
5660 bar.step();
5662 sLog.outString();
5663 sLog.outString( ">> Loaded %u corpses", count );
5664 return;
5667 barGoLink bar( result->GetRowCount() );
5671 bar.step();
5673 Field *fields = result->Fetch();
5675 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5677 Corpse *corpse = new Corpse;
5678 if(!corpse->LoadFromDB(guid,fields))
5680 delete corpse;
5681 continue;
5684 ObjectAccessor::Instance().AddCorpse(corpse);
5686 ++count;
5688 while (result->NextRow());
5689 delete result;
5691 sLog.outString();
5692 sLog.outString( ">> Loaded %u corpses", count );
5695 void ObjectMgr::LoadReputationOnKill()
5697 uint32 count = 0;
5699 // 0 1 2
5700 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5701 // 3 4 5 6 7 8 9
5702 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5703 "FROM creature_onkill_reputation");
5705 if(!result)
5707 barGoLink bar(1);
5709 bar.step();
5711 sLog.outString();
5712 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5713 return;
5716 barGoLink bar(result->GetRowCount());
5720 Field *fields = result->Fetch();
5721 bar.step();
5723 uint32 creature_id = fields[0].GetUInt32();
5725 ReputationOnKillEntry repOnKill;
5726 repOnKill.repfaction1 = fields[1].GetUInt32();
5727 repOnKill.repfaction2 = fields[2].GetUInt32();
5728 repOnKill.is_teamaward1 = fields[3].GetBool();
5729 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5730 repOnKill.repvalue1 = fields[5].GetInt32();
5731 repOnKill.is_teamaward2 = fields[6].GetBool();
5732 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5733 repOnKill.repvalue2 = fields[8].GetInt32();
5734 repOnKill.team_dependent = fields[9].GetUInt8();
5736 if(!GetCreatureTemplate(creature_id))
5738 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5739 continue;
5742 if(repOnKill.repfaction1)
5744 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5745 if(!factionEntry1)
5747 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5748 continue;
5752 if(repOnKill.repfaction2)
5754 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5755 if(!factionEntry2)
5757 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5758 continue;
5762 mRepOnKill[creature_id] = repOnKill;
5764 ++count;
5765 } while (result->NextRow());
5767 delete result;
5769 sLog.outString();
5770 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5773 void ObjectMgr::LoadWeatherZoneChances()
5775 uint32 count = 0;
5777 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5778 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");
5780 if(!result)
5782 barGoLink bar(1);
5784 bar.step();
5786 sLog.outString();
5787 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5788 return;
5791 barGoLink bar(result->GetRowCount());
5795 Field *fields = result->Fetch();
5796 bar.step();
5798 uint32 zone_id = fields[0].GetUInt32();
5800 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5802 for(int season = 0; season < WEATHER_SEASONS; ++season)
5804 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5805 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5806 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5808 if(wzc.data[season].rainChance > 100)
5810 wzc.data[season].rainChance = 25;
5811 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5814 if(wzc.data[season].snowChance > 100)
5816 wzc.data[season].snowChance = 25;
5817 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5820 if(wzc.data[season].stormChance > 100)
5822 wzc.data[season].stormChance = 25;
5823 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5827 ++count;
5828 } while (result->NextRow());
5830 delete result;
5832 sLog.outString();
5833 sLog.outString(">> Loaded %u weather definitions", count);
5836 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5838 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5839 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5840 if(t)
5841 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5844 void ObjectMgr::DeleteCreatureData(uint32 guid)
5846 // remove mapid*cellid -> guid_set map
5847 CreatureData const* data = GetCreatureData(guid);
5848 if(data)
5849 RemoveCreatureFromGrid(guid, data);
5851 mCreatureDataMap.erase(guid);
5854 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5856 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5857 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5858 if(t)
5859 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5862 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5864 RespawnTimes::iterator next;
5866 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5868 next = itr;
5869 ++next;
5871 if(GUID_HIPART(itr->first)==instance)
5872 mGORespawnTimes.erase(itr);
5875 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5877 next = itr;
5878 ++next;
5880 if(GUID_HIPART(itr->first)==instance)
5881 mCreatureRespawnTimes.erase(itr);
5884 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5885 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5888 void ObjectMgr::DeleteGOData(uint32 guid)
5890 // remove mapid*cellid -> guid_set map
5891 GameObjectData const* data = GetGOData(guid);
5892 if(data)
5893 RemoveGameobjectFromGrid(guid, data);
5895 mGameObjectDataMap.erase(guid);
5898 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5900 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5901 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5902 cell_guids.corpses[player_guid] = instance;
5905 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5907 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5908 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5909 cell_guids.corpses.erase(player_guid);
5912 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5914 map.clear(); // need for reload case
5916 uint32 count = 0;
5918 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5920 if(!result)
5922 barGoLink bar(1);
5924 bar.step();
5926 sLog.outString();
5927 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5928 return;
5931 barGoLink bar(result->GetRowCount());
5935 Field *fields = result->Fetch();
5936 bar.step();
5938 uint32 id = fields[0].GetUInt32();
5939 uint32 quest = fields[1].GetUInt32();
5941 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5943 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5944 continue;
5947 map.insert(QuestRelations::value_type(id,quest));
5949 ++count;
5950 } while (result->NextRow());
5952 delete result;
5954 sLog.outString();
5955 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5958 void ObjectMgr::LoadGameobjectQuestRelations()
5960 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5962 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5964 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5965 if(!goInfo)
5966 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5967 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5968 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5972 void ObjectMgr::LoadGameobjectInvolvedRelations()
5974 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5976 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5978 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5979 if(!goInfo)
5980 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5981 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5982 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5986 void ObjectMgr::LoadCreatureQuestRelations()
5988 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5990 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5992 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5993 if(!cInfo)
5994 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5995 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5996 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);
6000 void ObjectMgr::LoadCreatureInvolvedRelations()
6002 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6004 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6006 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6007 if(!cInfo)
6008 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6009 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6010 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);
6014 void ObjectMgr::LoadReservedPlayersNames()
6016 m_ReservedNames.clear(); // need for reload case
6018 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6020 uint32 count = 0;
6022 if( !result )
6024 barGoLink bar( 1 );
6025 bar.step();
6027 sLog.outString();
6028 sLog.outString( ">> Loaded %u reserved player names", count );
6029 return;
6032 barGoLink bar( result->GetRowCount() );
6034 Field* fields;
6037 bar.step();
6038 fields = result->Fetch();
6039 std::string name= fields[0].GetCppString();
6040 if(normalizePlayerName(name))
6042 m_ReservedNames.insert(name);
6043 ++count;
6045 } while ( result->NextRow() );
6047 delete result;
6049 sLog.outString();
6050 sLog.outString( ">> Loaded %u reserved player names", count );
6053 enum LanguageType
6055 LT_BASIC_LATIN = 0x0000,
6056 LT_EXTENDEN_LATIN = 0x0001,
6057 LT_CYRILLIC = 0x0002,
6058 LT_EAST_ASIA = 0x0004,
6059 LT_ANY = 0xFFFF
6062 static LanguageType GetRealmLanguageType(bool create)
6064 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6066 case REALM_ZONE_UNKNOWN: // any language
6067 case REALM_ZONE_DEVELOPMENT:
6068 case REALM_ZONE_TEST_SERVER:
6069 case REALM_ZONE_QA_SERVER:
6070 return LT_ANY;
6071 case REALM_ZONE_UNITED_STATES: // extended-Latin
6072 case REALM_ZONE_OCEANIC:
6073 case REALM_ZONE_LATIN_AMERICA:
6074 case REALM_ZONE_ENGLISH:
6075 case REALM_ZONE_GERMAN:
6076 case REALM_ZONE_FRENCH:
6077 case REALM_ZONE_SPANISH:
6078 return LT_EXTENDEN_LATIN;
6079 case REALM_ZONE_KOREA: // East-Asian
6080 case REALM_ZONE_TAIWAN:
6081 case REALM_ZONE_CHINA:
6082 return LT_EAST_ASIA;
6083 case REALM_ZONE_RUSSIAN: // Cyrillic
6084 return LT_CYRILLIC;
6085 default:
6086 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6090 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6092 if(strictMask==0) // any language, ignore realm
6094 if(isExtendedLatinString(wstr,numericOrSpace))
6095 return true;
6096 if(isCyrillicString(wstr,numericOrSpace))
6097 return true;
6098 if(isEastAsianString(wstr,numericOrSpace))
6099 return true;
6100 return false;
6103 if(strictMask & 0x2) // realm zone specific
6105 LanguageType lt = GetRealmLanguageType(create);
6106 if(lt & LT_EXTENDEN_LATIN)
6107 if(isExtendedLatinString(wstr,numericOrSpace))
6108 return true;
6109 if(lt & LT_CYRILLIC)
6110 if(isCyrillicString(wstr,numericOrSpace))
6111 return true;
6112 if(lt & LT_EAST_ASIA)
6113 if(isEastAsianString(wstr,numericOrSpace))
6114 return true;
6117 if(strictMask & 0x1) // basic Latin
6119 if(isBasicLatinString(wstr,numericOrSpace))
6120 return true;
6123 return false;
6126 bool ObjectMgr::IsValidName( std::string name, bool create )
6128 std::wstring wname;
6129 if(!Utf8toWStr(name,wname))
6130 return false;
6132 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6133 return false;
6135 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6137 return isValidString(wname,strictMask,false,create);
6140 bool ObjectMgr::IsValidCharterName( std::string name )
6142 std::wstring wname;
6143 if(!Utf8toWStr(name,wname))
6144 return false;
6146 if(wname.size() < 1)
6147 return false;
6149 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6151 return isValidString(wname,strictMask,true);
6154 bool ObjectMgr::IsValidPetName( std::string name )
6156 std::wstring wname;
6157 if(!Utf8toWStr(name,wname))
6158 return false;
6160 if(wname.size() < 1)
6161 return false;
6163 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6165 return isValidString(wname,strictMask,false);
6168 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6170 if(loc==LOCALE_enUS)
6171 return -1;
6173 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6174 if(m_LocalForIndex[i]==loc)
6175 return i;
6177 return -1;
6180 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6182 if (i<0 || i>=m_LocalForIndex.size())
6183 return LOCALE_enUS;
6185 return m_LocalForIndex[i];
6188 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6190 if(loc==LOCALE_enUS)
6191 return -1;
6193 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6194 if(m_LocalForIndex[i]==loc)
6195 return i;
6197 m_LocalForIndex.push_back(loc);
6198 return m_LocalForIndex.size()-1;
6201 void ObjectMgr::LoadBattleMastersEntry()
6203 mBattleMastersMap.clear(); // need for reload case
6205 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6207 uint32 count = 0;
6209 if( !result )
6211 barGoLink bar( 1 );
6212 bar.step();
6214 sLog.outString();
6215 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6216 return;
6219 barGoLink bar( result->GetRowCount() );
6223 ++count;
6224 bar.step();
6226 Field *fields = result->Fetch();
6228 uint32 entry = fields[0].GetUInt32();
6229 uint32 bgTypeId = fields[1].GetUInt32();
6231 mBattleMastersMap[entry] = bgTypeId;
6233 } while( result->NextRow() );
6235 delete result;
6237 sLog.outString();
6238 sLog.outString( ">> Loaded %u battlemaster entries", count );
6241 void ObjectMgr::LoadGameObjectForQuests()
6243 mGameObjectForQuestSet.clear(); // need for reload case
6245 uint32 count = 0;
6247 // collect GO entries for GO that must activated
6248 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6250 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6251 if(!goInfo)
6252 continue;
6254 switch(goInfo->type)
6256 // scan GO chest with loot including quest items
6257 case GAMEOBJECT_TYPE_CHEST:
6259 uint32 loot_id = GameObject::GetLootId(goInfo);
6261 // find quest loot for GO
6262 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6264 mGameObjectForQuestSet.insert(go_entry);
6265 ++count;
6267 break;
6269 case GAMEOBJECT_TYPE_GOOBER:
6271 if(goInfo->goober.questId) //quests objects
6273 mGameObjectForQuestSet.insert(go_entry);
6274 count++;
6276 break;
6278 default:
6279 break;
6283 sLog.outString();
6284 sLog.outString( ">> Loaded %u GameObject for quests", count );
6287 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6289 // cleanup affected map part for reloading case
6290 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6292 if(itr->first >= min_value && itr->first <= max_value)
6294 MangosStringLocaleMap::iterator itr2 = itr;
6295 ++itr;
6296 mMangosStringLocaleMap.erase(itr2);
6298 else
6299 ++itr;
6302 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);
6304 if(!result)
6306 barGoLink bar(1);
6308 bar.step();
6310 sLog.outString("");
6311 if(min_value > 0) // error only in case internal strings
6312 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6313 else
6314 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6315 return false;
6318 uint32 count = 0;
6320 barGoLink bar(result->GetRowCount());
6324 Field *fields = result->Fetch();
6325 bar.step();
6327 int32 entry = fields[0].GetInt32();
6329 if(entry==0)
6331 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6332 continue;
6334 else if(entry < min_value || entry > max_value)
6336 int32 start = min_value > 0 ? min_value : max_value;
6337 int32 end = min_value > 0 ? max_value : min_value;
6338 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6339 continue;
6342 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6344 if(data.Content.size() > 0)
6346 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6347 continue;
6350 data.Content.resize(1);
6351 ++count;
6353 // 0 -> default, idx in to idx+1
6354 data.Content[0] = fields[1].GetCppString();
6356 for(int i = 1; i < MAX_LOCALE; ++i)
6358 std::string str = fields[i+1].GetCppString();
6359 if(!str.empty())
6361 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6362 if(idx >= 0)
6364 // 0 -> default, idx in to idx+1
6365 if(data.Content.size() <= idx+1)
6366 data.Content.resize(idx+2);
6368 data.Content[idx+1] = str;
6372 } while (result->NextRow());
6374 delete result;
6376 sLog.outString();
6377 if(min_value > 0) // internal mangos strings
6378 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6379 else
6380 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6382 return true;
6385 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6387 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6388 // Content[0] always exist if exist MangosStringLocale
6389 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6391 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6392 return msl->Content[locale_idx+1].c_str();
6393 else
6394 return msl->Content[0].c_str();
6397 if(entry > 0)
6398 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6399 else
6400 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6401 return "<error>";
6404 void ObjectMgr::LoadFishingBaseSkillLevel()
6406 mFishingBaseForArea.clear(); // for reload case
6408 uint32 count = 0;
6409 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6411 if( !result )
6413 barGoLink bar( 1 );
6415 bar.step();
6417 sLog.outString();
6418 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6419 return;
6422 barGoLink bar( result->GetRowCount() );
6426 bar.step();
6428 Field *fields = result->Fetch();
6429 uint32 entry = fields[0].GetUInt32();
6430 int32 skill = fields[1].GetInt32();
6432 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6433 if(!fArea)
6435 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6436 continue;
6439 mFishingBaseForArea[entry] = skill;
6440 ++count;
6442 while (result->NextRow());
6444 delete result;
6446 sLog.outString();
6447 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6450 // Searches for the same condition already in Conditions store
6451 // Returns Id if found, else adds it to Conditions and returns Id
6452 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6454 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6455 for (uint16 i=0; i < mConditions.size(); ++i)
6457 if (lc == mConditions[i])
6458 return i;
6461 mConditions.push_back(lc);
6463 if(mConditions.size() > 0xFFFF)
6465 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6466 return 0;
6469 return mConditions.size() - 1;
6472 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6474 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6476 std::wstring wname;
6477 if(!Utf8toWStr(names.name[i],wname))
6478 return false;
6480 if(mainpart!=GetMainPartOfName(wname,i+1))
6481 return false;
6483 return true;
6486 const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6488 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6489 if(i!= mAreaTriggerScripts.end())
6490 return i->second.c_str();
6491 return "";
6494 // Checks if player meets the condition
6495 bool PlayerCondition::Meets(Player const * player) const
6497 if( !player )
6498 return false; // player not present, return false
6500 switch (condition)
6502 case CONDITION_NONE:
6503 return true; // empty condition, always met
6504 case CONDITION_AURA:
6505 return player->HasAura(value1, value2);
6506 case CONDITION_ITEM:
6507 return player->HasItemCount(value1, value2);
6508 case CONDITION_ITEM_EQUIPPED:
6509 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6510 case CONDITION_ZONEID:
6511 return player->GetZoneId() == value1;
6512 case CONDITION_REPUTATION_RANK:
6514 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6515 return faction && player->GetReputationRank(faction) >= value2;
6517 case CONDITION_TEAM:
6518 return player->GetTeam() == value1;
6519 case CONDITION_SKILL:
6520 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6521 case CONDITION_QUESTREWARDED:
6522 return player->GetQuestRewardStatus(value1);
6523 case CONDITION_QUESTTAKEN:
6525 QuestStatus status = player->GetQuestStatus(value1);
6526 return (status == QUEST_STATUS_INCOMPLETE);
6528 case CONDITION_AD_COMMISSION_AURA:
6530 Unit::AuraMap const& auras = player->GetAuras();
6531 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6532 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6533 return true;
6534 return false;
6536 case CONDITION_NO_AURA:
6537 return !player->HasAura(value1, value2);
6538 case CONDITION_ACTIVE_EVENT:
6539 return gameeventmgr.IsActiveEvent(value1);
6540 default:
6541 return false;
6545 // Verification of condition values validity
6546 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6548 if( condition >= MAX_CONDITION) // Wrong condition type
6550 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6551 return false;
6554 switch (condition)
6556 case CONDITION_AURA:
6558 if(!sSpellStore.LookupEntry(value1))
6560 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6561 return false;
6563 if(value2 > 2)
6565 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6566 return false;
6568 break;
6570 case CONDITION_ITEM:
6572 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6573 if(!proto)
6575 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6576 return false;
6578 break;
6580 case CONDITION_ITEM_EQUIPPED:
6582 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6583 if(!proto)
6585 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6586 return false;
6588 break;
6590 case CONDITION_ZONEID:
6592 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6593 if(!areaEntry)
6595 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6596 return false;
6598 if(areaEntry->zone != 0)
6600 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6601 return false;
6603 break;
6605 case CONDITION_REPUTATION_RANK:
6607 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6608 if(!factionEntry)
6610 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6611 return false;
6613 break;
6615 case CONDITION_TEAM:
6617 if (value1 != ALLIANCE && value1 != HORDE)
6619 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6620 return false;
6622 break;
6624 case CONDITION_SKILL:
6626 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6627 if (!pSkill)
6629 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6630 return false;
6632 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6634 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6635 return false;
6637 break;
6639 case CONDITION_QUESTREWARDED:
6640 case CONDITION_QUESTTAKEN:
6642 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6643 if (!Quest)
6645 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6646 return false;
6648 if(value2)
6649 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6650 break;
6652 case CONDITION_AD_COMMISSION_AURA:
6654 if(value1)
6655 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6656 if(value2)
6657 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6658 break;
6660 case CONDITION_NO_AURA:
6662 if(!sSpellStore.LookupEntry(value1))
6664 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6665 return false;
6667 if(value2 > 2)
6669 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6670 return false;
6672 break;
6674 case CONDITION_ACTIVE_EVENT:
6676 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6677 if(value1 >=events.size() || !events[value1].isValid())
6679 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6680 return false;
6682 break;
6685 return true;
6688 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6690 switch(pSkill->categoryId)
6692 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6693 case SKILL_CATEGORY_WEAPON:
6694 if(pSkill->id!=SKILL_FIST_WEAPONS)
6695 return SKILL_RANGE_LEVEL;
6696 else
6697 return SKILL_RANGE_MONO;
6698 case SKILL_CATEGORY_ARMOR:
6699 case SKILL_CATEGORY_CLASS:
6700 if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6701 return SKILL_RANGE_MONO;
6702 else
6703 return SKILL_RANGE_LEVEL;
6704 case SKILL_CATEGORY_SECONDARY:
6705 case SKILL_CATEGORY_PROFESSION:
6706 // not set skills for professions and racial abilities
6707 if(IsProfessionSkill(pSkill->id))
6708 return SKILL_RANGE_RANK;
6709 else if(racial)
6710 return SKILL_RANGE_NONE;
6711 else
6712 return SKILL_RANGE_MONO;
6713 default:
6714 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6715 case SKILL_CATEGORY_NOT_DISPLAYED: //only GENEREC(DND)
6716 return SKILL_RANGE_NONE;
6720 void ObjectMgr::LoadGameTele()
6722 m_GameTeleMap.clear(); // for reload case
6724 uint32 count = 0;
6725 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6727 if( !result )
6729 barGoLink bar( 1 );
6731 bar.step();
6733 sLog.outString();
6734 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6735 return;
6738 barGoLink bar( result->GetRowCount() );
6742 bar.step();
6744 Field *fields = result->Fetch();
6746 uint32 id = fields[0].GetUInt32();
6748 GameTele gt;
6750 gt.position_x = fields[1].GetFloat();
6751 gt.position_y = fields[2].GetFloat();
6752 gt.position_z = fields[3].GetFloat();
6753 gt.orientation = fields[4].GetFloat();
6754 gt.mapId = fields[5].GetUInt32();
6755 gt.name = fields[6].GetCppString();
6757 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6759 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6760 continue;
6763 if(!Utf8toWStr(gt.name,gt.wnameLow))
6765 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6766 continue;
6769 wstrToLower( gt.wnameLow );
6771 m_GameTeleMap[id] = gt;
6773 ++count;
6775 while (result->NextRow());
6777 delete result;
6779 sLog.outString();
6780 sLog.outString( ">> Loaded %u game tele's", count );
6783 GameTele const* ObjectMgr::GetGameTele(std::string name) const
6785 // explicit name case
6786 std::wstring wname;
6787 if(!Utf8toWStr(name,wname))
6788 return false;
6790 // converting string that we try to find to lower case
6791 wstrToLower( wname );
6793 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6794 const GameTele* alt = NULL;
6795 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6796 if(itr->second.wnameLow == wname)
6797 return &itr->second;
6798 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6799 alt = &itr->second;
6801 return alt;
6804 bool ObjectMgr::AddGameTele(GameTele& tele)
6806 // find max id
6807 uint32 new_id = 0;
6808 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6809 if(itr->first > new_id)
6810 new_id = itr->first;
6812 // use next
6813 ++new_id;
6815 if(!Utf8toWStr(tele.name,tele.wnameLow))
6816 return false;
6818 wstrToLower( tele.wnameLow );
6820 m_GameTeleMap[new_id] = tele;
6822 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')",
6823 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6826 bool ObjectMgr::DeleteGameTele(std::string name)
6828 // explicit name case
6829 std::wstring wname;
6830 if(!Utf8toWStr(name,wname))
6831 return false;
6833 // converting string that we try to find to lower case
6834 wstrToLower( wname );
6836 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6838 if(itr->second.wnameLow == wname)
6840 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6841 m_GameTeleMap.erase(itr);
6842 return true;
6846 return false;
6849 void ObjectMgr::LoadTrainerSpell()
6851 // For reload case
6852 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6853 itr->second.Clear();
6854 m_mCacheTrainerSpellMap.clear();
6856 std::set<uint32> skip_trainers;
6858 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6860 if( !result )
6862 barGoLink bar( 1 );
6864 bar.step();
6866 sLog.outString();
6867 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6868 return;
6871 barGoLink bar( result->GetRowCount() );
6873 uint32 count = 0;
6876 bar.step();
6878 Field* fields = result->Fetch();
6880 uint32 entry = fields[0].GetUInt32();
6881 uint32 spell = fields[1].GetUInt32();
6883 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6885 if(!cInfo)
6887 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6888 continue;
6891 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6893 if(skip_trainers.count(entry) == 0)
6895 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6896 skip_trainers.insert(entry);
6898 continue;
6901 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6902 if(!spellinfo)
6904 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6905 continue;
6908 if(!SpellMgr::IsSpellValid(spellinfo))
6910 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6911 continue;
6914 TrainerSpell* pTrainerSpell = new TrainerSpell();
6915 pTrainerSpell->spell = spell;
6916 pTrainerSpell->spellcost = fields[2].GetUInt32();
6917 pTrainerSpell->reqskill = fields[3].GetUInt32();
6918 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6919 pTrainerSpell->reqlevel = fields[5].GetUInt32();
6921 if(!pTrainerSpell->reqlevel)
6922 pTrainerSpell->reqlevel = spellinfo->spellLevel;
6925 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6927 if(SpellMgr::IsProfessionSpell(spell))
6928 data.trainerType = 2;
6930 data.spellList.push_back(pTrainerSpell);
6931 ++count;
6933 } while (result->NextRow());
6934 delete result;
6936 sLog.outString();
6937 sLog.outString( ">> Loaded Trainers %d", count );
6940 void ObjectMgr::LoadVendors()
6942 // For reload case
6943 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6944 itr->second.Clear();
6945 m_mCacheVendorItemMap.clear();
6947 std::set<uint32> skip_vendors;
6949 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6950 if( !result )
6952 barGoLink bar( 1 );
6954 bar.step();
6956 sLog.outString();
6957 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6958 return;
6961 barGoLink bar( result->GetRowCount() );
6963 uint32 count = 0;
6966 bar.step();
6967 Field* fields = result->Fetch();
6969 uint32 entry = fields[0].GetUInt32();
6970 uint32 item_id = fields[1].GetUInt32();
6971 uint32 maxcount = fields[2].GetUInt32();
6972 uint32 incrtime = fields[3].GetUInt32();
6973 uint32 ExtendedCost = fields[4].GetUInt32();
6975 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6976 continue;
6978 VendorItemData& vList = m_mCacheVendorItemMap[entry];
6980 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
6981 ++count;
6983 } while (result->NextRow());
6984 delete result;
6986 sLog.outString();
6987 sLog.outString( ">> Loaded %d Vendors ", count );
6990 void ObjectMgr::LoadNpcTextId()
6993 m_mCacheNpcTextIdMap.clear();
6995 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
6996 if( !result )
6998 barGoLink bar( 1 );
7000 bar.step();
7002 sLog.outString();
7003 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7004 return;
7007 barGoLink bar( result->GetRowCount() );
7009 uint32 count = 0;
7010 uint32 guid,textid;
7013 bar.step();
7015 Field* fields = result->Fetch();
7017 guid = fields[0].GetUInt32();
7018 textid = fields[1].GetUInt32();
7020 if (!GetCreatureData(guid))
7022 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7023 continue;
7025 if (!GetGossipText(textid))
7027 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7028 continue;
7031 m_mCacheNpcTextIdMap[guid] = textid ;
7032 ++count;
7034 } while (result->NextRow());
7035 delete result;
7037 sLog.outString();
7038 sLog.outString( ">> Loaded %d NpcTextId ", count );
7041 void ObjectMgr::LoadNpcOptions()
7043 m_mCacheNpcOptionList.clear(); // For reload case
7045 QueryResult *result = WorldDatabase.Query(
7046 // 0 1 2 3 4 5 6 7 8
7047 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7048 "FROM npc_option");
7050 if( !result )
7052 barGoLink bar( 1 );
7054 bar.step();
7056 sLog.outString();
7057 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7058 return;
7061 barGoLink bar( result->GetRowCount() );
7063 uint32 count = 0;
7067 bar.step();
7069 Field* fields = result->Fetch();
7071 GossipOption go;
7072 go.Id = fields[0].GetUInt32();
7073 go.GossipId = fields[1].GetUInt32();
7074 go.NpcFlag = fields[2].GetUInt32();
7075 go.Icon = fields[3].GetUInt32();
7076 go.Action = fields[4].GetUInt32();
7077 go.BoxMoney = fields[5].GetUInt32();
7078 go.Coded = fields[6].GetUInt8()!=0;
7079 go.OptionText = fields[7].GetCppString();
7080 go.BoxText = fields[8].GetCppString();
7082 m_mCacheNpcOptionList.push_back(go);
7084 ++count;
7086 } while (result->NextRow());
7087 delete result;
7089 sLog.outString();
7090 sLog.outString( ">> Loaded %d npc_option entries", count );
7093 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7095 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7096 vList.AddItem(item,maxcount,incrtime,extendedcost);
7098 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7101 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7103 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7104 if(iter == m_mCacheVendorItemMap.end())
7105 return false;
7107 if(!iter->second.FindItem(item))
7108 return false;
7110 iter->second.RemoveItem(item);
7111 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7112 return true;
7115 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7117 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7118 if(!cInfo)
7120 if(pl)
7121 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7122 else
7123 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7124 return false;
7127 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7129 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7131 if(pl)
7132 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7133 else
7134 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7136 if(skip_vendors)
7137 skip_vendors->insert(vendor_entry);
7139 return false;
7142 if(!GetItemPrototype(item_id))
7144 if(pl)
7145 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7146 else
7147 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7148 return false;
7151 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7153 if(pl)
7154 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7155 else
7156 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7157 return false;
7160 if(maxcount > 0 && incrtime == 0)
7162 if(pl)
7163 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7164 else
7165 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7166 return false;
7168 else if(maxcount==0 && incrtime > 0)
7170 if(pl)
7171 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7172 else
7173 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7174 return false;
7177 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7178 if(!vItems)
7179 return true; // later checks for non-empty lists
7181 if(vItems->FindItem(item_id))
7183 if(pl)
7184 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7185 else
7186 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7187 return false;
7190 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7192 if(pl)
7193 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7194 else
7195 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7196 return false;
7199 return true;
7202 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7204 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7206 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7208 if(itrM->second.dataint)
7210 if(ids.count(itrM->second.dataint))
7211 ids.erase(itrM->second.dataint);
7212 else
7213 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", *itrM);
7219 void ObjectMgr::LoadDbScriptStrings()
7221 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7223 std::set<int32> ids;
7225 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7226 if(GetMangosStringLocale(i))
7227 ids.insert(i);
7229 CheckScripts(sQuestEndScripts,ids);
7230 CheckScripts(sQuestStartScripts,ids);
7231 CheckScripts(sSpellScripts,ids);
7232 CheckScripts(sGameObjectScripts,ids);
7233 CheckScripts(sEventScripts,ids);
7235 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7236 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7240 // Functions for scripting access
7241 const char* GetAreaTriggerScriptNameById(uint32 id)
7243 return objmgr.GetAreaTriggerScriptName(id);
7246 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7248 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7250 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());
7251 start_value = -1;
7252 end_value = std::numeric_limits<int32>::min();
7255 // for scripting localized strings allowed use _only_ negative entries
7256 return objmgr.LoadMangosStrings(db,table,end_value,start_value);