[6982] Implemented gmlevel-based command security
[getmangos.git] / src / game / ObjectMgr.cpp
blobf492192e16955d11fcb204cf76e2af8504d2839b
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
24 #include "Log.h"
25 #include "MapManager.h"
26 #include "ObjectMgr.h"
27 #include "SpellMgr.h"
28 #include "UpdateMask.h"
29 #include "World.h"
30 #include "WorldSession.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Policies/SingletonImp.h"
37 #include "Language.h"
38 #include "GameEvent.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
45 #include "WaypointManager.h"
47 INSTANTIATE_SINGLETON_1(ObjectMgr);
49 ScriptMapMap sQuestEndScripts;
50 ScriptMapMap sQuestStartScripts;
51 ScriptMapMap sSpellScripts;
52 ScriptMapMap sGameObjectScripts;
53 ScriptMapMap sEventScripts;
55 bool normalizePlayerName(std::string& name)
57 if(name.empty())
58 return false;
60 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
61 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
63 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
64 return false;
66 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
67 for(size_t i = 1; i < wstr_len; ++i)
68 wstr_buf[i] = wcharToLower(wstr_buf[i]);
70 if(!WStrToUtf8(wstr_buf,wstr_len,name))
71 return false;
73 return true;
76 LanguageDesc lang_description[LANGUAGES_COUNT] =
78 { LANG_ADDON, 0, 0 },
79 { LANG_UNIVERSAL, 0, 0 },
80 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
81 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
82 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
83 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
84 { LANG_COMMON, 668, SKILL_LANG_COMMON },
85 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
86 { LANG_TITAN, 816, SKILL_LANG_TITAN },
87 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
88 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
89 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
90 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
91 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
92 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
93 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
94 { LANG_ZOMBIE, 0, 0 },
95 { LANG_GNOMISH_BINARY, 0, 0 },
96 { LANG_GOBLIN_BINARY, 0, 0 }
99 LanguageDesc const* GetLanguageDescByID(uint32 lang)
101 for(int i = 0; i < LANGUAGES_COUNT; ++i)
103 if(uint32(lang_description[i].lang_id) == lang)
104 return &lang_description[i];
107 return NULL;
110 ObjectMgr::ObjectMgr()
112 m_hiCharGuid = 1;
113 m_hiCreatureGuid = 1;
114 m_hiPetGuid = 1;
115 m_hiVehicleGuid = 1;
116 m_hiItemGuid = 1;
117 m_hiGoGuid = 1;
118 m_hiDoGuid = 1;
119 m_hiCorpseGuid = 1;
120 m_hiPetNumber = 1;
121 m_ItemTextId = 1;
122 m_mailid = 1;
123 m_auctionid = 1;
124 m_guildId = 1;
125 m_arenaTeamId = 1;
127 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
128 mGuildBankTabPrice[0] = 100;
129 mGuildBankTabPrice[1] = 250;
130 mGuildBankTabPrice[2] = 500;
131 mGuildBankTabPrice[3] = 1000;
132 mGuildBankTabPrice[4] = 2500;
133 mGuildBankTabPrice[5] = 5000;
135 // Only zero condition left, others will be added while loading DB tables
136 mConditions.resize(1);
139 ObjectMgr::~ObjectMgr()
141 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
143 delete i->second;
145 mQuestTemplates.clear( );
147 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++i )
149 delete i->second;
151 mGossipText.clear( );
153 mAreaTriggers.clear();
155 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
157 delete[] i->second;
159 petInfo.clear();
161 // free only if loaded
162 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
163 delete[] playerClassInfo[class_].levelInfo;
165 for (int race = 0; race < MAX_RACES; ++race)
166 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
167 delete[] playerInfo[race][class_].levelInfo;
169 // free group and guild objects
170 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
171 delete (*itr);
172 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
173 delete (*itr);
175 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
176 delete itr->second;
178 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
179 itr->second.Clear();
181 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
182 itr->second.Clear();
185 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
187 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
188 if ((*itr)->GetLeaderGUID() == guid)
189 return *itr;
191 return NULL;
194 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
196 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
197 if ((*itr)->GetId() == GuildId)
198 return *itr;
200 return NULL;
203 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
205 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
206 if ((*itr)->GetName() == guildname)
207 return *itr;
209 return NULL;
212 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
214 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
215 if ((*itr)->GetId() == GuildId)
216 return (*itr)->GetName();
218 return "";
221 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
223 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
224 if( (*itr)->GetLeader() == guid)
225 return *itr;
227 return NULL;
230 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 arenateamid) const
232 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
233 if (itr != mArenaTeamMap.end())
234 return itr->second;
236 return NULL;
239 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
241 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
242 if (itr->second->GetName() == arenateamname)
243 return itr->second;
245 return NULL;
248 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
250 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
251 if (itr->second->GetCaptain() == guid)
252 return itr->second;
254 return NULL;
257 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
259 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
262 void ObjectMgr::RemoveArenaTeam(ArenaTeam* arenaTeam)
264 mArenaTeamMap.erase( arenaTeam->GetId() );
267 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
269 switch ( location )
271 case 6: //horde
272 return & mHordeAuctions;
273 break;
274 case 2: //alliance
275 return & mAllianceAuctions;
276 break;
277 default: //neutral
278 return & mNeutralAuctions;
282 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
284 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
285 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
286 else
287 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
290 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
292 float percentance; // in 0..1
293 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
294 percentance = 0.75f;
295 else
296 percentance = 0.15f;
298 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
300 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
303 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
304 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
306 uint32 outbid = (currentBid / 100) * 5;
307 if (!outbid)
308 outbid = 1;
309 return outbid;
312 //does not clear ram
313 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
315 Item *pItem = GetAItem(auction->item_guidlow);
316 if(!pItem)
317 return;
319 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
320 Player *bidder = GetPlayer(bidder_guid);
322 uint32 bidder_accId = 0;
324 // data for gm.log
325 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
327 uint32 bidder_security = 0;
328 std::string bidder_name;
329 if (bidder)
331 bidder_accId = bidder->GetSession()->GetAccountId();
332 bidder_security = bidder->GetSession()->GetSecurity();
333 bidder_name = bidder->GetName();
335 else
337 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
338 bidder_security = accmgr.GetSecurity(bidder_accId);
340 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
342 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
343 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
347 if( bidder_security > SEC_PLAYER )
349 std::string owner_name;
350 if(!GetPlayerNameByGUID(auction->owner,owner_name))
351 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
353 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
355 sLog.outCommand(bidder_accId,"GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
356 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
359 else if(!bidder)
360 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
362 // receiver exist
363 if(bidder || bidder_accId)
365 std::ostringstream msgAuctionWonSubject;
366 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
368 std::ostringstream msgAuctionWonBody;
369 msgAuctionWonBody.width(16);
370 msgAuctionWonBody << std::right << std::hex << auction->owner;
371 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
372 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
374 //prepare mail data... :
375 uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
377 // set owner to bidder (to prevent delete item with sender char deleting)
378 // owner in `data` will set at mail receive and item extracting
379 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
380 CharacterDatabase.CommitTransaction();
382 MailItemsInfo mi;
383 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
385 if (bidder)
386 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
387 else
388 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
390 // will delete item or place to receiver mail list
391 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
393 // receiver not exist
394 else
396 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
397 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
398 delete pItem;
402 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
404 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
405 Player *owner = GetPlayer(owner_guid);
407 // owner exist (online or offline)
408 if(owner || GetPlayerAccountIdByGUID(owner_guid))
410 std::ostringstream msgAuctionSalePendingSubject;
411 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
413 std::ostringstream msgAuctionSalePendingBody;
414 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
416 time_t distrTime = time(NULL) + HOUR;
418 msgAuctionSalePendingBody.width(16);
419 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
420 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
421 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
422 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
424 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
426 uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
428 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
432 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
433 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
435 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
436 Player *owner = GetPlayer(owner_guid);
438 uint32 owner_accId = 0;
439 if(!owner)
440 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
442 // owner exist
443 if(owner || owner_accId)
445 std::ostringstream msgAuctionSuccessfulSubject;
446 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
448 std::ostringstream auctionSuccessfulBody;
449 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
451 auctionSuccessfulBody.width(16);
452 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
453 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
454 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
456 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
458 uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
460 uint32 profit = auction->bid + auction->deposit - auctionCut;
462 if (owner)
464 //send auction owner notification, bidder must be current!
465 owner->GetSession()->SendAuctionOwnerNotification( auction );
468 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
472 //does not clear ram
473 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
474 { //return an item in auction to its owner by mail
475 Item *pItem = GetAItem(auction->item_guidlow);
476 if(!pItem)
478 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
479 return;
482 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
483 Player *owner = GetPlayer(owner_guid);
485 uint32 owner_accId = 0;
486 if(!owner)
487 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
489 // owner exist
490 if(owner || owner_accId)
492 std::ostringstream subject;
493 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
495 if ( owner )
496 owner->GetSession()->SendAuctionOwnerNotification( auction );
497 else
498 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
500 MailItemsInfo mi;
501 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
503 // will delete item or place to receiver mail list
504 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
506 // owner not found
507 else
509 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
510 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
511 delete pItem;
515 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
517 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
520 void ObjectMgr::LoadCreatureLocales()
522 mCreatureLocaleMap.clear(); // need for reload case
524 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");
526 if(!result)
528 barGoLink bar(1);
530 bar.step();
532 sLog.outString("");
533 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
534 return;
537 barGoLink bar(result->GetRowCount());
541 Field *fields = result->Fetch();
542 bar.step();
544 uint32 entry = fields[0].GetUInt32();
546 CreatureLocale& data = mCreatureLocaleMap[entry];
548 for(int i = 1; i < MAX_LOCALE; ++i)
550 std::string str = fields[1+2*(i-1)].GetCppString();
551 if(!str.empty())
553 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
554 if(idx >= 0)
556 if(data.Name.size() <= idx)
557 data.Name.resize(idx+1);
559 data.Name[idx] = str;
562 str = fields[1+2*(i-1)+1].GetCppString();
563 if(!str.empty())
565 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
566 if(idx >= 0)
568 if(data.SubName.size() <= idx)
569 data.SubName.resize(idx+1);
571 data.SubName[idx] = str;
575 } while (result->NextRow());
577 delete result;
579 sLog.outString();
580 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
583 void ObjectMgr::LoadCompletedAchievements()
585 QueryResult *result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
587 if(!result)
588 return;
592 Field *fields = result->Fetch();
593 allCompletedAchievements.insert(fields[0].GetUInt32());
594 } while(result->NextRow());
596 delete result;
599 void ObjectMgr::LoadNpcOptionLocales()
601 mNpcOptionLocaleMap.clear(); // need for reload case
603 QueryResult *result = WorldDatabase.Query("SELECT entry,"
604 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
605 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
606 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
607 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
608 "FROM locales_npc_option");
610 if(!result)
612 barGoLink bar(1);
614 bar.step();
616 sLog.outString("");
617 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
618 return;
621 barGoLink bar(result->GetRowCount());
625 Field *fields = result->Fetch();
626 bar.step();
628 uint32 entry = fields[0].GetUInt32();
630 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
632 for(int i = 1; i < MAX_LOCALE; ++i)
634 std::string str = fields[1+2*(i-1)].GetCppString();
635 if(!str.empty())
637 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
638 if(idx >= 0)
640 if(data.OptionText.size() <= idx)
641 data.OptionText.resize(idx+1);
643 data.OptionText[idx] = str;
646 str = fields[1+2*(i-1)+1].GetCppString();
647 if(!str.empty())
649 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
650 if(idx >= 0)
652 if(data.BoxText.size() <= idx)
653 data.BoxText.resize(idx+1);
655 data.BoxText[idx] = str;
659 } while (result->NextRow());
661 delete result;
663 sLog.outString();
664 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
667 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
669 template<class D>
670 void convert_from_str(uint32 field_pos, char *src, D &dst)
672 dst = D(objmgr.GetScriptId(src));
676 void ObjectMgr::LoadCreatureTemplates()
678 SQLCreatureLoader loader;
679 loader.Load(sCreatureStorage);
681 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
682 sLog.outString();
684 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
685 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
687 // check data correctness
688 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
690 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
691 if(!cInfo)
692 continue;
694 if(cInfo->HeroicEntry)
696 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
697 if(!heroicInfo)
699 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
700 continue;
703 if(heroicEntries.find(i)!=heroicEntries.end())
705 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
706 continue;
709 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
711 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
712 continue;
715 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
717 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
718 continue;
721 if(cInfo->npcflag != heroicInfo->npcflag)
723 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
724 continue;
727 if(cInfo->classNum != heroicInfo->classNum)
729 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
730 continue;
733 if(cInfo->race != heroicInfo->race)
735 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
736 continue;
739 if(cInfo->trainer_type != heroicInfo->trainer_type)
741 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
742 continue;
745 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
747 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
748 continue;
751 hasHeroicEntries.insert(i);
752 heroicEntries.insert(cInfo->HeroicEntry);
755 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
756 if(!factionTemplate)
757 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
759 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
760 if(!factionTemplate)
761 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
763 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
764 if (!minfo)
765 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
766 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
767 if (!minfo)
768 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
770 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
772 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
773 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
776 if(cInfo->baseattacktime == 0)
777 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
779 if(cInfo->rangeattacktime == 0)
780 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
782 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
783 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
785 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
787 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
788 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
791 if(cInfo->PetSpellDataId)
793 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
794 if(!spellDataId)
795 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
798 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
800 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
801 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
804 if(cInfo->equipmentId > 0) // 0 no equipment
806 if(!GetEquipmentInfo(cInfo->equipmentId))
808 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);
809 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
813 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
814 if(cInfo->scale <= 0.0f)
816 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
817 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
822 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
824 // Now add the auras, format "spellid effectindex spellid effectindex..."
825 char *p,*s;
826 std::vector<int> val;
827 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
828 if(p)
830 while (p[0]!=0)
832 ++p;
833 if (p[0]==' ')
835 val.push_back(atoi(s));
836 s=++p;
839 if (p!=s)
840 val.push_back(atoi(s));
842 // free char* loaded memory
843 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
845 // wrong list
846 if (val.size()%2)
848 addon->auras = NULL;
849 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
850 return;
854 // empty list
855 if(val.empty())
857 addon->auras = NULL;
858 return;
861 // replace by new structures array
862 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
864 int i=0;
865 for(int j=0;j<val.size()/2;++j)
867 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
868 cAura.spell_id = (uint32)val[2*j+0];
869 cAura.effect_idx = (uint32)val[2*j+1];
870 if ( cAura.effect_idx > 2 )
872 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);
873 continue;
875 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
876 if (!AdditionalSpellInfo)
878 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
879 continue;
882 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
884 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);
885 continue;
888 ++i;
891 // fill terminator element (after last added)
892 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
893 endAura.spell_id = 0;
894 endAura.effect_idx = 0;
897 void ObjectMgr::LoadCreatureAddons()
899 sCreatureInfoAddonStorage.Load();
901 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
902 sLog.outString();
904 // check data correctness and convert 'auras'
905 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
907 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
908 if(!addon)
909 continue;
911 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
913 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
914 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
917 sCreatureDataAddonStorage.Load();
919 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
920 sLog.outString();
922 // check data correctness and convert 'auras'
923 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
925 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
926 if(!addon)
927 continue;
929 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
931 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
932 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
936 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
938 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
941 void ObjectMgr::LoadEquipmentTemplates()
943 sEquipmentStorage.Load();
945 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
947 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
949 if(!eqInfo)
950 continue;
952 for(uint8 j=0; j<3; j++)
954 if(!eqInfo->equipentry[j])
955 continue;
957 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
959 if(!dbcitem)
961 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
962 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
963 continue;
966 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
967 dbcitem->InventoryType != INVTYPE_SHIELD &&
968 dbcitem->InventoryType != INVTYPE_RANGED &&
969 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
970 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
971 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
972 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
973 dbcitem->InventoryType != INVTYPE_THROWN &&
974 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
976 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);
977 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
981 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
982 sLog.outString();
984 // This DBC is currently only used for item templates and creature equipments checks.
985 sItemStore.Clear();
988 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
990 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
993 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
995 // Load creature model (display id)
996 uint32 display_id;
997 if (!data || data->displayid == 0) // use defaults from the template
999 // DisplayID_A is used if no team is given
1000 if (team == HORDE)
1001 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
1002 else
1003 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
1005 else // overridden in creature data
1006 display_id = data->displayid;
1008 return display_id;
1011 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
1013 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
1014 if(!minfo)
1015 return NULL;
1017 // If a model for another gender exists, 50% chance to use it
1018 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
1020 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
1021 if(!minfo_tmp)
1023 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
1024 return minfo; // not fatal, just use the previous one
1026 else
1027 return minfo_tmp;
1029 else
1030 return minfo;
1033 void ObjectMgr::LoadCreatureModelInfo()
1035 sCreatureModelStorage.Load();
1037 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1038 sLog.outString();
1041 void ObjectMgr::LoadCreatures()
1043 uint32 count = 0;
1044 // 0 1 2 3
1045 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1046 // 4 5 6 7 8 9 10 11
1047 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1048 // 12 13 14 15 16 17
1049 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
1050 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
1052 if(!result)
1054 barGoLink bar(1);
1056 bar.step();
1058 sLog.outString("");
1059 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1060 return;
1063 // build single time for check creature data
1064 std::set<uint32> heroicCreatures;
1065 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1066 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1067 if(cInfo->HeroicEntry)
1068 heroicCreatures.insert(cInfo->HeroicEntry);
1070 barGoLink bar(result->GetRowCount());
1074 Field *fields = result->Fetch();
1075 bar.step();
1077 uint32 guid = fields[0].GetUInt32();
1079 CreatureData& data = mCreatureDataMap[guid];
1081 data.id = fields[ 1].GetUInt32();
1082 data.mapid = fields[ 2].GetUInt32();
1083 data.displayid = fields[ 3].GetUInt32();
1084 data.equipmentId = fields[ 4].GetUInt32();
1085 data.posX = fields[ 5].GetFloat();
1086 data.posY = fields[ 6].GetFloat();
1087 data.posZ = fields[ 7].GetFloat();
1088 data.orientation = fields[ 8].GetFloat();
1089 data.spawntimesecs = fields[ 9].GetUInt32();
1090 data.spawndist = fields[10].GetFloat();
1091 data.currentwaypoint= fields[11].GetUInt32();
1092 data.curhealth = fields[12].GetUInt32();
1093 data.curmana = fields[13].GetUInt32();
1094 data.is_dead = fields[14].GetBool();
1095 data.movementType = fields[15].GetUInt8();
1096 data.spawnMask = fields[16].GetUInt8();
1097 int16 gameEvent = fields[17].GetInt16();
1099 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1100 if(!cInfo)
1102 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1103 continue;
1106 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1108 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1109 continue;
1112 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1114 if(!GetEquipmentInfo(data.equipmentId))
1116 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);
1117 data.equipmentId = -1;
1121 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1123 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 );
1124 data.curhealth = cInfo->minhealth;
1127 if(data.curmana < cInfo->minmana)
1129 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 );
1130 data.curmana = cInfo->minmana;
1133 if(data.spawndist < 0.0f)
1135 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1136 data.spawndist = 0.0f;
1138 else if(data.movementType == RANDOM_MOTION_TYPE)
1140 if(data.spawndist == 0.0f)
1142 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 );
1143 data.movementType = IDLE_MOTION_TYPE;
1146 else if(data.movementType == IDLE_MOTION_TYPE)
1148 if(data.spawndist != 0.0f)
1150 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1151 data.spawndist = 0.0f;
1155 if (gameEvent==0) // if not this is to be managed by GameEvent System
1156 AddCreatureToGrid(guid, &data);
1157 ++count;
1159 } while (result->NextRow());
1161 delete result;
1163 sLog.outString();
1164 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1167 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1169 uint8 mask = data->spawnMask;
1170 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1172 if(mask & 1)
1174 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1175 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1177 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1178 cell_guids.creatures.insert(guid);
1183 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1185 uint8 mask = data->spawnMask;
1186 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1188 if(mask & 1)
1190 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1191 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1193 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1194 cell_guids.creatures.erase(guid);
1199 void ObjectMgr::LoadGameobjects()
1201 uint32 count = 0;
1203 // 0 1 2 3 4 5 6
1204 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1205 // 7 8 9 10 11 12 13 14 15
1206 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1207 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1209 if(!result)
1211 barGoLink bar(1);
1213 bar.step();
1215 sLog.outString();
1216 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1217 return;
1220 barGoLink bar(result->GetRowCount());
1224 Field *fields = result->Fetch();
1225 bar.step();
1227 uint32 guid = fields[0].GetUInt32();
1229 GameObjectData& data = mGameObjectDataMap[guid];
1231 data.id = fields[ 1].GetUInt32();
1232 data.mapid = fields[ 2].GetUInt32();
1233 data.posX = fields[ 3].GetFloat();
1234 data.posY = fields[ 4].GetFloat();
1235 data.posZ = fields[ 5].GetFloat();
1236 data.orientation = fields[ 6].GetFloat();
1237 data.rotation0 = fields[ 7].GetFloat();
1238 data.rotation1 = fields[ 8].GetFloat();
1239 data.rotation2 = fields[ 9].GetFloat();
1240 data.rotation3 = fields[10].GetFloat();
1241 data.spawntimesecs = fields[11].GetInt32();
1242 data.animprogress = fields[12].GetUInt32();
1243 data.go_state = fields[13].GetUInt32();
1244 data.spawnMask = fields[14].GetUInt8();
1245 int16 gameEvent = fields[15].GetInt16();
1247 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1248 if(!gInfo)
1250 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1251 continue;
1254 if (gameEvent==0) // if not this is to be managed by GameEvent System
1255 AddGameobjectToGrid(guid, &data);
1256 ++count;
1258 } while (result->NextRow());
1260 delete result;
1262 sLog.outString();
1263 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1266 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1268 uint8 mask = data->spawnMask;
1269 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1271 if(mask & 1)
1273 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1274 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1276 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1277 cell_guids.gameobjects.insert(guid);
1282 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1284 uint8 mask = data->spawnMask;
1285 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1287 if(mask & 1)
1289 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1290 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1292 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1293 cell_guids.gameobjects.erase(guid);
1298 void ObjectMgr::LoadCreatureRespawnTimes()
1300 // remove outdated data
1301 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1303 uint32 count = 0;
1305 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1307 if(!result)
1309 barGoLink bar(1);
1311 bar.step();
1313 sLog.outString();
1314 sLog.outString(">> Loaded 0 creature respawn time.");
1315 return;
1318 barGoLink bar(result->GetRowCount());
1322 Field *fields = result->Fetch();
1323 bar.step();
1325 uint32 loguid = fields[0].GetUInt32();
1326 uint64 respawn_time = fields[1].GetUInt64();
1327 uint32 instance = fields[2].GetUInt32();
1329 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1331 ++count;
1332 } while (result->NextRow());
1334 delete result;
1336 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1337 sLog.outString();
1340 void ObjectMgr::LoadGameobjectRespawnTimes()
1342 // remove outdated data
1343 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1345 uint32 count = 0;
1347 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1349 if(!result)
1351 barGoLink bar(1);
1353 bar.step();
1355 sLog.outString();
1356 sLog.outString(">> Loaded 0 gameobject respawn time.");
1357 return;
1360 barGoLink bar(result->GetRowCount());
1364 Field *fields = result->Fetch();
1365 bar.step();
1367 uint32 loguid = fields[0].GetUInt32();
1368 uint64 respawn_time = fields[1].GetUInt64();
1369 uint32 instance = fields[2].GetUInt32();
1371 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1373 ++count;
1374 } while (result->NextRow());
1376 delete result;
1378 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1379 sLog.outString();
1382 // name must be checked to correctness (if received) before call this function
1383 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1385 uint64 guid = 0;
1387 CharacterDatabase.escape_string(name);
1389 // Player name safe to sending to DB (checked at login) and this function using
1390 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1391 if(result)
1393 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1395 delete result;
1398 return guid;
1401 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1403 // prevent DB access for online player
1404 if(Player* player = GetPlayer(guid))
1406 name = player->GetName();
1407 return true;
1410 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1412 if(result)
1414 name = (*result)[0].GetCppString();
1415 delete result;
1416 return true;
1419 return false;
1422 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1424 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1426 if(result)
1428 uint8 race = (*result)[0].GetUInt8();
1429 delete result;
1430 return Player::TeamForRace(race);
1433 return 0;
1436 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1438 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1439 if(result)
1441 uint32 acc = (*result)[0].GetUInt32();
1442 delete result;
1443 return acc;
1446 return 0;
1449 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1451 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1452 if(result)
1454 uint32 acc = (*result)[0].GetUInt32();
1455 delete result;
1456 return acc;
1459 return 0;
1462 void ObjectMgr::LoadAuctions()
1464 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1465 if( !result )
1466 return;
1468 Field *fields = result->Fetch();
1469 uint32 AuctionCount=fields[0].GetUInt32();
1470 delete result;
1472 if(!AuctionCount)
1473 return;
1475 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1476 if( !result )
1477 return;
1479 barGoLink bar( AuctionCount );
1481 AuctionEntry *aItem;
1485 fields = result->Fetch();
1487 bar.step();
1489 aItem = new AuctionEntry;
1490 aItem->Id = fields[0].GetUInt32();
1491 aItem->auctioneer = fields[1].GetUInt32();
1492 aItem->item_guidlow = fields[2].GetUInt32();
1493 aItem->item_template = fields[3].GetUInt32();
1494 aItem->owner = fields[4].GetUInt32();
1495 aItem->buyout = fields[5].GetUInt32();
1496 aItem->time = fields[6].GetUInt32();
1497 aItem->bidder = fields[7].GetUInt32();
1498 aItem->bid = fields[8].GetUInt32();
1499 aItem->startbid = fields[9].GetUInt32();
1500 aItem->deposit = fields[10].GetUInt32();
1501 aItem->location = fields[11].GetUInt8();
1502 //check if sold item exists
1503 if ( GetAItem( aItem->item_guidlow ) )
1505 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1507 else
1509 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1510 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1511 delete aItem;
1513 } while (result->NextRow());
1514 delete result;
1516 sLog.outString();
1517 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1518 sLog.outString();
1521 void ObjectMgr::LoadItemLocales()
1523 mItemLocaleMap.clear(); // need for reload case
1525 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");
1527 if(!result)
1529 barGoLink bar(1);
1531 bar.step();
1533 sLog.outString("");
1534 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1535 return;
1538 barGoLink bar(result->GetRowCount());
1542 Field *fields = result->Fetch();
1543 bar.step();
1545 uint32 entry = fields[0].GetUInt32();
1547 ItemLocale& data = mItemLocaleMap[entry];
1549 for(int i = 1; i < MAX_LOCALE; ++i)
1551 std::string str = fields[1+2*(i-1)].GetCppString();
1552 if(!str.empty())
1554 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1555 if(idx >= 0)
1557 if(data.Name.size() <= idx)
1558 data.Name.resize(idx+1);
1560 data.Name[idx] = str;
1564 str = fields[1+2*(i-1)+1].GetCppString();
1565 if(!str.empty())
1567 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1568 if(idx >= 0)
1570 if(data.Description.size() <= idx)
1571 data.Description.resize(idx+1);
1573 data.Description[idx] = str;
1577 } while (result->NextRow());
1579 delete result;
1581 sLog.outString();
1582 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1585 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1587 template<class D>
1588 void convert_from_str(uint32 field_pos, char *src, D &dst)
1590 dst = D(objmgr.GetScriptId(src));
1594 void ObjectMgr::LoadItemPrototypes()
1596 SQLItemLoader loader;
1597 loader.Load(sItemStorage);
1598 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1599 sLog.outString();
1601 // check data correctness
1602 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1604 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1605 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1606 if(!proto)
1608 /* to many errors, and possible not all items really used in game
1609 if (dbcitem)
1610 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1612 continue;
1615 if(dbcitem)
1617 if(proto->InventoryType != dbcitem->InventoryType)
1619 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1620 // It safe let use InventoryType from DB
1623 if(proto->DisplayInfoID != dbcitem->DisplayId)
1625 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1626 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1628 if(proto->Sheath != dbcitem->Sheath)
1630 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1631 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1634 else
1636 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1639 if(proto->Class >= MAX_ITEM_CLASS)
1641 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1642 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1645 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1647 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1648 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1651 if(proto->Quality >= MAX_ITEM_QUALITY)
1653 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1654 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1657 if(proto->BuyCount <= 0)
1659 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1660 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1663 if(proto->InventoryType >= MAX_INVTYPE)
1665 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1666 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1669 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1671 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1672 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1675 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1677 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1680 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1682 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1685 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1687 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1688 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1691 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1692 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1694 if(proto->RequiredReputationFaction)
1696 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1698 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1699 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1702 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1703 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1705 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1706 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1708 if(proto->Stackable==0)
1710 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1711 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1713 else if(proto->Stackable > 255)
1715 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1716 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1719 for (int j = 0; j < 10; j++)
1721 // for ItemStatValue != 0
1722 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1724 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1725 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1729 for (int j = 0; j < 5; j++)
1731 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1733 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1734 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1738 // special format
1739 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1741 // spell_1
1742 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1744 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);
1745 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1746 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1747 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1748 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1751 // spell_2 have learning spell
1752 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1754 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);
1755 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1756 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1757 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1759 else if(!proto->Spells[1].SpellId)
1761 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1762 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1763 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1765 else
1767 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1768 if(!spellInfo)
1770 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1771 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1772 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1773 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1775 // allowed only in special format
1776 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1778 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1779 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1780 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1781 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1785 // spell_3*,spell_4*,spell_5* is empty
1786 for (int j = 2; j < 5; j++)
1788 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1790 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1791 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1792 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1794 else if(proto->Spells[j].SpellId != 0)
1796 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1797 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1801 // normal spell list
1802 else
1804 for (int j = 0; j < 5; j++)
1806 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1808 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1809 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1810 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1813 if(proto->Spells[j].SpellId)
1815 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1816 if(!spellInfo)
1818 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1819 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1821 // allowed only in special format
1822 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1824 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1825 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1831 if(proto->Bonding >= MAX_BIND_TYPE)
1832 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1834 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1835 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1837 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1838 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1840 if(proto->Sheath >= MAX_SHEATHETYPE)
1842 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1843 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1846 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1848 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1849 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1852 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1854 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1855 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1858 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1860 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1861 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1864 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1865 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1867 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1868 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1870 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1871 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1873 for (int j = 0; j < 3; j++)
1875 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1877 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1878 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1882 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1883 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1885 if(proto->FoodType >= MAX_PET_DIET)
1887 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1888 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1893 void ObjectMgr::LoadAuctionItems()
1895 // data needs to be at first place for Item::LoadFromDB
1896 QueryResult *result = CharacterDatabase.Query( "SELECT data,itemguid,item_template FROM auctionhouse JOIN item_instance ON itemguid = guid" );
1898 if( !result )
1899 return;
1901 barGoLink bar( result->GetRowCount() );
1903 uint32 count = 0;
1905 Field *fields;
1908 bar.step();
1910 fields = result->Fetch();
1911 uint32 item_guid = fields[1].GetUInt32();
1912 uint32 item_template = fields[2].GetUInt32();
1914 ItemPrototype const *proto = GetItemPrototype(item_template);
1916 if(!proto)
1918 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1919 continue;
1922 Item *item = NewItemOrBag(proto);
1924 if(!item->LoadFromDB(item_guid,0, result))
1926 delete item;
1927 continue;
1929 AddAItem(item);
1931 ++count;
1933 while( result->NextRow() );
1935 delete result;
1937 sLog.outString();
1938 sLog.outString( ">> Loaded %u auction items", count );
1941 void ObjectMgr::LoadPetLevelInfo()
1943 // Loading levels data
1945 // 0 1 2 3 4 5 6 7 8 9
1946 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1948 uint32 count = 0;
1950 if (!result)
1952 barGoLink bar( 1 );
1954 sLog.outString();
1955 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1956 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1957 return;
1960 barGoLink bar( result->GetRowCount() );
1964 Field* fields = result->Fetch();
1966 uint32 creature_id = fields[0].GetUInt32();
1967 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1969 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1970 continue;
1973 uint32 current_level = fields[1].GetUInt32();
1974 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1976 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1977 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1978 else
1979 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1980 continue;
1982 else if(current_level < 1)
1984 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1985 continue;
1988 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1990 if(pInfoMapEntry==NULL)
1991 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1993 // data for level 1 stored in [0] array element, ...
1994 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1996 pLevelInfo->health = fields[2].GetUInt16();
1997 pLevelInfo->mana = fields[3].GetUInt16();
1998 pLevelInfo->armor = fields[9].GetUInt16();
2000 for (int i = 0; i < MAX_STATS; i++)
2002 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2005 bar.step();
2006 ++count;
2008 while (result->NextRow());
2010 delete result;
2012 sLog.outString();
2013 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2016 // Fill gaps and check integrity
2017 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2019 PetLevelInfo* pInfo = itr->second;
2021 // fatal error if no level 1 data
2022 if(!pInfo || pInfo[0].health == 0 )
2024 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2025 exit(1);
2028 // fill level gaps
2029 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2031 if(pInfo[level].health == 0)
2033 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2034 pInfo[level] = pInfo[level-1];
2040 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2042 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2043 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2045 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2046 if(itr == petInfo.end())
2047 return NULL;
2049 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2052 void ObjectMgr::LoadPlayerInfo()
2054 // Load playercreate
2056 // 0 1 2 3 4 5 6
2057 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2059 uint32 count = 0;
2061 if (!result)
2063 barGoLink bar( 1 );
2065 sLog.outString();
2066 sLog.outString( ">> Loaded %u player create definitions", count );
2067 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2068 exit(1);
2071 barGoLink bar( result->GetRowCount() );
2075 Field* fields = result->Fetch();
2077 uint32 current_race = fields[0].GetUInt32();
2078 uint32 current_class = fields[1].GetUInt32();
2079 uint32 mapId = fields[2].GetUInt32();
2080 uint32 zoneId = fields[3].GetUInt32();
2081 float positionX = fields[4].GetFloat();
2082 float positionY = fields[5].GetFloat();
2083 float positionZ = fields[6].GetFloat();
2085 if(current_race >= MAX_RACES)
2087 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2088 continue;
2091 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2092 if(!rEntry)
2094 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2095 continue;
2098 if(current_class >= MAX_CLASSES)
2100 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2101 continue;
2104 if(!sChrClassesStore.LookupEntry(current_class))
2106 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2107 continue;
2110 // accept DB data only for valid position (and non instanceable)
2111 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2113 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2114 continue;
2117 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2119 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2120 continue;
2123 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2125 pInfo->mapId = mapId;
2126 pInfo->zoneId = zoneId;
2127 pInfo->positionX = positionX;
2128 pInfo->positionY = positionY;
2129 pInfo->positionZ = positionZ;
2131 pInfo->displayId_m = rEntry->model_m;
2132 pInfo->displayId_f = rEntry->model_f;
2134 bar.step();
2135 ++count;
2137 while (result->NextRow());
2139 delete result;
2141 sLog.outString();
2142 sLog.outString( ">> Loaded %u player create definitions", count );
2145 // Load playercreate items
2147 // 0 1 2 3
2148 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2150 uint32 count = 0;
2152 if (!result)
2154 barGoLink bar( 1 );
2156 bar.step();
2158 sLog.outString();
2159 sLog.outString( ">> Loaded %u custom player create items", count );
2161 else
2163 barGoLink bar( result->GetRowCount() );
2167 Field* fields = result->Fetch();
2169 uint32 current_race = fields[0].GetUInt32();
2170 if(current_race >= MAX_RACES)
2172 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2173 continue;
2176 uint32 current_class = fields[1].GetUInt32();
2177 if(current_class >= MAX_CLASSES)
2179 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2180 continue;
2183 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2185 uint32 item_id = fields[2].GetUInt32();
2187 if(!GetItemPrototype(item_id))
2189 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);
2190 continue;
2193 uint32 amount = fields[3].GetUInt32();
2195 if(!amount)
2197 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2198 continue;
2201 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2203 bar.step();
2204 ++count;
2206 while(result->NextRow());
2208 delete result;
2210 sLog.outString();
2211 sLog.outString( ">> Loaded %u custom player create items", count );
2215 // Load playercreate spells
2217 // 0 1 2 3
2218 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2220 uint32 count = 0;
2222 if (!result)
2224 barGoLink bar( 1 );
2226 sLog.outString();
2227 sLog.outString( ">> Loaded %u player create spells", count );
2228 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2230 else
2232 barGoLink bar( result->GetRowCount() );
2236 Field* fields = result->Fetch();
2238 uint32 current_race = fields[0].GetUInt32();
2239 if(current_race >= MAX_RACES)
2241 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2242 continue;
2245 uint32 current_class = fields[1].GetUInt32();
2246 if(current_class >= MAX_CLASSES)
2248 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2249 continue;
2252 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2253 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2255 bar.step();
2256 ++count;
2258 while( result->NextRow() );
2260 delete result;
2262 sLog.outString();
2263 sLog.outString( ">> Loaded %u player create spells", count );
2267 // Load playercreate actions
2269 // 0 1 2 3 4 5
2270 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2272 uint32 count = 0;
2274 if (!result)
2276 barGoLink bar( 1 );
2278 sLog.outString();
2279 sLog.outString( ">> Loaded %u player create actions", count );
2280 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2282 else
2284 barGoLink bar( result->GetRowCount() );
2288 Field* fields = result->Fetch();
2290 uint32 current_race = fields[0].GetUInt32();
2291 if(current_race >= MAX_RACES)
2293 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2294 continue;
2297 uint32 current_class = fields[1].GetUInt32();
2298 if(current_class >= MAX_CLASSES)
2300 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2301 continue;
2304 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2305 pInfo->action[0].push_back(fields[2].GetUInt16());
2306 pInfo->action[1].push_back(fields[3].GetUInt16());
2307 pInfo->action[2].push_back(fields[4].GetUInt16());
2308 pInfo->action[3].push_back(fields[5].GetUInt16());
2310 bar.step();
2311 ++count;
2313 while( result->NextRow() );
2315 delete result;
2317 sLog.outString();
2318 sLog.outString( ">> Loaded %u player create actions", count );
2322 // Loading levels data (class only dependent)
2324 // 0 1 2 3
2325 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2327 uint32 count = 0;
2329 if (!result)
2331 barGoLink bar( 1 );
2333 sLog.outString();
2334 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2335 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2336 exit(1);
2339 barGoLink bar( result->GetRowCount() );
2343 Field* fields = result->Fetch();
2345 uint32 current_class = fields[0].GetUInt32();
2346 if(current_class >= MAX_CLASSES)
2348 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2349 continue;
2352 uint32 current_level = fields[1].GetUInt32();
2353 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2355 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2356 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2357 else
2358 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2359 continue;
2362 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2364 if(!pClassInfo->levelInfo)
2365 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2367 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2369 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2370 pClassLevelInfo->basemana = fields[3].GetUInt16();
2372 bar.step();
2373 ++count;
2375 while (result->NextRow());
2377 delete result;
2379 sLog.outString();
2380 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2383 // Fill gaps and check integrity
2384 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2386 // skip non existed classes
2387 if(!sChrClassesStore.LookupEntry(class_))
2388 continue;
2390 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2392 // fatal error if no level 1 data
2393 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2395 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2396 exit(1);
2399 // fill level gaps
2400 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2402 if(pClassInfo->levelInfo[level].basehealth == 0)
2404 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2405 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2410 // Loading levels data (class/race dependent)
2412 // 0 1 2 3 4 5 6 7
2413 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2415 uint32 count = 0;
2417 if (!result)
2419 barGoLink bar( 1 );
2421 sLog.outString();
2422 sLog.outString( ">> Loaded %u level stats definitions", count );
2423 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2424 exit(1);
2427 barGoLink bar( result->GetRowCount() );
2431 Field* fields = result->Fetch();
2433 uint32 current_race = fields[0].GetUInt32();
2434 if(current_race >= MAX_RACES)
2436 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2437 continue;
2440 uint32 current_class = fields[1].GetUInt32();
2441 if(current_class >= MAX_CLASSES)
2443 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2444 continue;
2447 uint32 current_level = fields[2].GetUInt32();
2448 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2450 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2451 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2452 else
2453 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2454 continue;
2457 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2459 if(!pInfo->levelInfo)
2460 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2462 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2464 for (int i = 0; i < MAX_STATS; i++)
2466 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2469 bar.step();
2470 ++count;
2472 while (result->NextRow());
2474 delete result;
2476 sLog.outString();
2477 sLog.outString( ">> Loaded %u level stats definitions", count );
2480 // Fill gaps and check integrity
2481 for (int race = 0; race < MAX_RACES; ++race)
2483 // skip non existed races
2484 if(!sChrRacesStore.LookupEntry(race))
2485 continue;
2487 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2489 // skip non existed classes
2490 if(!sChrClassesStore.LookupEntry(class_))
2491 continue;
2493 PlayerInfo* pInfo = &playerInfo[race][class_];
2495 // skip non loaded combinations
2496 if(!pInfo->displayId_m || !pInfo->displayId_f)
2497 continue;
2499 // skip expansion races if not playing with expansion
2500 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2501 continue;
2503 // skip expansion classes if not playing with expansion
2504 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2505 continue;
2507 // fatal error if no level 1 data
2508 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2510 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2511 exit(1);
2514 // fill level gaps
2515 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2517 if(pInfo->levelInfo[level].stats[0] == 0)
2519 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2520 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2527 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2529 if(level < 1 || class_ >= MAX_CLASSES)
2530 return;
2532 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2534 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2535 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2537 *info = pInfo->levelInfo[level-1];
2540 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2542 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2543 return;
2545 PlayerInfo const* pInfo = &playerInfo[race][class_];
2546 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2547 return;
2549 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2550 *info = pInfo->levelInfo[level-1];
2551 else
2552 BuildPlayerLevelInfo(race,class_,level,info);
2555 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2557 // base data (last known level)
2558 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2560 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2562 switch(_class)
2564 case CLASS_WARRIOR:
2565 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2566 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2567 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2568 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2569 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2570 break;
2571 case CLASS_PALADIN:
2572 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2573 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2574 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2575 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2576 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2577 break;
2578 case CLASS_HUNTER:
2579 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2580 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2581 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2582 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2583 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2584 break;
2585 case CLASS_ROGUE:
2586 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2587 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2588 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2589 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2590 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2591 break;
2592 case CLASS_PRIEST:
2593 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2594 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2595 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2596 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2597 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2598 break;
2599 case CLASS_SHAMAN:
2600 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2601 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2602 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2603 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2604 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2605 break;
2606 case CLASS_MAGE:
2607 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2608 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2609 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2610 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2611 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2612 break;
2613 case CLASS_WARLOCK:
2614 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2615 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2616 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2617 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2618 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2619 break;
2620 case CLASS_DRUID:
2621 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2622 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2623 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2624 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2625 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2630 void ObjectMgr::LoadGuilds()
2632 Guild *newguild;
2633 uint32 count = 0;
2635 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2637 if( !result )
2640 barGoLink bar( 1 );
2642 bar.step();
2644 sLog.outString();
2645 sLog.outString( ">> Loaded %u guild definitions", count );
2646 return;
2649 barGoLink bar( result->GetRowCount() );
2653 Field *fields = result->Fetch();
2655 bar.step();
2656 ++count;
2658 newguild = new Guild;
2659 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2661 newguild->Disband();
2662 delete newguild;
2663 continue;
2665 AddGuild(newguild);
2667 }while( result->NextRow() );
2669 delete result;
2671 sLog.outString();
2672 sLog.outString( ">> Loaded %u guild definitions", count );
2675 void ObjectMgr::LoadArenaTeams()
2677 uint32 count = 0;
2679 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2681 if( !result )
2684 barGoLink bar( 1 );
2686 bar.step();
2688 sLog.outString();
2689 sLog.outString( ">> Loaded %u arenateam definitions", count );
2690 return;
2693 barGoLink bar( result->GetRowCount() );
2697 Field *fields = result->Fetch();
2699 bar.step();
2700 ++count;
2702 ArenaTeam *newarenateam = new ArenaTeam;
2703 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2705 delete newarenateam;
2706 continue;
2708 AddArenaTeam(newarenateam);
2709 }while( result->NextRow() );
2711 delete result;
2713 sLog.outString();
2714 sLog.outString( ">> Loaded %u arenateam definitions", count );
2717 void ObjectMgr::LoadGroups()
2719 // -- loading groups --
2720 Group *group = NULL;
2721 uint64 leaderGuid = 0;
2722 uint32 count = 0;
2723 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2724 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2726 if( !result )
2728 barGoLink bar( 1 );
2730 bar.step();
2732 sLog.outString();
2733 sLog.outString( ">> Loaded %u group definitions", count );
2734 return;
2737 barGoLink bar( result->GetRowCount() );
2741 bar.step();
2742 Field *fields = result->Fetch();
2743 ++count;
2744 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2746 group = new Group;
2747 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2749 group->Disband();
2750 delete group;
2751 continue;
2753 AddGroup(group);
2754 }while( result->NextRow() );
2756 delete result;
2758 sLog.outString();
2759 sLog.outString( ">> Loaded %u group definitions", count );
2761 // -- loading members --
2762 count = 0;
2763 group = NULL;
2764 leaderGuid = 0;
2765 // 0 1 2 3
2766 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2767 if(!result)
2769 barGoLink bar( 1 );
2770 bar.step();
2772 else
2774 barGoLink bar( result->GetRowCount() );
2777 bar.step();
2778 Field *fields = result->Fetch();
2779 count++;
2780 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2781 if(!group || group->GetLeaderGUID() != leaderGuid)
2783 group = GetGroupByLeader(leaderGuid);
2784 if(!group)
2786 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2787 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2788 continue;
2792 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2794 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2795 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2797 }while( result->NextRow() );
2798 delete result;
2801 // clean groups
2802 // TODO: maybe delete from the DB before loading in this case
2803 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2805 if((*itr)->GetMembersCount() < 2)
2807 (*itr)->Disband();
2808 delete *itr;
2809 mGroupSet.erase(itr++);
2811 else
2812 ++itr;
2815 // -- loading instances --
2816 count = 0;
2817 group = NULL;
2818 leaderGuid = 0;
2819 result = CharacterDatabase.Query(
2820 // 0 1 2 3 4 5
2821 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2822 // 6
2823 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2824 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2827 if(!result)
2829 barGoLink bar( 1 );
2830 bar.step();
2832 else
2834 barGoLink bar( result->GetRowCount() );
2837 bar.step();
2838 Field *fields = result->Fetch();
2839 count++;
2840 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2841 if(!group || group->GetLeaderGUID() != leaderGuid)
2843 group = GetGroupByLeader(leaderGuid);
2844 if(!group)
2846 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2847 continue;
2851 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2852 group->BindToInstance(save, fields[3].GetBool(), true);
2853 }while( result->NextRow() );
2854 delete result;
2857 sLog.outString();
2858 sLog.outString( ">> Loaded %u group-instance binds total", count );
2860 sLog.outString();
2861 sLog.outString( ">> Loaded %u group members total", count );
2864 void ObjectMgr::LoadQuests()
2866 // For reload case
2867 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2868 delete itr->second;
2869 mQuestTemplates.clear();
2871 mExclusiveQuestGroups.clear();
2873 // 0 1 2 3 4 5 6 7 8
2874 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2875 // 9 10 11 12 13 14 15 16
2876 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2877 // 17 18 19 20 21 22 23 24 25 26 27 28
2878 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2879 // 29 30 31 32 33 34 35 36 37 38
2880 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2881 // 39 40 41 42 43 44 45 46
2882 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2883 // 47 48 49 50 51 52 53 54 55 56 57 58
2884 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2885 // 59 60 61 62 63 64 65 66
2886 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2887 // 67 68 69 70
2888 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2889 // 71 72 73 74 75 76
2890 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2891 // 77 78 79 80 81 82
2892 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2893 // 83 84 85 86 87 88 89 90
2894 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2895 // 91 92 93 94 95 96 97 98 99 100
2896 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2897 // 101 102 103 104 105 106 107 108 109 110 111
2898 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2899 // 112 113 114 115 116 117 118 119 120 121
2900 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2901 // 122 123
2902 "StartScript, CompleteScript"
2903 " FROM quest_template");
2904 if(result == NULL)
2906 barGoLink bar( 1 );
2907 bar.step();
2909 sLog.outString();
2910 sLog.outString( ">> Loaded 0 quests definitions" );
2911 sLog.outErrorDb("`quest_template` table is empty!");
2912 return;
2915 // create multimap previous quest for each existed quest
2916 // some quests can have many previous maps set by NextQuestId in previous quest
2917 // for example set of race quests can lead to single not race specific quest
2918 barGoLink bar( result->GetRowCount() );
2921 bar.step();
2922 Field *fields = result->Fetch();
2924 Quest * newQuest = new Quest(fields);
2925 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2926 } while( result->NextRow() );
2928 delete result;
2930 // Post processing
2931 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2933 Quest * qinfo = iter->second;
2935 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2937 if( qinfo->GetQuestMethod() >= 3 )
2939 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2942 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2944 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2945 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2946 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2949 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2951 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2953 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2954 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2958 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2960 // at auto-reward can be rewarded only RewChoiceItemId[0]
2961 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2963 if(uint32 id = qinfo->RewChoiceItemId[j])
2965 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2966 qinfo->GetQuestId(),j+1,id,j+1);
2967 // no changes, quest ignore this data
2972 // client quest log visual (area case)
2973 if( qinfo->ZoneOrSort > 0 )
2975 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2977 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2978 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2979 // no changes, quest not dependent from this value but can have problems at client
2982 // client quest log visual (sort case)
2983 if( qinfo->ZoneOrSort < 0 )
2985 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2986 if( !qSort )
2988 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2989 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2990 // 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)
2992 //check SkillOrClass value (class case).
2993 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2995 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2996 if(qinfo->SkillOrClass < 0)
2998 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2999 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3002 //check for proper SkillOrClass value (skill case)
3003 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3005 // skill is positive value in SkillOrClass
3006 if(qinfo->SkillOrClass != skill_id )
3008 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3009 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3010 //override, and force proper value here?
3015 // SkillOrClass (class case)
3016 if( qinfo->SkillOrClass < 0 )
3018 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3020 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3021 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3024 // SkillOrClass (skill case)
3025 if( qinfo->SkillOrClass > 0 )
3027 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3029 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3030 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3034 if( qinfo->RequiredSkillValue )
3036 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3038 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3039 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3040 // no changes, quest can't be done for this requirement
3043 if( qinfo->SkillOrClass <= 0 )
3045 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3046 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3047 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3050 // else Skill quests can have 0 skill level, this is ok
3052 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3054 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3055 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3056 // no changes, quest can't be done for this requirement
3059 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3061 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3062 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3063 // no changes, quest can't be done for this requirement
3066 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3068 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3069 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3070 // no changes, quest can't be done for this requirement
3073 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3075 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3076 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3077 // no changes, quest can't be done for this requirement
3080 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3082 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3083 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3084 // no changes, quest can't be done for this requirement
3087 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3089 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3090 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3091 // warning
3094 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3096 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3097 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3098 // warning
3101 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3103 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3104 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3105 // warning
3108 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3110 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3111 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3112 qinfo->CharTitleId = 0;
3113 // quest can't reward this title
3116 if(qinfo->SrcItemId)
3118 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3120 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3121 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3122 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3124 else if(qinfo->SrcItemCount==0)
3126 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3127 qinfo->GetQuestId(),qinfo->SrcItemId);
3128 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3131 else if(qinfo->SrcItemCount>0)
3133 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3134 qinfo->GetQuestId(),qinfo->SrcItemCount);
3135 qinfo->SrcItemCount=0; // no quest work changes in fact
3138 if(qinfo->SrcSpell)
3140 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3141 if(!spellInfo)
3143 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3144 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3145 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3147 else if(!SpellMgr::IsSpellValid(spellInfo))
3149 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3150 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3151 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3155 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3157 uint32 id = qinfo->ReqItemId[j];
3158 if(id)
3160 if(qinfo->ReqItemCount[j]==0)
3162 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3163 qinfo->GetQuestId(),j+1,id,j+1);
3164 // no changes, quest can't be done for this requirement
3167 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3169 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3171 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3172 qinfo->GetQuestId(),j+1,id,id);
3173 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3176 else if(qinfo->ReqItemCount[j]>0)
3178 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3179 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3180 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3184 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3186 uint32 id = qinfo->ReqSourceId[j];
3187 if(id)
3189 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3191 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3192 qinfo->GetQuestId(),j+1,id,id);
3193 // no changes, quest can't be done for this requirement
3196 if(!qinfo->ReqSourceCount[j])
3198 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3199 qinfo->GetQuestId(),j+1,id,j+1);
3200 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3203 if(!qinfo->ReqSourceRef[j])
3205 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3206 qinfo->GetQuestId(),j+1,id,j+1);
3207 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3210 else
3212 if(qinfo->ReqSourceCount[j]>0)
3214 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3215 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3216 // no changes, quest ignore this data
3219 if(qinfo->ReqSourceRef[j]>0)
3221 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3222 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3223 // no changes, quest ignore this data
3228 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3230 uint32 ref = qinfo->ReqSourceRef[j];
3231 if(ref)
3233 if(ref > QUEST_OBJECTIVES_COUNT)
3235 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3236 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3237 // no changes, quest can't be done for this requirement
3239 else
3240 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3242 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3243 qinfo->GetQuestId(),j+1,ref,ref,ref);
3244 // no changes, quest can't be done for this requirement
3246 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3248 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3249 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3250 // no changes, quest can't be done for this requirement
3251 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3256 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3258 uint32 id = qinfo->ReqSpell[j];
3259 if(id)
3261 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3262 if(!spellInfo)
3264 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3265 qinfo->GetQuestId(),j+1,id,id);
3266 // no changes, quest can't be done for this requirement
3269 if(!qinfo->ReqCreatureOrGOId[j])
3271 bool found = false;
3272 for(int k = 0; k < 3; ++k)
3274 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3275 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3277 found = true;
3278 break;
3282 if(found)
3284 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3286 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);
3288 // this will prevent quest completing without objective
3289 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3292 else
3294 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.",
3295 qinfo->GetQuestId(),j+1,id,j+1,id);
3296 // no changes, quest can't be done for this requirement
3302 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3304 int32 id = qinfo->ReqCreatureOrGOId[j];
3305 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3307 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3308 qinfo->GetQuestId(),j+1,id,uint32(-id));
3309 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3312 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3314 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3315 qinfo->GetQuestId(),j+1,id,uint32(id));
3316 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3319 if(id)
3321 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3323 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3325 if(!qinfo->ReqCreatureOrGOCount[j])
3327 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3328 qinfo->GetQuestId(),j+1,id,j+1);
3329 // no changes, quest can be incorrectly done, but we already report this
3332 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3334 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3335 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3336 // no changes, quest ignore this data
3340 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3342 uint32 id = qinfo->RewChoiceItemId[j];
3343 if(id)
3345 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3347 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3348 qinfo->GetQuestId(),j+1,id,id);
3349 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3352 if(!qinfo->RewChoiceItemCount[j])
3354 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3355 qinfo->GetQuestId(),j+1,id,j+1);
3356 // no changes, quest can't be done
3359 else if(qinfo->RewChoiceItemCount[j]>0)
3361 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3362 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3363 // no changes, quest ignore this data
3367 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3369 uint32 id = qinfo->RewItemId[j];
3370 if(id)
3372 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3374 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3375 qinfo->GetQuestId(),j+1,id,id);
3376 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3379 if(!qinfo->RewItemCount[j])
3381 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3382 qinfo->GetQuestId(),j+1,id,j+1);
3383 // no changes
3386 else if(qinfo->RewItemCount[j]>0)
3388 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3389 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3390 // no changes, quest ignore this data
3394 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3396 if(qinfo->RewRepFaction[j])
3398 if(!qinfo->RewRepValue[j])
3400 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3401 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3402 // no changes
3405 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3407 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.",
3408 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3409 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3412 else if(qinfo->RewRepValue[j]!=0)
3414 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3415 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3416 // no changes, quest ignore this data
3420 if(qinfo->RewSpell)
3422 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3424 if(!spellInfo)
3426 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3427 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3428 qinfo->RewSpell = 0; // no spell reward will display for this quest
3431 else if(!SpellMgr::IsSpellValid(spellInfo))
3433 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3434 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3435 qinfo->RewSpell = 0; // no spell reward will display for this quest
3440 if(qinfo->RewSpellCast)
3442 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3444 if(!spellInfo)
3446 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3447 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3448 qinfo->RewSpellCast = 0; // no spell will be casted on player
3451 else if(!SpellMgr::IsSpellValid(spellInfo))
3453 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3454 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3455 qinfo->RewSpellCast = 0; // no spell will be casted on player
3460 if(qinfo->RewMailTemplateId)
3462 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3464 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3465 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3466 qinfo->RewMailTemplateId = 0; // no mail will send to player
3467 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3471 if(qinfo->NextQuestInChain)
3473 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3475 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3476 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3477 qinfo->NextQuestInChain = 0;
3479 else
3480 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3483 // fill additional data stores
3484 if(qinfo->PrevQuestId)
3486 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3488 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3490 else
3492 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3496 if(qinfo->NextQuestId)
3498 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3500 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3502 else
3504 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3505 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3509 if(qinfo->ExclusiveGroup)
3510 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3511 if(qinfo->LimitTime)
3512 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3515 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3516 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3518 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3519 if(!spellInfo)
3520 continue;
3522 for(int j = 0; j < 3; ++j)
3524 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3525 continue;
3527 uint32 quest_id = spellInfo->EffectMiscValue[j];
3529 Quest const* quest = GetQuestTemplate(quest_id);
3531 // some quest referenced in spells not exist (outdated spells)
3532 if(!quest)
3533 continue;
3535 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3537 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);
3539 // this will prevent quest completing without objective
3540 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3545 sLog.outString();
3546 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3549 void ObjectMgr::LoadQuestLocales()
3551 mQuestLocaleMap.clear(); // need for reload case
3553 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3554 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3555 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3556 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3557 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3558 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3559 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3560 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3561 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3562 " FROM locales_quest"
3565 if(!result)
3567 barGoLink bar(1);
3569 bar.step();
3571 sLog.outString("");
3572 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3573 return;
3576 barGoLink bar(result->GetRowCount());
3580 Field *fields = result->Fetch();
3581 bar.step();
3583 uint32 entry = fields[0].GetUInt32();
3585 QuestLocale& data = mQuestLocaleMap[entry];
3587 for(int i = 1; i < MAX_LOCALE; ++i)
3589 std::string str = fields[1+10*(i-1)].GetCppString();
3590 if(!str.empty())
3592 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3593 if(idx >= 0)
3595 if(data.Title.size() <= idx)
3596 data.Title.resize(idx+1);
3598 data.Title[idx] = str;
3601 str = fields[1+10*(i-1)+1].GetCppString();
3602 if(!str.empty())
3604 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3605 if(idx >= 0)
3607 if(data.Details.size() <= idx)
3608 data.Details.resize(idx+1);
3610 data.Details[idx] = str;
3613 str = fields[1+10*(i-1)+2].GetCppString();
3614 if(!str.empty())
3616 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3617 if(idx >= 0)
3619 if(data.Objectives.size() <= idx)
3620 data.Objectives.resize(idx+1);
3622 data.Objectives[idx] = str;
3625 str = fields[1+10*(i-1)+3].GetCppString();
3626 if(!str.empty())
3628 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3629 if(idx >= 0)
3631 if(data.OfferRewardText.size() <= idx)
3632 data.OfferRewardText.resize(idx+1);
3634 data.OfferRewardText[idx] = str;
3637 str = fields[1+10*(i-1)+4].GetCppString();
3638 if(!str.empty())
3640 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3641 if(idx >= 0)
3643 if(data.RequestItemsText.size() <= idx)
3644 data.RequestItemsText.resize(idx+1);
3646 data.RequestItemsText[idx] = str;
3649 str = fields[1+10*(i-1)+5].GetCppString();
3650 if(!str.empty())
3652 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3653 if(idx >= 0)
3655 if(data.EndText.size() <= idx)
3656 data.EndText.resize(idx+1);
3658 data.EndText[idx] = str;
3661 for(int k = 0; k < 4; ++k)
3663 str = fields[1+10*(i-1)+6+k].GetCppString();
3664 if(!str.empty())
3666 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3667 if(idx >= 0)
3669 if(data.ObjectiveText[k].size() <= idx)
3670 data.ObjectiveText[k].resize(idx+1);
3672 data.ObjectiveText[k][idx] = str;
3677 } while (result->NextRow());
3679 delete result;
3681 sLog.outString();
3682 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3685 void ObjectMgr::LoadPetCreateSpells()
3687 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3688 if(!result)
3690 barGoLink bar( 1 );
3691 bar.step();
3693 sLog.outString();
3694 sLog.outString( ">> Loaded 0 pet create spells" );
3695 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3696 return;
3699 uint32 count = 0;
3701 barGoLink bar( result->GetRowCount() );
3703 mPetCreateSpell.clear();
3707 Field *fields = result->Fetch();
3708 bar.step();
3710 uint32 creature_id = fields[0].GetUInt32();
3712 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3713 continue;
3715 PetCreateSpellEntry PetCreateSpell;
3716 for(int i = 0; i < 4; i++)
3718 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3720 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3721 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3724 mPetCreateSpell[creature_id] = PetCreateSpell;
3726 ++count;
3728 while (result->NextRow());
3730 delete result;
3732 sLog.outString();
3733 sLog.outString( ">> Loaded %u pet create spells", count );
3736 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3738 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3739 return;
3741 sLog.outString( "%s :", tablename);
3743 scripts.clear(); // need for reload support
3745 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3747 uint32 count = 0;
3749 if( !result )
3751 barGoLink bar( 1 );
3752 bar.step();
3754 sLog.outString();
3755 sLog.outString( ">> Loaded %u script definitions", count );
3756 return;
3759 barGoLink bar( result->GetRowCount() );
3763 bar.step();
3765 Field *fields = result->Fetch();
3766 ScriptInfo tmp;
3767 tmp.id = fields[0].GetUInt32();
3768 tmp.delay = fields[1].GetUInt32();
3769 tmp.command = fields[2].GetUInt32();
3770 tmp.datalong = fields[3].GetUInt32();
3771 tmp.datalong2 = fields[4].GetUInt32();
3772 tmp.dataint = fields[5].GetInt32();
3773 tmp.x = fields[6].GetFloat();
3774 tmp.y = fields[7].GetFloat();
3775 tmp.z = fields[8].GetFloat();
3776 tmp.o = fields[9].GetFloat();
3778 // generic command args check
3779 switch(tmp.command)
3781 case SCRIPT_COMMAND_TALK:
3783 if(tmp.datalong > 3)
3785 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3786 continue;
3788 if(tmp.dataint==0)
3790 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3791 continue;
3793 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3795 sLog.outErrorDb("Table `%s` has out of range text id (dataint = %i expected %u-%u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID,tmp.id);
3796 continue;
3799 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3800 break;
3803 case SCRIPT_COMMAND_TELEPORT_TO:
3805 if(!sMapStore.LookupEntry(tmp.datalong))
3807 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3808 continue;
3811 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3813 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);
3814 continue;
3816 break;
3819 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3821 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3823 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);
3824 continue;
3827 if(!GetCreatureTemplate(tmp.datalong))
3829 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3830 continue;
3832 break;
3835 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3837 GameObjectData const* data = GetGOData(tmp.datalong);
3838 if(!data)
3840 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3841 continue;
3844 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3845 if(!info)
3847 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);
3848 continue;
3851 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3852 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3853 info->type==GAMEOBJECT_TYPE_DOOR ||
3854 info->type==GAMEOBJECT_TYPE_BUTTON ||
3855 info->type==GAMEOBJECT_TYPE_TRAP )
3857 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3858 continue;
3860 break;
3862 case SCRIPT_COMMAND_OPEN_DOOR:
3863 case SCRIPT_COMMAND_CLOSE_DOOR:
3865 GameObjectData const* data = GetGOData(tmp.datalong);
3866 if(!data)
3868 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);
3869 continue;
3872 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3873 if(!info)
3875 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);
3876 continue;
3879 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3881 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);
3882 continue;
3885 break;
3887 case SCRIPT_COMMAND_QUEST_EXPLORED:
3889 Quest const* quest = GetQuestTemplate(tmp.datalong);
3890 if(!quest)
3892 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);
3893 continue;
3896 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3898 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);
3900 // this will prevent quest completing without objective
3901 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3903 // continue; - quest objective requirement set and command can be allowed
3906 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3908 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",
3909 tablename,tmp.datalong2,tmp.id);
3910 continue;
3913 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3915 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %f or 0 for disable distance check",
3916 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3917 continue;
3920 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3922 sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %f or 0 for disable distance check",
3923 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3924 continue;
3927 break;
3930 case SCRIPT_COMMAND_REMOVE_AURA:
3931 case SCRIPT_COMMAND_CAST_SPELL:
3933 if(!sSpellStore.LookupEntry(tmp.datalong))
3935 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3936 tablename,tmp.datalong,tmp.id);
3937 continue;
3939 break;
3943 if (scripts.find(tmp.id) == scripts.end())
3945 ScriptMap emptyMap;
3946 scripts[tmp.id] = emptyMap;
3948 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3950 ++count;
3951 } while( result->NextRow() );
3953 delete result;
3955 sLog.outString();
3956 sLog.outString( ">> Loaded %u script definitions", count );
3959 void ObjectMgr::LoadGameObjectScripts()
3961 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3963 // check ids
3964 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3966 if(!GetGOData(itr->first))
3967 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3971 void ObjectMgr::LoadQuestEndScripts()
3973 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3975 // check ids
3976 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3978 if(!GetQuestTemplate(itr->first))
3979 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3983 void ObjectMgr::LoadQuestStartScripts()
3985 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3987 // check ids
3988 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3990 if(!GetQuestTemplate(itr->first))
3991 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3995 void ObjectMgr::LoadSpellScripts()
3997 LoadScripts(sSpellScripts, "spell_scripts");
3999 // check ids
4000 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4002 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4004 if(!spellInfo)
4006 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4007 continue;
4010 //check for correct spellEffect
4011 bool found = false;
4012 for(int i=0; i<3; ++i)
4014 // skip empty effects
4015 if( !spellInfo->Effect[i] )
4016 continue;
4018 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4020 found = true;
4021 break;
4025 if(!found)
4026 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4030 void ObjectMgr::LoadEventScripts()
4032 LoadScripts(sEventScripts, "event_scripts");
4034 std::set<uint32> evt_scripts;
4035 // Load all possible script entries from gameobjects
4036 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4038 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4039 if (goInfo)
4041 switch(goInfo->type)
4043 case GAMEOBJECT_TYPE_GOOBER:
4044 if(goInfo->goober.eventId)
4045 evt_scripts.insert(goInfo->goober.eventId);
4046 break;
4047 case GAMEOBJECT_TYPE_CHEST:
4048 if(goInfo->chest.eventId)
4049 evt_scripts.insert(goInfo->chest.eventId);
4050 break;
4051 default:
4052 break;
4056 // Load all possible script entries from spells
4057 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4059 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4060 if (spell)
4062 for(int j=0; j<3; ++j)
4064 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4066 if (spell->EffectMiscValue[j])
4067 evt_scripts.insert(spell->EffectMiscValue[j]);
4072 // Then check if all scripts are in above list of possible script entries
4073 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4075 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4076 if (itr2 == evt_scripts.end())
4077 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
4081 void ObjectMgr::LoadItemTexts()
4083 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4085 uint32 count = 0;
4087 if( !result )
4089 barGoLink bar( 1 );
4090 bar.step();
4092 sLog.outString();
4093 sLog.outString( ">> Loaded %u item pages", count );
4094 return;
4097 barGoLink bar( result->GetRowCount() );
4099 Field* fields;
4102 bar.step();
4104 fields = result->Fetch();
4106 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4108 ++count;
4110 } while ( result->NextRow() );
4112 delete result;
4114 sLog.outString();
4115 sLog.outString( ">> Loaded %u item texts", count );
4118 void ObjectMgr::LoadPageTexts()
4120 sPageTextStore.Free(); // for reload case
4122 sPageTextStore.Load();
4123 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4124 sLog.outString();
4126 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4128 // check data correctness
4129 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4130 if(!page)
4131 continue;
4133 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4135 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4136 continue;
4139 // detect circular reference
4140 std::set<uint32> checkedPages;
4141 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4143 if(!pageItr->Next_Page)
4144 break;
4145 checkedPages.insert(pageItr->Page_ID);
4146 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4148 std::ostringstream ss;
4149 ss<< "The text page(s) ";
4150 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4151 ss << *itr << " ";
4152 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4153 << pageItr->Page_ID <<" to 0";
4154 sLog.outErrorDb(ss.str().c_str());
4155 const_cast<PageText*>(pageItr)->Next_Page = 0;
4156 break;
4162 void ObjectMgr::LoadPageTextLocales()
4164 mPageTextLocaleMap.clear(); // need for reload case
4166 QueryResult *result = WorldDatabase.Query("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4168 if(!result)
4170 barGoLink bar(1);
4172 bar.step();
4174 sLog.outString("");
4175 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4176 return;
4179 barGoLink bar(result->GetRowCount());
4183 Field *fields = result->Fetch();
4184 bar.step();
4186 uint32 entry = fields[0].GetUInt32();
4188 PageTextLocale& data = mPageTextLocaleMap[entry];
4190 for(int i = 1; i < MAX_LOCALE; ++i)
4192 std::string str = fields[i].GetCppString();
4193 if(str.empty())
4194 continue;
4196 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4197 if(idx >= 0)
4199 if(data.Text.size() <= idx)
4200 data.Text.resize(idx+1);
4202 data.Text[idx] = str;
4206 } while (result->NextRow());
4208 delete result;
4210 sLog.outString();
4211 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4214 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4216 template<class D>
4217 void convert_from_str(uint32 field_pos, char *src, D &dst)
4219 dst = D(objmgr.GetScriptId(src));
4223 void ObjectMgr::LoadInstanceTemplate()
4225 SQLInstanceLoader loader;
4226 loader.Load(sInstanceTemplate);
4228 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4230 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4231 if(!temp) continue;
4232 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4233 if(!entry)
4235 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4236 continue;
4238 else if(!entry->HasResetTime())
4239 continue;
4241 if(temp->reset_delay == 0)
4243 // use defaults from the DBC
4244 if(entry->SupportsHeroicMode())
4246 temp->reset_delay = entry->resetTimeHeroic / DAY;
4248 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4250 temp->reset_delay = entry->resetTimeRaid / DAY;
4254 // the reset_delay must be at least one day
4255 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4258 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4259 sLog.outString();
4262 void ObjectMgr::AddGossipText(GossipText *pGText)
4264 ASSERT( pGText->Text_ID );
4265 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4266 mGossipText[pGText->Text_ID] = pGText;
4269 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4271 GossipTextMap::const_iterator itr;
4272 for (itr = mGossipText.begin(); itr != mGossipText.end(); ++itr)
4274 if(itr->second->Text_ID == Text_ID)
4275 return itr->second;
4277 return NULL;
4280 void ObjectMgr::LoadGossipText()
4282 GossipText *pGText;
4283 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4285 int count = 0;
4286 if( !result )
4288 barGoLink bar( 1 );
4289 bar.step();
4291 sLog.outString();
4292 sLog.outString( ">> Loaded %u npc texts", count );
4293 return;
4296 int cic;
4298 barGoLink bar( result->GetRowCount() );
4302 ++count;
4303 cic = 0;
4305 Field *fields = result->Fetch();
4307 bar.step();
4309 pGText = new GossipText;
4310 pGText->Text_ID = fields[cic++].GetUInt32();
4312 for (int i=0; i< 8; i++)
4314 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4315 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4317 pGText->Options[i].Language = fields[cic++].GetUInt32();
4318 pGText->Options[i].Probability = fields[cic++].GetFloat();
4320 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4321 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4323 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4324 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4326 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4327 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4330 if ( !pGText->Text_ID ) continue;
4331 AddGossipText( pGText );
4333 } while( result->NextRow() );
4335 sLog.outString();
4336 sLog.outString( ">> Loaded %u npc texts", count );
4337 delete result;
4340 void ObjectMgr::LoadNpcTextLocales()
4342 mNpcTextLocaleMap.clear(); // need for reload case
4344 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4345 "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,"
4346 "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,"
4347 "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,"
4348 "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,"
4349 "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,"
4350 "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,"
4351 "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, "
4352 "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 "
4353 " FROM locales_npc_text");
4355 if(!result)
4357 barGoLink bar(1);
4359 bar.step();
4361 sLog.outString("");
4362 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4363 return;
4366 barGoLink bar(result->GetRowCount());
4370 Field *fields = result->Fetch();
4371 bar.step();
4373 uint32 entry = fields[0].GetUInt32();
4375 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4377 for(int i=1; i<MAX_LOCALE; ++i)
4379 for(int j=0; j<8; ++j)
4381 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4382 if(!str0.empty())
4384 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4385 if(idx >= 0)
4387 if(data.Text_0[j].size() <= idx)
4388 data.Text_0[j].resize(idx+1);
4390 data.Text_0[j][idx] = str0;
4393 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4394 if(!str1.empty())
4396 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4397 if(idx >= 0)
4399 if(data.Text_1[j].size() <= idx)
4400 data.Text_1[j].resize(idx+1);
4402 data.Text_1[j][idx] = str1;
4407 } while (result->NextRow());
4409 delete result;
4411 sLog.outString();
4412 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4415 //not very fast function but it is called only once a day, or on starting-up
4416 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4418 time_t basetime = time(NULL);
4419 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4420 //delete all old mails without item and without body immediately, if starting server
4421 if (!serverUp)
4422 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4423 // 0 1 2 3 4 5 6 7 8 9
4424 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);
4425 if ( !result )
4426 return; // any mails need to be returned or deleted
4427 Field *fields;
4428 //std::ostringstream delitems, delmails; //will be here for optimization
4429 //bool deletemail = false, deleteitem = false;
4430 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4431 //delmails << "DELETE FROM mail WHERE id IN ( "
4434 fields = result->Fetch();
4435 Mail *m = new Mail;
4436 m->messageID = fields[0].GetUInt32();
4437 m->messageType = fields[1].GetUInt8();
4438 m->sender = fields[2].GetUInt32();
4439 m->receiver = fields[3].GetUInt32();
4440 m->itemTextId = fields[4].GetUInt32();
4441 bool has_items = fields[5].GetBool();
4442 m->expire_time = (time_t)fields[6].GetUInt64();
4443 m->deliver_time = 0;
4444 m->COD = fields[7].GetUInt32();
4445 m->checked = fields[8].GetUInt32();
4446 m->mailTemplateId = fields[9].GetInt16();
4448 Player *pl = 0;
4449 if (serverUp)
4450 pl = GetPlayer((uint64)m->receiver);
4451 if (pl && pl->m_mailsLoaded)
4452 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4453 //his in mailbox and he has already listed his mails )
4454 delete m;
4455 continue;
4457 //delete or return mail:
4458 if (has_items)
4460 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4461 if(resultItems)
4465 Field *fields2 = resultItems->Fetch();
4467 uint32 item_guid_low = fields2[0].GetUInt32();
4468 uint32 item_template = fields2[1].GetUInt32();
4470 m->AddItem(item_guid_low, item_template);
4472 while (resultItems->NextRow());
4474 delete resultItems;
4476 //if it is mail from AH, it shouldn't be returned, but deleted
4477 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4479 // mail open and then not returned
4480 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4481 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4483 else
4485 //mail will be returned:
4486 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);
4487 delete m;
4488 continue;
4492 if (m->itemTextId)
4493 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4495 //deletemail = true;
4496 //delmails << m->messageID << ", ";
4497 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4498 delete m;
4499 } while (result->NextRow());
4500 delete result;
4503 void ObjectMgr::LoadQuestAreaTriggers()
4505 mQuestAreaTriggerMap.clear(); // need for reload case
4507 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4509 uint32 count = 0;
4511 if( !result )
4513 barGoLink bar( 1 );
4514 bar.step();
4516 sLog.outString();
4517 sLog.outString( ">> Loaded %u quest trigger points", 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();
4531 uint32 quest_ID = fields[1].GetUInt32();
4533 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4534 if(!atEntry)
4536 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4537 continue;
4540 Quest const* quest = GetQuestTemplate(quest_ID);
4542 if(!quest)
4544 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4545 continue;
4548 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4550 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);
4552 // this will prevent quest completing without objective
4553 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4555 // continue; - quest modified to required objective and trigger can be allowed.
4558 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4560 } while( result->NextRow() );
4562 delete result;
4564 sLog.outString();
4565 sLog.outString( ">> Loaded %u quest trigger points", count );
4568 void ObjectMgr::LoadTavernAreaTriggers()
4570 mTavernAreaTriggerSet.clear(); // need for reload case
4572 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4574 uint32 count = 0;
4576 if( !result )
4578 barGoLink bar( 1 );
4579 bar.step();
4581 sLog.outString();
4582 sLog.outString( ">> Loaded %u tavern triggers", count );
4583 return;
4586 barGoLink bar( result->GetRowCount() );
4590 ++count;
4591 bar.step();
4593 Field *fields = result->Fetch();
4595 uint32 Trigger_ID = fields[0].GetUInt32();
4597 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4598 if(!atEntry)
4600 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4601 continue;
4604 mTavernAreaTriggerSet.insert(Trigger_ID);
4605 } while( result->NextRow() );
4607 delete result;
4609 sLog.outString();
4610 sLog.outString( ">> Loaded %u tavern triggers", count );
4613 void ObjectMgr::LoadAreaTriggerScripts()
4615 mAreaTriggerScripts.clear(); // need for reload case
4616 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4618 uint32 count = 0;
4620 if( !result )
4622 barGoLink bar( 1 );
4623 bar.step();
4625 sLog.outString();
4626 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4627 return;
4630 barGoLink bar( result->GetRowCount() );
4634 ++count;
4635 bar.step();
4637 Field *fields = result->Fetch();
4639 uint32 Trigger_ID = fields[0].GetUInt32();
4640 const char *scriptName = fields[1].GetString();
4642 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4643 if(!atEntry)
4645 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4646 continue;
4648 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4649 } while( result->NextRow() );
4651 delete result;
4653 sLog.outString();
4654 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4657 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4659 bool found = false;
4660 float dist;
4661 uint32 id = 0;
4663 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4665 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4666 if(node && node->map_id == mapid)
4668 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4669 if(found)
4671 if(dist2 < dist)
4673 dist = dist2;
4674 id = i;
4677 else
4679 found = true;
4680 dist = dist2;
4681 id = i;
4686 return id;
4689 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4691 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4692 if(src_i==sTaxiPathSetBySource.end())
4694 path = 0;
4695 cost = 0;
4696 return;
4699 TaxiPathSetForSource& pathSet = src_i->second;
4701 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4702 if(dest_i==pathSet.end())
4704 path = 0;
4705 cost = 0;
4706 return;
4709 cost = dest_i->second.price;
4710 path = dest_i->second.ID;
4713 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4715 uint16 mount_entry = 0;
4716 uint16 mount_id = 0;
4718 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4719 if(node)
4721 if (team == ALLIANCE)
4723 mount_entry = node->MountCreatureID[1];
4724 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4725 if(ci)
4726 mount_id = ci->DisplayID_A;
4728 if (team == HORDE)
4730 mount_entry = node->MountCreatureID[0];
4731 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4732 if(ci)
4733 mount_id = ci->DisplayID_H;
4737 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4738 if(!minfo)
4740 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. ",
4741 mount_entry,id,team,mount_id);
4743 return false;
4745 if(minfo->modelid_other_gender!=0)
4746 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4748 return mount_id;
4751 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4753 if(path >= sTaxiPathNodesByPath.size())
4754 return;
4756 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4758 pathnodes.Resize(nodeList.size());
4759 mapIds.resize(nodeList.size());
4761 for(size_t i = 0; i < nodeList.size(); ++i)
4763 pathnodes[ i ].x = nodeList[i].x;
4764 pathnodes[ i ].y = nodeList[i].y;
4765 pathnodes[ i ].z = nodeList[i].z;
4767 mapIds[i] = nodeList[i].mapid;
4771 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4773 if(path >= sTaxiPathNodesByPath.size())
4774 return;
4776 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4778 pathnodes.Resize(nodeList.size());
4780 for(size_t i = 0; i < nodeList.size(); ++i)
4782 pathnodes[ i ].mapid = nodeList[i].mapid;
4783 pathnodes[ i ].x = nodeList[i].x;
4784 pathnodes[ i ].y = nodeList[i].y;
4785 pathnodes[ i ].z = nodeList[i].z;
4786 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4787 pathnodes[ i ].delay = nodeList[i].delay;
4791 void ObjectMgr::LoadGraveyardZones()
4793 mGraveYardMap.clear(); // need for reload case
4795 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4797 uint32 count = 0;
4799 if( !result )
4801 barGoLink bar( 1 );
4802 bar.step();
4804 sLog.outString();
4805 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4806 return;
4809 barGoLink bar( result->GetRowCount() );
4813 ++count;
4814 bar.step();
4816 Field *fields = result->Fetch();
4818 uint32 safeLocId = fields[0].GetUInt32();
4819 uint32 zoneId = fields[1].GetUInt32();
4820 uint32 team = fields[2].GetUInt32();
4822 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4823 if(!entry)
4825 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4826 continue;
4829 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4830 if(!areaEntry)
4832 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4833 continue;
4836 if(areaEntry->zone != 0)
4838 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4839 continue;
4842 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4844 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4845 continue;
4848 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4849 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4850 } while( result->NextRow() );
4852 delete result;
4854 sLog.outString();
4855 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4858 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4860 // search for zone associated closest graveyard
4861 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4863 // Simulate std. algorithm:
4864 // found some graveyard associated to (ghost_zone,ghost_map)
4866 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4867 // then check faction
4868 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4869 // then check faction
4870 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4871 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4872 if(graveLow==graveUp)
4874 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4875 return NULL;
4878 // at corpse map
4879 bool foundNear = false;
4880 float distNear;
4881 WorldSafeLocsEntry const* entryNear = NULL;
4883 // at entrance map for corpse map
4884 bool foundEntr = false;
4885 float distEntr;
4886 WorldSafeLocsEntry const* entryEntr = NULL;
4888 // some where other
4889 WorldSafeLocsEntry const* entryFar = NULL;
4891 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4893 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4895 GraveYardData const& data = itr->second;
4897 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4898 if(!entry)
4900 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4901 continue;
4904 // skip enemy faction graveyard
4905 // team == 0 case can be at call from .neargrave
4906 if(data.team != 0 && team != 0 && data.team != team)
4907 continue;
4909 // find now nearest graveyard at other map
4910 if(MapId != entry->map_id)
4912 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4913 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4914 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4916 // not have any corrdinates for check distance anyway
4917 entryFar = entry;
4918 continue;
4921 // at entrance map calculate distance (2D);
4922 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4923 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4924 if(foundEntr)
4926 if(dist2 < distEntr)
4928 distEntr = dist2;
4929 entryEntr = entry;
4932 else
4934 foundEntr = true;
4935 distEntr = dist2;
4936 entryEntr = entry;
4939 // find now nearest graveyard at same map
4940 else
4942 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4943 if(foundNear)
4945 if(dist2 < distNear)
4947 distNear = dist2;
4948 entryNear = entry;
4951 else
4953 foundNear = true;
4954 distNear = dist2;
4955 entryNear = entry;
4960 if(entryNear)
4961 return entryNear;
4963 if(entryEntr)
4964 return entryEntr;
4966 return entryFar;
4969 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4971 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4972 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4974 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4976 if(itr->second.safeLocId==id)
4977 return &itr->second;
4980 return NULL;
4983 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4985 if(FindGraveYardData(id,zoneId))
4986 return false;
4988 // add link to loaded data
4989 GraveYardData data;
4990 data.safeLocId = id;
4991 data.team = team;
4993 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4995 // add link to DB
4996 if(inDB)
4998 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4999 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5002 return true;
5005 void ObjectMgr::LoadAreaTriggerTeleports()
5007 mAreaTriggers.clear(); // need for reload case
5009 uint32 count = 0;
5011 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5012 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");
5013 if( !result )
5016 barGoLink bar( 1 );
5018 bar.step();
5020 sLog.outString();
5021 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5022 return;
5025 barGoLink bar( result->GetRowCount() );
5029 Field *fields = result->Fetch();
5031 bar.step();
5033 ++count;
5035 uint32 Trigger_ID = fields[0].GetUInt32();
5037 AreaTrigger at;
5039 at.requiredLevel = fields[1].GetUInt8();
5040 at.requiredItem = fields[2].GetUInt32();
5041 at.requiredItem2 = fields[3].GetUInt32();
5042 at.heroicKey = fields[4].GetUInt32();
5043 at.heroicKey2 = fields[5].GetUInt32();
5044 at.requiredQuest = fields[6].GetUInt32();
5045 at.requiredFailedText = fields[7].GetCppString();
5046 at.target_mapId = fields[8].GetUInt32();
5047 at.target_X = fields[9].GetFloat();
5048 at.target_Y = fields[10].GetFloat();
5049 at.target_Z = fields[11].GetFloat();
5050 at.target_Orientation = fields[12].GetFloat();
5052 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5053 if(!atEntry)
5055 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5056 continue;
5059 if(at.requiredItem)
5061 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5062 if(!pProto)
5064 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5065 at.requiredItem = 0;
5068 if(at.requiredItem2)
5070 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5071 if(!pProto)
5073 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5074 at.requiredItem2 = 0;
5078 if(at.heroicKey)
5080 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5081 if(!pProto)
5083 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5084 at.heroicKey = 0;
5088 if(at.heroicKey2)
5090 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5091 if(!pProto)
5093 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5094 at.heroicKey2 = 0;
5098 if(at.requiredQuest)
5100 if(!mQuestTemplates[at.requiredQuest])
5102 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5103 at.requiredQuest = 0;
5107 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5108 if(!mapEntry)
5110 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5111 continue;
5114 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5116 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5117 continue;
5120 mAreaTriggers[Trigger_ID] = at;
5122 } while( result->NextRow() );
5124 delete result;
5126 sLog.outString();
5127 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5130 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5132 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5133 if(!mapEntry) return NULL;
5134 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5136 if(itr->second.target_mapId == mapEntry->entrance_map)
5138 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5139 if(atEntry && atEntry->mapid == Map)
5140 return &itr->second;
5143 return NULL;
5146 void ObjectMgr::SetHighestGuids()
5148 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5149 if( result )
5151 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5152 delete result;
5155 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5156 if( result )
5158 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5159 delete result;
5162 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5163 m_hiPetGuid = 0;
5164 // same for vehicles
5165 m_hiVehicleGuid = 0;
5167 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5168 if( result )
5170 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5171 delete result;
5174 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5175 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5176 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5177 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5178 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5180 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5181 if( result )
5183 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5184 delete result;
5187 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5188 if( result )
5190 m_auctionid = (*result)[0].GetUInt32()+1;
5191 delete result;
5194 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5195 if( result )
5197 m_mailid = (*result)[0].GetUInt32()+1;
5198 delete result;
5201 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5202 if( result )
5204 m_ItemTextId = (*result)[0].GetUInt32()+1;
5205 delete result;
5208 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5209 if( result )
5211 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5212 delete result;
5215 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5216 if (result)
5218 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5219 delete result;
5222 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5223 if (result)
5225 m_guildId = (*result)[0].GetUInt32()+1;
5226 delete result;
5230 uint32 ObjectMgr::GenerateArenaTeamId()
5232 if(m_arenaTeamId>=0xFFFFFFFE)
5234 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5235 World::StopNow(ERROR_EXIT_CODE);
5237 return m_arenaTeamId++;
5240 uint32 ObjectMgr::GenerateGuildId()
5242 if(m_guildId>=0xFFFFFFFE)
5244 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5245 World::StopNow(ERROR_EXIT_CODE);
5247 return m_guildId++;
5250 uint32 ObjectMgr::GenerateAuctionID()
5252 if(m_auctionid>=0xFFFFFFFE)
5254 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5255 World::StopNow(ERROR_EXIT_CODE);
5257 return m_auctionid++;
5260 uint32 ObjectMgr::GenerateMailID()
5262 if(m_mailid>=0xFFFFFFFE)
5264 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5265 World::StopNow(ERROR_EXIT_CODE);
5267 return m_mailid++;
5270 uint32 ObjectMgr::GenerateItemTextID()
5272 if(m_ItemTextId>=0xFFFFFFFE)
5274 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5275 World::StopNow(ERROR_EXIT_CODE);
5277 return m_ItemTextId++;
5280 uint32 ObjectMgr::CreateItemText(std::string text)
5282 uint32 newItemTextId = GenerateItemTextID();
5283 //insert new itempage to container
5284 mItemTexts[ newItemTextId ] = text;
5285 //save new itempage
5286 CharacterDatabase.escape_string(text);
5287 //any Delete query needed, itemTextId is maximum of all ids
5288 std::ostringstream query;
5289 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5290 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5291 return newItemTextId;
5294 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5296 switch(guidhigh)
5298 case HIGHGUID_ITEM:
5299 if(m_hiItemGuid>=0xFFFFFFFE)
5301 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5302 World::StopNow(ERROR_EXIT_CODE);
5304 return m_hiItemGuid++;
5305 case HIGHGUID_UNIT:
5306 if(m_hiCreatureGuid>=0x00FFFFFE)
5308 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5309 World::StopNow(ERROR_EXIT_CODE);
5311 return m_hiCreatureGuid++;
5312 case HIGHGUID_PET:
5313 if(m_hiPetGuid>=0x00FFFFFE)
5315 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5316 World::StopNow(ERROR_EXIT_CODE);
5318 return m_hiPetGuid++;
5319 case HIGHGUID_VEHICLE:
5320 ++m_hiVehicleGuid;
5321 if(m_hiVehicleGuid>=0x00FFFFFF)
5323 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5324 World::StopNow(ERROR_EXIT_CODE);
5326 return m_hiVehicleGuid++;
5327 case HIGHGUID_PLAYER:
5328 if(m_hiCharGuid>=0xFFFFFFFE)
5330 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5331 World::StopNow(ERROR_EXIT_CODE);
5333 return m_hiCharGuid++;
5334 case HIGHGUID_GAMEOBJECT:
5335 if(m_hiGoGuid>=0x00FFFFFE)
5337 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5338 World::StopNow(ERROR_EXIT_CODE);
5340 return m_hiGoGuid++;
5341 case HIGHGUID_CORPSE:
5342 if(m_hiCorpseGuid>=0xFFFFFFFE)
5344 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5345 World::StopNow(ERROR_EXIT_CODE);
5347 return m_hiCorpseGuid++;
5348 case HIGHGUID_DYNAMICOBJECT:
5349 if(m_hiDoGuid>=0xFFFFFFFE)
5351 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5352 World::StopNow(ERROR_EXIT_CODE);
5354 return m_hiDoGuid++;
5355 default:
5356 ASSERT(0);
5359 ASSERT(0);
5360 return 0;
5363 void ObjectMgr::LoadGameObjectLocales()
5365 mGameObjectLocaleMap.clear(); // need for reload case
5367 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5368 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5369 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5370 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5372 if(!result)
5374 barGoLink bar(1);
5376 bar.step();
5378 sLog.outString("");
5379 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5380 return;
5383 barGoLink bar(result->GetRowCount());
5387 Field *fields = result->Fetch();
5388 bar.step();
5390 uint32 entry = fields[0].GetUInt32();
5392 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5394 for(int i = 1; i < MAX_LOCALE; ++i)
5396 std::string str = fields[i].GetCppString();
5397 if(!str.empty())
5399 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5400 if(idx >= 0)
5402 if(data.Name.size() <= idx)
5403 data.Name.resize(idx+1);
5405 data.Name[idx] = str;
5410 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5412 std::string str = fields[i].GetCppString();
5413 if(!str.empty())
5415 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5416 if(idx >= 0)
5418 if(data.CastBarCaption.size() <= idx)
5419 data.CastBarCaption.resize(idx+1);
5421 data.CastBarCaption[idx] = str;
5426 } while (result->NextRow());
5428 delete result;
5430 sLog.outString();
5431 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5434 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5436 template<class D>
5437 void convert_from_str(uint32 field_pos, char *src, D &dst)
5439 dst = D(objmgr.GetScriptId(src));
5443 void ObjectMgr::LoadGameobjectInfo()
5445 SQLGameObjectLoader loader;
5446 loader.Load(sGOStorage);
5448 // some checks
5449 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5451 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5452 if(!goInfo)
5453 continue;
5455 switch(goInfo->type)
5457 case GAMEOBJECT_TYPE_DOOR: //0
5459 if(goInfo->door.lockId)
5461 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5462 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5463 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5465 break;
5467 case GAMEOBJECT_TYPE_BUTTON: //1
5469 if(goInfo->button.lockId)
5471 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5472 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5473 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5475 break;
5477 case GAMEOBJECT_TYPE_CHEST: //3
5479 if(goInfo->chest.lockId)
5481 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5482 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5483 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5485 if(goInfo->chest.linkedTrapId) // linked trap
5487 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5489 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5490 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5491 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5493 /* disable check for while
5494 else
5495 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5496 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5499 break;
5501 case GAMEOBJECT_TYPE_TRAP: //6
5503 /* disable check for while
5504 if(goInfo->trap.spellId) // spell
5506 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5507 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5508 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5511 break;
5513 case GAMEOBJECT_TYPE_CHAIR: //7
5514 if(goInfo->chair.height > 2)
5516 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5517 id,goInfo->type,goInfo->chair.height);
5519 // prevent client and server unexpected work
5520 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5522 break;
5523 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5525 if(goInfo->spellFocus.focusId)
5527 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5528 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5529 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5532 if(goInfo->spellFocus.linkedTrapId) // linked trap
5534 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5536 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5537 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5538 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5540 /* disable check for while
5541 else
5542 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5543 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5546 break;
5548 case GAMEOBJECT_TYPE_GOOBER: //10
5550 if(goInfo->goober.pageId) // pageId
5552 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5553 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5554 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5556 /* disable check for while
5557 if(goInfo->goober.spellId) // spell
5559 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5560 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5561 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5564 if(goInfo->goober.linkedTrapId) // linked trap
5566 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5568 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5569 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5570 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5572 /* disable check for while
5573 else
5574 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5575 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5578 break;
5580 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5582 if(goInfo->moTransport.taxiPathId)
5584 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5585 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5586 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5588 break;
5590 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5592 /* disabled
5593 if(goInfo->summoningRitual.spellId)
5595 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5596 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5597 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5600 break;
5602 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5604 if(goInfo->spellcaster.spellId) // spell
5606 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5607 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5608 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5610 break;
5615 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5616 sLog.outString();
5619 void ObjectMgr::LoadExplorationBaseXP()
5621 uint32 count = 0;
5622 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5624 if( !result )
5626 barGoLink bar( 1 );
5628 bar.step();
5630 sLog.outString();
5631 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5632 return;
5635 barGoLink bar( result->GetRowCount() );
5639 bar.step();
5641 Field *fields = result->Fetch();
5642 uint32 level = fields[0].GetUInt32();
5643 uint32 basexp = fields[1].GetUInt32();
5644 mBaseXPTable[level] = basexp;
5645 ++count;
5647 while (result->NextRow());
5649 delete result;
5651 sLog.outString();
5652 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5655 uint32 ObjectMgr::GetBaseXP(uint32 level)
5657 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5660 void ObjectMgr::LoadPetNames()
5662 uint32 count = 0;
5663 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5665 if( !result )
5667 barGoLink bar( 1 );
5669 bar.step();
5671 sLog.outString();
5672 sLog.outString( ">> Loaded %u pet name parts", count );
5673 return;
5676 barGoLink bar( result->GetRowCount() );
5680 bar.step();
5682 Field *fields = result->Fetch();
5683 std::string word = fields[0].GetString();
5684 uint32 entry = fields[1].GetUInt32();
5685 bool half = fields[2].GetBool();
5686 if(half)
5687 PetHalfName1[entry].push_back(word);
5688 else
5689 PetHalfName0[entry].push_back(word);
5690 ++count;
5692 while (result->NextRow());
5693 delete result;
5695 sLog.outString();
5696 sLog.outString( ">> Loaded %u pet name parts", count );
5699 void ObjectMgr::LoadPetNumber()
5701 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5702 if(result)
5704 Field *fields = result->Fetch();
5705 m_hiPetNumber = fields[0].GetUInt32()+1;
5706 delete result;
5709 barGoLink bar( 1 );
5710 bar.step();
5712 sLog.outString();
5713 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5716 std::string ObjectMgr::GeneratePetName(uint32 entry)
5718 std::vector<std::string> & list0 = PetHalfName0[entry];
5719 std::vector<std::string> & list1 = PetHalfName1[entry];
5721 if(list0.empty() || list1.empty())
5723 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5724 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5725 if(!petname)
5726 petname = cinfo->Name;
5727 return std::string(petname);
5730 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5733 uint32 ObjectMgr::GeneratePetNumber()
5735 return ++m_hiPetNumber;
5738 void ObjectMgr::LoadCorpses()
5740 uint32 count = 0;
5741 // 0 1 2 3 4 5 6 7 8 10
5742 QueryResult *result = CharacterDatabase.Query("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5744 if( !result )
5746 barGoLink bar( 1 );
5748 bar.step();
5750 sLog.outString();
5751 sLog.outString( ">> Loaded %u corpses", count );
5752 return;
5755 barGoLink bar( result->GetRowCount() );
5759 bar.step();
5761 Field *fields = result->Fetch();
5763 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5765 Corpse *corpse = new Corpse;
5766 if(!corpse->LoadFromDB(guid,fields))
5768 delete corpse;
5769 continue;
5772 ObjectAccessor::Instance().AddCorpse(corpse);
5774 ++count;
5776 while (result->NextRow());
5777 delete result;
5779 sLog.outString();
5780 sLog.outString( ">> Loaded %u corpses", count );
5783 void ObjectMgr::LoadReputationOnKill()
5785 uint32 count = 0;
5787 // 0 1 2
5788 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5789 // 3 4 5 6 7 8 9
5790 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5791 "FROM creature_onkill_reputation");
5793 if(!result)
5795 barGoLink bar(1);
5797 bar.step();
5799 sLog.outString();
5800 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5801 return;
5804 barGoLink bar(result->GetRowCount());
5808 Field *fields = result->Fetch();
5809 bar.step();
5811 uint32 creature_id = fields[0].GetUInt32();
5813 ReputationOnKillEntry repOnKill;
5814 repOnKill.repfaction1 = fields[1].GetUInt32();
5815 repOnKill.repfaction2 = fields[2].GetUInt32();
5816 repOnKill.is_teamaward1 = fields[3].GetBool();
5817 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5818 repOnKill.repvalue1 = fields[5].GetInt32();
5819 repOnKill.is_teamaward2 = fields[6].GetBool();
5820 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5821 repOnKill.repvalue2 = fields[8].GetInt32();
5822 repOnKill.team_dependent = fields[9].GetUInt8();
5824 if(!GetCreatureTemplate(creature_id))
5826 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5827 continue;
5830 if(repOnKill.repfaction1)
5832 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5833 if(!factionEntry1)
5835 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5836 continue;
5840 if(repOnKill.repfaction2)
5842 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5843 if(!factionEntry2)
5845 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5846 continue;
5850 mRepOnKill[creature_id] = repOnKill;
5852 ++count;
5853 } while (result->NextRow());
5855 delete result;
5857 sLog.outString();
5858 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5861 void ObjectMgr::LoadWeatherZoneChances()
5863 uint32 count = 0;
5865 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5866 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");
5868 if(!result)
5870 barGoLink bar(1);
5872 bar.step();
5874 sLog.outString();
5875 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5876 return;
5879 barGoLink bar(result->GetRowCount());
5883 Field *fields = result->Fetch();
5884 bar.step();
5886 uint32 zone_id = fields[0].GetUInt32();
5888 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5890 for(int season = 0; season < WEATHER_SEASONS; ++season)
5892 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5893 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5894 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5896 if(wzc.data[season].rainChance > 100)
5898 wzc.data[season].rainChance = 25;
5899 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5902 if(wzc.data[season].snowChance > 100)
5904 wzc.data[season].snowChance = 25;
5905 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5908 if(wzc.data[season].stormChance > 100)
5910 wzc.data[season].stormChance = 25;
5911 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5915 ++count;
5916 } while (result->NextRow());
5918 delete result;
5920 sLog.outString();
5921 sLog.outString(">> Loaded %u weather definitions", count);
5924 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5926 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5927 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5928 if(t)
5929 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5932 void ObjectMgr::DeleteCreatureData(uint32 guid)
5934 // remove mapid*cellid -> guid_set map
5935 CreatureData const* data = GetCreatureData(guid);
5936 if(data)
5937 RemoveCreatureFromGrid(guid, data);
5939 mCreatureDataMap.erase(guid);
5942 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5944 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5945 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5946 if(t)
5947 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5950 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5952 RespawnTimes::iterator next;
5954 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5956 next = itr;
5957 ++next;
5959 if(GUID_HIPART(itr->first)==instance)
5960 mGORespawnTimes.erase(itr);
5963 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5965 next = itr;
5966 ++next;
5968 if(GUID_HIPART(itr->first)==instance)
5969 mCreatureRespawnTimes.erase(itr);
5972 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5973 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5976 void ObjectMgr::DeleteGOData(uint32 guid)
5978 // remove mapid*cellid -> guid_set map
5979 GameObjectData const* data = GetGOData(guid);
5980 if(data)
5981 RemoveGameobjectFromGrid(guid, data);
5983 mGameObjectDataMap.erase(guid);
5986 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5988 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5989 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5990 cell_guids.corpses[player_guid] = instance;
5993 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5995 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5996 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5997 cell_guids.corpses.erase(player_guid);
6000 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6002 map.clear(); // need for reload case
6004 uint32 count = 0;
6006 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6008 if(!result)
6010 barGoLink bar(1);
6012 bar.step();
6014 sLog.outString();
6015 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6016 return;
6019 barGoLink bar(result->GetRowCount());
6023 Field *fields = result->Fetch();
6024 bar.step();
6026 uint32 id = fields[0].GetUInt32();
6027 uint32 quest = fields[1].GetUInt32();
6029 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6031 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6032 continue;
6035 map.insert(QuestRelations::value_type(id,quest));
6037 ++count;
6038 } while (result->NextRow());
6040 delete result;
6042 sLog.outString();
6043 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6046 void ObjectMgr::LoadGameobjectQuestRelations()
6048 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6050 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6052 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6053 if(!goInfo)
6054 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6055 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6056 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6060 void ObjectMgr::LoadGameobjectInvolvedRelations()
6062 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6064 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6066 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6067 if(!goInfo)
6068 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6069 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6070 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6074 void ObjectMgr::LoadCreatureQuestRelations()
6076 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6078 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6080 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6081 if(!cInfo)
6082 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6083 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6084 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);
6088 void ObjectMgr::LoadCreatureInvolvedRelations()
6090 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6092 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6094 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6095 if(!cInfo)
6096 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6097 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6098 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);
6102 void ObjectMgr::LoadReservedPlayersNames()
6104 m_ReservedNames.clear(); // need for reload case
6106 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6108 uint32 count = 0;
6110 if( !result )
6112 barGoLink bar( 1 );
6113 bar.step();
6115 sLog.outString();
6116 sLog.outString( ">> Loaded %u reserved player names", count );
6117 return;
6120 barGoLink bar( result->GetRowCount() );
6122 Field* fields;
6125 bar.step();
6126 fields = result->Fetch();
6127 std::string name= fields[0].GetCppString();
6128 if(normalizePlayerName(name))
6130 m_ReservedNames.insert(name);
6131 ++count;
6133 } while ( result->NextRow() );
6135 delete result;
6137 sLog.outString();
6138 sLog.outString( ">> Loaded %u reserved player names", count );
6141 enum LanguageType
6143 LT_BASIC_LATIN = 0x0000,
6144 LT_EXTENDEN_LATIN = 0x0001,
6145 LT_CYRILLIC = 0x0002,
6146 LT_EAST_ASIA = 0x0004,
6147 LT_ANY = 0xFFFF
6150 static LanguageType GetRealmLanguageType(bool create)
6152 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6154 case REALM_ZONE_UNKNOWN: // any language
6155 case REALM_ZONE_DEVELOPMENT:
6156 case REALM_ZONE_TEST_SERVER:
6157 case REALM_ZONE_QA_SERVER:
6158 return LT_ANY;
6159 case REALM_ZONE_UNITED_STATES: // extended-Latin
6160 case REALM_ZONE_OCEANIC:
6161 case REALM_ZONE_LATIN_AMERICA:
6162 case REALM_ZONE_ENGLISH:
6163 case REALM_ZONE_GERMAN:
6164 case REALM_ZONE_FRENCH:
6165 case REALM_ZONE_SPANISH:
6166 return LT_EXTENDEN_LATIN;
6167 case REALM_ZONE_KOREA: // East-Asian
6168 case REALM_ZONE_TAIWAN:
6169 case REALM_ZONE_CHINA:
6170 return LT_EAST_ASIA;
6171 case REALM_ZONE_RUSSIAN: // Cyrillic
6172 return LT_CYRILLIC;
6173 default:
6174 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6178 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6180 if(strictMask==0) // any language, ignore realm
6182 if(isExtendedLatinString(wstr,numericOrSpace))
6183 return true;
6184 if(isCyrillicString(wstr,numericOrSpace))
6185 return true;
6186 if(isEastAsianString(wstr,numericOrSpace))
6187 return true;
6188 return false;
6191 if(strictMask & 0x2) // realm zone specific
6193 LanguageType lt = GetRealmLanguageType(create);
6194 if(lt & LT_EXTENDEN_LATIN)
6195 if(isExtendedLatinString(wstr,numericOrSpace))
6196 return true;
6197 if(lt & LT_CYRILLIC)
6198 if(isCyrillicString(wstr,numericOrSpace))
6199 return true;
6200 if(lt & LT_EAST_ASIA)
6201 if(isEastAsianString(wstr,numericOrSpace))
6202 return true;
6205 if(strictMask & 0x1) // basic Latin
6207 if(isBasicLatinString(wstr,numericOrSpace))
6208 return true;
6211 return false;
6214 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6216 std::wstring wname;
6217 if(!Utf8toWStr(name,wname))
6218 return false;
6220 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6221 return false;
6223 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6225 return isValidString(wname,strictMask,false,create);
6228 bool ObjectMgr::IsValidCharterName( const std::string& name )
6230 std::wstring wname;
6231 if(!Utf8toWStr(name,wname))
6232 return false;
6234 if(wname.size() < 1)
6235 return false;
6237 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6239 return isValidString(wname,strictMask,true);
6242 bool ObjectMgr::IsValidPetName( const std::string& name )
6244 std::wstring wname;
6245 if(!Utf8toWStr(name,wname))
6246 return false;
6248 if(wname.size() < 1)
6249 return false;
6251 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6253 return isValidString(wname,strictMask,false);
6256 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6258 if(loc==LOCALE_enUS)
6259 return -1;
6261 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6262 if(m_LocalForIndex[i]==loc)
6263 return i;
6265 return -1;
6268 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6270 if (i<0 || i>=m_LocalForIndex.size())
6271 return LOCALE_enUS;
6273 return m_LocalForIndex[i];
6276 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6278 if(loc==LOCALE_enUS)
6279 return -1;
6281 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6282 if(m_LocalForIndex[i]==loc)
6283 return i;
6285 m_LocalForIndex.push_back(loc);
6286 return m_LocalForIndex.size()-1;
6289 AchievementCriteriaEntryList const& ObjectMgr::GetAchievementCriteriaByType(AchievementCriteriaTypes type)
6291 return m_AchievementCriteriasByType[type];
6294 void ObjectMgr::LoadAchievementCriteriaList()
6296 for (uint32 entryId = 0; entryId<sAchievementCriteriaStore.GetNumRows(); entryId++)
6298 AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId);
6299 if(!criteria)
6300 continue;
6302 m_AchievementCriteriasByType[criteria->requiredType].push_back(criteria);
6306 void ObjectMgr::LoadBattleMastersEntry()
6308 mBattleMastersMap.clear(); // need for reload case
6310 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6312 uint32 count = 0;
6314 if( !result )
6316 barGoLink bar( 1 );
6317 bar.step();
6319 sLog.outString();
6320 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6321 return;
6324 barGoLink bar( result->GetRowCount() );
6328 ++count;
6329 bar.step();
6331 Field *fields = result->Fetch();
6333 uint32 entry = fields[0].GetUInt32();
6334 uint32 bgTypeId = fields[1].GetUInt32();
6336 mBattleMastersMap[entry] = bgTypeId;
6338 } while( result->NextRow() );
6340 delete result;
6342 sLog.outString();
6343 sLog.outString( ">> Loaded %u battlemaster entries", count );
6346 void ObjectMgr::LoadGameObjectForQuests()
6348 mGameObjectForQuestSet.clear(); // need for reload case
6350 uint32 count = 0;
6352 // collect GO entries for GO that must activated
6353 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6355 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6356 if(!goInfo)
6357 continue;
6359 switch(goInfo->type)
6361 // scan GO chest with loot including quest items
6362 case GAMEOBJECT_TYPE_CHEST:
6364 uint32 loot_id = GameObject::GetLootId(goInfo);
6366 // find quest loot for GO
6367 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6369 mGameObjectForQuestSet.insert(go_entry);
6370 ++count;
6372 break;
6374 case GAMEOBJECT_TYPE_GOOBER:
6376 if(goInfo->goober.questId) //quests objects
6378 mGameObjectForQuestSet.insert(go_entry);
6379 count++;
6381 break;
6383 default:
6384 break;
6388 sLog.outString();
6389 sLog.outString( ">> Loaded %u GameObject for quests", count );
6392 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6394 // cleanup affected map part for reloading case
6395 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6397 if(itr->first >= min_value && itr->first <= max_value)
6399 MangosStringLocaleMap::iterator itr2 = itr;
6400 ++itr;
6401 mMangosStringLocaleMap.erase(itr2);
6403 else
6404 ++itr;
6407 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);
6409 if(!result)
6411 barGoLink bar(1);
6413 bar.step();
6415 sLog.outString("");
6416 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6417 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6418 else
6419 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6420 return false;
6423 uint32 count = 0;
6425 barGoLink bar(result->GetRowCount());
6429 Field *fields = result->Fetch();
6430 bar.step();
6432 int32 entry = fields[0].GetInt32();
6434 if(entry==0)
6436 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6437 continue;
6439 else if(entry < min_value || entry > max_value)
6441 int32 start = min_value > 0 ? min_value : max_value;
6442 int32 end = min_value > 0 ? max_value : min_value;
6443 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6444 continue;
6447 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6449 if(data.Content.size() > 0)
6451 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6452 continue;
6455 data.Content.resize(1);
6456 ++count;
6458 // 0 -> default, idx in to idx+1
6459 data.Content[0] = fields[1].GetCppString();
6461 for(int i = 1; i < MAX_LOCALE; ++i)
6463 std::string str = fields[i+1].GetCppString();
6464 if(!str.empty())
6466 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6467 if(idx >= 0)
6469 // 0 -> default, idx in to idx+1
6470 if(data.Content.size() <= idx+1)
6471 data.Content.resize(idx+2);
6473 data.Content[idx+1] = str;
6477 } while (result->NextRow());
6479 delete result;
6481 sLog.outString();
6482 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6483 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6484 else
6485 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6487 return true;
6490 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6492 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6493 // Content[0] always exist if exist MangosStringLocale
6494 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6496 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6497 return msl->Content[locale_idx+1].c_str();
6498 else
6499 return msl->Content[0].c_str();
6502 if(entry > 0)
6503 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6504 else
6505 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6506 return "<error>";
6509 void ObjectMgr::LoadFishingBaseSkillLevel()
6511 mFishingBaseForArea.clear(); // for reload case
6513 uint32 count = 0;
6514 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6516 if( !result )
6518 barGoLink bar( 1 );
6520 bar.step();
6522 sLog.outString();
6523 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6524 return;
6527 barGoLink bar( result->GetRowCount() );
6531 bar.step();
6533 Field *fields = result->Fetch();
6534 uint32 entry = fields[0].GetUInt32();
6535 int32 skill = fields[1].GetInt32();
6537 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6538 if(!fArea)
6540 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6541 continue;
6544 mFishingBaseForArea[entry] = skill;
6545 ++count;
6547 while (result->NextRow());
6549 delete result;
6551 sLog.outString();
6552 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6555 // Searches for the same condition already in Conditions store
6556 // Returns Id if found, else adds it to Conditions and returns Id
6557 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6559 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6560 for (uint16 i=0; i < mConditions.size(); ++i)
6562 if (lc == mConditions[i])
6563 return i;
6566 mConditions.push_back(lc);
6568 if(mConditions.size() > 0xFFFF)
6570 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6571 return 0;
6574 return mConditions.size() - 1;
6577 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6579 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6581 std::wstring wname;
6582 if(!Utf8toWStr(names.name[i],wname))
6583 return false;
6585 if(mainpart!=GetMainPartOfName(wname,i+1))
6586 return false;
6588 return true;
6591 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6593 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6594 if(i!= mAreaTriggerScripts.end())
6595 return i->second;
6596 return 0;
6599 // Checks if player meets the condition
6600 bool PlayerCondition::Meets(Player const * player) const
6602 if( !player )
6603 return false; // player not present, return false
6605 switch (condition)
6607 case CONDITION_NONE:
6608 return true; // empty condition, always met
6609 case CONDITION_AURA:
6610 return player->HasAura(value1, value2);
6611 case CONDITION_ITEM:
6612 return player->HasItemCount(value1, value2);
6613 case CONDITION_ITEM_EQUIPPED:
6614 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6615 case CONDITION_ZONEID:
6616 return player->GetZoneId() == value1;
6617 case CONDITION_REPUTATION_RANK:
6619 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6620 return faction && player->GetReputationRank(faction) >= value2;
6622 case CONDITION_TEAM:
6623 return player->GetTeam() == value1;
6624 case CONDITION_SKILL:
6625 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6626 case CONDITION_QUESTREWARDED:
6627 return player->GetQuestRewardStatus(value1);
6628 case CONDITION_QUESTTAKEN:
6630 QuestStatus status = player->GetQuestStatus(value1);
6631 return (status == QUEST_STATUS_INCOMPLETE);
6633 case CONDITION_AD_COMMISSION_AURA:
6635 Unit::AuraMap const& auras = player->GetAuras();
6636 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6637 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6638 return true;
6639 return false;
6641 case CONDITION_NO_AURA:
6642 return !player->HasAura(value1, value2);
6643 case CONDITION_ACTIVE_EVENT:
6644 return gameeventmgr.IsActiveEvent(value1);
6645 default:
6646 return false;
6650 // Verification of condition values validity
6651 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6653 if( condition >= MAX_CONDITION) // Wrong condition type
6655 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6656 return false;
6659 switch (condition)
6661 case CONDITION_AURA:
6663 if(!sSpellStore.LookupEntry(value1))
6665 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6666 return false;
6668 if(value2 > 2)
6670 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6671 return false;
6673 break;
6675 case CONDITION_ITEM:
6677 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6678 if(!proto)
6680 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6681 return false;
6683 break;
6685 case CONDITION_ITEM_EQUIPPED:
6687 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6688 if(!proto)
6690 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6691 return false;
6693 break;
6695 case CONDITION_ZONEID:
6697 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6698 if(!areaEntry)
6700 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6701 return false;
6703 if(areaEntry->zone != 0)
6705 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6706 return false;
6708 break;
6710 case CONDITION_REPUTATION_RANK:
6712 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6713 if(!factionEntry)
6715 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6716 return false;
6718 break;
6720 case CONDITION_TEAM:
6722 if (value1 != ALLIANCE && value1 != HORDE)
6724 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6725 return false;
6727 break;
6729 case CONDITION_SKILL:
6731 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6732 if (!pSkill)
6734 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6735 return false;
6737 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6739 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6740 return false;
6742 break;
6744 case CONDITION_QUESTREWARDED:
6745 case CONDITION_QUESTTAKEN:
6747 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6748 if (!Quest)
6750 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6751 return false;
6753 if(value2)
6754 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6755 break;
6757 case CONDITION_AD_COMMISSION_AURA:
6759 if(value1)
6760 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6761 if(value2)
6762 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6763 break;
6765 case CONDITION_NO_AURA:
6767 if(!sSpellStore.LookupEntry(value1))
6769 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6770 return false;
6772 if(value2 > 2)
6774 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6775 return false;
6777 break;
6779 case CONDITION_ACTIVE_EVENT:
6781 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6782 if(value1 >=events.size() || !events[value1].isValid())
6784 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6785 return false;
6787 break;
6790 return true;
6793 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6795 switch(pSkill->categoryId)
6797 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6798 case SKILL_CATEGORY_WEAPON:
6799 if(pSkill->id!=SKILL_FIST_WEAPONS)
6800 return SKILL_RANGE_LEVEL;
6801 else
6802 return SKILL_RANGE_MONO;
6803 case SKILL_CATEGORY_ARMOR:
6804 case SKILL_CATEGORY_CLASS:
6805 if(pSkill->id != SKILL_LOCKPICKING)
6806 return SKILL_RANGE_MONO;
6807 else
6808 return SKILL_RANGE_LEVEL;
6809 case SKILL_CATEGORY_SECONDARY:
6810 case SKILL_CATEGORY_PROFESSION:
6811 // not set skills for professions and racial abilities
6812 if(IsProfessionSkill(pSkill->id))
6813 return SKILL_RANGE_RANK;
6814 else if(racial)
6815 return SKILL_RANGE_NONE;
6816 else
6817 return SKILL_RANGE_MONO;
6818 default:
6819 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6820 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6821 return SKILL_RANGE_NONE;
6825 void ObjectMgr::LoadGameTele()
6827 m_GameTeleMap.clear(); // for reload case
6829 uint32 count = 0;
6830 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6832 if( !result )
6834 barGoLink bar( 1 );
6836 bar.step();
6838 sLog.outString();
6839 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6840 return;
6843 barGoLink bar( result->GetRowCount() );
6847 bar.step();
6849 Field *fields = result->Fetch();
6851 uint32 id = fields[0].GetUInt32();
6853 GameTele gt;
6855 gt.position_x = fields[1].GetFloat();
6856 gt.position_y = fields[2].GetFloat();
6857 gt.position_z = fields[3].GetFloat();
6858 gt.orientation = fields[4].GetFloat();
6859 gt.mapId = fields[5].GetUInt32();
6860 gt.name = fields[6].GetCppString();
6862 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6864 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6865 continue;
6868 if(!Utf8toWStr(gt.name,gt.wnameLow))
6870 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6871 continue;
6874 wstrToLower( gt.wnameLow );
6876 m_GameTeleMap[id] = gt;
6878 ++count;
6880 while (result->NextRow());
6882 delete result;
6884 sLog.outString();
6885 sLog.outString( ">> Loaded %u game tele's", count );
6888 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6890 // explicit name case
6891 std::wstring wname;
6892 if(!Utf8toWStr(name,wname))
6893 return false;
6895 // converting string that we try to find to lower case
6896 wstrToLower( wname );
6898 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6899 const GameTele* alt = NULL;
6900 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6901 if(itr->second.wnameLow == wname)
6902 return &itr->second;
6903 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6904 alt = &itr->second;
6906 return alt;
6909 bool ObjectMgr::AddGameTele(GameTele& tele)
6911 // find max id
6912 uint32 new_id = 0;
6913 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6914 if(itr->first > new_id)
6915 new_id = itr->first;
6917 // use next
6918 ++new_id;
6920 if(!Utf8toWStr(tele.name,tele.wnameLow))
6921 return false;
6923 wstrToLower( tele.wnameLow );
6925 m_GameTeleMap[new_id] = tele;
6927 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')",
6928 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6931 bool ObjectMgr::DeleteGameTele(const std::string& name)
6933 // explicit name case
6934 std::wstring wname;
6935 if(!Utf8toWStr(name,wname))
6936 return false;
6938 // converting string that we try to find to lower case
6939 wstrToLower( wname );
6941 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6943 if(itr->second.wnameLow == wname)
6945 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6946 m_GameTeleMap.erase(itr);
6947 return true;
6951 return false;
6954 void ObjectMgr::LoadTrainerSpell()
6956 // For reload case
6957 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6958 itr->second.Clear();
6959 m_mCacheTrainerSpellMap.clear();
6961 std::set<uint32> skip_trainers;
6963 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6965 if( !result )
6967 barGoLink bar( 1 );
6969 bar.step();
6971 sLog.outString();
6972 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6973 return;
6976 barGoLink bar( result->GetRowCount() );
6978 uint32 count = 0;
6981 bar.step();
6983 Field* fields = result->Fetch();
6985 uint32 entry = fields[0].GetUInt32();
6986 uint32 spell = fields[1].GetUInt32();
6988 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6990 if(!cInfo)
6992 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6993 continue;
6996 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6998 if(skip_trainers.count(entry) == 0)
7000 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7001 skip_trainers.insert(entry);
7003 continue;
7006 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7007 if(!spellinfo)
7009 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7010 continue;
7013 if(!SpellMgr::IsSpellValid(spellinfo))
7015 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7016 continue;
7019 TrainerSpell* pTrainerSpell = new TrainerSpell();
7020 pTrainerSpell->spell = spell;
7021 pTrainerSpell->spellcost = fields[2].GetUInt32();
7022 pTrainerSpell->reqskill = fields[3].GetUInt32();
7023 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
7024 pTrainerSpell->reqlevel = fields[5].GetUInt32();
7026 if(!pTrainerSpell->reqlevel)
7027 pTrainerSpell->reqlevel = spellinfo->spellLevel;
7030 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7032 if(SpellMgr::IsProfessionSpell(spell))
7033 data.trainerType = 2;
7035 data.spellList.push_back(pTrainerSpell);
7036 ++count;
7038 } while (result->NextRow());
7039 delete result;
7041 sLog.outString();
7042 sLog.outString( ">> Loaded Trainers %d", count );
7045 void ObjectMgr::LoadVendors()
7047 // For reload case
7048 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7049 itr->second.Clear();
7050 m_mCacheVendorItemMap.clear();
7052 std::set<uint32> skip_vendors;
7054 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7055 if( !result )
7057 barGoLink bar( 1 );
7059 bar.step();
7061 sLog.outString();
7062 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7063 return;
7066 barGoLink bar( result->GetRowCount() );
7068 uint32 count = 0;
7071 bar.step();
7072 Field* fields = result->Fetch();
7074 uint32 entry = fields[0].GetUInt32();
7075 uint32 item_id = fields[1].GetUInt32();
7076 uint32 maxcount = fields[2].GetUInt32();
7077 uint32 incrtime = fields[3].GetUInt32();
7078 uint32 ExtendedCost = fields[4].GetUInt32();
7080 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7081 continue;
7083 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7085 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7086 ++count;
7088 } while (result->NextRow());
7089 delete result;
7091 sLog.outString();
7092 sLog.outString( ">> Loaded %d Vendors ", count );
7095 void ObjectMgr::LoadNpcTextId()
7098 m_mCacheNpcTextIdMap.clear();
7100 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7101 if( !result )
7103 barGoLink bar( 1 );
7105 bar.step();
7107 sLog.outString();
7108 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7109 return;
7112 barGoLink bar( result->GetRowCount() );
7114 uint32 count = 0;
7115 uint32 guid,textid;
7118 bar.step();
7120 Field* fields = result->Fetch();
7122 guid = fields[0].GetUInt32();
7123 textid = fields[1].GetUInt32();
7125 if (!GetCreatureData(guid))
7127 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7128 continue;
7130 if (!GetGossipText(textid))
7132 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7133 continue;
7136 m_mCacheNpcTextIdMap[guid] = textid ;
7137 ++count;
7139 } while (result->NextRow());
7140 delete result;
7142 sLog.outString();
7143 sLog.outString( ">> Loaded %d NpcTextId ", count );
7146 void ObjectMgr::LoadNpcOptions()
7148 m_mCacheNpcOptionList.clear(); // For reload case
7150 QueryResult *result = WorldDatabase.Query(
7151 // 0 1 2 3 4 5 6 7 8
7152 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7153 "FROM npc_option");
7155 if( !result )
7157 barGoLink bar( 1 );
7159 bar.step();
7161 sLog.outString();
7162 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7163 return;
7166 barGoLink bar( result->GetRowCount() );
7168 uint32 count = 0;
7172 bar.step();
7174 Field* fields = result->Fetch();
7176 GossipOption go;
7177 go.Id = fields[0].GetUInt32();
7178 go.GossipId = fields[1].GetUInt32();
7179 go.NpcFlag = fields[2].GetUInt32();
7180 go.Icon = fields[3].GetUInt32();
7181 go.Action = fields[4].GetUInt32();
7182 go.BoxMoney = fields[5].GetUInt32();
7183 go.Coded = fields[6].GetUInt8()!=0;
7184 go.OptionText = fields[7].GetCppString();
7185 go.BoxText = fields[8].GetCppString();
7187 m_mCacheNpcOptionList.push_back(go);
7189 ++count;
7191 } while (result->NextRow());
7192 delete result;
7194 sLog.outString();
7195 sLog.outString( ">> Loaded %d npc_option entries", count );
7198 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7200 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7201 vList.AddItem(item,maxcount,incrtime,extendedcost);
7203 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7206 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7208 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7209 if(iter == m_mCacheVendorItemMap.end())
7210 return false;
7212 if(!iter->second.FindItem(item))
7213 return false;
7215 iter->second.RemoveItem(item);
7216 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7217 return true;
7220 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7222 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7223 if(!cInfo)
7225 if(pl)
7226 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7227 else
7228 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7229 return false;
7232 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7234 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7236 if(pl)
7237 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7238 else
7239 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7241 if(skip_vendors)
7242 skip_vendors->insert(vendor_entry);
7244 return false;
7247 if(!GetItemPrototype(item_id))
7249 if(pl)
7250 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7251 else
7252 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7253 return false;
7256 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7258 if(pl)
7259 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7260 else
7261 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7262 return false;
7265 if(maxcount > 0 && incrtime == 0)
7267 if(pl)
7268 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7269 else
7270 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7271 return false;
7273 else if(maxcount==0 && incrtime > 0)
7275 if(pl)
7276 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7277 else
7278 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7279 return false;
7282 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7283 if(!vItems)
7284 return true; // later checks for non-empty lists
7286 if(vItems->FindItem(item_id))
7288 if(pl)
7289 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7290 else
7291 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7292 return false;
7295 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7297 if(pl)
7298 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7299 else
7300 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7301 return false;
7304 return true;
7307 void ObjectMgr::LoadScriptNames()
7309 m_scriptNames.push_back("");
7310 QueryResult *result = WorldDatabase.Query(
7311 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7312 "UNION "
7313 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7314 "UNION "
7315 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7316 "UNION "
7317 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7318 "UNION "
7319 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7320 if(result)
7324 m_scriptNames.push_back((*result)[0].GetString());
7325 } while (result->NextRow());
7326 delete result;
7329 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7332 uint32 ObjectMgr::GetScriptId(const char *name)
7334 // use binary search to find the script name in the sorted vector
7335 // assume "" is the first element
7336 if(!name) return 0;
7337 ScriptNameMap::const_iterator itr =
7338 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7339 if(itr == m_scriptNames.end() || *itr != name) return 0;
7340 return itr - m_scriptNames.begin();
7343 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7345 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7347 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7349 if(itrM->second.dataint)
7351 if(!GetMangosStringLocale (itrM->second.dataint))
7352 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7354 if(ids.count(itrM->second.dataint))
7355 ids.erase(itrM->second.dataint);
7361 void ObjectMgr::LoadDbScriptStrings()
7363 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7365 std::set<int32> ids;
7367 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7368 if(GetMangosStringLocale(i))
7369 ids.insert(i);
7371 CheckScripts(sQuestEndScripts,ids);
7372 CheckScripts(sQuestStartScripts,ids);
7373 CheckScripts(sSpellScripts,ids);
7374 CheckScripts(sGameObjectScripts,ids);
7375 CheckScripts(sEventScripts,ids);
7377 WaypointMgr.CheckTextsExistance(ids);
7379 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7380 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7383 // Functions for scripting access
7384 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7386 return objmgr.GetAreaTriggerScriptId(trigger_id);
7389 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7391 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7393 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());
7394 start_value = -1;
7395 end_value = std::numeric_limits<int32>::min();
7398 // for scripting localized strings allowed use _only_ negative entries
7399 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7402 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7404 return objmgr.GetScriptId(name);
7407 ObjectMgr::ScriptNameMap & GetScriptNames()
7409 return objmgr.GetScriptNames();