Fixed mixing up character and world database
[AHbot.git] / src / game / ObjectMgr.cpp
blob356deb8b935aaccfcf4ad00dff961b6120000d6c
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 = this->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 = this->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 = this->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::LoadCompletedAchievements()
568 QueryResult *result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
570 if(!result)
571 return;
575 Field *fields = result->Fetch();
576 allCompletedAchievements.insert(fields[0].GetUInt32());
577 } while(result->NextRow());
579 delete result;
582 void ObjectMgr::LoadNpcOptionLocales()
584 mNpcOptionLocaleMap.clear(); // need for reload case
586 QueryResult *result = WorldDatabase.Query("SELECT entry,"
587 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
588 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
589 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
590 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
591 "FROM locales_npc_option");
593 if(!result)
595 barGoLink bar(1);
597 bar.step();
599 sLog.outString("");
600 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
601 return;
604 barGoLink bar(result->GetRowCount());
608 Field *fields = result->Fetch();
609 bar.step();
611 uint32 entry = fields[0].GetUInt32();
613 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
615 for(int i = 1; i < MAX_LOCALE; ++i)
617 std::string str = fields[1+2*(i-1)].GetCppString();
618 if(!str.empty())
620 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
621 if(idx >= 0)
623 if(data.OptionText.size() <= idx)
624 data.OptionText.resize(idx+1);
626 data.OptionText[idx] = str;
629 str = fields[1+2*(i-1)+1].GetCppString();
630 if(!str.empty())
632 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
633 if(idx >= 0)
635 if(data.BoxText.size() <= idx)
636 data.BoxText.resize(idx+1);
638 data.BoxText[idx] = str;
642 } while (result->NextRow());
644 delete result;
646 sLog.outString();
647 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
650 void ObjectMgr::LoadCreatureTemplates()
652 sCreatureStorage.Load();
654 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
655 sLog.outString();
657 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
658 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
660 // check data correctness
661 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
663 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
664 if(!cInfo)
665 continue;
667 if(cInfo->HeroicEntry)
669 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
670 if(!heroicInfo)
672 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
673 continue;
676 if(heroicEntries.find(i)!=heroicEntries.end())
678 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
679 continue;
682 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
684 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
685 continue;
688 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
690 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
691 continue;
694 if(cInfo->npcflag != heroicInfo->npcflag)
696 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
697 continue;
700 if(cInfo->classNum != heroicInfo->classNum)
702 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
703 continue;
706 if(cInfo->race != heroicInfo->race)
708 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
709 continue;
712 if(cInfo->trainer_type != heroicInfo->trainer_type)
714 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
715 continue;
718 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
720 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
721 continue;
724 hasHeroicEntries.insert(i);
725 heroicEntries.insert(cInfo->HeroicEntry);
728 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
729 if(!factionTemplate)
730 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
732 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
733 if(!factionTemplate)
734 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
736 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
737 if (!minfo)
738 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
739 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
740 if (!minfo)
741 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
743 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
745 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
746 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
749 if(cInfo->baseattacktime == 0)
750 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
752 if(cInfo->rangeattacktime == 0)
753 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
755 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
756 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
758 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
760 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
761 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
764 if(cInfo->PetSpellDataId)
766 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
767 if(!spellDataId)
768 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
771 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
773 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
774 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
777 if(cInfo->equipmentId > 0) // 0 no equipment
779 if(!GetEquipmentInfo(cInfo->equipmentId))
781 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);
782 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
786 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
787 if(cInfo->scale <= 0.0f)
789 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
790 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
795 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
797 // Now add the auras, format "spellid effectindex spellid effectindex..."
798 char *p,*s;
799 std::vector<int> val;
800 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
801 if(p)
803 while (p[0]!=0)
805 ++p;
806 if (p[0]==' ')
808 val.push_back(atoi(s));
809 s=++p;
812 if (p!=s)
813 val.push_back(atoi(s));
815 // free char* loaded memory
816 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
818 // wrong list
819 if (val.size()%2)
821 addon->auras = NULL;
822 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
823 return;
827 // empty list
828 if(val.empty())
830 addon->auras = NULL;
831 return;
834 // replace by new strucutres array
835 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
837 int i=0;
838 for(int j=0;j<val.size()/2;++j)
840 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
841 cAura.spell_id = (uint32)val[2*j+0];
842 cAura.effect_idx = (uint32)val[2*j+1];
843 if ( cAura.effect_idx > 2 )
845 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);
846 continue;
848 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
849 if (!AdditionalSpellInfo)
851 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
852 continue;
855 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
857 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);
858 continue;
861 ++i;
864 // fill terminator element (after last added)
865 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
866 endAura.spell_id = 0;
867 endAura.effect_idx = 0;
870 void ObjectMgr::LoadCreatureAddons()
872 sCreatureInfoAddonStorage.Load();
874 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
875 sLog.outString();
877 // check data correctness and convert 'auras'
878 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
880 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
881 if(!addon)
882 continue;
884 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
886 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
887 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
890 sCreatureDataAddonStorage.Load();
892 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
893 sLog.outString();
895 // check data correctness and convert 'auras'
896 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
898 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
899 if(!addon)
900 continue;
902 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
904 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
905 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
909 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
911 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
914 void ObjectMgr::LoadEquipmentTemplates()
916 sEquipmentStorage.Load();
918 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
920 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
922 if(!eqInfo)
923 continue;
925 for(uint8 j=0; j<3; j++)
927 if(!eqInfo->equipentry[j])
928 continue;
930 ItemPrototype const* proto = objmgr.GetItemPrototype(eqInfo->equipentry[j]);
932 if(!proto)
934 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
935 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
936 continue;
939 if(proto->InventoryType != INVTYPE_WEAPON &&
940 proto->InventoryType != INVTYPE_SHIELD &&
941 proto->InventoryType != INVTYPE_RANGED &&
942 proto->InventoryType != INVTYPE_2HWEAPON &&
943 proto->InventoryType != INVTYPE_WEAPONMAINHAND &&
944 proto->InventoryType != INVTYPE_WEAPONOFFHAND &&
945 proto->InventoryType != INVTYPE_HOLDABLE &&
946 proto->InventoryType != INVTYPE_THROWN &&
947 proto->InventoryType != INVTYPE_RANGEDRIGHT)
949 sLog.outErrorDb("Item (entry=%u) in creature_equip_template.equipentry%u for entry = %u is not equipable in a hand, forced to 0.", eqInfo->equipentry[j], j+1, i);
950 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
954 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
955 sLog.outString();
958 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
960 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
963 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
965 // Load creature model (display id)
966 uint32 display_id;
967 if (!data || data->displayid == 0) // use defaults from the template
969 // DisplayID_A is used if no team is given
970 if (team == HORDE)
971 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
972 else
973 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
975 else // overriden in creature data
976 display_id = data->displayid;
978 return display_id;
981 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
983 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
984 if(!minfo)
985 return NULL;
987 // If a model for another gender exists, 50% chance to use it
988 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
990 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
991 if(!minfo_tmp)
993 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
994 return minfo; // not fatal, just use the previous one
996 else
997 return minfo_tmp;
999 else
1000 return minfo;
1003 void ObjectMgr::LoadCreatureModelInfo()
1005 sCreatureModelStorage.Load();
1007 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1008 sLog.outString();
1011 void ObjectMgr::LoadCreatures()
1013 uint32 count = 0;
1014 // 0 1 2 3
1015 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1016 // 4 5 6 7 8 9 10 11
1017 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1018 // 12 13 14 15 16 17
1019 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
1020 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
1022 if(!result)
1024 barGoLink bar(1);
1026 bar.step();
1028 sLog.outString("");
1029 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1030 return;
1033 // build single time for check creature data
1034 std::set<uint32> heroicCreatures;
1035 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1036 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1037 if(cInfo->HeroicEntry)
1038 heroicCreatures.insert(cInfo->HeroicEntry);
1040 barGoLink bar(result->GetRowCount());
1044 Field *fields = result->Fetch();
1045 bar.step();
1047 uint32 guid = fields[0].GetUInt32();
1049 CreatureData& data = mCreatureDataMap[guid];
1051 data.id = fields[ 1].GetUInt32();
1052 data.mapid = fields[ 2].GetUInt32();
1053 data.displayid = fields[ 3].GetUInt32();
1054 data.equipmentId = fields[ 4].GetUInt32();
1055 data.posX = fields[ 5].GetFloat();
1056 data.posY = fields[ 6].GetFloat();
1057 data.posZ = fields[ 7].GetFloat();
1058 data.orientation = fields[ 8].GetFloat();
1059 data.spawntimesecs = fields[ 9].GetUInt32();
1060 data.spawndist = fields[10].GetFloat();
1061 data.currentwaypoint= fields[11].GetUInt32();
1062 data.curhealth = fields[12].GetUInt32();
1063 data.curmana = fields[13].GetUInt32();
1064 data.is_dead = fields[14].GetBool();
1065 data.movementType = fields[15].GetUInt8();
1066 data.spawnMask = fields[16].GetUInt8();
1067 int16 gameEvent = fields[17].GetInt16();
1069 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1070 if(!cInfo)
1072 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1073 continue;
1076 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1078 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1079 continue;
1082 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1084 if(!GetEquipmentInfo(data.equipmentId))
1086 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);
1087 data.equipmentId = -1;
1091 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1093 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 );
1094 data.curhealth = cInfo->minhealth;
1097 if(data.curmana < cInfo->minmana)
1099 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 );
1100 data.curmana = cInfo->minmana;
1103 if(data.spawndist < 0.0f)
1105 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1106 data.spawndist = 0.0f;
1108 else if(data.movementType == RANDOM_MOTION_TYPE)
1110 if(data.spawndist == 0.0f)
1112 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 );
1113 data.movementType = IDLE_MOTION_TYPE;
1116 else if(data.movementType == IDLE_MOTION_TYPE)
1118 if(data.spawndist != 0.0f)
1120 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1121 data.spawndist = 0.0f;
1125 if (gameEvent==0) // if not this is to be managed by GameEvent System
1126 AddCreatureToGrid(guid, &data);
1127 ++count;
1129 } while (result->NextRow());
1131 delete result;
1133 sLog.outString();
1134 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1137 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1139 uint8 mask = data->spawnMask;
1140 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1142 if(mask & 1)
1144 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1145 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1147 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1148 cell_guids.creatures.insert(guid);
1153 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1155 uint8 mask = data->spawnMask;
1156 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1158 if(mask & 1)
1160 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1161 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1163 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1164 cell_guids.creatures.erase(guid);
1169 void ObjectMgr::LoadGameobjects()
1171 uint32 count = 0;
1173 // 0 1 2 3 4 5 6
1174 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1175 // 7 8 9 10 11 12 13 14 15
1176 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1177 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1179 if(!result)
1181 barGoLink bar(1);
1183 bar.step();
1185 sLog.outString();
1186 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1187 return;
1190 barGoLink bar(result->GetRowCount());
1194 Field *fields = result->Fetch();
1195 bar.step();
1197 uint32 guid = fields[0].GetUInt32();
1199 GameObjectData& data = mGameObjectDataMap[guid];
1201 data.id = fields[ 1].GetUInt32();
1202 data.mapid = fields[ 2].GetUInt32();
1203 data.posX = fields[ 3].GetFloat();
1204 data.posY = fields[ 4].GetFloat();
1205 data.posZ = fields[ 5].GetFloat();
1206 data.orientation = fields[ 6].GetFloat();
1207 data.rotation0 = fields[ 7].GetFloat();
1208 data.rotation1 = fields[ 8].GetFloat();
1209 data.rotation2 = fields[ 9].GetFloat();
1210 data.rotation3 = fields[10].GetFloat();
1211 data.spawntimesecs = fields[11].GetInt32();
1212 data.animprogress = fields[12].GetUInt32();
1213 data.go_state = fields[13].GetUInt32();
1214 data.spawnMask = fields[14].GetUInt8();
1215 int16 gameEvent = fields[15].GetInt16();
1217 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1218 if(!gInfo)
1220 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1221 continue;
1224 if (gameEvent==0) // if not this is to be managed by GameEvent System
1225 AddGameobjectToGrid(guid, &data);
1226 ++count;
1228 } while (result->NextRow());
1230 delete result;
1232 sLog.outString();
1233 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1236 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1238 uint8 mask = data->spawnMask;
1239 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1241 if(mask & 1)
1243 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1244 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1246 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1247 cell_guids.gameobjects.insert(guid);
1252 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1254 uint8 mask = data->spawnMask;
1255 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1257 if(mask & 1)
1259 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1260 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1262 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1263 cell_guids.gameobjects.erase(guid);
1268 void ObjectMgr::LoadCreatureRespawnTimes()
1270 // remove outdated data
1271 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1273 uint32 count = 0;
1275 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1277 if(!result)
1279 barGoLink bar(1);
1281 bar.step();
1283 sLog.outString();
1284 sLog.outString(">> Loaded 0 creature respawn time.");
1285 return;
1288 barGoLink bar(result->GetRowCount());
1292 Field *fields = result->Fetch();
1293 bar.step();
1295 uint32 loguid = fields[0].GetUInt32();
1296 uint64 respawn_time = fields[1].GetUInt64();
1297 uint32 instance = fields[2].GetUInt32();
1299 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1301 ++count;
1302 } while (result->NextRow());
1304 delete result;
1306 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1307 sLog.outString();
1310 void ObjectMgr::LoadGameobjectRespawnTimes()
1312 // remove outdated data
1313 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1315 uint32 count = 0;
1317 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1319 if(!result)
1321 barGoLink bar(1);
1323 bar.step();
1325 sLog.outString();
1326 sLog.outString(">> Loaded 0 gameobject respawn time.");
1327 return;
1330 barGoLink bar(result->GetRowCount());
1334 Field *fields = result->Fetch();
1335 bar.step();
1337 uint32 loguid = fields[0].GetUInt32();
1338 uint64 respawn_time = fields[1].GetUInt64();
1339 uint32 instance = fields[2].GetUInt32();
1341 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1343 ++count;
1344 } while (result->NextRow());
1346 delete result;
1348 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1349 sLog.outString();
1352 // name must be checked to correctness (if received) before call this function
1353 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1355 uint64 guid = 0;
1357 CharacterDatabase.escape_string(name);
1359 // Player name safe to sending to DB (checked at login) and this function using
1360 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1361 if(result)
1363 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1365 delete result;
1368 return guid;
1371 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1373 // prevent DB access for online player
1374 if(Player* player = GetPlayer(guid))
1376 name = player->GetName();
1377 return true;
1380 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1382 if(result)
1384 name = (*result)[0].GetCppString();
1385 delete result;
1386 return true;
1389 return false;
1392 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1394 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1396 if(result)
1398 uint8 race = (*result)[0].GetUInt8();
1399 delete result;
1400 return Player::TeamForRace(race);
1403 return 0;
1406 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1408 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1409 if(result)
1411 uint32 acc = (*result)[0].GetUInt32();
1412 delete result;
1413 return acc;
1416 return 0;
1419 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(std::string name) const
1421 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1422 if(result)
1424 uint32 acc = (*result)[0].GetUInt32();
1425 delete result;
1426 return acc;
1429 return 0;
1432 void ObjectMgr::LoadAuctions()
1434 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1435 if( !result )
1436 return;
1438 Field *fields = result->Fetch();
1439 uint32 AuctionCount=fields[0].GetUInt32();
1440 delete result;
1442 if(!AuctionCount)
1443 return;
1445 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1446 if( !result )
1447 return;
1449 barGoLink bar( AuctionCount );
1451 AuctionEntry *aItem;
1455 fields = result->Fetch();
1457 bar.step();
1459 aItem = new AuctionEntry;
1460 aItem->Id = fields[0].GetUInt32();
1461 aItem->auctioneer = fields[1].GetUInt32();
1462 aItem->item_guidlow = fields[2].GetUInt32();
1463 aItem->item_template = fields[3].GetUInt32();
1464 aItem->owner = fields[4].GetUInt32();
1465 aItem->buyout = fields[5].GetUInt32();
1466 aItem->time = fields[6].GetUInt32();
1467 aItem->bidder = fields[7].GetUInt32();
1468 aItem->bid = fields[8].GetUInt32();
1469 aItem->startbid = fields[9].GetUInt32();
1470 aItem->deposit = fields[10].GetUInt32();
1471 aItem->location = fields[11].GetUInt8();
1472 //check if sold item exists
1473 if ( this->GetAItem( aItem->item_guidlow ) )
1475 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1477 else
1479 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1480 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1481 delete aItem;
1483 } while (result->NextRow());
1484 delete result;
1486 sLog.outString();
1487 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1488 sLog.outString();
1491 void ObjectMgr::LoadItemLocales()
1493 mItemLocaleMap.clear(); // need for reload case
1495 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");
1497 if(!result)
1499 barGoLink bar(1);
1501 bar.step();
1503 sLog.outString("");
1504 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1505 return;
1508 barGoLink bar(result->GetRowCount());
1512 Field *fields = result->Fetch();
1513 bar.step();
1515 uint32 entry = fields[0].GetUInt32();
1517 ItemLocale& data = mItemLocaleMap[entry];
1519 for(int i = 1; i < MAX_LOCALE; ++i)
1521 std::string str = fields[1+2*(i-1)].GetCppString();
1522 if(!str.empty())
1524 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1525 if(idx >= 0)
1527 if(data.Name.size() <= idx)
1528 data.Name.resize(idx+1);
1530 data.Name[idx] = str;
1534 str = fields[1+2*(i-1)+1].GetCppString();
1535 if(!str.empty())
1537 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1538 if(idx >= 0)
1540 if(data.Description.size() <= idx)
1541 data.Description.resize(idx+1);
1543 data.Description[idx] = str;
1547 } while (result->NextRow());
1549 delete result;
1551 sLog.outString();
1552 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1555 void ObjectMgr::LoadItemPrototypes()
1557 sItemStorage.Load ();
1558 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1559 sLog.outString();
1561 // check data correctness
1562 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1564 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1565 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1566 if(!proto)
1568 /* to many errors, and possible not all items really used in game
1569 if (dbcitem)
1570 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1572 continue;
1575 if(dbcitem)
1577 if(proto->InventoryType != dbcitem->InventoryType)
1579 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1580 // It safe let use InventoryType from DB
1583 if(proto->DisplayInfoID != dbcitem->DisplayId)
1585 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1586 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1588 if(proto->Sheath != dbcitem->Sheath)
1590 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1591 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1594 else
1596 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1599 if(proto->Class >= MAX_ITEM_CLASS)
1601 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1602 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1605 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1607 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1608 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1611 if(proto->Quality >= MAX_ITEM_QUALITY)
1613 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1614 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1617 if(proto->BuyCount <= 0)
1619 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1620 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1623 if(proto->InventoryType >= MAX_INVTYPE)
1625 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1626 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1629 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1631 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1632 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1635 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1637 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1640 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1642 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1645 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1647 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1648 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1651 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1652 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1654 if(proto->RequiredReputationFaction)
1656 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1658 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1659 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1662 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1663 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1665 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1666 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1668 if(proto->Stackable==0)
1670 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1671 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1673 else if(proto->Stackable > 255)
1675 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1676 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1679 for (int j = 0; j < 10; j++)
1681 // for ItemStatValue != 0
1682 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1684 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1685 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1689 for (int j = 0; j < 5; j++)
1691 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1693 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1694 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1698 // special format
1699 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1701 // spell_1
1702 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1704 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);
1705 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1706 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1707 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1708 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1711 // spell_2 have learning spell
1712 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1714 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);
1715 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1716 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1717 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1719 else if(!proto->Spells[1].SpellId)
1721 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1722 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1723 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1725 else
1727 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1728 if(!spellInfo)
1730 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1731 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1732 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1733 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1735 // allowed only in special format
1736 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1738 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1739 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1740 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1741 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1745 // spell_3*,spell_4*,spell_5* is empty
1746 for (int j = 2; j < 5; j++)
1748 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1750 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1751 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1752 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1754 else if(proto->Spells[j].SpellId != 0)
1756 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1757 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1761 // normal spell list
1762 else
1764 for (int j = 0; j < 5; j++)
1766 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1768 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1769 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1770 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1773 if(proto->Spells[j].SpellId)
1775 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1776 if(!spellInfo)
1778 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1779 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1781 // allowed only in special format
1782 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1784 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1785 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1791 if(proto->Bonding >= MAX_BIND_TYPE)
1792 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1794 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1795 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1797 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1798 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1800 if(proto->Sheath >= MAX_SHEATHETYPE)
1802 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1803 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1806 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1808 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1809 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1812 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1814 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1815 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1818 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1820 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1821 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1824 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1825 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1827 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1828 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1830 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1831 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1833 for (int j = 0; j < 3; j++)
1835 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1837 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1838 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1842 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1843 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1845 if(proto->FoodType >= MAX_PET_DIET)
1847 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1848 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1852 // this DBC used currently only for check item templates in DB.
1853 sItemStore.Clear();
1856 void ObjectMgr::LoadAuctionItems()
1858 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1860 if( !result )
1861 return;
1863 barGoLink bar( result->GetRowCount() );
1865 uint32 count = 0;
1867 Field *fields;
1870 bar.step();
1872 fields = result->Fetch();
1873 uint32 item_guid = fields[0].GetUInt32();
1874 uint32 item_template = fields[1].GetUInt32();
1876 ItemPrototype const *proto = GetItemPrototype(item_template);
1878 if(!proto)
1880 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1881 continue;
1884 Item *item = NewItemOrBag(proto);
1886 if(!item->LoadFromDB(item_guid,0))
1888 delete item;
1889 continue;
1891 AddAItem(item);
1893 ++count;
1895 while( result->NextRow() );
1897 delete result;
1899 sLog.outString();
1900 sLog.outString( ">> Loaded %u auction items", count );
1903 void ObjectMgr::LoadPetLevelInfo()
1905 // Loading levels data
1907 // 0 1 2 3 4 5 6 7 8 9
1908 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1910 uint32 count = 0;
1912 if (!result)
1914 barGoLink bar( 1 );
1916 sLog.outString();
1917 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1918 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1919 return;
1922 barGoLink bar( result->GetRowCount() );
1926 Field* fields = result->Fetch();
1928 uint32 creature_id = fields[0].GetUInt32();
1929 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1931 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1932 continue;
1935 uint32 current_level = fields[1].GetUInt32();
1936 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1938 if(current_level > 255) // hardcoded level maximum
1939 sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1940 else
1941 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1942 continue;
1944 else if(current_level < 1)
1946 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1947 continue;
1950 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1952 if(pInfoMapEntry==NULL)
1953 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1955 // data for level 1 stored in [0] array element, ...
1956 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1958 pLevelInfo->health = fields[2].GetUInt16();
1959 pLevelInfo->mana = fields[3].GetUInt16();
1960 pLevelInfo->armor = fields[9].GetUInt16();
1962 for (int i = 0; i < MAX_STATS; i++)
1964 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1967 bar.step();
1968 ++count;
1970 while (result->NextRow());
1972 delete result;
1974 sLog.outString();
1975 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1978 // Fill gaps and check integrity
1979 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1981 PetLevelInfo* pInfo = itr->second;
1983 // fatal error if no level 1 data
1984 if(!pInfo || pInfo[0].health == 0 )
1986 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1987 exit(1);
1990 // fill level gaps
1991 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1993 if(pInfo[level].health == 0)
1995 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1996 pInfo[level] = pInfo[level-1];
2002 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2004 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2005 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2007 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2008 if(itr == petInfo.end())
2009 return NULL;
2011 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2014 void ObjectMgr::LoadPlayerInfo()
2016 // Load playercreate
2018 // 0 1 2 3 4 5 6
2019 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2021 uint32 count = 0;
2023 if (!result)
2025 barGoLink bar( 1 );
2027 sLog.outString();
2028 sLog.outString( ">> Loaded %u player create definitions", count );
2029 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2030 exit(1);
2033 barGoLink bar( result->GetRowCount() );
2037 Field* fields = result->Fetch();
2039 uint32 current_race = fields[0].GetUInt32();
2040 uint32 current_class = fields[1].GetUInt32();
2041 uint32 mapId = fields[2].GetUInt32();
2042 uint32 zoneId = fields[3].GetUInt32();
2043 float positionX = fields[4].GetFloat();
2044 float positionY = fields[5].GetFloat();
2045 float positionZ = fields[6].GetFloat();
2047 if(current_race >= MAX_RACES)
2049 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2050 continue;
2053 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2054 if(!rEntry)
2056 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2057 continue;
2060 if(current_class >= MAX_CLASSES)
2062 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2063 continue;
2066 if(!sChrClassesStore.LookupEntry(current_class))
2068 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2069 continue;
2072 // accept DB data only for valid position (and non instanceable)
2073 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2075 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2076 continue;
2079 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2081 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2082 continue;
2085 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2087 pInfo->mapId = mapId;
2088 pInfo->zoneId = zoneId;
2089 pInfo->positionX = positionX;
2090 pInfo->positionY = positionY;
2091 pInfo->positionZ = positionZ;
2093 pInfo->displayId_m = rEntry->model_m;
2094 pInfo->displayId_f = rEntry->model_f;
2096 bar.step();
2097 ++count;
2099 while (result->NextRow());
2101 delete result;
2103 sLog.outString();
2104 sLog.outString( ">> Loaded %u player create definitions", count );
2107 // Load playercreate items
2109 // 0 1 2 3
2110 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2112 uint32 count = 0;
2114 if (!result)
2116 barGoLink bar( 1 );
2118 sLog.outString();
2119 sLog.outString( ">> Loaded %u player create items", count );
2120 sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2122 else
2124 barGoLink bar( result->GetRowCount() );
2128 Field* fields = result->Fetch();
2130 uint32 current_race = fields[0].GetUInt32();
2131 if(current_race >= MAX_RACES)
2133 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2134 continue;
2137 uint32 current_class = fields[1].GetUInt32();
2138 if(current_class >= MAX_CLASSES)
2140 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2141 continue;
2144 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2146 uint32 item_id = fields[2].GetUInt32();
2148 if(!GetItemPrototype(item_id))
2150 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);
2151 continue;
2154 uint32 amount = fields[3].GetUInt32();
2156 if(!amount)
2158 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2159 continue;
2162 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2164 bar.step();
2165 ++count;
2167 while(result->NextRow());
2169 delete result;
2171 sLog.outString();
2172 sLog.outString( ">> Loaded %u player create items", count );
2176 // Load playercreate spells
2178 // 0 1 2 3
2179 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2181 uint32 count = 0;
2183 if (!result)
2185 barGoLink bar( 1 );
2187 sLog.outString();
2188 sLog.outString( ">> Loaded %u player create spells", count );
2189 sLog.outErrorDb( "Error loading `playercreateinfo_spell` 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_spell` 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_spell` table, ignoring.",current_class);
2210 continue;
2213 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2214 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2216 bar.step();
2217 ++count;
2219 while( result->NextRow() );
2221 delete result;
2223 sLog.outString();
2224 sLog.outString( ">> Loaded %u player create spells", count );
2228 // Load playercreate actions
2230 // 0 1 2 3 4 5
2231 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2233 uint32 count = 0;
2235 if (!result)
2237 barGoLink bar( 1 );
2239 sLog.outString();
2240 sLog.outString( ">> Loaded %u player create actions", count );
2241 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2243 else
2245 barGoLink bar( result->GetRowCount() );
2249 Field* fields = result->Fetch();
2251 uint32 current_race = fields[0].GetUInt32();
2252 if(current_race >= MAX_RACES)
2254 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2255 continue;
2258 uint32 current_class = fields[1].GetUInt32();
2259 if(current_class >= MAX_CLASSES)
2261 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2262 continue;
2265 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2266 pInfo->action[0].push_back(fields[2].GetUInt16());
2267 pInfo->action[1].push_back(fields[3].GetUInt16());
2268 pInfo->action[2].push_back(fields[4].GetUInt16());
2269 pInfo->action[3].push_back(fields[5].GetUInt16());
2271 bar.step();
2272 ++count;
2274 while( result->NextRow() );
2276 delete result;
2278 sLog.outString();
2279 sLog.outString( ">> Loaded %u player create actions", count );
2283 // Loading levels data (class only dependent)
2285 // 0 1 2 3
2286 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2288 uint32 count = 0;
2290 if (!result)
2292 barGoLink bar( 1 );
2294 sLog.outString();
2295 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2296 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2297 exit(1);
2300 barGoLink bar( result->GetRowCount() );
2304 Field* fields = result->Fetch();
2306 uint32 current_class = fields[0].GetUInt32();
2307 if(current_class >= MAX_CLASSES)
2309 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2310 continue;
2313 uint32 current_level = fields[1].GetUInt32();
2314 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2316 if(current_level > 255) // hardcoded level maximum
2317 sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2318 else
2319 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2320 continue;
2323 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2325 if(!pClassInfo->levelInfo)
2326 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2328 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2330 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2331 pClassLevelInfo->basemana = fields[3].GetUInt16();
2333 bar.step();
2334 ++count;
2336 while (result->NextRow());
2338 delete result;
2340 sLog.outString();
2341 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2344 // Fill gaps and check integrity
2345 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2347 // skip non existed classes
2348 if(!sChrClassesStore.LookupEntry(class_))
2349 continue;
2351 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2353 // fatal error if no level 1 data
2354 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2356 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2357 exit(1);
2360 // fill level gaps
2361 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2363 if(pClassInfo->levelInfo[level].basehealth == 0)
2365 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2366 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2371 // Loading levels data (class/race dependent)
2373 // 0 1 2 3 4 5 6 7
2374 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2376 uint32 count = 0;
2378 if (!result)
2380 barGoLink bar( 1 );
2382 sLog.outString();
2383 sLog.outString( ">> Loaded %u level stats definitions", count );
2384 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2385 exit(1);
2388 barGoLink bar( result->GetRowCount() );
2392 Field* fields = result->Fetch();
2394 uint32 current_race = fields[0].GetUInt32();
2395 if(current_race >= MAX_RACES)
2397 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2398 continue;
2401 uint32 current_class = fields[1].GetUInt32();
2402 if(current_class >= MAX_CLASSES)
2404 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2405 continue;
2408 uint32 current_level = fields[2].GetUInt32();
2409 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2411 if(current_level > 255) // hardcoded level maximum
2412 sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2413 else
2414 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2415 continue;
2418 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2420 if(!pInfo->levelInfo)
2421 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2423 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2425 for (int i = 0; i < MAX_STATS; i++)
2427 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2430 bar.step();
2431 ++count;
2433 while (result->NextRow());
2435 delete result;
2437 sLog.outString();
2438 sLog.outString( ">> Loaded %u level stats definitions", count );
2441 // Fill gaps and check integrity
2442 for (int race = 0; race < MAX_RACES; ++race)
2444 // skip non existed races
2445 if(!sChrRacesStore.LookupEntry(race))
2446 continue;
2448 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2450 // skip non existed classes
2451 if(!sChrClassesStore.LookupEntry(class_))
2452 continue;
2454 PlayerInfo* pInfo = &playerInfo[race][class_];
2456 // skip non loaded combinations
2457 if(!pInfo->displayId_m || !pInfo->displayId_f)
2458 continue;
2460 // skip expansion races if not playing with expansion
2461 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2462 continue;
2464 // skip expansion classes if not playing with expansion
2465 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2466 continue;
2468 // fatal error if no level 1 data
2469 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2471 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2472 exit(1);
2475 // fill level gaps
2476 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2478 if(pInfo->levelInfo[level].stats[0] == 0)
2480 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2481 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2488 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2490 if(level < 1 || class_ >= MAX_CLASSES)
2491 return;
2493 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2495 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2496 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2498 *info = pInfo->levelInfo[level-1];
2501 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2503 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2504 return;
2506 PlayerInfo const* pInfo = &playerInfo[race][class_];
2507 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2508 return;
2510 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2511 *info = pInfo->levelInfo[level-1];
2512 else
2513 BuildPlayerLevelInfo(race,class_,level,info);
2516 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2518 // base data (last known level)
2519 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2521 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2523 switch(_class)
2525 case CLASS_WARRIOR:
2526 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2527 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2528 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2529 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2530 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2531 break;
2532 case CLASS_PALADIN:
2533 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2534 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2535 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2536 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2537 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2538 break;
2539 case CLASS_HUNTER:
2540 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2541 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2542 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2543 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2544 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2545 break;
2546 case CLASS_ROGUE:
2547 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2548 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2549 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2550 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2551 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2552 break;
2553 case CLASS_PRIEST:
2554 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2555 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2556 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2557 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2558 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2559 break;
2560 case CLASS_SHAMAN:
2561 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2562 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2563 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2564 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2565 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2566 break;
2567 case CLASS_MAGE:
2568 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2569 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2570 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2571 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2572 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2573 break;
2574 case CLASS_WARLOCK:
2575 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2576 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2577 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2578 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2579 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2580 break;
2581 case CLASS_DRUID:
2582 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2583 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2584 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2585 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2586 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2591 void ObjectMgr::LoadGuilds()
2593 Guild *newguild;
2594 uint32 count = 0;
2596 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2598 if( !result )
2601 barGoLink bar( 1 );
2603 bar.step();
2605 sLog.outString();
2606 sLog.outString( ">> Loaded %u guild definitions", count );
2607 return;
2610 barGoLink bar( result->GetRowCount() );
2614 Field *fields = result->Fetch();
2616 bar.step();
2617 ++count;
2619 newguild = new Guild;
2620 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2622 newguild->Disband();
2623 delete newguild;
2624 continue;
2626 AddGuild(newguild);
2628 }while( result->NextRow() );
2630 delete result;
2632 sLog.outString();
2633 sLog.outString( ">> Loaded %u guild definitions", count );
2636 void ObjectMgr::LoadArenaTeams()
2638 uint32 count = 0;
2640 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2642 if( !result )
2645 barGoLink bar( 1 );
2647 bar.step();
2649 sLog.outString();
2650 sLog.outString( ">> Loaded %u arenateam definitions", count );
2651 return;
2654 barGoLink bar( result->GetRowCount() );
2658 Field *fields = result->Fetch();
2660 bar.step();
2661 ++count;
2663 ArenaTeam *newarenateam = new ArenaTeam;
2664 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2666 delete newarenateam;
2667 continue;
2669 AddArenaTeam(newarenateam);
2670 }while( result->NextRow() );
2672 delete result;
2674 sLog.outString();
2675 sLog.outString( ">> Loaded %u arenateam definitions", count );
2678 void ObjectMgr::LoadGroups()
2680 // -- loading groups --
2681 Group *group = NULL;
2682 uint64 leaderGuid = 0;
2683 uint32 count = 0;
2684 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2685 QueryResult *result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2687 if( !result )
2689 barGoLink bar( 1 );
2691 bar.step();
2693 sLog.outString();
2694 sLog.outString( ">> Loaded %u group definitions", count );
2695 return;
2698 barGoLink bar( result->GetRowCount() );
2702 bar.step();
2703 Field *fields = result->Fetch();
2704 ++count;
2705 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2707 group = new Group;
2708 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2710 group->Disband();
2711 delete group;
2712 continue;
2714 AddGroup(group);
2715 }while( result->NextRow() );
2717 delete result;
2719 sLog.outString();
2720 sLog.outString( ">> Loaded %u group definitions", count );
2722 // -- loading members --
2723 count = 0;
2724 group = NULL;
2725 leaderGuid = 0;
2726 // 0 1 2 3
2727 result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2728 if(!result)
2730 barGoLink bar( 1 );
2731 bar.step();
2733 else
2735 barGoLink bar( result->GetRowCount() );
2738 bar.step();
2739 Field *fields = result->Fetch();
2740 count++;
2741 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2742 if(!group || group->GetLeaderGUID() != leaderGuid)
2744 group = GetGroupByLeader(leaderGuid);
2745 if(!group)
2747 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2748 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2749 continue;
2753 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2755 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2756 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2758 }while( result->NextRow() );
2759 delete result;
2762 // clean groups
2763 // TODO: maybe delete from the DB before loading in this case
2764 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2766 if((*itr)->GetMembersCount() < 2)
2768 (*itr)->Disband();
2769 delete *itr;
2770 mGroupSet.erase(itr++);
2772 else
2773 ++itr;
2776 // -- loading instances --
2777 count = 0;
2778 group = NULL;
2779 leaderGuid = 0;
2780 result = CharacterDatabase.PQuery(
2781 // 0 1 2 3 4 5
2782 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2783 // 6
2784 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2785 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2788 if(!result)
2790 barGoLink bar( 1 );
2791 bar.step();
2793 else
2795 barGoLink bar( result->GetRowCount() );
2798 bar.step();
2799 Field *fields = result->Fetch();
2800 count++;
2801 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2802 if(!group || group->GetLeaderGUID() != leaderGuid)
2804 group = GetGroupByLeader(leaderGuid);
2805 if(!group)
2807 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2808 continue;
2812 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2813 group->BindToInstance(save, fields[3].GetBool(), true);
2814 }while( result->NextRow() );
2815 delete result;
2818 sLog.outString();
2819 sLog.outString( ">> Loaded %u group-instance binds total", count );
2821 sLog.outString();
2822 sLog.outString( ">> Loaded %u group members total", count );
2825 void ObjectMgr::LoadQuests()
2827 // For reload case
2828 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2829 delete itr->second;
2830 mQuestTemplates.clear();
2832 mExclusiveQuestGroups.clear();
2834 // 0 1 2 3 4 5 6 7 8
2835 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2836 // 9 10 11 12 13 14 15 16
2837 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2838 // 17 18 19 20 21 22 23 24 25 26
2839 "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2840 // 27 28 29 30 31 32 33 34 35 36
2841 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2842 // 37 38 39 40 41 42 43 44
2843 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2844 // 45 46 47 48 49 50 51 52 53 54 54 55
2845 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2846 // 57 58 59 60 61 62 63 64
2847 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2848 // 65 66 67 68
2849 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2850 // 69 70 71 72 73 74
2851 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2852 // 75 76 77 78 79 80
2853 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2854 // 81 82 83 84 85 86 87 88
2855 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2856 // 89 90 91 92 93 94 95 96 97 98
2857 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2858 // 99 100 101 102 103 104 105 106 107 108 109
2859 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2860 // 110 111 112 113 114 115 116 117 118 119
2861 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2862 // 120 121
2863 "StartScript, CompleteScript"
2864 " FROM quest_template");
2865 if(result == NULL)
2867 barGoLink bar( 1 );
2868 bar.step();
2870 sLog.outString();
2871 sLog.outString( ">> Loaded 0 quests definitions" );
2872 sLog.outErrorDb("`quest_template` table is empty!");
2873 return;
2876 // create multimap previous quest for each existed quest
2877 // some quests can have many previous maps set by NextQuestId in previous quest
2878 // for example set of race quests can lead to single not race specific quest
2879 barGoLink bar( result->GetRowCount() );
2882 bar.step();
2883 Field *fields = result->Fetch();
2885 Quest * newQuest = new Quest(fields);
2886 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2887 } while( result->NextRow() );
2889 delete result;
2891 // Post processing
2892 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2894 Quest * qinfo = iter->second;
2896 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2898 if( qinfo->GetQuestMethod() >= 3 )
2900 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2903 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2905 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2906 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2907 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2910 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2912 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2914 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2915 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2919 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2921 // at auto-reward can be rewarded only RewChoiceItemId[0]
2922 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2924 if(uint32 id = qinfo->RewChoiceItemId[j])
2926 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2927 qinfo->GetQuestId(),j+1,id,j+1);
2928 // no changes, quest ignore this data
2933 // client quest log visual (area case)
2934 if( qinfo->ZoneOrSort > 0 )
2936 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2938 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2939 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2940 // no changes, quest not dependent from this value but can have problems at client
2943 // client quest log visual (sort case)
2944 if( qinfo->ZoneOrSort < 0 )
2946 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2947 if( !qSort )
2949 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2950 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2951 // 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)
2953 //check SkillOrClass value (class case).
2954 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2956 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2957 if(qinfo->SkillOrClass < 0)
2959 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2960 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2963 //check for proper SkillOrClass value (skill case)
2964 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2966 // skill is positive value in SkillOrClass
2967 if(qinfo->SkillOrClass != skill_id )
2969 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2970 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2971 //override, and force proper value here?
2976 // SkillOrClass (class case)
2977 if( qinfo->SkillOrClass < 0 )
2979 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2981 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2982 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2985 // SkillOrClass (skill case)
2986 if( qinfo->SkillOrClass > 0 )
2988 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2990 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2991 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2995 if( qinfo->RequiredSkillValue )
2997 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2999 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3000 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3001 // no changes, quest can't be done for this requirement
3004 if( qinfo->SkillOrClass <= 0 )
3006 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3007 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3008 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3011 // else Skill quests can have 0 skill level, this is ok
3013 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3015 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3016 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3017 // no changes, quest can't be done for this requirement
3020 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3022 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3023 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3024 // no changes, quest can't be done for this requirement
3027 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3029 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3030 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3031 // no changes, quest can't be done for this requirement
3034 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3036 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3037 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3038 // no changes, quest can't be done for this requirement
3041 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3043 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3044 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3045 // no changes, quest can't be done for this requirement
3048 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3050 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3051 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3052 // warning
3055 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3057 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3058 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3059 // warning
3062 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3064 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3065 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3066 // warning
3069 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3071 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3072 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3073 qinfo->CharTitleId = 0;
3074 // quest can't reward this title
3077 if(qinfo->SrcItemId)
3079 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3081 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3082 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3083 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3085 else if(qinfo->SrcItemCount==0)
3087 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3088 qinfo->GetQuestId(),qinfo->SrcItemId);
3089 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward comptibility with DB
3092 else if(qinfo->SrcItemCount>0)
3094 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3095 qinfo->GetQuestId(),qinfo->SrcItemCount);
3096 qinfo->SrcItemCount=0; // no quest work changes in fact
3099 if(qinfo->SrcSpell)
3101 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3102 if(!spellInfo)
3104 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3105 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3106 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3108 else if(!SpellMgr::IsSpellValid(spellInfo))
3110 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3111 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3112 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3116 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3118 uint32 id = qinfo->ReqItemId[j];
3119 if(id)
3121 if(qinfo->ReqItemCount[j]==0)
3123 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3124 qinfo->GetQuestId(),j+1,id,j+1);
3125 // no changes, quest can't be done for this requirement
3128 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3130 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3132 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3133 qinfo->GetQuestId(),j+1,id,id);
3134 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3137 else if(qinfo->ReqItemCount[j]>0)
3139 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3140 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3141 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3145 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3147 uint32 id = qinfo->ReqSourceId[j];
3148 if(id)
3150 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3152 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3153 qinfo->GetQuestId(),j+1,id,id);
3154 // no changes, quest can't be done for this requirement
3157 if(!qinfo->ReqSourceCount[j])
3159 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3160 qinfo->GetQuestId(),j+1,id,j+1);
3161 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3164 if(!qinfo->ReqSourceRef[j])
3166 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3167 qinfo->GetQuestId(),j+1,id,j+1);
3168 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3171 else
3173 if(qinfo->ReqSourceCount[j]>0)
3175 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3176 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3177 // no changes, quest ignore this data
3180 if(qinfo->ReqSourceRef[j]>0)
3182 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3183 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3184 // no changes, quest ignore this data
3189 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3191 uint32 ref = qinfo->ReqSourceRef[j];
3192 if(ref)
3194 if(ref > QUEST_OBJECTIVES_COUNT)
3196 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3197 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3198 // no changes, quest can't be done for this requirement
3200 else
3201 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3203 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3204 qinfo->GetQuestId(),j+1,ref,ref,ref);
3205 // no changes, quest can't be done for this requirement
3207 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3209 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3210 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3211 // no changes, quest can't be done for this requirement
3212 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3217 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3219 uint32 id = qinfo->ReqSpell[j];
3220 if(id)
3222 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3223 if(!spellInfo)
3225 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3226 qinfo->GetQuestId(),j+1,id,id);
3227 // no changes, quest can't be done for this requirement
3230 if(!qinfo->ReqCreatureOrGOId[j])
3232 bool found = false;
3233 for(int k = 0; k < 3; ++k)
3235 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3236 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3238 found = true;
3239 break;
3243 if(found)
3245 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3247 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);
3249 // this will prevent quest completing without objective
3250 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3253 else
3255 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.",
3256 qinfo->GetQuestId(),j+1,id,j+1,id);
3257 // no changes, quest can't be done for this requirement
3263 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3265 int32 id = qinfo->ReqCreatureOrGOId[j];
3266 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3268 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3269 qinfo->GetQuestId(),j+1,id,uint32(-id));
3270 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3273 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3275 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3276 qinfo->GetQuestId(),j+1,id,uint32(id));
3277 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3280 if(id)
3282 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3284 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3286 if(!qinfo->ReqCreatureOrGOCount[j])
3288 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3289 qinfo->GetQuestId(),j+1,id,j+1);
3290 // no changes, quest can be incorrectly done, but we already report this
3293 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3295 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3296 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3297 // no changes, quest ignore this data
3301 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3303 uint32 id = qinfo->RewChoiceItemId[j];
3304 if(id)
3306 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3308 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3309 qinfo->GetQuestId(),j+1,id,id);
3310 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3313 if(!qinfo->RewChoiceItemCount[j])
3315 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3316 qinfo->GetQuestId(),j+1,id,j+1);
3317 // no changes, quest can't be done
3320 else if(qinfo->RewChoiceItemCount[j]>0)
3322 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3323 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3324 // no changes, quest ignore this data
3328 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3330 uint32 id = qinfo->RewItemId[j];
3331 if(id)
3333 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3335 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3336 qinfo->GetQuestId(),j+1,id,id);
3337 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3340 if(!qinfo->RewItemCount[j])
3342 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3343 qinfo->GetQuestId(),j+1,id,j+1);
3344 // no changes
3347 else if(qinfo->RewItemCount[j]>0)
3349 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3350 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3351 // no changes, quest ignore this data
3355 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3357 if(qinfo->RewRepFaction[j])
3359 if(!qinfo->RewRepValue[j])
3361 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3362 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3363 // no changes
3366 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3368 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.",
3369 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3370 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3373 else if(qinfo->RewRepValue[j]!=0)
3375 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3376 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3377 // no changes, quest ignore this data
3381 if(qinfo->RewSpell)
3383 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3385 if(!spellInfo)
3387 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3388 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3389 qinfo->RewSpell = 0; // no spell reward will display for this quest
3392 else if(!SpellMgr::IsSpellValid(spellInfo))
3394 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3395 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3396 qinfo->RewSpell = 0; // no spell reward will display for this quest
3401 if(qinfo->RewSpellCast)
3403 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3405 if(!spellInfo)
3407 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3408 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3409 qinfo->RewSpellCast = 0; // no spell will be casted on player
3412 else if(!SpellMgr::IsSpellValid(spellInfo))
3414 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3415 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3416 qinfo->RewSpellCast = 0; // no spell will be casted on player
3421 if(qinfo->RewMailTemplateId)
3423 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3425 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3426 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3427 qinfo->RewMailTemplateId = 0; // no mail will send to player
3428 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3432 if(qinfo->NextQuestInChain)
3434 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3436 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3437 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3438 qinfo->NextQuestInChain = 0;
3440 else
3441 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3444 // fill additional data stores
3445 if(qinfo->PrevQuestId)
3447 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3449 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3451 else
3453 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3457 if(qinfo->NextQuestId)
3459 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3461 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3463 else
3465 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3466 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3470 if(qinfo->ExclusiveGroup)
3471 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3472 if(qinfo->LimitTime)
3473 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3476 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3477 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3479 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3480 if(!spellInfo)
3481 continue;
3483 for(int j = 0; j < 3; ++j)
3485 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3486 continue;
3488 uint32 quest_id = spellInfo->EffectMiscValue[j];
3490 Quest const* quest = GetQuestTemplate(quest_id);
3492 // some quest referenced in spells not exist (outdataed spells)
3493 if(!quest)
3494 continue;
3496 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3498 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);
3500 // this will prevent quest completing without objective
3501 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3506 sLog.outString();
3507 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3510 void ObjectMgr::LoadQuestLocales()
3512 mQuestLocaleMap.clear(); // need for reload case
3514 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3515 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3516 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3517 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3518 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3519 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3520 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3521 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3522 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3523 " FROM locales_quest"
3526 if(!result)
3528 barGoLink bar(1);
3530 bar.step();
3532 sLog.outString("");
3533 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3534 return;
3537 barGoLink bar(result->GetRowCount());
3541 Field *fields = result->Fetch();
3542 bar.step();
3544 uint32 entry = fields[0].GetUInt32();
3546 QuestLocale& data = mQuestLocaleMap[entry];
3548 for(int i = 1; i < MAX_LOCALE; ++i)
3550 std::string str = fields[1+10*(i-1)].GetCppString();
3551 if(!str.empty())
3553 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3554 if(idx >= 0)
3556 if(data.Title.size() <= idx)
3557 data.Title.resize(idx+1);
3559 data.Title[idx] = str;
3562 str = fields[1+10*(i-1)+1].GetCppString();
3563 if(!str.empty())
3565 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3566 if(idx >= 0)
3568 if(data.Details.size() <= idx)
3569 data.Details.resize(idx+1);
3571 data.Details[idx] = str;
3574 str = fields[1+10*(i-1)+2].GetCppString();
3575 if(!str.empty())
3577 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3578 if(idx >= 0)
3580 if(data.Objectives.size() <= idx)
3581 data.Objectives.resize(idx+1);
3583 data.Objectives[idx] = str;
3586 str = fields[1+10*(i-1)+3].GetCppString();
3587 if(!str.empty())
3589 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3590 if(idx >= 0)
3592 if(data.OfferRewardText.size() <= idx)
3593 data.OfferRewardText.resize(idx+1);
3595 data.OfferRewardText[idx] = str;
3598 str = fields[1+10*(i-1)+4].GetCppString();
3599 if(!str.empty())
3601 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3602 if(idx >= 0)
3604 if(data.RequestItemsText.size() <= idx)
3605 data.RequestItemsText.resize(idx+1);
3607 data.RequestItemsText[idx] = str;
3610 str = fields[1+10*(i-1)+5].GetCppString();
3611 if(!str.empty())
3613 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3614 if(idx >= 0)
3616 if(data.EndText.size() <= idx)
3617 data.EndText.resize(idx+1);
3619 data.EndText[idx] = str;
3622 for(int k = 0; k < 4; ++k)
3624 str = fields[1+10*(i-1)+6+k].GetCppString();
3625 if(!str.empty())
3627 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3628 if(idx >= 0)
3630 if(data.ObjectiveText[k].size() <= idx)
3631 data.ObjectiveText[k].resize(idx+1);
3633 data.ObjectiveText[k][idx] = str;
3638 } while (result->NextRow());
3640 delete result;
3642 sLog.outString();
3643 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3646 void ObjectMgr::LoadPetCreateSpells()
3648 QueryResult *result = WorldDatabase.PQuery("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3649 if(!result)
3651 barGoLink bar( 1 );
3652 bar.step();
3654 sLog.outString();
3655 sLog.outString( ">> Loaded 0 pet create spells" );
3656 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3657 return;
3660 uint32 count = 0;
3662 barGoLink bar( result->GetRowCount() );
3664 mPetCreateSpell.clear();
3668 Field *fields = result->Fetch();
3669 bar.step();
3671 uint32 creature_id = fields[0].GetUInt32();
3673 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3674 continue;
3676 PetCreateSpellEntry PetCreateSpell;
3677 for(int i = 0; i < 4; i++)
3679 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3681 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3682 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3685 mPetCreateSpell[creature_id] = PetCreateSpell;
3687 ++count;
3689 while (result->NextRow());
3691 delete result;
3693 sLog.outString();
3694 sLog.outString( ">> Loaded %u pet create spells", count );
3697 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3699 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3700 return;
3702 sLog.outString( "%s :", tablename);
3704 scripts.clear(); // need for reload support
3706 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3708 uint32 count = 0;
3710 if( !result )
3712 barGoLink bar( 1 );
3713 bar.step();
3715 sLog.outString();
3716 sLog.outString( ">> Loaded %u script definitions", count );
3717 return;
3720 barGoLink bar( result->GetRowCount() );
3724 bar.step();
3726 Field *fields = result->Fetch();
3727 ScriptInfo tmp;
3728 tmp.id = fields[0].GetUInt32();
3729 tmp.delay = fields[1].GetUInt32();
3730 tmp.command = fields[2].GetUInt32();
3731 tmp.datalong = fields[3].GetUInt32();
3732 tmp.datalong2 = fields[4].GetUInt32();
3733 tmp.datatext = fields[5].GetCppString();
3734 tmp.x = fields[6].GetFloat();
3735 tmp.y = fields[7].GetFloat();
3736 tmp.z = fields[8].GetFloat();
3737 tmp.o = fields[9].GetFloat();
3739 // generic command args check
3740 switch(tmp.command)
3742 case SCRIPT_COMMAND_TALK:
3744 if(tmp.datalong > 3)
3746 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3747 continue;
3749 break;
3752 case SCRIPT_COMMAND_TELEPORT_TO:
3754 if(!sMapStore.LookupEntry(tmp.datalong))
3756 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3757 continue;
3760 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3762 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);
3763 continue;
3765 break;
3768 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3770 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3772 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);
3773 continue;
3776 if(!GetCreatureTemplate(tmp.datalong))
3778 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3779 continue;
3781 break;
3784 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3786 GameObjectData const* data = GetGOData(tmp.datalong);
3787 if(!data)
3789 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3790 continue;
3793 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3794 if(!info)
3796 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);
3797 continue;
3800 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3801 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3802 info->type==GAMEOBJECT_TYPE_DOOR ||
3803 info->type==GAMEOBJECT_TYPE_BUTTON ||
3804 info->type==GAMEOBJECT_TYPE_TRAP )
3806 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3807 continue;
3809 break;
3811 case SCRIPT_COMMAND_OPEN_DOOR:
3812 case SCRIPT_COMMAND_CLOSE_DOOR:
3814 GameObjectData const* data = GetGOData(tmp.datalong);
3815 if(!data)
3817 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);
3818 continue;
3821 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3822 if(!info)
3824 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);
3825 continue;
3828 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3830 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);
3831 continue;
3834 break;
3836 case SCRIPT_COMMAND_QUEST_EXPLORED:
3838 Quest const* quest = GetQuestTemplate(tmp.datalong);
3839 if(!quest)
3841 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);
3842 continue;
3845 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3847 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);
3849 // this will prevent quest completing without objective
3850 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3852 // continue; - quest objective requiremet set and command can be allowed
3855 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3857 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",tablename,tmp.datalong2,tmp.id);
3858 continue;
3861 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3863 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(DEFAULT_VISIBILITY_DISTANCE));
3864 continue;
3867 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3869 sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(INTERACTION_DISTANCE));
3870 continue;
3873 break;
3876 case SCRIPT_COMMAND_REMOVE_AURA:
3877 case SCRIPT_COMMAND_CAST_SPELL:
3879 if(!sSpellStore.LookupEntry(tmp.datalong))
3881 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",tablename,tmp.datalong,tmp.id);
3882 continue;
3884 break;
3888 if (scripts.find(tmp.id) == scripts.end())
3890 ScriptMap emptyMap;
3891 scripts[tmp.id] = emptyMap;
3893 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3895 ++count;
3896 } while( result->NextRow() );
3898 delete result;
3900 sLog.outString();
3901 sLog.outString( ">> Loaded %u script definitions", count );
3904 void ObjectMgr::LoadGameObjectScripts()
3906 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3908 // check ids
3909 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3911 if(!GetGOData(itr->first))
3912 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3916 void ObjectMgr::LoadQuestEndScripts()
3918 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3920 // check ids
3921 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3923 if(!GetQuestTemplate(itr->first))
3924 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3928 void ObjectMgr::LoadQuestStartScripts()
3930 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3932 // check ids
3933 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3935 if(!GetQuestTemplate(itr->first))
3936 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3940 void ObjectMgr::LoadSpellScripts()
3942 LoadScripts(sSpellScripts, "spell_scripts");
3944 // check ids
3945 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3947 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3949 if(!spellInfo)
3951 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3952 continue;
3955 //check for correct spellEffect
3956 bool found = false;
3957 for(int i=0; i<3; ++i)
3959 // skip empty effects
3960 if( !spellInfo->Effect[i] )
3961 continue;
3963 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3965 found = true;
3966 break;
3970 if(!found)
3971 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3975 void ObjectMgr::LoadEventScripts()
3977 LoadScripts(sEventScripts, "event_scripts");
3979 std::set<uint32> evt_scripts;
3980 // Load all possible script entries from gameobjects
3981 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3983 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3984 if (goInfo)
3986 switch(goInfo->type)
3988 case GAMEOBJECT_TYPE_GOOBER:
3989 if(goInfo->goober.eventId)
3990 evt_scripts.insert(goInfo->goober.eventId);
3991 break;
3992 case GAMEOBJECT_TYPE_CHEST:
3993 if(goInfo->chest.eventId)
3994 evt_scripts.insert(goInfo->chest.eventId);
3995 break;
3996 default:
3997 break;
4001 // Load all possible script entries from spells
4002 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4004 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4005 if (spell)
4007 for(int j=0; j<3; ++j)
4009 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4011 if (spell->EffectMiscValue[j])
4012 evt_scripts.insert(spell->EffectMiscValue[j]);
4017 // Then check if all scripts are in above list of possible script entries
4018 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4020 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4021 if (itr2 == evt_scripts.end())
4022 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not refering to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
4026 void ObjectMgr::LoadItemTexts()
4028 QueryResult *result = CharacterDatabase.PQuery("SELECT id, text FROM item_text");
4030 uint32 count = 0;
4032 if( !result )
4034 barGoLink bar( 1 );
4035 bar.step();
4037 sLog.outString();
4038 sLog.outString( ">> Loaded %u item pages", count );
4039 return;
4042 barGoLink bar( result->GetRowCount() );
4044 Field* fields;
4047 bar.step();
4049 fields = result->Fetch();
4051 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4053 ++count;
4055 } while ( result->NextRow() );
4057 delete result;
4059 sLog.outString();
4060 sLog.outString( ">> Loaded %u item texts", count );
4063 void ObjectMgr::LoadPageTexts()
4065 sPageTextStore.Free(); // for reload case
4067 sPageTextStore.Load();
4068 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4069 sLog.outString();
4071 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4073 // check data correctness
4074 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4075 if(!page)
4076 continue;
4078 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4080 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4081 continue;
4084 // detect circular reference
4085 std::set<uint32> checkedPages;
4086 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4088 if(!pageItr->Next_Page)
4089 break;
4090 checkedPages.insert(pageItr->Page_ID);
4091 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4093 std::ostringstream ss;
4094 ss<< "The text page(s) ";
4095 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
4096 ss << *itr << " ";
4097 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4098 << pageItr->Page_ID <<" to 0";
4099 sLog.outErrorDb(ss.str().c_str());
4100 const_cast<PageText*>(pageItr)->Next_Page = 0;
4101 break;
4107 void ObjectMgr::LoadPageTextLocales()
4109 mPageTextLocaleMap.clear(); // need for reload case
4111 QueryResult *result = WorldDatabase.PQuery("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4113 if(!result)
4115 barGoLink bar(1);
4117 bar.step();
4119 sLog.outString("");
4120 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4121 return;
4124 barGoLink bar(result->GetRowCount());
4128 Field *fields = result->Fetch();
4129 bar.step();
4131 uint32 entry = fields[0].GetUInt32();
4133 PageTextLocale& data = mPageTextLocaleMap[entry];
4135 for(int i = 1; i < MAX_LOCALE; ++i)
4137 std::string str = fields[i].GetCppString();
4138 if(str.empty())
4139 continue;
4141 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4142 if(idx >= 0)
4144 if(data.Text.size() <= idx)
4145 data.Text.resize(idx+1);
4147 data.Text[idx] = str;
4151 } while (result->NextRow());
4153 delete result;
4155 sLog.outString();
4156 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4159 void ObjectMgr::LoadInstanceTemplate()
4161 sInstanceTemplate.Load();
4163 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4165 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4166 if(!temp) continue;
4167 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4168 if(!entry)
4170 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4171 continue;
4173 else if(!entry->HasResetTime())
4174 continue;
4176 if(temp->reset_delay == 0)
4178 // use defaults from the DBC
4179 if(entry->SupportsHeroicMode())
4181 temp->reset_delay = entry->resetTimeHeroic / DAY;
4183 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4185 temp->reset_delay = entry->resetTimeRaid / DAY;
4189 // the reset_delay must be atleast one day
4190 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4193 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4194 sLog.outString();
4197 void ObjectMgr::AddGossipText(GossipText *pGText)
4199 ASSERT( pGText->Text_ID );
4200 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4201 mGossipText[pGText->Text_ID] = pGText;
4204 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4206 GossipTextMap::const_iterator itr;
4207 for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4209 if(itr->second->Text_ID == Text_ID)
4210 return itr->second;
4212 return NULL;
4215 void ObjectMgr::LoadGossipText()
4217 GossipText *pGText;
4218 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4220 int count = 0;
4221 if( !result )
4223 barGoLink bar( 1 );
4224 bar.step();
4226 sLog.outString();
4227 sLog.outString( ">> Loaded %u npc texts", count );
4228 return;
4231 int cic;
4233 barGoLink bar( result->GetRowCount() );
4237 ++count;
4238 cic = 0;
4240 Field *fields = result->Fetch();
4242 bar.step();
4244 pGText = new GossipText;
4245 pGText->Text_ID = fields[cic++].GetUInt32();
4247 for (int i=0; i< 8; i++)
4249 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4250 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4252 pGText->Options[i].Language = fields[cic++].GetUInt32();
4253 pGText->Options[i].Probability = fields[cic++].GetFloat();
4255 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4256 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4258 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4259 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4261 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4262 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4265 if ( !pGText->Text_ID ) continue;
4266 AddGossipText( pGText );
4268 } while( result->NextRow() );
4270 sLog.outString();
4271 sLog.outString( ">> Loaded %u npc texts", count );
4272 delete result;
4275 void ObjectMgr::LoadNpcTextLocales()
4277 mNpcTextLocaleMap.clear(); // need for reload case
4279 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4280 "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,"
4281 "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,"
4282 "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,"
4283 "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,"
4284 "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,"
4285 "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,"
4286 "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, "
4287 "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 "
4288 " FROM locales_npc_text");
4290 if(!result)
4292 barGoLink bar(1);
4294 bar.step();
4296 sLog.outString("");
4297 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4298 return;
4301 barGoLink bar(result->GetRowCount());
4305 Field *fields = result->Fetch();
4306 bar.step();
4308 uint32 entry = fields[0].GetUInt32();
4310 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4312 for(int i=1; i<MAX_LOCALE; ++i)
4314 for(int j=0; j<8; ++j)
4316 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4317 if(!str0.empty())
4319 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4320 if(idx >= 0)
4322 if(data.Text_0[j].size() <= idx)
4323 data.Text_0[j].resize(idx+1);
4325 data.Text_0[j][idx] = str0;
4328 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4329 if(!str1.empty())
4331 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4332 if(idx >= 0)
4334 if(data.Text_1[j].size() <= idx)
4335 data.Text_1[j].resize(idx+1);
4337 data.Text_1[j][idx] = str1;
4342 } while (result->NextRow());
4344 delete result;
4346 sLog.outString();
4347 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4350 //not very fast function but it is called only once a day, or on starting-up
4351 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4353 time_t basetime = time(NULL);
4354 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4355 //delete all old mails without item and without body immediately, if starting server
4356 if (!serverUp)
4357 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4358 // 0 1 2 3 4 5 6 7 8 9
4359 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);
4360 if ( !result )
4361 return; // any mails need to be returned or deleted
4362 Field *fields;
4363 //std::ostringstream delitems, delmails; //will be here for optimization
4364 //bool deletemail = false, deleteitem = false;
4365 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4366 //delmails << "DELETE FROM mail WHERE id IN ( "
4369 fields = result->Fetch();
4370 Mail *m = new Mail;
4371 m->messageID = fields[0].GetUInt32();
4372 m->messageType = fields[1].GetUInt8();
4373 m->sender = fields[2].GetUInt32();
4374 m->receiver = fields[3].GetUInt32();
4375 m->itemTextId = fields[4].GetUInt32();
4376 bool has_items = fields[5].GetBool();
4377 m->expire_time = (time_t)fields[6].GetUInt64();
4378 m->deliver_time = 0;
4379 m->COD = fields[7].GetUInt32();
4380 m->checked = fields[8].GetUInt32();
4381 m->mailTemplateId = fields[9].GetInt16();
4383 Player *pl = 0;
4384 if (serverUp)
4385 pl = GetPlayer((uint64)m->receiver);
4386 if (pl && pl->m_mailsLoaded)
4387 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4388 //his in mailbox and he has already listed his mails )
4389 delete m;
4390 continue;
4392 //delete or return mail:
4393 if (has_items)
4395 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4396 if(resultItems)
4400 Field *fields2 = resultItems->Fetch();
4402 uint32 item_guid_low = fields2[0].GetUInt32();
4403 uint32 item_template = fields2[1].GetUInt32();
4405 m->AddItem(item_guid_low, item_template);
4407 while (resultItems->NextRow());
4409 delete resultItems;
4411 //if it is mail from AH, it shouldn't be returned, but deleted
4412 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4414 // mail open and then not returned
4415 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4416 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4418 else
4420 //mail will be returned:
4421 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);
4422 delete m;
4423 continue;
4427 if (m->itemTextId)
4428 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4430 //deletemail = true;
4431 //delmails << m->messageID << ", ";
4432 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4433 delete m;
4434 } while (result->NextRow());
4435 delete result;
4438 void ObjectMgr::LoadQuestAreaTriggers()
4440 mQuestAreaTriggerMap.clear(); // need for reload case
4442 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4444 uint32 count = 0;
4446 if( !result )
4448 barGoLink bar( 1 );
4449 bar.step();
4451 sLog.outString();
4452 sLog.outString( ">> Loaded %u quest trigger points", count );
4453 return;
4456 barGoLink bar( result->GetRowCount() );
4460 ++count;
4461 bar.step();
4463 Field *fields = result->Fetch();
4465 uint32 trigger_ID = fields[0].GetUInt32();
4466 uint32 quest_ID = fields[1].GetUInt32();
4468 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4469 if(!atEntry)
4471 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4472 continue;
4475 Quest const* quest = GetQuestTemplate(quest_ID);
4477 if(!quest)
4479 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4480 continue;
4483 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4485 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);
4487 // this will prevent quest completing without objective
4488 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4490 // continue; - quest modified to required obkective and trigger can be allowed.
4493 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4495 } while( result->NextRow() );
4497 delete result;
4499 sLog.outString();
4500 sLog.outString( ">> Loaded %u quest trigger points", count );
4503 void ObjectMgr::LoadTavernAreaTriggers()
4505 mTavernAreaTriggerSet.clear(); // need for reload case
4507 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4509 uint32 count = 0;
4511 if( !result )
4513 barGoLink bar( 1 );
4514 bar.step();
4516 sLog.outString();
4517 sLog.outString( ">> Loaded %u tavern triggers", count );
4518 return;
4521 barGoLink bar( result->GetRowCount() );
4525 ++count;
4526 bar.step();
4528 Field *fields = result->Fetch();
4530 uint32 Trigger_ID = fields[0].GetUInt32();
4532 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4533 if(!atEntry)
4535 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4536 continue;
4539 mTavernAreaTriggerSet.insert(Trigger_ID);
4540 } while( result->NextRow() );
4542 delete result;
4544 sLog.outString();
4545 sLog.outString( ">> Loaded %u tavern triggers", count );
4548 void ObjectMgr::LoadAreaTriggerScripts()
4550 mAreaTriggerScripts.clear(); // need for reload case
4551 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4553 uint32 count = 0;
4555 if( !result )
4557 barGoLink bar( 1 );
4558 bar.step();
4560 sLog.outString();
4561 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4562 return;
4565 barGoLink bar( result->GetRowCount() );
4569 ++count;
4570 bar.step();
4572 Field *fields = result->Fetch();
4574 uint32 Trigger_ID = fields[0].GetUInt32();
4575 std::string scriptName = fields[1].GetCppString();
4577 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4578 if(!atEntry)
4580 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4581 continue;
4583 mAreaTriggerScripts[Trigger_ID] = scriptName;
4584 } while( result->NextRow() );
4586 delete result;
4588 sLog.outString();
4589 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4592 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4594 bool found = false;
4595 float dist;
4596 uint32 id = 0;
4598 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4600 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4601 if(node && node->map_id == mapid)
4603 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4604 if(found)
4606 if(dist2 < dist)
4608 dist = dist2;
4609 id = i;
4612 else
4614 found = true;
4615 dist = dist2;
4616 id = i;
4621 return id;
4624 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4626 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4627 if(src_i==sTaxiPathSetBySource.end())
4629 path = 0;
4630 cost = 0;
4631 return;
4634 TaxiPathSetForSource& pathSet = src_i->second;
4636 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4637 if(dest_i==pathSet.end())
4639 path = 0;
4640 cost = 0;
4641 return;
4644 cost = dest_i->second.price;
4645 path = dest_i->second.ID;
4648 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4650 uint16 mount_entry = 0;
4651 uint16 mount_id = 0;
4653 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4654 if(node)
4656 if (team == ALLIANCE)
4658 mount_entry = node->alliance_mount_type;
4659 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4660 if(ci)
4661 mount_id = ci->DisplayID_A;
4663 if (team == HORDE)
4665 mount_entry = node->horde_mount_type;
4666 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4667 if(ci)
4668 mount_id = ci->DisplayID_H;
4672 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4673 if(!minfo)
4675 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. ",
4676 mount_entry,id,team,mount_id);
4678 return false;
4680 if(minfo->modelid_other_gender!=0)
4681 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4683 return mount_id;
4686 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4688 if(path >= sTaxiPathNodesByPath.size())
4689 return;
4691 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4693 pathnodes.Resize(nodeList.size());
4694 mapIds.resize(nodeList.size());
4696 for(size_t i = 0; i < nodeList.size(); ++i)
4698 pathnodes[ i ].x = nodeList[i].x;
4699 pathnodes[ i ].y = nodeList[i].y;
4700 pathnodes[ i ].z = nodeList[i].z;
4702 mapIds[i] = nodeList[i].mapid;
4706 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4708 if(path >= sTaxiPathNodesByPath.size())
4709 return;
4711 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4713 pathnodes.Resize(nodeList.size());
4715 for(size_t i = 0; i < nodeList.size(); ++i)
4717 pathnodes[ i ].mapid = nodeList[i].mapid;
4718 pathnodes[ i ].x = nodeList[i].x;
4719 pathnodes[ i ].y = nodeList[i].y;
4720 pathnodes[ i ].z = nodeList[i].z;
4721 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4722 pathnodes[ i ].delay = nodeList[i].delay;
4726 void ObjectMgr::LoadGraveyardZones()
4728 mGraveYardMap.clear(); // need for reload case
4730 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4732 uint32 count = 0;
4734 if( !result )
4736 barGoLink bar( 1 );
4737 bar.step();
4739 sLog.outString();
4740 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4741 return;
4744 barGoLink bar( result->GetRowCount() );
4748 ++count;
4749 bar.step();
4751 Field *fields = result->Fetch();
4753 uint32 safeLocId = fields[0].GetUInt32();
4754 uint32 zoneId = fields[1].GetUInt32();
4755 uint32 team = fields[2].GetUInt32();
4757 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4758 if(!entry)
4760 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4761 continue;
4764 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4765 if(!areaEntry)
4767 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4768 continue;
4771 if(areaEntry->zone != 0)
4773 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4774 continue;
4777 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4779 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4780 continue;
4783 if(entry->map_id != areaEntry->mapid && team != 0)
4785 sLog.outErrorDb("Table `game_graveyard_zone` has record for ghost zone (%u) at map %u and graveyard (%u) at map %u for team %u, but in case maps are different, player faction setting is ignored. Use faction 0 instead.",zoneId,areaEntry->mapid, safeLocId, entry->map_id, team);
4786 team = 0;
4789 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4790 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Garveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4791 } while( result->NextRow() );
4793 delete result;
4795 sLog.outString();
4796 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4799 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4801 // search for zone associated closest graveyard
4802 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4804 // Simulate std. algorithm:
4805 // found some graveyard associated to (ghost_zone,ghost_map)
4807 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4808 // then check faction
4809 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4810 // then skip check faction
4811 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4812 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4813 if(graveLow==graveUp)
4815 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4816 return NULL;
4819 bool foundNear = false;
4820 float distNear;
4821 WorldSafeLocsEntry const* entryNear = NULL;
4822 WorldSafeLocsEntry const* entryFar = NULL;
4824 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4826 GraveYardData const& data = itr->second;
4828 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4829 if(!entry)
4831 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4832 continue;
4835 // remember first graveyard at another map and ignore other
4836 if(MapId != entry->map_id)
4838 if(!entryFar)
4839 entryFar = entry;
4840 continue;
4843 // skip enemy faction graveyard at same map (normal area, city, or battleground)
4844 // team == 0 case can be at call from .neargrave
4845 if(data.team != 0 && team != 0 && data.team != team)
4846 continue;
4848 // find now nearest graveyard at same map
4849 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4850 if(foundNear)
4852 if(dist2 < distNear)
4854 distNear = dist2;
4855 entryNear = entry;
4858 else
4860 foundNear = true;
4861 distNear = dist2;
4862 entryNear = entry;
4866 if(entryNear)
4867 return entryNear;
4869 return entryFar;
4872 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4874 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4875 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4877 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4879 if(itr->second.safeLocId==id)
4880 return &itr->second;
4883 return NULL;
4886 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4888 if(FindGraveYardData(id,zoneId))
4889 return false;
4891 // add link to loaded data
4892 GraveYardData data;
4893 data.safeLocId = id;
4894 data.team = team;
4896 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4898 // add link to DB
4899 if(inDB)
4901 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4902 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4905 return true;
4908 void ObjectMgr::LoadAreaTriggerTeleports()
4910 mAreaTriggers.clear(); // need for reload case
4912 uint32 count = 0;
4914 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4915 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");
4916 if( !result )
4919 barGoLink bar( 1 );
4921 bar.step();
4923 sLog.outString();
4924 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4925 return;
4928 barGoLink bar( result->GetRowCount() );
4932 Field *fields = result->Fetch();
4934 bar.step();
4936 ++count;
4938 uint32 Trigger_ID = fields[0].GetUInt32();
4940 AreaTrigger at;
4942 at.requiredLevel = fields[1].GetUInt8();
4943 at.requiredItem = fields[2].GetUInt32();
4944 at.requiredItem2 = fields[3].GetUInt32();
4945 at.heroicKey = fields[4].GetUInt32();
4946 at.heroicKey2 = fields[5].GetUInt32();
4947 at.requiredQuest = fields[6].GetUInt32();
4948 at.requiredFailedText = fields[7].GetCppString();
4949 at.target_mapId = fields[8].GetUInt32();
4950 at.target_X = fields[9].GetFloat();
4951 at.target_Y = fields[10].GetFloat();
4952 at.target_Z = fields[11].GetFloat();
4953 at.target_Orientation = fields[12].GetFloat();
4955 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4956 if(!atEntry)
4958 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4959 continue;
4962 if(at.requiredItem)
4964 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4965 if(!pProto)
4967 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4968 at.requiredItem = 0;
4971 if(at.requiredItem2)
4973 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4974 if(!pProto)
4976 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4977 at.requiredItem2 = 0;
4981 if(at.heroicKey)
4983 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4984 if(!pProto)
4986 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4987 at.heroicKey = 0;
4991 if(at.heroicKey2)
4993 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4994 if(!pProto)
4996 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4997 at.heroicKey2 = 0;
5001 if(at.requiredQuest)
5003 if(!mQuestTemplates[at.requiredQuest])
5005 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5006 at.requiredQuest = 0;
5010 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5011 if(!mapEntry)
5013 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5014 continue;
5017 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5019 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5020 continue;
5023 mAreaTriggers[Trigger_ID] = at;
5025 } while( result->NextRow() );
5027 delete result;
5029 sLog.outString();
5030 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5033 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5035 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5036 if(!mapEntry) return NULL;
5037 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
5039 if(itr->second.target_mapId == mapEntry->entrance_map)
5041 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5042 if(atEntry && atEntry->mapid == Map)
5043 return &itr->second;
5046 return NULL;
5049 void ObjectMgr::SetHighestGuids()
5051 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5052 if( result )
5054 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5056 delete result;
5059 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5060 if( result )
5062 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5064 delete result;
5067 result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
5068 if( result )
5070 m_hiPetGuid = (*result)[0].GetUInt32()+1;
5072 delete result;
5075 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5076 if( result )
5078 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5080 delete result;
5083 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5084 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5085 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5086 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5087 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5089 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5090 if( result )
5092 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5094 delete result;
5097 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5098 if( result )
5100 m_auctionid = (*result)[0].GetUInt32()+1;
5102 delete result;
5104 else
5106 m_auctionid = 0;
5108 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5109 if( result )
5111 m_mailid = (*result)[0].GetUInt32()+1;
5113 delete result;
5115 else
5117 m_mailid = 0;
5119 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5120 if( result )
5122 m_ItemTextId = (*result)[0].GetUInt32();
5124 delete result;
5126 else
5127 m_ItemTextId = 0;
5129 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5130 if( result )
5132 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5134 delete result;
5138 uint32 ObjectMgr::GenerateAuctionID()
5140 ++m_auctionid;
5141 if(m_auctionid>=0xFFFFFFFF)
5143 sLog.outError("Auctions ids overflow!! Can't continue, shuting down server. ");
5144 sWorld.m_stopEvent = true;
5146 return m_auctionid;
5149 uint32 ObjectMgr::GenerateMailID()
5151 ++m_mailid;
5152 if(m_mailid>=0xFFFFFFFF)
5154 sLog.outError("Mail ids overflow!! Can't continue, shuting down server. ");
5155 sWorld.m_stopEvent = true;
5157 return m_mailid;
5160 uint32 ObjectMgr::GenerateItemTextID()
5162 ++m_ItemTextId;
5163 if(m_ItemTextId>=0xFFFFFFFF)
5165 sLog.outError("Item text ids overflow!! Can't continue, shuting down server. ");
5166 sWorld.m_stopEvent = true;
5168 return m_ItemTextId;
5171 uint32 ObjectMgr::CreateItemText(std::string text)
5173 uint32 newItemTextId = GenerateItemTextID();
5174 //insert new itempage to container
5175 mItemTexts[ newItemTextId ] = text;
5176 //save new itempage
5177 CharacterDatabase.escape_string(text);
5178 //any Delete query needed, itemTextId is maximum of all ids
5179 std::ostringstream query;
5180 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5181 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5182 return newItemTextId;
5185 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5187 switch(guidhigh)
5189 case HIGHGUID_ITEM:
5190 ++m_hiItemGuid;
5191 if(m_hiItemGuid>=0xFFFFFFFF)
5193 sLog.outError("Item guid overflow!! Can't continue, shuting down server. ");
5194 sWorld.m_stopEvent = true;
5196 return m_hiItemGuid;
5197 case HIGHGUID_UNIT:
5198 ++m_hiCreatureGuid;
5199 if(m_hiCreatureGuid>=0x00FFFFFF)
5201 sLog.outError("Creature guid overflow!! Can't continue, shuting down server. ");
5202 sWorld.m_stopEvent = true;
5204 return m_hiCreatureGuid;
5205 case HIGHGUID_PET:
5206 ++m_hiPetGuid;
5207 if(m_hiPetGuid>=0x00FFFFFF)
5209 sLog.outError("Pet guid overflow!! Can't continue, shuting down server. ");
5210 sWorld.m_stopEvent = true;
5212 return m_hiPetGuid;
5213 case HIGHGUID_PLAYER:
5214 ++m_hiCharGuid;
5215 if(m_hiCharGuid>=0xFFFFFFFF)
5217 sLog.outError("Players guid overflow!! Can't continue, shuting down server. ");
5218 sWorld.m_stopEvent = true;
5220 return m_hiCharGuid;
5221 case HIGHGUID_GAMEOBJECT:
5222 ++m_hiGoGuid;
5223 if(m_hiGoGuid>=0x00FFFFFF)
5225 sLog.outError("Gameobject guid overflow!! Can't continue, shuting down server. ");
5226 sWorld.m_stopEvent = true;
5228 return m_hiGoGuid;
5229 case HIGHGUID_CORPSE:
5230 ++m_hiCorpseGuid;
5231 if(m_hiCorpseGuid>=0xFFFFFFFF)
5233 sLog.outError("Corpse guid overflow!! Can't continue, shuting down server. ");
5234 sWorld.m_stopEvent = true;
5236 return m_hiCorpseGuid;
5237 case HIGHGUID_DYNAMICOBJECT:
5238 ++m_hiDoGuid;
5239 if(m_hiDoGuid>=0xFFFFFFFF)
5241 sLog.outError("DynamicObject guid overflow!! Can't continue, shuting down server. ");
5242 sWorld.m_stopEvent = true;
5244 return m_hiDoGuid;
5245 default:
5246 ASSERT(0);
5249 ASSERT(0);
5250 return 0;
5253 void ObjectMgr::LoadGameObjectLocales()
5255 mGameObjectLocaleMap.clear(); // need for reload case
5257 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5258 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5259 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5260 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5262 if(!result)
5264 barGoLink bar(1);
5266 bar.step();
5268 sLog.outString("");
5269 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5270 return;
5273 barGoLink bar(result->GetRowCount());
5277 Field *fields = result->Fetch();
5278 bar.step();
5280 uint32 entry = fields[0].GetUInt32();
5282 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5284 for(int i = 1; i < MAX_LOCALE; ++i)
5286 std::string str = fields[i].GetCppString();
5287 if(!str.empty())
5289 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5290 if(idx >= 0)
5292 if(data.Name.size() <= idx)
5293 data.Name.resize(idx+1);
5295 data.Name[idx] = str;
5300 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5302 std::string str = fields[i].GetCppString();
5303 if(!str.empty())
5305 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5306 if(idx >= 0)
5308 if(data.CastBarCaption.size() <= idx)
5309 data.CastBarCaption.resize(idx+1);
5311 data.CastBarCaption[idx] = str;
5316 } while (result->NextRow());
5318 delete result;
5320 sLog.outString();
5321 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5324 void ObjectMgr::LoadGameobjectInfo()
5326 sGOStorage.Load();
5328 // some checks
5329 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5331 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5332 if(!goInfo)
5333 continue;
5335 switch(goInfo->type)
5337 case GAMEOBJECT_TYPE_DOOR: //0
5339 if(goInfo->door.lockId)
5341 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5342 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5343 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5345 break;
5347 case GAMEOBJECT_TYPE_BUTTON: //1
5349 if(goInfo->button.lockId)
5351 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5352 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5353 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5355 break;
5357 case GAMEOBJECT_TYPE_CHEST: //3
5359 if(goInfo->chest.lockId)
5361 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5362 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5363 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5365 if(goInfo->chest.linkedTrapId) // linked trap
5367 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5369 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5370 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5371 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5373 /* disable check for while
5374 else
5375 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5376 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5379 break;
5381 case GAMEOBJECT_TYPE_TRAP: //6
5383 /* disable check for while
5384 if(goInfo->trap.spellId) // spell
5386 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5387 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5388 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5391 break;
5393 case GAMEOBJECT_TYPE_CHAIR: //7
5394 if(goInfo->chair.height > 2)
5396 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5397 id,goInfo->type,goInfo->chair.height);
5399 // prevent client and server unexpected work
5400 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5402 break;
5403 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5405 if(goInfo->spellFocus.focusId)
5407 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5408 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5409 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5412 if(goInfo->spellFocus.linkedTrapId) // linked trap
5414 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5416 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5417 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5418 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5420 /* disable check for while
5421 else
5422 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5423 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5426 break;
5428 case GAMEOBJECT_TYPE_GOOBER: //10
5430 if(goInfo->goober.pageId) // pageId
5432 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5433 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5434 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5436 /* disable check for while
5437 if(goInfo->goober.spellId) // spell
5439 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5440 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5441 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5444 if(goInfo->goober.linkedTrapId) // linked trap
5446 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5448 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5449 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5450 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5452 /* disable check for while
5453 else
5454 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5455 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5458 break;
5460 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5462 if(goInfo->moTransport.taxiPathId)
5464 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5465 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5466 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5468 break;
5470 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5472 /* disabled
5473 if(goInfo->summoningRitual.spellId)
5475 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5476 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5477 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5480 break;
5482 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5484 if(goInfo->spellcaster.spellId) // spell
5486 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5487 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5488 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5490 break;
5495 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5496 sLog.outString();
5499 void ObjectMgr::LoadExplorationBaseXP()
5501 uint32 count = 0;
5502 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5504 if( !result )
5506 barGoLink bar( 1 );
5508 bar.step();
5510 sLog.outString();
5511 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5512 return;
5515 barGoLink bar( result->GetRowCount() );
5519 bar.step();
5521 Field *fields = result->Fetch();
5522 uint32 level = fields[0].GetUInt32();
5523 uint32 basexp = fields[1].GetUInt32();
5524 mBaseXPTable[level] = basexp;
5525 ++count;
5527 while (result->NextRow());
5529 delete result;
5531 sLog.outString();
5532 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5535 uint32 ObjectMgr::GetBaseXP(uint32 level)
5537 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5540 void ObjectMgr::LoadPetNames()
5542 uint32 count = 0;
5543 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5545 if( !result )
5547 barGoLink bar( 1 );
5549 bar.step();
5551 sLog.outString();
5552 sLog.outString( ">> Loaded %u pet name parts", count );
5553 return;
5556 barGoLink bar( result->GetRowCount() );
5560 bar.step();
5562 Field *fields = result->Fetch();
5563 std::string word = fields[0].GetString();
5564 uint32 entry = fields[1].GetUInt32();
5565 bool half = fields[2].GetBool();
5566 if(half)
5567 PetHalfName1[entry].push_back(word);
5568 else
5569 PetHalfName0[entry].push_back(word);
5570 ++count;
5572 while (result->NextRow());
5573 delete result;
5575 sLog.outString();
5576 sLog.outString( ">> Loaded %u pet name parts", count );
5579 void ObjectMgr::LoadPetNumber()
5581 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5582 if(result)
5584 Field *fields = result->Fetch();
5585 m_hiPetNumber = fields[0].GetUInt32()+1;
5586 delete result;
5589 barGoLink bar( 1 );
5590 bar.step();
5592 sLog.outString();
5593 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5596 std::string ObjectMgr::GeneratePetName(uint32 entry)
5598 std::vector<std::string> & list0 = PetHalfName0[entry];
5599 std::vector<std::string> & list1 = PetHalfName1[entry];
5601 if(list0.empty() || list1.empty())
5603 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5604 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5605 if(!petname)
5606 petname = cinfo->Name;
5607 return std::string(petname);
5610 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5613 uint32 ObjectMgr::GeneratePetNumber()
5615 return ++m_hiPetNumber;
5618 void ObjectMgr::LoadCorpses()
5620 uint32 count = 0;
5621 // 0 1 2 3 4 5 6 7 8 10
5622 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5624 if( !result )
5626 barGoLink bar( 1 );
5628 bar.step();
5630 sLog.outString();
5631 sLog.outString( ">> Loaded %u corpses", count );
5632 return;
5635 barGoLink bar( result->GetRowCount() );
5639 bar.step();
5641 Field *fields = result->Fetch();
5643 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5645 Corpse *corpse = new Corpse;
5646 if(!corpse->LoadFromDB(guid,fields))
5648 delete corpse;
5649 continue;
5652 ObjectAccessor::Instance().AddCorpse(corpse);
5654 ++count;
5656 while (result->NextRow());
5657 delete result;
5659 sLog.outString();
5660 sLog.outString( ">> Loaded %u corpses", count );
5663 void ObjectMgr::LoadReputationOnKill()
5665 uint32 count = 0;
5667 // 0 1 2
5668 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5669 // 3 4 5 6 7 8 9
5670 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5671 "FROM creature_onkill_reputation");
5673 if(!result)
5675 barGoLink bar(1);
5677 bar.step();
5679 sLog.outString();
5680 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5681 return;
5684 barGoLink bar(result->GetRowCount());
5688 Field *fields = result->Fetch();
5689 bar.step();
5691 uint32 creature_id = fields[0].GetUInt32();
5693 ReputationOnKillEntry repOnKill;
5694 repOnKill.repfaction1 = fields[1].GetUInt32();
5695 repOnKill.repfaction2 = fields[2].GetUInt32();
5696 repOnKill.is_teamaward1 = fields[3].GetBool();
5697 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5698 repOnKill.repvalue1 = fields[5].GetInt32();
5699 repOnKill.is_teamaward2 = fields[6].GetBool();
5700 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5701 repOnKill.repvalue2 = fields[8].GetInt32();
5702 repOnKill.team_dependent = fields[9].GetUInt8();
5704 if(!GetCreatureTemplate(creature_id))
5706 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5707 continue;
5710 if(repOnKill.repfaction1)
5712 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5713 if(!factionEntry1)
5715 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5716 continue;
5720 if(repOnKill.repfaction2)
5722 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5723 if(!factionEntry2)
5725 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5726 continue;
5730 mRepOnKill[creature_id] = repOnKill;
5732 ++count;
5733 } while (result->NextRow());
5735 delete result;
5737 sLog.outString();
5738 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5741 void ObjectMgr::LoadWeatherZoneChances()
5743 uint32 count = 0;
5745 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5746 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");
5748 if(!result)
5750 barGoLink bar(1);
5752 bar.step();
5754 sLog.outString();
5755 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5756 return;
5759 barGoLink bar(result->GetRowCount());
5763 Field *fields = result->Fetch();
5764 bar.step();
5766 uint32 zone_id = fields[0].GetUInt32();
5768 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5770 for(int season = 0; season < WEATHER_SEASONS; ++season)
5772 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5773 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5774 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5776 if(wzc.data[season].rainChance > 100)
5778 wzc.data[season].rainChance = 25;
5779 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5782 if(wzc.data[season].snowChance > 100)
5784 wzc.data[season].snowChance = 25;
5785 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5788 if(wzc.data[season].stormChance > 100)
5790 wzc.data[season].stormChance = 25;
5791 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5795 ++count;
5796 } while (result->NextRow());
5798 delete result;
5800 sLog.outString();
5801 sLog.outString(">> Loaded %u weather definitions", count);
5804 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5806 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5807 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5808 if(t)
5809 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5812 void ObjectMgr::DeleteCreatureData(uint32 guid)
5814 // remove mapid*cellid -> guid_set map
5815 CreatureData const* data = GetCreatureData(guid);
5816 if(data)
5817 RemoveCreatureFromGrid(guid, data);
5819 mCreatureDataMap.erase(guid);
5822 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5824 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5825 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5826 if(t)
5827 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5830 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5832 RespawnTimes::iterator next;
5834 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5836 next = itr;
5837 ++next;
5839 if(GUID_HIPART(itr->first)==instance)
5840 mGORespawnTimes.erase(itr);
5843 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5845 next = itr;
5846 ++next;
5848 if(GUID_HIPART(itr->first)==instance)
5849 mCreatureRespawnTimes.erase(itr);
5852 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5853 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5856 void ObjectMgr::DeleteGOData(uint32 guid)
5858 // remove mapid*cellid -> guid_set map
5859 GameObjectData const* data = GetGOData(guid);
5860 if(data)
5861 RemoveGameobjectFromGrid(guid, data);
5863 mGameObjectDataMap.erase(guid);
5866 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5868 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5869 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5870 cell_guids.corpses[player_guid] = instance;
5873 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5875 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5876 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5877 cell_guids.corpses.erase(player_guid);
5880 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5882 map.clear(); // need for reload case
5884 uint32 count = 0;
5886 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5888 if(!result)
5890 barGoLink bar(1);
5892 bar.step();
5894 sLog.outString();
5895 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5896 return;
5899 barGoLink bar(result->GetRowCount());
5903 Field *fields = result->Fetch();
5904 bar.step();
5906 uint32 id = fields[0].GetUInt32();
5907 uint32 quest = fields[1].GetUInt32();
5909 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5911 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5912 continue;
5915 map.insert(QuestRelations::value_type(id,quest));
5917 ++count;
5918 } while (result->NextRow());
5920 delete result;
5922 sLog.outString();
5923 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5926 void ObjectMgr::LoadGameobjectQuestRelations()
5928 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5930 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5932 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5933 if(!goInfo)
5934 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5935 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5936 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5940 void ObjectMgr::LoadGameobjectInvolvedRelations()
5942 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5944 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5946 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5947 if(!goInfo)
5948 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5949 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5950 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5954 void ObjectMgr::LoadCreatureQuestRelations()
5956 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5958 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5960 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5961 if(!cInfo)
5962 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5963 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5964 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);
5968 void ObjectMgr::LoadCreatureInvolvedRelations()
5970 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
5972 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
5974 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5975 if(!cInfo)
5976 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5977 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5978 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);
5982 void ObjectMgr::LoadReservedPlayersNames()
5984 m_ReservedNames.clear(); // need for reload case
5986 QueryResult *result = WorldDatabase.PQuery("SELECT name FROM reserved_name");
5988 uint32 count = 0;
5990 if( !result )
5992 barGoLink bar( 1 );
5993 bar.step();
5995 sLog.outString();
5996 sLog.outString( ">> Loaded %u reserved player names", count );
5997 return;
6000 barGoLink bar( result->GetRowCount() );
6002 Field* fields;
6005 bar.step();
6006 fields = result->Fetch();
6007 std::string name= fields[0].GetCppString();
6008 if(normalizePlayerName(name))
6010 m_ReservedNames.insert(name);
6011 ++count;
6013 } while ( result->NextRow() );
6015 delete result;
6017 sLog.outString();
6018 sLog.outString( ">> Loaded %u reserved player names", count );
6021 enum LanguageType
6023 LT_BASIC_LATIN = 0x0000,
6024 LT_EXTENDEN_LATIN = 0x0001,
6025 LT_CYRILLIC = 0x0002,
6026 LT_EAST_ASIA = 0x0004,
6027 LT_ANY = 0xFFFF
6030 static LanguageType GetRealmLanguageType(bool create)
6032 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6034 case REALM_ZONE_UNKNOWN: // any language
6035 case REALM_ZONE_DEVELOPMENT:
6036 case REALM_ZONE_TEST_SERVER:
6037 case REALM_ZONE_QA_SERVER:
6038 return LT_ANY;
6039 case REALM_ZONE_UNITED_STATES: // extended-Latin
6040 case REALM_ZONE_OCEANIC:
6041 case REALM_ZONE_LATIN_AMERICA:
6042 case REALM_ZONE_ENGLISH:
6043 case REALM_ZONE_GERMAN:
6044 case REALM_ZONE_FRENCH:
6045 case REALM_ZONE_SPANISH:
6046 return LT_EXTENDEN_LATIN;
6047 case REALM_ZONE_KOREA: // East-Asian
6048 case REALM_ZONE_TAIWAN:
6049 case REALM_ZONE_CHINA:
6050 return LT_EAST_ASIA;
6051 case REALM_ZONE_RUSSIAN: // Cyrillic
6052 return LT_CYRILLIC;
6053 default:
6054 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6058 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6060 if(strictMask==0) // any language, ignore realm
6062 if(isExtendedLatinString(wstr,numericOrSpace))
6063 return true;
6064 if(isCyrillicString(wstr,numericOrSpace))
6065 return true;
6066 if(isEastAsianString(wstr,numericOrSpace))
6067 return true;
6068 return false;
6071 if(strictMask & 0x2) // realm zone specific
6073 LanguageType lt = GetRealmLanguageType(create);
6074 if(lt & LT_EXTENDEN_LATIN)
6075 if(isExtendedLatinString(wstr,numericOrSpace))
6076 return true;
6077 if(lt & LT_CYRILLIC)
6078 if(isCyrillicString(wstr,numericOrSpace))
6079 return true;
6080 if(lt & LT_EAST_ASIA)
6081 if(isEastAsianString(wstr,numericOrSpace))
6082 return true;
6085 if(strictMask & 0x1) // basic latin
6087 if(isBasicLatinString(wstr,numericOrSpace))
6088 return true;
6091 return false;
6094 bool ObjectMgr::IsValidName( std::string name, bool create )
6096 std::wstring wname;
6097 if(!Utf8toWStr(name,wname))
6098 return false;
6100 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6101 return false;
6103 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6105 return isValidString(wname,strictMask,false,create);
6108 bool ObjectMgr::IsValidCharterName( std::string name )
6110 std::wstring wname;
6111 if(!Utf8toWStr(name,wname))
6112 return false;
6114 if(wname.size() < 1)
6115 return false;
6117 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6119 return isValidString(wname,strictMask,true);
6122 bool ObjectMgr::IsValidPetName( std::string name )
6124 std::wstring wname;
6125 if(!Utf8toWStr(name,wname))
6126 return false;
6128 if(wname.size() < 1)
6129 return false;
6131 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6133 return isValidString(wname,strictMask,false);
6136 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6138 if(loc==LOCALE_enUS)
6139 return -1;
6141 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6142 if(m_LocalForIndex[i]==loc)
6143 return i;
6145 return -1;
6148 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6150 if (i<0 || i>=m_LocalForIndex.size())
6151 return LOCALE_enUS;
6153 return m_LocalForIndex[i];
6156 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6158 if(loc==LOCALE_enUS)
6159 return -1;
6161 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6162 if(m_LocalForIndex[i]==loc)
6163 return i;
6165 m_LocalForIndex.push_back(loc);
6166 return m_LocalForIndex.size()-1;
6169 AchievementCriteriaEntryList const& ObjectMgr::GetAchievementCriteriaByType(AchievementCriteriaTypes type)
6171 return m_AchievementCriteriasByType[type];
6174 void ObjectMgr::LoadAchievementCriteriaList()
6176 for (uint32 entryId = 0; entryId<sAchievementCriteriaStore.GetNumRows(); entryId++)
6178 AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId);
6179 if(!criteria)
6180 continue;
6182 m_AchievementCriteriasByType[criteria->requiredType].push_back(criteria);
6186 void ObjectMgr::LoadBattleMastersEntry()
6188 mBattleMastersMap.clear(); // need for reload case
6190 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6192 uint32 count = 0;
6194 if( !result )
6196 barGoLink bar( 1 );
6197 bar.step();
6199 sLog.outString();
6200 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6201 return;
6204 barGoLink bar( result->GetRowCount() );
6208 ++count;
6209 bar.step();
6211 Field *fields = result->Fetch();
6213 uint32 entry = fields[0].GetUInt32();
6214 uint32 bgTypeId = fields[1].GetUInt32();
6216 mBattleMastersMap[entry] = bgTypeId;
6218 } while( result->NextRow() );
6220 delete result;
6222 sLog.outString();
6223 sLog.outString( ">> Loaded %u battlemaster entries", count );
6226 void ObjectMgr::LoadGameObjectForQuests()
6228 mGameObjectForQuestSet.clear(); // need for reload case
6230 uint32 count = 0;
6232 // collect GO entries for GO that must activated
6233 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6235 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6236 if(!goInfo)
6237 continue;
6239 switch(goInfo->type)
6241 // scan GO chest with loot including quest items
6242 case GAMEOBJECT_TYPE_CHEST:
6244 uint32 loot_id = GameObject::GetLootId(goInfo);
6246 // find quest loot for GO
6247 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6249 mGameObjectForQuestSet.insert(go_entry);
6250 ++count;
6252 break;
6254 case GAMEOBJECT_TYPE_GOOBER:
6256 if(goInfo->goober.questId) //quests objects
6258 mGameObjectForQuestSet.insert(go_entry);
6259 count++;
6261 break;
6263 default:
6264 break;
6268 sLog.outString();
6269 sLog.outString( ">> Loaded %u GameObject for quests", count );
6272 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6274 // cleanup affected map part for reloading case
6275 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6277 if(itr->first >= min_value && itr->first <= max_value)
6279 MangosStringLocaleMap::iterator itr2 = itr;
6280 ++itr;
6281 mMangosStringLocaleMap.erase(itr2);
6283 else
6284 ++itr;
6287 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);
6289 if(!result)
6291 barGoLink bar(1);
6293 bar.step();
6295 sLog.outString("");
6296 if(min_value > 0) // error only in case internal strings
6297 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6298 else
6299 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6300 return false;
6303 uint32 count = 0;
6305 barGoLink bar(result->GetRowCount());
6309 Field *fields = result->Fetch();
6310 bar.step();
6312 int32 entry = fields[0].GetInt32();
6314 if(entry==0)
6316 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6317 continue;
6319 else if(entry < min_value || entry > max_value)
6321 int32 start = min_value > 0 ? min_value : max_value;
6322 int32 end = min_value > 0 ? max_value : min_value;
6323 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6324 continue;
6327 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6329 if(data.Content.size() > 0)
6331 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6332 continue;
6335 data.Content.resize(1);
6336 ++count;
6338 // 0 -> default, idx in to idx+1
6339 data.Content[0] = fields[1].GetCppString();
6341 for(int i = 1; i < MAX_LOCALE; ++i)
6343 std::string str = fields[i+1].GetCppString();
6344 if(!str.empty())
6346 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6347 if(idx >= 0)
6349 // 0 -> default, idx in to idx+1
6350 if(data.Content.size() <= idx+1)
6351 data.Content.resize(idx+2);
6353 data.Content[idx+1] = str;
6357 } while (result->NextRow());
6359 delete result;
6361 sLog.outString();
6362 if(min_value > 0) // internal mangos strings
6363 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6364 else
6365 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6367 return true;
6370 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6372 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6373 // Content[0] always exist if exist MangosStringLocale
6374 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6376 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6377 return msl->Content[locale_idx+1].c_str();
6378 else
6379 return msl->Content[0].c_str();
6382 if(entry > 0)
6383 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6384 else
6385 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6386 return "<error>";
6389 void ObjectMgr::LoadFishingBaseSkillLevel()
6391 mFishingBaseForArea.clear(); // for relaod case
6393 uint32 count = 0;
6394 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6396 if( !result )
6398 barGoLink bar( 1 );
6400 bar.step();
6402 sLog.outString();
6403 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6404 return;
6407 barGoLink bar( result->GetRowCount() );
6411 bar.step();
6413 Field *fields = result->Fetch();
6414 uint32 entry = fields[0].GetUInt32();
6415 int32 skill = fields[1].GetInt32();
6417 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6418 if(!fArea)
6420 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6421 continue;
6424 mFishingBaseForArea[entry] = skill;
6425 ++count;
6427 while (result->NextRow());
6429 delete result;
6431 sLog.outString();
6432 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6435 // Searches for the same condition already in Conditions store
6436 // Returns Id if found, else adds it to Conditions and returns Id
6437 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6439 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6440 for (uint16 i=0; i < mConditions.size(); ++i)
6442 if (lc == mConditions[i])
6443 return i;
6446 mConditions.push_back(lc);
6448 if(mConditions.size() > 0xFFFF)
6450 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6451 return 0;
6454 return mConditions.size() - 1;
6457 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6459 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6461 std::wstring wname;
6462 if(!Utf8toWStr(names.name[i],wname))
6463 return false;
6465 if(mainpart!=GetMainPartOfName(wname,i+1))
6466 return false;
6468 return true;
6471 const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6473 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6474 if(i!= mAreaTriggerScripts.end())
6475 return i->second.c_str();
6476 return "";
6479 // Checks if player meets the condition
6480 bool PlayerCondition::Meets(Player const * player) const
6482 if( !player )
6483 return false; // player not present, return false
6485 switch (condition)
6487 case CONDITION_NONE:
6488 return true; // empty condition, always met
6489 case CONDITION_AURA:
6490 return player->HasAura(value1, value2);
6491 case CONDITION_ITEM:
6492 return player->HasItemCount(value1, value2);
6493 case CONDITION_ITEM_EQUIPPED:
6494 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6495 case CONDITION_ZONEID:
6496 return player->GetZoneId() == value1;
6497 case CONDITION_REPUTATION_RANK:
6499 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6500 return faction && player->GetReputationRank(faction) >= value2;
6502 case CONDITION_TEAM:
6503 return player->GetTeam() == value1;
6504 case CONDITION_SKILL:
6505 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6506 case CONDITION_QUESTREWARDED:
6507 return player->GetQuestRewardStatus(value1);
6508 case CONDITION_QUESTTAKEN:
6510 QuestStatus status = player->GetQuestStatus(value1);
6511 return (status == QUEST_STATUS_INCOMPLETE);
6513 case CONDITION_AD_COMMISSION_AURA:
6515 Unit::AuraMap const& auras = player->GetAuras();
6516 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6517 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6518 return true;
6519 return false;
6521 case CONDITION_NO_AURA:
6522 return !player->HasAura(value1, value2);
6523 case CONDITION_ACTIVE_EVENT:
6524 return gameeventmgr.IsActiveEvent(value1);
6525 default:
6526 return false;
6530 // Verification of condition values validity
6531 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6533 if( condition >= MAX_CONDITION) // Wrong condition type
6535 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6536 return false;
6539 switch (condition)
6541 case CONDITION_AURA:
6543 if(!sSpellStore.LookupEntry(value1))
6545 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6546 return false;
6548 if(value2 > 2)
6550 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6551 return false;
6553 break;
6555 case CONDITION_ITEM:
6557 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6558 if(!proto)
6560 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6561 return false;
6563 break;
6565 case CONDITION_ITEM_EQUIPPED:
6567 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6568 if(!proto)
6570 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6571 return false;
6573 break;
6575 case CONDITION_ZONEID:
6577 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6578 if(!areaEntry)
6580 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6581 return false;
6583 if(areaEntry->zone != 0)
6585 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6586 return false;
6588 break;
6590 case CONDITION_REPUTATION_RANK:
6592 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6593 if(!factionEntry)
6595 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6596 return false;
6598 break;
6600 case CONDITION_TEAM:
6602 if (value1 != ALLIANCE && value1 != HORDE)
6604 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6605 return false;
6607 break;
6609 case CONDITION_SKILL:
6611 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6612 if (!pSkill)
6614 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6615 return false;
6617 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6619 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6620 return false;
6622 break;
6624 case CONDITION_QUESTREWARDED:
6625 case CONDITION_QUESTTAKEN:
6627 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6628 if (!Quest)
6630 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6631 return false;
6633 if(value2)
6634 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6635 break;
6637 case CONDITION_AD_COMMISSION_AURA:
6639 if(value1)
6640 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6641 if(value2)
6642 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6643 break;
6645 case CONDITION_NO_AURA:
6647 if(!sSpellStore.LookupEntry(value1))
6649 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6650 return false;
6652 if(value2 > 2)
6654 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6655 return false;
6657 break;
6659 case CONDITION_ACTIVE_EVENT:
6661 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6662 if(value1 >=events.size() || !events[value1].isValid())
6664 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6665 return false;
6667 break;
6670 return true;
6673 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6675 switch(pSkill->categoryId)
6677 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6678 case SKILL_CATEGORY_WEAPON:
6679 if(pSkill->id!=SKILL_FIST_WEAPONS)
6680 return SKILL_RANGE_LEVEL;
6681 else
6682 return SKILL_RANGE_MONO;
6683 case SKILL_CATEGORY_ARMOR:
6684 case SKILL_CATEGORY_CLASS:
6685 if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6686 return SKILL_RANGE_MONO;
6687 else
6688 return SKILL_RANGE_LEVEL;
6689 case SKILL_CATEGORY_SECONDARY:
6690 case SKILL_CATEGORY_PROFESSION:
6691 // not set skills for professions and racial abilities
6692 if(IsProfessionSkill(pSkill->id))
6693 return SKILL_RANGE_RANK;
6694 else if(racial)
6695 return SKILL_RANGE_NONE;
6696 else
6697 return SKILL_RANGE_MONO;
6698 default:
6699 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6700 case SKILL_CATEGORY_NOT_DISPLAYED: //only GENEREC(DND)
6701 return SKILL_RANGE_NONE;
6705 void ObjectMgr::LoadGameTele()
6707 m_GameTeleMap.clear(); // for relaod case
6709 uint32 count = 0;
6710 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6712 if( !result )
6714 barGoLink bar( 1 );
6716 bar.step();
6718 sLog.outString();
6719 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6720 return;
6723 barGoLink bar( result->GetRowCount() );
6727 bar.step();
6729 Field *fields = result->Fetch();
6731 uint32 id = fields[0].GetUInt32();
6733 GameTele gt;
6735 gt.position_x = fields[1].GetFloat();
6736 gt.position_y = fields[2].GetFloat();
6737 gt.position_z = fields[3].GetFloat();
6738 gt.orientation = fields[4].GetFloat();
6739 gt.mapId = fields[5].GetUInt32();
6740 gt.name = fields[6].GetCppString();
6742 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6744 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6745 continue;
6748 if(!Utf8toWStr(gt.name,gt.wnameLow))
6750 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6751 continue;
6754 wstrToLower( gt.wnameLow );
6756 m_GameTeleMap[id] = gt;
6758 ++count;
6760 while (result->NextRow());
6762 delete result;
6764 sLog.outString();
6765 sLog.outString( ">> Loaded %u game tele's", count );
6768 GameTele const* ObjectMgr::GetGameTele(std::string name) const
6770 // explicit name case
6771 std::wstring wname;
6772 if(!Utf8toWStr(name,wname))
6773 return false;
6775 // converting string that we try to find to lower case
6776 wstrToLower( wname );
6778 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6779 const GameTele* alt = NULL;
6780 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6781 if(itr->second.wnameLow == wname)
6782 return &itr->second;
6783 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6784 alt = &itr->second;
6786 return alt;
6789 bool ObjectMgr::AddGameTele(GameTele& tele)
6791 // find max id
6792 uint32 new_id = 0;
6793 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6794 if(itr->first > new_id)
6795 new_id = itr->first;
6797 // use next
6798 ++new_id;
6800 if(!Utf8toWStr(tele.name,tele.wnameLow))
6801 return false;
6803 wstrToLower( tele.wnameLow );
6805 m_GameTeleMap[new_id] = tele;
6807 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')",
6808 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6811 bool ObjectMgr::DeleteGameTele(std::string name)
6813 // explicit name case
6814 std::wstring wname;
6815 if(!Utf8toWStr(name,wname))
6816 return false;
6818 // converting string that we try to find to lower case
6819 wstrToLower( wname );
6821 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6823 if(itr->second.wnameLow == wname)
6825 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6826 m_GameTeleMap.erase(itr);
6827 return true;
6831 return false;
6834 void ObjectMgr::LoadTrainerSpell()
6836 // For reload case
6837 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6838 itr->second.Clear();
6839 m_mCacheTrainerSpellMap.clear();
6841 std::set<uint32> skip_trainers;
6843 QueryResult *result = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6845 if( !result )
6847 barGoLink bar( 1 );
6849 bar.step();
6851 sLog.outString();
6852 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6853 return;
6856 barGoLink bar( result->GetRowCount() );
6858 uint32 count = 0;
6861 bar.step();
6863 Field* fields = result->Fetch();
6865 uint32 entry = fields[0].GetUInt32();
6866 uint32 spell = fields[1].GetUInt32();
6868 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6870 if(!cInfo)
6872 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6873 continue;
6876 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6878 if(skip_trainers.count(entry) == 0)
6880 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6881 skip_trainers.insert(entry);
6883 continue;
6886 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6887 if(!spellinfo)
6889 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6890 continue;
6893 if(!SpellMgr::IsSpellValid(spellinfo))
6895 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6896 continue;
6899 TrainerSpell* pTrainerSpell = new TrainerSpell();
6900 pTrainerSpell->spell = spell;
6901 pTrainerSpell->spellcost = fields[2].GetUInt32();
6902 pTrainerSpell->reqskill = fields[3].GetUInt32();
6903 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6904 pTrainerSpell->reqlevel = fields[5].GetUInt32();
6906 if(!pTrainerSpell->reqlevel)
6907 pTrainerSpell->reqlevel = spellinfo->spellLevel;
6910 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6912 if(SpellMgr::IsProfessionSpell(spell))
6913 data.trainerType = 2;
6915 data.spellList.push_back(pTrainerSpell);
6916 ++count;
6918 } while (result->NextRow());
6919 delete result;
6921 sLog.outString();
6922 sLog.outString( ">> Loaded Trainers %d", count );
6925 void ObjectMgr::LoadVendors()
6927 // For reload case
6928 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6929 itr->second.Clear();
6930 m_mCacheVendorItemMap.clear();
6932 std::set<uint32> skip_vendors;
6934 QueryResult *result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6935 if( !result )
6937 barGoLink bar( 1 );
6939 bar.step();
6941 sLog.outString();
6942 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6943 return;
6946 barGoLink bar( result->GetRowCount() );
6948 uint32 count = 0;
6951 bar.step();
6952 Field* fields = result->Fetch();
6954 uint32 entry = fields[0].GetUInt32();
6955 uint32 item_id = fields[1].GetUInt32();
6956 uint32 maxcount = fields[2].GetUInt32();
6957 uint32 incrtime = fields[3].GetUInt32();
6958 uint32 ExtendedCost = fields[4].GetUInt32();
6960 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6961 continue;
6963 VendorItemData& vList = m_mCacheVendorItemMap[entry];
6965 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
6966 ++count;
6968 } while (result->NextRow());
6969 delete result;
6971 sLog.outString();
6972 sLog.outString( ">> Loaded %d Vendors ", count );
6975 void ObjectMgr::LoadNpcTextId()
6978 m_mCacheNpcTextIdMap.clear();
6980 QueryResult* result = WorldDatabase.PQuery("SELECT npc_guid, textid FROM npc_gossip");
6981 if( !result )
6983 barGoLink bar( 1 );
6985 bar.step();
6987 sLog.outString();
6988 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
6989 return;
6992 barGoLink bar( result->GetRowCount() );
6994 uint32 count = 0;
6995 uint32 guid,textid;
6998 bar.step();
7000 Field* fields = result->Fetch();
7002 guid = fields[0].GetUInt32();
7003 textid = fields[1].GetUInt32();
7005 if (!GetCreatureData(guid))
7007 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7008 continue;
7010 if (!GetGossipText(textid))
7012 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7013 continue;
7016 m_mCacheNpcTextIdMap[guid] = textid ;
7017 ++count;
7019 } while (result->NextRow());
7020 delete result;
7022 sLog.outString();
7023 sLog.outString( ">> Loaded %d NpcTextId ", count );
7026 void ObjectMgr::LoadNpcOptions()
7028 m_mCacheNpcOptionList.clear(); // For reload case
7030 QueryResult *result = WorldDatabase.Query(
7031 // 0 1 2 3 4 5 6 7 8
7032 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7033 "FROM npc_option");
7035 if( !result )
7037 barGoLink bar( 1 );
7039 bar.step();
7041 sLog.outString();
7042 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7043 return;
7046 barGoLink bar( result->GetRowCount() );
7048 uint32 count = 0;
7052 bar.step();
7054 Field* fields = result->Fetch();
7056 GossipOption go;
7057 go.Id = fields[0].GetUInt32();
7058 go.GossipId = fields[1].GetUInt32();
7059 go.NpcFlag = fields[2].GetUInt32();
7060 go.Icon = fields[3].GetUInt32();
7061 go.Action = fields[4].GetUInt32();
7062 go.BoxMoney = fields[5].GetUInt32();
7063 go.Coded = fields[6].GetUInt8()!=0;
7064 go.OptionText = fields[7].GetCppString();
7065 go.BoxText = fields[8].GetCppString();
7067 m_mCacheNpcOptionList.push_back(go);
7069 ++count;
7071 } while (result->NextRow());
7072 delete result;
7074 sLog.outString();
7075 sLog.outString( ">> Loaded %d npc_option entries", count );
7078 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7080 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7081 vList.AddItem(item,maxcount,incrtime,extendedcost);
7083 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7086 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7088 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7089 if(iter == m_mCacheVendorItemMap.end())
7090 return false;
7092 if(!iter->second.FindItem(item))
7093 return false;
7095 iter->second.RemoveItem(item);
7096 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7097 return true;
7100 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7102 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7103 if(!cInfo)
7105 if(pl)
7106 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7107 else
7108 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7109 return false;
7112 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7114 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7116 if(pl)
7117 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7118 else
7119 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7121 if(skip_vendors)
7122 skip_vendors->insert(vendor_entry);
7124 return false;
7127 if(!GetItemPrototype(item_id))
7129 if(pl)
7130 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7131 else
7132 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7133 return false;
7136 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7138 if(pl)
7139 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7140 else
7141 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7142 return false;
7145 if(maxcount > 0 && incrtime == 0)
7147 if(pl)
7148 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7149 else
7150 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7151 return false;
7153 else if(maxcount==0 && incrtime > 0)
7155 if(pl)
7156 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7157 else
7158 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7159 return false;
7162 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7163 if(!vItems)
7164 return true; // later checks for non-empty lists
7166 if(vItems->FindItem(item_id))
7168 if(pl)
7169 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7170 else
7171 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7172 return false;
7175 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7177 if(pl)
7178 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7179 else
7180 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7181 return false;
7184 return true;
7187 // Functions for scripting access
7188 const char* GetAreaTriggerScriptNameById(uint32 id)
7190 return objmgr.GetAreaTriggerScriptName(id);
7193 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7195 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7197 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());
7198 start_value = -1;
7199 end_value = std::numeric_limits<int32>::min();
7202 // for scripting localized strings allowed use _only_ negative entries
7203 return objmgr.LoadMangosStrings(db,table,end_value,start_value);