[6922] Whitespace and newline fixes
[getmangos.git] / src / game / ObjectMgr.cpp
blobf25b93a466ffcec40657dff74c4817aa99731f8f
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 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1897 if( !result )
1898 return;
1900 barGoLink bar( result->GetRowCount() );
1902 uint32 count = 0;
1904 Field *fields;
1907 bar.step();
1909 fields = result->Fetch();
1910 uint32 item_guid = fields[0].GetUInt32();
1911 uint32 item_template = fields[1].GetUInt32();
1913 ItemPrototype const *proto = GetItemPrototype(item_template);
1915 if(!proto)
1917 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1918 continue;
1921 Item *item = NewItemOrBag(proto);
1923 if(!item->LoadFromDB(item_guid,0))
1925 delete item;
1926 continue;
1928 AddAItem(item);
1930 ++count;
1932 while( result->NextRow() );
1934 delete result;
1936 sLog.outString();
1937 sLog.outString( ">> Loaded %u auction items", count );
1940 void ObjectMgr::LoadPetLevelInfo()
1942 // Loading levels data
1944 // 0 1 2 3 4 5 6 7 8 9
1945 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1947 uint32 count = 0;
1949 if (!result)
1951 barGoLink bar( 1 );
1953 sLog.outString();
1954 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1955 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1956 return;
1959 barGoLink bar( result->GetRowCount() );
1963 Field* fields = result->Fetch();
1965 uint32 creature_id = fields[0].GetUInt32();
1966 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1968 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1969 continue;
1972 uint32 current_level = fields[1].GetUInt32();
1973 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1975 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1976 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1977 else
1978 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1979 continue;
1981 else if(current_level < 1)
1983 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1984 continue;
1987 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1989 if(pInfoMapEntry==NULL)
1990 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1992 // data for level 1 stored in [0] array element, ...
1993 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1995 pLevelInfo->health = fields[2].GetUInt16();
1996 pLevelInfo->mana = fields[3].GetUInt16();
1997 pLevelInfo->armor = fields[9].GetUInt16();
1999 for (int i = 0; i < MAX_STATS; i++)
2001 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2004 bar.step();
2005 ++count;
2007 while (result->NextRow());
2009 delete result;
2011 sLog.outString();
2012 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2015 // Fill gaps and check integrity
2016 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2018 PetLevelInfo* pInfo = itr->second;
2020 // fatal error if no level 1 data
2021 if(!pInfo || pInfo[0].health == 0 )
2023 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2024 exit(1);
2027 // fill level gaps
2028 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2030 if(pInfo[level].health == 0)
2032 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2033 pInfo[level] = pInfo[level-1];
2039 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2041 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2042 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2044 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2045 if(itr == petInfo.end())
2046 return NULL;
2048 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2051 void ObjectMgr::LoadPlayerInfo()
2053 // Load playercreate
2055 // 0 1 2 3 4 5 6
2056 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2058 uint32 count = 0;
2060 if (!result)
2062 barGoLink bar( 1 );
2064 sLog.outString();
2065 sLog.outString( ">> Loaded %u player create definitions", count );
2066 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2067 exit(1);
2070 barGoLink bar( result->GetRowCount() );
2074 Field* fields = result->Fetch();
2076 uint32 current_race = fields[0].GetUInt32();
2077 uint32 current_class = fields[1].GetUInt32();
2078 uint32 mapId = fields[2].GetUInt32();
2079 uint32 zoneId = fields[3].GetUInt32();
2080 float positionX = fields[4].GetFloat();
2081 float positionY = fields[5].GetFloat();
2082 float positionZ = fields[6].GetFloat();
2084 if(current_race >= MAX_RACES)
2086 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2087 continue;
2090 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2091 if(!rEntry)
2093 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2094 continue;
2097 if(current_class >= MAX_CLASSES)
2099 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2100 continue;
2103 if(!sChrClassesStore.LookupEntry(current_class))
2105 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2106 continue;
2109 // accept DB data only for valid position (and non instanceable)
2110 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2112 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2113 continue;
2116 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2118 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2119 continue;
2122 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2124 pInfo->mapId = mapId;
2125 pInfo->zoneId = zoneId;
2126 pInfo->positionX = positionX;
2127 pInfo->positionY = positionY;
2128 pInfo->positionZ = positionZ;
2130 pInfo->displayId_m = rEntry->model_m;
2131 pInfo->displayId_f = rEntry->model_f;
2133 bar.step();
2134 ++count;
2136 while (result->NextRow());
2138 delete result;
2140 sLog.outString();
2141 sLog.outString( ">> Loaded %u player create definitions", count );
2144 // Load playercreate items
2146 // 0 1 2 3
2147 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2149 uint32 count = 0;
2151 if (!result)
2153 barGoLink bar( 1 );
2155 sLog.outString();
2156 sLog.outString( ">> Loaded %u custom player create items", count );
2158 else
2160 barGoLink bar( result->GetRowCount() );
2164 Field* fields = result->Fetch();
2166 uint32 current_race = fields[0].GetUInt32();
2167 if(current_race >= MAX_RACES)
2169 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2170 continue;
2173 uint32 current_class = fields[1].GetUInt32();
2174 if(current_class >= MAX_CLASSES)
2176 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2177 continue;
2180 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2182 uint32 item_id = fields[2].GetUInt32();
2184 if(!GetItemPrototype(item_id))
2186 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);
2187 continue;
2190 uint32 amount = fields[3].GetUInt32();
2192 if(!amount)
2194 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2195 continue;
2198 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2200 bar.step();
2201 ++count;
2203 while(result->NextRow());
2205 delete result;
2207 sLog.outString();
2208 sLog.outString( ">> Loaded %u custom player create items", count );
2212 // Load playercreate spells
2214 // 0 1 2 3
2215 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2217 uint32 count = 0;
2219 if (!result)
2221 barGoLink bar( 1 );
2223 sLog.outString();
2224 sLog.outString( ">> Loaded %u player create spells", count );
2225 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2227 else
2229 barGoLink bar( result->GetRowCount() );
2233 Field* fields = result->Fetch();
2235 uint32 current_race = fields[0].GetUInt32();
2236 if(current_race >= MAX_RACES)
2238 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2239 continue;
2242 uint32 current_class = fields[1].GetUInt32();
2243 if(current_class >= MAX_CLASSES)
2245 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2246 continue;
2249 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2250 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2252 bar.step();
2253 ++count;
2255 while( result->NextRow() );
2257 delete result;
2259 sLog.outString();
2260 sLog.outString( ">> Loaded %u player create spells", count );
2264 // Load playercreate actions
2266 // 0 1 2 3 4 5
2267 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2269 uint32 count = 0;
2271 if (!result)
2273 barGoLink bar( 1 );
2275 sLog.outString();
2276 sLog.outString( ">> Loaded %u player create actions", count );
2277 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2279 else
2281 barGoLink bar( result->GetRowCount() );
2285 Field* fields = result->Fetch();
2287 uint32 current_race = fields[0].GetUInt32();
2288 if(current_race >= MAX_RACES)
2290 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2291 continue;
2294 uint32 current_class = fields[1].GetUInt32();
2295 if(current_class >= MAX_CLASSES)
2297 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2298 continue;
2301 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2302 pInfo->action[0].push_back(fields[2].GetUInt16());
2303 pInfo->action[1].push_back(fields[3].GetUInt16());
2304 pInfo->action[2].push_back(fields[4].GetUInt16());
2305 pInfo->action[3].push_back(fields[5].GetUInt16());
2307 bar.step();
2308 ++count;
2310 while( result->NextRow() );
2312 delete result;
2314 sLog.outString();
2315 sLog.outString( ">> Loaded %u player create actions", count );
2319 // Loading levels data (class only dependent)
2321 // 0 1 2 3
2322 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2324 uint32 count = 0;
2326 if (!result)
2328 barGoLink bar( 1 );
2330 sLog.outString();
2331 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2332 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2333 exit(1);
2336 barGoLink bar( result->GetRowCount() );
2340 Field* fields = result->Fetch();
2342 uint32 current_class = fields[0].GetUInt32();
2343 if(current_class >= MAX_CLASSES)
2345 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2346 continue;
2349 uint32 current_level = fields[1].GetUInt32();
2350 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2352 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2353 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2354 else
2355 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2356 continue;
2359 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2361 if(!pClassInfo->levelInfo)
2362 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2364 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2366 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2367 pClassLevelInfo->basemana = fields[3].GetUInt16();
2369 bar.step();
2370 ++count;
2372 while (result->NextRow());
2374 delete result;
2376 sLog.outString();
2377 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2380 // Fill gaps and check integrity
2381 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2383 // skip non existed classes
2384 if(!sChrClassesStore.LookupEntry(class_))
2385 continue;
2387 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2389 // fatal error if no level 1 data
2390 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2392 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2393 exit(1);
2396 // fill level gaps
2397 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2399 if(pClassInfo->levelInfo[level].basehealth == 0)
2401 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2402 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2407 // Loading levels data (class/race dependent)
2409 // 0 1 2 3 4 5 6 7
2410 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2412 uint32 count = 0;
2414 if (!result)
2416 barGoLink bar( 1 );
2418 sLog.outString();
2419 sLog.outString( ">> Loaded %u level stats definitions", count );
2420 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2421 exit(1);
2424 barGoLink bar( result->GetRowCount() );
2428 Field* fields = result->Fetch();
2430 uint32 current_race = fields[0].GetUInt32();
2431 if(current_race >= MAX_RACES)
2433 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2434 continue;
2437 uint32 current_class = fields[1].GetUInt32();
2438 if(current_class >= MAX_CLASSES)
2440 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2441 continue;
2444 uint32 current_level = fields[2].GetUInt32();
2445 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2447 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2448 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2449 else
2450 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2451 continue;
2454 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2456 if(!pInfo->levelInfo)
2457 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2459 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2461 for (int i = 0; i < MAX_STATS; i++)
2463 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2466 bar.step();
2467 ++count;
2469 while (result->NextRow());
2471 delete result;
2473 sLog.outString();
2474 sLog.outString( ">> Loaded %u level stats definitions", count );
2477 // Fill gaps and check integrity
2478 for (int race = 0; race < MAX_RACES; ++race)
2480 // skip non existed races
2481 if(!sChrRacesStore.LookupEntry(race))
2482 continue;
2484 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2486 // skip non existed classes
2487 if(!sChrClassesStore.LookupEntry(class_))
2488 continue;
2490 PlayerInfo* pInfo = &playerInfo[race][class_];
2492 // skip non loaded combinations
2493 if(!pInfo->displayId_m || !pInfo->displayId_f)
2494 continue;
2496 // skip expansion races if not playing with expansion
2497 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2498 continue;
2500 // skip expansion classes if not playing with expansion
2501 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2502 continue;
2504 // fatal error if no level 1 data
2505 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2507 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2508 exit(1);
2511 // fill level gaps
2512 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2514 if(pInfo->levelInfo[level].stats[0] == 0)
2516 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2517 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2524 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2526 if(level < 1 || class_ >= MAX_CLASSES)
2527 return;
2529 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2531 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2532 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2534 *info = pInfo->levelInfo[level-1];
2537 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2539 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2540 return;
2542 PlayerInfo const* pInfo = &playerInfo[race][class_];
2543 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2544 return;
2546 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2547 *info = pInfo->levelInfo[level-1];
2548 else
2549 BuildPlayerLevelInfo(race,class_,level,info);
2552 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2554 // base data (last known level)
2555 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2557 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2559 switch(_class)
2561 case CLASS_WARRIOR:
2562 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2563 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2564 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2565 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2566 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2567 break;
2568 case CLASS_PALADIN:
2569 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2570 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2571 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2572 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2573 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2574 break;
2575 case CLASS_HUNTER:
2576 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2577 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2578 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2579 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2580 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2581 break;
2582 case CLASS_ROGUE:
2583 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2584 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2585 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2586 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2587 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2588 break;
2589 case CLASS_PRIEST:
2590 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2591 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2592 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2593 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2594 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2595 break;
2596 case CLASS_SHAMAN:
2597 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2598 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2599 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2600 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2601 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2602 break;
2603 case CLASS_MAGE:
2604 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2605 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2606 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2607 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2608 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2609 break;
2610 case CLASS_WARLOCK:
2611 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2612 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2613 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2614 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2615 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2616 break;
2617 case CLASS_DRUID:
2618 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2619 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2620 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2621 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2622 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2627 void ObjectMgr::LoadGuilds()
2629 Guild *newguild;
2630 uint32 count = 0;
2632 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2634 if( !result )
2637 barGoLink bar( 1 );
2639 bar.step();
2641 sLog.outString();
2642 sLog.outString( ">> Loaded %u guild definitions", count );
2643 return;
2646 barGoLink bar( result->GetRowCount() );
2650 Field *fields = result->Fetch();
2652 bar.step();
2653 ++count;
2655 newguild = new Guild;
2656 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2658 newguild->Disband();
2659 delete newguild;
2660 continue;
2662 AddGuild(newguild);
2664 }while( result->NextRow() );
2666 delete result;
2668 sLog.outString();
2669 sLog.outString( ">> Loaded %u guild definitions", count );
2672 void ObjectMgr::LoadArenaTeams()
2674 uint32 count = 0;
2676 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2678 if( !result )
2681 barGoLink bar( 1 );
2683 bar.step();
2685 sLog.outString();
2686 sLog.outString( ">> Loaded %u arenateam definitions", count );
2687 return;
2690 barGoLink bar( result->GetRowCount() );
2694 Field *fields = result->Fetch();
2696 bar.step();
2697 ++count;
2699 ArenaTeam *newarenateam = new ArenaTeam;
2700 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2702 delete newarenateam;
2703 continue;
2705 AddArenaTeam(newarenateam);
2706 }while( result->NextRow() );
2708 delete result;
2710 sLog.outString();
2711 sLog.outString( ">> Loaded %u arenateam definitions", count );
2714 void ObjectMgr::LoadGroups()
2716 // -- loading groups --
2717 Group *group = NULL;
2718 uint64 leaderGuid = 0;
2719 uint32 count = 0;
2720 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2721 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2723 if( !result )
2725 barGoLink bar( 1 );
2727 bar.step();
2729 sLog.outString();
2730 sLog.outString( ">> Loaded %u group definitions", count );
2731 return;
2734 barGoLink bar( result->GetRowCount() );
2738 bar.step();
2739 Field *fields = result->Fetch();
2740 ++count;
2741 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2743 group = new Group;
2744 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2746 group->Disband();
2747 delete group;
2748 continue;
2750 AddGroup(group);
2751 }while( result->NextRow() );
2753 delete result;
2755 sLog.outString();
2756 sLog.outString( ">> Loaded %u group definitions", count );
2758 // -- loading members --
2759 count = 0;
2760 group = NULL;
2761 leaderGuid = 0;
2762 // 0 1 2 3
2763 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2764 if(!result)
2766 barGoLink bar( 1 );
2767 bar.step();
2769 else
2771 barGoLink bar( result->GetRowCount() );
2774 bar.step();
2775 Field *fields = result->Fetch();
2776 count++;
2777 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2778 if(!group || group->GetLeaderGUID() != leaderGuid)
2780 group = GetGroupByLeader(leaderGuid);
2781 if(!group)
2783 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2784 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2785 continue;
2789 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2791 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2792 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2794 }while( result->NextRow() );
2795 delete result;
2798 // clean groups
2799 // TODO: maybe delete from the DB before loading in this case
2800 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2802 if((*itr)->GetMembersCount() < 2)
2804 (*itr)->Disband();
2805 delete *itr;
2806 mGroupSet.erase(itr++);
2808 else
2809 ++itr;
2812 // -- loading instances --
2813 count = 0;
2814 group = NULL;
2815 leaderGuid = 0;
2816 result = CharacterDatabase.Query(
2817 // 0 1 2 3 4 5
2818 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2819 // 6
2820 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2821 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2824 if(!result)
2826 barGoLink bar( 1 );
2827 bar.step();
2829 else
2831 barGoLink bar( result->GetRowCount() );
2834 bar.step();
2835 Field *fields = result->Fetch();
2836 count++;
2837 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2838 if(!group || group->GetLeaderGUID() != leaderGuid)
2840 group = GetGroupByLeader(leaderGuid);
2841 if(!group)
2843 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2844 continue;
2848 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2849 group->BindToInstance(save, fields[3].GetBool(), true);
2850 }while( result->NextRow() );
2851 delete result;
2854 sLog.outString();
2855 sLog.outString( ">> Loaded %u group-instance binds total", count );
2857 sLog.outString();
2858 sLog.outString( ">> Loaded %u group members total", count );
2861 void ObjectMgr::LoadQuests()
2863 // For reload case
2864 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2865 delete itr->second;
2866 mQuestTemplates.clear();
2868 mExclusiveQuestGroups.clear();
2870 // 0 1 2 3 4 5 6 7 8
2871 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2872 // 9 10 11 12 13 14 15 16
2873 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2874 // 17 18 19 20 21 22 23 24 25 26 27 28
2875 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2876 // 29 30 31 32 33 34 35 36 37 38
2877 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2878 // 39 40 41 42 43 44 45 46
2879 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2880 // 47 48 49 50 51 52 53 54 55 56 57 58
2881 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2882 // 59 60 61 62 63 64 65 66
2883 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2884 // 67 68 69 70
2885 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2886 // 71 72 73 74 75 76
2887 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2888 // 77 78 79 80 81 82
2889 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2890 // 83 84 85 86 87 88 89 90
2891 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2892 // 91 92 93 94 95 96 97 98 99 100
2893 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2894 // 101 102 103 104 105 106 107 108 109 110 111
2895 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2896 // 112 113 114 115 116 117 118 119 120 121
2897 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2898 // 122 123
2899 "StartScript, CompleteScript"
2900 " FROM quest_template");
2901 if(result == NULL)
2903 barGoLink bar( 1 );
2904 bar.step();
2906 sLog.outString();
2907 sLog.outString( ">> Loaded 0 quests definitions" );
2908 sLog.outErrorDb("`quest_template` table is empty!");
2909 return;
2912 // create multimap previous quest for each existed quest
2913 // some quests can have many previous maps set by NextQuestId in previous quest
2914 // for example set of race quests can lead to single not race specific quest
2915 barGoLink bar( result->GetRowCount() );
2918 bar.step();
2919 Field *fields = result->Fetch();
2921 Quest * newQuest = new Quest(fields);
2922 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2923 } while( result->NextRow() );
2925 delete result;
2927 // Post processing
2928 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2930 Quest * qinfo = iter->second;
2932 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2934 if( qinfo->GetQuestMethod() >= 3 )
2936 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2939 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2941 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2942 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2943 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2946 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2948 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2950 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2951 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2955 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2957 // at auto-reward can be rewarded only RewChoiceItemId[0]
2958 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2960 if(uint32 id = qinfo->RewChoiceItemId[j])
2962 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2963 qinfo->GetQuestId(),j+1,id,j+1);
2964 // no changes, quest ignore this data
2969 // client quest log visual (area case)
2970 if( qinfo->ZoneOrSort > 0 )
2972 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2974 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2975 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2976 // no changes, quest not dependent from this value but can have problems at client
2979 // client quest log visual (sort case)
2980 if( qinfo->ZoneOrSort < 0 )
2982 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2983 if( !qSort )
2985 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2986 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2987 // 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)
2989 //check SkillOrClass value (class case).
2990 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2992 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2993 if(qinfo->SkillOrClass < 0)
2995 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2996 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2999 //check for proper SkillOrClass value (skill case)
3000 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3002 // skill is positive value in SkillOrClass
3003 if(qinfo->SkillOrClass != skill_id )
3005 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3006 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3007 //override, and force proper value here?
3012 // SkillOrClass (class case)
3013 if( qinfo->SkillOrClass < 0 )
3015 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3017 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3018 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3021 // SkillOrClass (skill case)
3022 if( qinfo->SkillOrClass > 0 )
3024 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3026 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3027 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3031 if( qinfo->RequiredSkillValue )
3033 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3035 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3036 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3037 // no changes, quest can't be done for this requirement
3040 if( qinfo->SkillOrClass <= 0 )
3042 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3043 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3044 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3047 // else Skill quests can have 0 skill level, this is ok
3049 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3051 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3052 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3053 // no changes, quest can't be done for this requirement
3056 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3058 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3059 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3060 // no changes, quest can't be done for this requirement
3063 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3065 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3066 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3067 // no changes, quest can't be done for this requirement
3070 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3072 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3073 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3074 // no changes, quest can't be done for this requirement
3077 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3079 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3080 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3081 // no changes, quest can't be done for this requirement
3084 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3086 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3087 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3088 // warning
3091 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3093 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3094 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3095 // warning
3098 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3100 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3101 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3102 // warning
3105 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3107 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3108 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3109 qinfo->CharTitleId = 0;
3110 // quest can't reward this title
3113 if(qinfo->SrcItemId)
3115 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3117 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3118 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3119 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3121 else if(qinfo->SrcItemCount==0)
3123 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3124 qinfo->GetQuestId(),qinfo->SrcItemId);
3125 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3128 else if(qinfo->SrcItemCount>0)
3130 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3131 qinfo->GetQuestId(),qinfo->SrcItemCount);
3132 qinfo->SrcItemCount=0; // no quest work changes in fact
3135 if(qinfo->SrcSpell)
3137 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3138 if(!spellInfo)
3140 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3141 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3142 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3144 else if(!SpellMgr::IsSpellValid(spellInfo))
3146 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3147 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3148 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3152 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3154 uint32 id = qinfo->ReqItemId[j];
3155 if(id)
3157 if(qinfo->ReqItemCount[j]==0)
3159 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3160 qinfo->GetQuestId(),j+1,id,j+1);
3161 // no changes, quest can't be done for this requirement
3164 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3166 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3168 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3169 qinfo->GetQuestId(),j+1,id,id);
3170 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3173 else if(qinfo->ReqItemCount[j]>0)
3175 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3176 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3177 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3181 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3183 uint32 id = qinfo->ReqSourceId[j];
3184 if(id)
3186 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3188 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3189 qinfo->GetQuestId(),j+1,id,id);
3190 // no changes, quest can't be done for this requirement
3193 if(!qinfo->ReqSourceCount[j])
3195 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3196 qinfo->GetQuestId(),j+1,id,j+1);
3197 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3200 if(!qinfo->ReqSourceRef[j])
3202 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3203 qinfo->GetQuestId(),j+1,id,j+1);
3204 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3207 else
3209 if(qinfo->ReqSourceCount[j]>0)
3211 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3212 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3213 // no changes, quest ignore this data
3216 if(qinfo->ReqSourceRef[j]>0)
3218 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3219 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3220 // no changes, quest ignore this data
3225 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3227 uint32 ref = qinfo->ReqSourceRef[j];
3228 if(ref)
3230 if(ref > QUEST_OBJECTIVES_COUNT)
3232 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3233 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3234 // no changes, quest can't be done for this requirement
3236 else
3237 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3239 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3240 qinfo->GetQuestId(),j+1,ref,ref,ref);
3241 // no changes, quest can't be done for this requirement
3243 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3245 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3246 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3247 // no changes, quest can't be done for this requirement
3248 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3253 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3255 uint32 id = qinfo->ReqSpell[j];
3256 if(id)
3258 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3259 if(!spellInfo)
3261 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3262 qinfo->GetQuestId(),j+1,id,id);
3263 // no changes, quest can't be done for this requirement
3266 if(!qinfo->ReqCreatureOrGOId[j])
3268 bool found = false;
3269 for(int k = 0; k < 3; ++k)
3271 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3272 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3274 found = true;
3275 break;
3279 if(found)
3281 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3283 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);
3285 // this will prevent quest completing without objective
3286 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3289 else
3291 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.",
3292 qinfo->GetQuestId(),j+1,id,j+1,id);
3293 // no changes, quest can't be done for this requirement
3299 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3301 int32 id = qinfo->ReqCreatureOrGOId[j];
3302 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3304 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3305 qinfo->GetQuestId(),j+1,id,uint32(-id));
3306 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3309 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3311 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3312 qinfo->GetQuestId(),j+1,id,uint32(id));
3313 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3316 if(id)
3318 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3320 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3322 if(!qinfo->ReqCreatureOrGOCount[j])
3324 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3325 qinfo->GetQuestId(),j+1,id,j+1);
3326 // no changes, quest can be incorrectly done, but we already report this
3329 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3331 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3332 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3333 // no changes, quest ignore this data
3337 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3339 uint32 id = qinfo->RewChoiceItemId[j];
3340 if(id)
3342 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3344 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3345 qinfo->GetQuestId(),j+1,id,id);
3346 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3349 if(!qinfo->RewChoiceItemCount[j])
3351 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3352 qinfo->GetQuestId(),j+1,id,j+1);
3353 // no changes, quest can't be done
3356 else if(qinfo->RewChoiceItemCount[j]>0)
3358 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3359 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3360 // no changes, quest ignore this data
3364 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3366 uint32 id = qinfo->RewItemId[j];
3367 if(id)
3369 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3371 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3372 qinfo->GetQuestId(),j+1,id,id);
3373 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3376 if(!qinfo->RewItemCount[j])
3378 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3379 qinfo->GetQuestId(),j+1,id,j+1);
3380 // no changes
3383 else if(qinfo->RewItemCount[j]>0)
3385 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3386 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3387 // no changes, quest ignore this data
3391 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3393 if(qinfo->RewRepFaction[j])
3395 if(!qinfo->RewRepValue[j])
3397 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3398 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3399 // no changes
3402 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3404 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.",
3405 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3406 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3409 else if(qinfo->RewRepValue[j]!=0)
3411 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3412 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3413 // no changes, quest ignore this data
3417 if(qinfo->RewSpell)
3419 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3421 if(!spellInfo)
3423 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3424 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3425 qinfo->RewSpell = 0; // no spell reward will display for this quest
3428 else if(!SpellMgr::IsSpellValid(spellInfo))
3430 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3431 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3432 qinfo->RewSpell = 0; // no spell reward will display for this quest
3437 if(qinfo->RewSpellCast)
3439 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3441 if(!spellInfo)
3443 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3444 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3445 qinfo->RewSpellCast = 0; // no spell will be casted on player
3448 else if(!SpellMgr::IsSpellValid(spellInfo))
3450 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3451 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3452 qinfo->RewSpellCast = 0; // no spell will be casted on player
3457 if(qinfo->RewMailTemplateId)
3459 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3461 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3462 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3463 qinfo->RewMailTemplateId = 0; // no mail will send to player
3464 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3468 if(qinfo->NextQuestInChain)
3470 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3472 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3473 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3474 qinfo->NextQuestInChain = 0;
3476 else
3477 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3480 // fill additional data stores
3481 if(qinfo->PrevQuestId)
3483 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3485 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3487 else
3489 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3493 if(qinfo->NextQuestId)
3495 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3497 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3499 else
3501 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3502 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3506 if(qinfo->ExclusiveGroup)
3507 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3508 if(qinfo->LimitTime)
3509 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3512 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3513 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3515 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3516 if(!spellInfo)
3517 continue;
3519 for(int j = 0; j < 3; ++j)
3521 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3522 continue;
3524 uint32 quest_id = spellInfo->EffectMiscValue[j];
3526 Quest const* quest = GetQuestTemplate(quest_id);
3528 // some quest referenced in spells not exist (outdated spells)
3529 if(!quest)
3530 continue;
3532 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3534 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);
3536 // this will prevent quest completing without objective
3537 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3542 sLog.outString();
3543 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3546 void ObjectMgr::LoadQuestLocales()
3548 mQuestLocaleMap.clear(); // need for reload case
3550 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3551 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3552 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3553 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3554 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3555 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3556 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3557 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3558 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3559 " FROM locales_quest"
3562 if(!result)
3564 barGoLink bar(1);
3566 bar.step();
3568 sLog.outString("");
3569 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3570 return;
3573 barGoLink bar(result->GetRowCount());
3577 Field *fields = result->Fetch();
3578 bar.step();
3580 uint32 entry = fields[0].GetUInt32();
3582 QuestLocale& data = mQuestLocaleMap[entry];
3584 for(int i = 1; i < MAX_LOCALE; ++i)
3586 std::string str = fields[1+10*(i-1)].GetCppString();
3587 if(!str.empty())
3589 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3590 if(idx >= 0)
3592 if(data.Title.size() <= idx)
3593 data.Title.resize(idx+1);
3595 data.Title[idx] = str;
3598 str = fields[1+10*(i-1)+1].GetCppString();
3599 if(!str.empty())
3601 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3602 if(idx >= 0)
3604 if(data.Details.size() <= idx)
3605 data.Details.resize(idx+1);
3607 data.Details[idx] = str;
3610 str = fields[1+10*(i-1)+2].GetCppString();
3611 if(!str.empty())
3613 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3614 if(idx >= 0)
3616 if(data.Objectives.size() <= idx)
3617 data.Objectives.resize(idx+1);
3619 data.Objectives[idx] = str;
3622 str = fields[1+10*(i-1)+3].GetCppString();
3623 if(!str.empty())
3625 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3626 if(idx >= 0)
3628 if(data.OfferRewardText.size() <= idx)
3629 data.OfferRewardText.resize(idx+1);
3631 data.OfferRewardText[idx] = str;
3634 str = fields[1+10*(i-1)+4].GetCppString();
3635 if(!str.empty())
3637 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3638 if(idx >= 0)
3640 if(data.RequestItemsText.size() <= idx)
3641 data.RequestItemsText.resize(idx+1);
3643 data.RequestItemsText[idx] = str;
3646 str = fields[1+10*(i-1)+5].GetCppString();
3647 if(!str.empty())
3649 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3650 if(idx >= 0)
3652 if(data.EndText.size() <= idx)
3653 data.EndText.resize(idx+1);
3655 data.EndText[idx] = str;
3658 for(int k = 0; k < 4; ++k)
3660 str = fields[1+10*(i-1)+6+k].GetCppString();
3661 if(!str.empty())
3663 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3664 if(idx >= 0)
3666 if(data.ObjectiveText[k].size() <= idx)
3667 data.ObjectiveText[k].resize(idx+1);
3669 data.ObjectiveText[k][idx] = str;
3674 } while (result->NextRow());
3676 delete result;
3678 sLog.outString();
3679 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3682 void ObjectMgr::LoadPetCreateSpells()
3684 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3685 if(!result)
3687 barGoLink bar( 1 );
3688 bar.step();
3690 sLog.outString();
3691 sLog.outString( ">> Loaded 0 pet create spells" );
3692 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3693 return;
3696 uint32 count = 0;
3698 barGoLink bar( result->GetRowCount() );
3700 mPetCreateSpell.clear();
3704 Field *fields = result->Fetch();
3705 bar.step();
3707 uint32 creature_id = fields[0].GetUInt32();
3709 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3710 continue;
3712 PetCreateSpellEntry PetCreateSpell;
3713 for(int i = 0; i < 4; i++)
3715 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3717 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3718 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3721 mPetCreateSpell[creature_id] = PetCreateSpell;
3723 ++count;
3725 while (result->NextRow());
3727 delete result;
3729 sLog.outString();
3730 sLog.outString( ">> Loaded %u pet create spells", count );
3733 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3735 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3736 return;
3738 sLog.outString( "%s :", tablename);
3740 scripts.clear(); // need for reload support
3742 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3744 uint32 count = 0;
3746 if( !result )
3748 barGoLink bar( 1 );
3749 bar.step();
3751 sLog.outString();
3752 sLog.outString( ">> Loaded %u script definitions", count );
3753 return;
3756 barGoLink bar( result->GetRowCount() );
3760 bar.step();
3762 Field *fields = result->Fetch();
3763 ScriptInfo tmp;
3764 tmp.id = fields[0].GetUInt32();
3765 tmp.delay = fields[1].GetUInt32();
3766 tmp.command = fields[2].GetUInt32();
3767 tmp.datalong = fields[3].GetUInt32();
3768 tmp.datalong2 = fields[4].GetUInt32();
3769 tmp.dataint = fields[5].GetInt32();
3770 tmp.x = fields[6].GetFloat();
3771 tmp.y = fields[7].GetFloat();
3772 tmp.z = fields[8].GetFloat();
3773 tmp.o = fields[9].GetFloat();
3775 // generic command args check
3776 switch(tmp.command)
3778 case SCRIPT_COMMAND_TALK:
3780 if(tmp.datalong > 3)
3782 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3783 continue;
3785 if(tmp.dataint==0)
3787 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3788 continue;
3790 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3792 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);
3793 continue;
3796 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3797 break;
3800 case SCRIPT_COMMAND_TELEPORT_TO:
3802 if(!sMapStore.LookupEntry(tmp.datalong))
3804 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3805 continue;
3808 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3810 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);
3811 continue;
3813 break;
3816 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3818 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3820 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);
3821 continue;
3824 if(!GetCreatureTemplate(tmp.datalong))
3826 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3827 continue;
3829 break;
3832 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3834 GameObjectData const* data = GetGOData(tmp.datalong);
3835 if(!data)
3837 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3838 continue;
3841 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3842 if(!info)
3844 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);
3845 continue;
3848 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3849 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3850 info->type==GAMEOBJECT_TYPE_DOOR ||
3851 info->type==GAMEOBJECT_TYPE_BUTTON ||
3852 info->type==GAMEOBJECT_TYPE_TRAP )
3854 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3855 continue;
3857 break;
3859 case SCRIPT_COMMAND_OPEN_DOOR:
3860 case SCRIPT_COMMAND_CLOSE_DOOR:
3862 GameObjectData const* data = GetGOData(tmp.datalong);
3863 if(!data)
3865 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);
3866 continue;
3869 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3870 if(!info)
3872 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);
3873 continue;
3876 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3878 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);
3879 continue;
3882 break;
3884 case SCRIPT_COMMAND_QUEST_EXPLORED:
3886 Quest const* quest = GetQuestTemplate(tmp.datalong);
3887 if(!quest)
3889 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);
3890 continue;
3893 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3895 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);
3897 // this will prevent quest completing without objective
3898 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3900 // continue; - quest objective requirement set and command can be allowed
3903 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3905 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",
3906 tablename,tmp.datalong2,tmp.id);
3907 continue;
3910 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3912 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",
3913 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3914 continue;
3917 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3919 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",
3920 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3921 continue;
3924 break;
3927 case SCRIPT_COMMAND_REMOVE_AURA:
3928 case SCRIPT_COMMAND_CAST_SPELL:
3930 if(!sSpellStore.LookupEntry(tmp.datalong))
3932 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3933 tablename,tmp.datalong,tmp.id);
3934 continue;
3936 break;
3940 if (scripts.find(tmp.id) == scripts.end())
3942 ScriptMap emptyMap;
3943 scripts[tmp.id] = emptyMap;
3945 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3947 ++count;
3948 } while( result->NextRow() );
3950 delete result;
3952 sLog.outString();
3953 sLog.outString( ">> Loaded %u script definitions", count );
3956 void ObjectMgr::LoadGameObjectScripts()
3958 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3960 // check ids
3961 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3963 if(!GetGOData(itr->first))
3964 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3968 void ObjectMgr::LoadQuestEndScripts()
3970 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3972 // check ids
3973 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3975 if(!GetQuestTemplate(itr->first))
3976 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3980 void ObjectMgr::LoadQuestStartScripts()
3982 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3984 // check ids
3985 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3987 if(!GetQuestTemplate(itr->first))
3988 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3992 void ObjectMgr::LoadSpellScripts()
3994 LoadScripts(sSpellScripts, "spell_scripts");
3996 // check ids
3997 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3999 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4001 if(!spellInfo)
4003 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4004 continue;
4007 //check for correct spellEffect
4008 bool found = false;
4009 for(int i=0; i<3; ++i)
4011 // skip empty effects
4012 if( !spellInfo->Effect[i] )
4013 continue;
4015 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4017 found = true;
4018 break;
4022 if(!found)
4023 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4027 void ObjectMgr::LoadEventScripts()
4029 LoadScripts(sEventScripts, "event_scripts");
4031 std::set<uint32> evt_scripts;
4032 // Load all possible script entries from gameobjects
4033 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4035 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4036 if (goInfo)
4038 switch(goInfo->type)
4040 case GAMEOBJECT_TYPE_GOOBER:
4041 if(goInfo->goober.eventId)
4042 evt_scripts.insert(goInfo->goober.eventId);
4043 break;
4044 case GAMEOBJECT_TYPE_CHEST:
4045 if(goInfo->chest.eventId)
4046 evt_scripts.insert(goInfo->chest.eventId);
4047 break;
4048 default:
4049 break;
4053 // Load all possible script entries from spells
4054 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4056 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4057 if (spell)
4059 for(int j=0; j<3; ++j)
4061 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4063 if (spell->EffectMiscValue[j])
4064 evt_scripts.insert(spell->EffectMiscValue[j]);
4069 // Then check if all scripts are in above list of possible script entries
4070 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4072 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4073 if (itr2 == evt_scripts.end())
4074 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);
4078 void ObjectMgr::LoadItemTexts()
4080 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4082 uint32 count = 0;
4084 if( !result )
4086 barGoLink bar( 1 );
4087 bar.step();
4089 sLog.outString();
4090 sLog.outString( ">> Loaded %u item pages", count );
4091 return;
4094 barGoLink bar( result->GetRowCount() );
4096 Field* fields;
4099 bar.step();
4101 fields = result->Fetch();
4103 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4105 ++count;
4107 } while ( result->NextRow() );
4109 delete result;
4111 sLog.outString();
4112 sLog.outString( ">> Loaded %u item texts", count );
4115 void ObjectMgr::LoadPageTexts()
4117 sPageTextStore.Free(); // for reload case
4119 sPageTextStore.Load();
4120 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4121 sLog.outString();
4123 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4125 // check data correctness
4126 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4127 if(!page)
4128 continue;
4130 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4132 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4133 continue;
4136 // detect circular reference
4137 std::set<uint32> checkedPages;
4138 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4140 if(!pageItr->Next_Page)
4141 break;
4142 checkedPages.insert(pageItr->Page_ID);
4143 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4145 std::ostringstream ss;
4146 ss<< "The text page(s) ";
4147 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4148 ss << *itr << " ";
4149 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4150 << pageItr->Page_ID <<" to 0";
4151 sLog.outErrorDb(ss.str().c_str());
4152 const_cast<PageText*>(pageItr)->Next_Page = 0;
4153 break;
4159 void ObjectMgr::LoadPageTextLocales()
4161 mPageTextLocaleMap.clear(); // need for reload case
4163 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");
4165 if(!result)
4167 barGoLink bar(1);
4169 bar.step();
4171 sLog.outString("");
4172 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4173 return;
4176 barGoLink bar(result->GetRowCount());
4180 Field *fields = result->Fetch();
4181 bar.step();
4183 uint32 entry = fields[0].GetUInt32();
4185 PageTextLocale& data = mPageTextLocaleMap[entry];
4187 for(int i = 1; i < MAX_LOCALE; ++i)
4189 std::string str = fields[i].GetCppString();
4190 if(str.empty())
4191 continue;
4193 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4194 if(idx >= 0)
4196 if(data.Text.size() <= idx)
4197 data.Text.resize(idx+1);
4199 data.Text[idx] = str;
4203 } while (result->NextRow());
4205 delete result;
4207 sLog.outString();
4208 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4211 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4213 template<class D>
4214 void convert_from_str(uint32 field_pos, char *src, D &dst)
4216 dst = D(objmgr.GetScriptId(src));
4220 void ObjectMgr::LoadInstanceTemplate()
4222 SQLInstanceLoader loader;
4223 loader.Load(sInstanceTemplate);
4225 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4227 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4228 if(!temp) continue;
4229 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4230 if(!entry)
4232 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4233 continue;
4235 else if(!entry->HasResetTime())
4236 continue;
4238 if(temp->reset_delay == 0)
4240 // use defaults from the DBC
4241 if(entry->SupportsHeroicMode())
4243 temp->reset_delay = entry->resetTimeHeroic / DAY;
4245 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4247 temp->reset_delay = entry->resetTimeRaid / DAY;
4251 // the reset_delay must be at least one day
4252 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4255 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4256 sLog.outString();
4259 void ObjectMgr::AddGossipText(GossipText *pGText)
4261 ASSERT( pGText->Text_ID );
4262 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4263 mGossipText[pGText->Text_ID] = pGText;
4266 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4268 GossipTextMap::const_iterator itr;
4269 for (itr = mGossipText.begin(); itr != mGossipText.end(); ++itr)
4271 if(itr->second->Text_ID == Text_ID)
4272 return itr->second;
4274 return NULL;
4277 void ObjectMgr::LoadGossipText()
4279 GossipText *pGText;
4280 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4282 int count = 0;
4283 if( !result )
4285 barGoLink bar( 1 );
4286 bar.step();
4288 sLog.outString();
4289 sLog.outString( ">> Loaded %u npc texts", count );
4290 return;
4293 int cic;
4295 barGoLink bar( result->GetRowCount() );
4299 ++count;
4300 cic = 0;
4302 Field *fields = result->Fetch();
4304 bar.step();
4306 pGText = new GossipText;
4307 pGText->Text_ID = fields[cic++].GetUInt32();
4309 for (int i=0; i< 8; i++)
4311 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4312 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4314 pGText->Options[i].Language = fields[cic++].GetUInt32();
4315 pGText->Options[i].Probability = fields[cic++].GetFloat();
4317 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4318 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4320 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4321 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4323 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4324 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4327 if ( !pGText->Text_ID ) continue;
4328 AddGossipText( pGText );
4330 } while( result->NextRow() );
4332 sLog.outString();
4333 sLog.outString( ">> Loaded %u npc texts", count );
4334 delete result;
4337 void ObjectMgr::LoadNpcTextLocales()
4339 mNpcTextLocaleMap.clear(); // need for reload case
4341 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4342 "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,"
4343 "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,"
4344 "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,"
4345 "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,"
4346 "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,"
4347 "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,"
4348 "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, "
4349 "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 "
4350 " FROM locales_npc_text");
4352 if(!result)
4354 barGoLink bar(1);
4356 bar.step();
4358 sLog.outString("");
4359 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4360 return;
4363 barGoLink bar(result->GetRowCount());
4367 Field *fields = result->Fetch();
4368 bar.step();
4370 uint32 entry = fields[0].GetUInt32();
4372 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4374 for(int i=1; i<MAX_LOCALE; ++i)
4376 for(int j=0; j<8; ++j)
4378 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4379 if(!str0.empty())
4381 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4382 if(idx >= 0)
4384 if(data.Text_0[j].size() <= idx)
4385 data.Text_0[j].resize(idx+1);
4387 data.Text_0[j][idx] = str0;
4390 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4391 if(!str1.empty())
4393 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4394 if(idx >= 0)
4396 if(data.Text_1[j].size() <= idx)
4397 data.Text_1[j].resize(idx+1);
4399 data.Text_1[j][idx] = str1;
4404 } while (result->NextRow());
4406 delete result;
4408 sLog.outString();
4409 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4412 //not very fast function but it is called only once a day, or on starting-up
4413 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4415 time_t basetime = time(NULL);
4416 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4417 //delete all old mails without item and without body immediately, if starting server
4418 if (!serverUp)
4419 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4420 // 0 1 2 3 4 5 6 7 8 9
4421 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);
4422 if ( !result )
4423 return; // any mails need to be returned or deleted
4424 Field *fields;
4425 //std::ostringstream delitems, delmails; //will be here for optimization
4426 //bool deletemail = false, deleteitem = false;
4427 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4428 //delmails << "DELETE FROM mail WHERE id IN ( "
4431 fields = result->Fetch();
4432 Mail *m = new Mail;
4433 m->messageID = fields[0].GetUInt32();
4434 m->messageType = fields[1].GetUInt8();
4435 m->sender = fields[2].GetUInt32();
4436 m->receiver = fields[3].GetUInt32();
4437 m->itemTextId = fields[4].GetUInt32();
4438 bool has_items = fields[5].GetBool();
4439 m->expire_time = (time_t)fields[6].GetUInt64();
4440 m->deliver_time = 0;
4441 m->COD = fields[7].GetUInt32();
4442 m->checked = fields[8].GetUInt32();
4443 m->mailTemplateId = fields[9].GetInt16();
4445 Player *pl = 0;
4446 if (serverUp)
4447 pl = GetPlayer((uint64)m->receiver);
4448 if (pl && pl->m_mailsLoaded)
4449 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4450 //his in mailbox and he has already listed his mails )
4451 delete m;
4452 continue;
4454 //delete or return mail:
4455 if (has_items)
4457 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4458 if(resultItems)
4462 Field *fields2 = resultItems->Fetch();
4464 uint32 item_guid_low = fields2[0].GetUInt32();
4465 uint32 item_template = fields2[1].GetUInt32();
4467 m->AddItem(item_guid_low, item_template);
4469 while (resultItems->NextRow());
4471 delete resultItems;
4473 //if it is mail from AH, it shouldn't be returned, but deleted
4474 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4476 // mail open and then not returned
4477 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4478 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4480 else
4482 //mail will be returned:
4483 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);
4484 delete m;
4485 continue;
4489 if (m->itemTextId)
4490 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4492 //deletemail = true;
4493 //delmails << m->messageID << ", ";
4494 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4495 delete m;
4496 } while (result->NextRow());
4497 delete result;
4500 void ObjectMgr::LoadQuestAreaTriggers()
4502 mQuestAreaTriggerMap.clear(); // need for reload case
4504 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4506 uint32 count = 0;
4508 if( !result )
4510 barGoLink bar( 1 );
4511 bar.step();
4513 sLog.outString();
4514 sLog.outString( ">> Loaded %u quest trigger points", count );
4515 return;
4518 barGoLink bar( result->GetRowCount() );
4522 ++count;
4523 bar.step();
4525 Field *fields = result->Fetch();
4527 uint32 trigger_ID = fields[0].GetUInt32();
4528 uint32 quest_ID = fields[1].GetUInt32();
4530 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4531 if(!atEntry)
4533 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4534 continue;
4537 Quest const* quest = GetQuestTemplate(quest_ID);
4539 if(!quest)
4541 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4542 continue;
4545 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4547 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);
4549 // this will prevent quest completing without objective
4550 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4552 // continue; - quest modified to required objective and trigger can be allowed.
4555 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4557 } while( result->NextRow() );
4559 delete result;
4561 sLog.outString();
4562 sLog.outString( ">> Loaded %u quest trigger points", count );
4565 void ObjectMgr::LoadTavernAreaTriggers()
4567 mTavernAreaTriggerSet.clear(); // need for reload case
4569 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4571 uint32 count = 0;
4573 if( !result )
4575 barGoLink bar( 1 );
4576 bar.step();
4578 sLog.outString();
4579 sLog.outString( ">> Loaded %u tavern triggers", count );
4580 return;
4583 barGoLink bar( result->GetRowCount() );
4587 ++count;
4588 bar.step();
4590 Field *fields = result->Fetch();
4592 uint32 Trigger_ID = fields[0].GetUInt32();
4594 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4595 if(!atEntry)
4597 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4598 continue;
4601 mTavernAreaTriggerSet.insert(Trigger_ID);
4602 } while( result->NextRow() );
4604 delete result;
4606 sLog.outString();
4607 sLog.outString( ">> Loaded %u tavern triggers", count );
4610 void ObjectMgr::LoadAreaTriggerScripts()
4612 mAreaTriggerScripts.clear(); // need for reload case
4613 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4615 uint32 count = 0;
4617 if( !result )
4619 barGoLink bar( 1 );
4620 bar.step();
4622 sLog.outString();
4623 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4624 return;
4627 barGoLink bar( result->GetRowCount() );
4631 ++count;
4632 bar.step();
4634 Field *fields = result->Fetch();
4636 uint32 Trigger_ID = fields[0].GetUInt32();
4637 const char *scriptName = fields[1].GetString();
4639 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4640 if(!atEntry)
4642 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4643 continue;
4645 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4646 } while( result->NextRow() );
4648 delete result;
4650 sLog.outString();
4651 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4654 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4656 bool found = false;
4657 float dist;
4658 uint32 id = 0;
4660 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4662 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4663 if(node && node->map_id == mapid)
4665 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4666 if(found)
4668 if(dist2 < dist)
4670 dist = dist2;
4671 id = i;
4674 else
4676 found = true;
4677 dist = dist2;
4678 id = i;
4683 return id;
4686 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4688 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4689 if(src_i==sTaxiPathSetBySource.end())
4691 path = 0;
4692 cost = 0;
4693 return;
4696 TaxiPathSetForSource& pathSet = src_i->second;
4698 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4699 if(dest_i==pathSet.end())
4701 path = 0;
4702 cost = 0;
4703 return;
4706 cost = dest_i->second.price;
4707 path = dest_i->second.ID;
4710 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4712 uint16 mount_entry = 0;
4713 uint16 mount_id = 0;
4715 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4716 if(node)
4718 if (team == ALLIANCE)
4720 mount_entry = node->MountCreatureID[1];
4721 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4722 if(ci)
4723 mount_id = ci->DisplayID_A;
4725 if (team == HORDE)
4727 mount_entry = node->MountCreatureID[0];
4728 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4729 if(ci)
4730 mount_id = ci->DisplayID_H;
4734 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4735 if(!minfo)
4737 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. ",
4738 mount_entry,id,team,mount_id);
4740 return false;
4742 if(minfo->modelid_other_gender!=0)
4743 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4745 return mount_id;
4748 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4750 if(path >= sTaxiPathNodesByPath.size())
4751 return;
4753 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4755 pathnodes.Resize(nodeList.size());
4756 mapIds.resize(nodeList.size());
4758 for(size_t i = 0; i < nodeList.size(); ++i)
4760 pathnodes[ i ].x = nodeList[i].x;
4761 pathnodes[ i ].y = nodeList[i].y;
4762 pathnodes[ i ].z = nodeList[i].z;
4764 mapIds[i] = nodeList[i].mapid;
4768 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4770 if(path >= sTaxiPathNodesByPath.size())
4771 return;
4773 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4775 pathnodes.Resize(nodeList.size());
4777 for(size_t i = 0; i < nodeList.size(); ++i)
4779 pathnodes[ i ].mapid = nodeList[i].mapid;
4780 pathnodes[ i ].x = nodeList[i].x;
4781 pathnodes[ i ].y = nodeList[i].y;
4782 pathnodes[ i ].z = nodeList[i].z;
4783 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4784 pathnodes[ i ].delay = nodeList[i].delay;
4788 void ObjectMgr::LoadGraveyardZones()
4790 mGraveYardMap.clear(); // need for reload case
4792 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4794 uint32 count = 0;
4796 if( !result )
4798 barGoLink bar( 1 );
4799 bar.step();
4801 sLog.outString();
4802 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4803 return;
4806 barGoLink bar( result->GetRowCount() );
4810 ++count;
4811 bar.step();
4813 Field *fields = result->Fetch();
4815 uint32 safeLocId = fields[0].GetUInt32();
4816 uint32 zoneId = fields[1].GetUInt32();
4817 uint32 team = fields[2].GetUInt32();
4819 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4820 if(!entry)
4822 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4823 continue;
4826 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4827 if(!areaEntry)
4829 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4830 continue;
4833 if(areaEntry->zone != 0)
4835 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4836 continue;
4839 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4841 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4842 continue;
4845 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4846 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4847 } while( result->NextRow() );
4849 delete result;
4851 sLog.outString();
4852 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4855 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4857 // search for zone associated closest graveyard
4858 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4860 // Simulate std. algorithm:
4861 // found some graveyard associated to (ghost_zone,ghost_map)
4863 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4864 // then check faction
4865 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4866 // then check faction
4867 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4868 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4869 if(graveLow==graveUp)
4871 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4872 return NULL;
4875 // at corpse map
4876 bool foundNear = false;
4877 float distNear;
4878 WorldSafeLocsEntry const* entryNear = NULL;
4880 // at entrance map for corpse map
4881 bool foundEntr = false;
4882 float distEntr;
4883 WorldSafeLocsEntry const* entryEntr = NULL;
4885 // some where other
4886 WorldSafeLocsEntry const* entryFar = NULL;
4888 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4890 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4892 GraveYardData const& data = itr->second;
4894 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4895 if(!entry)
4897 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4898 continue;
4901 // skip enemy faction graveyard
4902 // team == 0 case can be at call from .neargrave
4903 if(data.team != 0 && team != 0 && data.team != team)
4904 continue;
4906 // find now nearest graveyard at other map
4907 if(MapId != entry->map_id)
4909 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4910 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4911 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4913 // not have any corrdinates for check distance anyway
4914 entryFar = entry;
4915 continue;
4918 // at entrance map calculate distance (2D);
4919 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4920 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4921 if(foundEntr)
4923 if(dist2 < distEntr)
4925 distEntr = dist2;
4926 entryEntr = entry;
4929 else
4931 foundEntr = true;
4932 distEntr = dist2;
4933 entryEntr = entry;
4936 // find now nearest graveyard at same map
4937 else
4939 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4940 if(foundNear)
4942 if(dist2 < distNear)
4944 distNear = dist2;
4945 entryNear = entry;
4948 else
4950 foundNear = true;
4951 distNear = dist2;
4952 entryNear = entry;
4957 if(entryNear)
4958 return entryNear;
4960 if(entryEntr)
4961 return entryEntr;
4963 return entryFar;
4966 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4968 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4969 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4971 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4973 if(itr->second.safeLocId==id)
4974 return &itr->second;
4977 return NULL;
4980 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4982 if(FindGraveYardData(id,zoneId))
4983 return false;
4985 // add link to loaded data
4986 GraveYardData data;
4987 data.safeLocId = id;
4988 data.team = team;
4990 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4992 // add link to DB
4993 if(inDB)
4995 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4996 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4999 return true;
5002 void ObjectMgr::LoadAreaTriggerTeleports()
5004 mAreaTriggers.clear(); // need for reload case
5006 uint32 count = 0;
5008 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5009 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");
5010 if( !result )
5013 barGoLink bar( 1 );
5015 bar.step();
5017 sLog.outString();
5018 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5019 return;
5022 barGoLink bar( result->GetRowCount() );
5026 Field *fields = result->Fetch();
5028 bar.step();
5030 ++count;
5032 uint32 Trigger_ID = fields[0].GetUInt32();
5034 AreaTrigger at;
5036 at.requiredLevel = fields[1].GetUInt8();
5037 at.requiredItem = fields[2].GetUInt32();
5038 at.requiredItem2 = fields[3].GetUInt32();
5039 at.heroicKey = fields[4].GetUInt32();
5040 at.heroicKey2 = fields[5].GetUInt32();
5041 at.requiredQuest = fields[6].GetUInt32();
5042 at.requiredFailedText = fields[7].GetCppString();
5043 at.target_mapId = fields[8].GetUInt32();
5044 at.target_X = fields[9].GetFloat();
5045 at.target_Y = fields[10].GetFloat();
5046 at.target_Z = fields[11].GetFloat();
5047 at.target_Orientation = fields[12].GetFloat();
5049 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5050 if(!atEntry)
5052 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5053 continue;
5056 if(at.requiredItem)
5058 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5059 if(!pProto)
5061 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5062 at.requiredItem = 0;
5065 if(at.requiredItem2)
5067 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5068 if(!pProto)
5070 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5071 at.requiredItem2 = 0;
5075 if(at.heroicKey)
5077 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5078 if(!pProto)
5080 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5081 at.heroicKey = 0;
5085 if(at.heroicKey2)
5087 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5088 if(!pProto)
5090 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5091 at.heroicKey2 = 0;
5095 if(at.requiredQuest)
5097 if(!mQuestTemplates[at.requiredQuest])
5099 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5100 at.requiredQuest = 0;
5104 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5105 if(!mapEntry)
5107 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5108 continue;
5111 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5113 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5114 continue;
5117 mAreaTriggers[Trigger_ID] = at;
5119 } while( result->NextRow() );
5121 delete result;
5123 sLog.outString();
5124 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5127 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5129 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5130 if(!mapEntry) return NULL;
5131 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5133 if(itr->second.target_mapId == mapEntry->entrance_map)
5135 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5136 if(atEntry && atEntry->mapid == Map)
5137 return &itr->second;
5140 return NULL;
5143 void ObjectMgr::SetHighestGuids()
5145 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5146 if( result )
5148 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5149 delete result;
5152 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5153 if( result )
5155 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5156 delete result;
5159 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5160 m_hiPetGuid = 0;
5161 // same for vehicles
5162 m_hiVehicleGuid = 0;
5164 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5165 if( result )
5167 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5168 delete result;
5171 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5172 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5173 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5174 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5175 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5177 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5178 if( result )
5180 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5181 delete result;
5184 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5185 if( result )
5187 m_auctionid = (*result)[0].GetUInt32()+1;
5188 delete result;
5191 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5192 if( result )
5194 m_mailid = (*result)[0].GetUInt32()+1;
5195 delete result;
5198 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5199 if( result )
5201 m_ItemTextId = (*result)[0].GetUInt32()+1;
5202 delete result;
5205 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5206 if( result )
5208 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5209 delete result;
5212 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5213 if (result)
5215 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5216 delete result;
5219 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5220 if (result)
5222 m_guildId = (*result)[0].GetUInt32()+1;
5223 delete result;
5227 uint32 ObjectMgr::GenerateArenaTeamId()
5229 if(m_arenaTeamId>=0xFFFFFFFE)
5231 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5232 World::StopNow(ERROR_EXIT_CODE);
5234 return m_arenaTeamId++;
5237 uint32 ObjectMgr::GenerateGuildId()
5239 if(m_guildId>=0xFFFFFFFE)
5241 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5242 World::StopNow(ERROR_EXIT_CODE);
5244 return m_guildId++;
5247 uint32 ObjectMgr::GenerateAuctionID()
5249 if(m_auctionid>=0xFFFFFFFE)
5251 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5252 World::StopNow(ERROR_EXIT_CODE);
5254 return m_auctionid++;
5257 uint32 ObjectMgr::GenerateMailID()
5259 if(m_mailid>=0xFFFFFFFE)
5261 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5262 World::StopNow(ERROR_EXIT_CODE);
5264 return m_mailid++;
5267 uint32 ObjectMgr::GenerateItemTextID()
5269 if(m_ItemTextId>=0xFFFFFFFE)
5271 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5272 World::StopNow(ERROR_EXIT_CODE);
5274 return m_ItemTextId++;
5277 uint32 ObjectMgr::CreateItemText(std::string text)
5279 uint32 newItemTextId = GenerateItemTextID();
5280 //insert new itempage to container
5281 mItemTexts[ newItemTextId ] = text;
5282 //save new itempage
5283 CharacterDatabase.escape_string(text);
5284 //any Delete query needed, itemTextId is maximum of all ids
5285 std::ostringstream query;
5286 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5287 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5288 return newItemTextId;
5291 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5293 switch(guidhigh)
5295 case HIGHGUID_ITEM:
5296 if(m_hiItemGuid>=0xFFFFFFFE)
5298 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5299 World::StopNow(ERROR_EXIT_CODE);
5301 return m_hiItemGuid++;
5302 case HIGHGUID_UNIT:
5303 if(m_hiCreatureGuid>=0x00FFFFFE)
5305 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5306 World::StopNow(ERROR_EXIT_CODE);
5308 return m_hiCreatureGuid++;
5309 case HIGHGUID_PET:
5310 if(m_hiPetGuid>=0x00FFFFFE)
5312 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5313 World::StopNow(ERROR_EXIT_CODE);
5315 return m_hiPetGuid++;
5316 case HIGHGUID_VEHICLE:
5317 ++m_hiVehicleGuid;
5318 if(m_hiVehicleGuid>=0x00FFFFFF)
5320 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5321 World::StopNow(ERROR_EXIT_CODE);
5323 return m_hiVehicleGuid++;
5324 case HIGHGUID_PLAYER:
5325 if(m_hiCharGuid>=0xFFFFFFFE)
5327 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5328 World::StopNow(ERROR_EXIT_CODE);
5330 return m_hiCharGuid++;
5331 case HIGHGUID_GAMEOBJECT:
5332 if(m_hiGoGuid>=0x00FFFFFE)
5334 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5335 World::StopNow(ERROR_EXIT_CODE);
5337 return m_hiGoGuid++;
5338 case HIGHGUID_CORPSE:
5339 if(m_hiCorpseGuid>=0xFFFFFFFE)
5341 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5342 World::StopNow(ERROR_EXIT_CODE);
5344 return m_hiCorpseGuid++;
5345 case HIGHGUID_DYNAMICOBJECT:
5346 if(m_hiDoGuid>=0xFFFFFFFE)
5348 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5349 World::StopNow(ERROR_EXIT_CODE);
5351 return m_hiDoGuid++;
5352 default:
5353 ASSERT(0);
5356 ASSERT(0);
5357 return 0;
5360 void ObjectMgr::LoadGameObjectLocales()
5362 mGameObjectLocaleMap.clear(); // need for reload case
5364 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5365 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5366 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5367 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5369 if(!result)
5371 barGoLink bar(1);
5373 bar.step();
5375 sLog.outString("");
5376 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5377 return;
5380 barGoLink bar(result->GetRowCount());
5384 Field *fields = result->Fetch();
5385 bar.step();
5387 uint32 entry = fields[0].GetUInt32();
5389 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5391 for(int i = 1; i < MAX_LOCALE; ++i)
5393 std::string str = fields[i].GetCppString();
5394 if(!str.empty())
5396 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5397 if(idx >= 0)
5399 if(data.Name.size() <= idx)
5400 data.Name.resize(idx+1);
5402 data.Name[idx] = str;
5407 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5409 std::string str = fields[i].GetCppString();
5410 if(!str.empty())
5412 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5413 if(idx >= 0)
5415 if(data.CastBarCaption.size() <= idx)
5416 data.CastBarCaption.resize(idx+1);
5418 data.CastBarCaption[idx] = str;
5423 } while (result->NextRow());
5425 delete result;
5427 sLog.outString();
5428 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5431 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5433 template<class D>
5434 void convert_from_str(uint32 field_pos, char *src, D &dst)
5436 dst = D(objmgr.GetScriptId(src));
5440 void ObjectMgr::LoadGameobjectInfo()
5442 SQLGameObjectLoader loader;
5443 loader.Load(sGOStorage);
5445 // some checks
5446 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5448 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5449 if(!goInfo)
5450 continue;
5452 switch(goInfo->type)
5454 case GAMEOBJECT_TYPE_DOOR: //0
5456 if(goInfo->door.lockId)
5458 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5459 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5460 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5462 break;
5464 case GAMEOBJECT_TYPE_BUTTON: //1
5466 if(goInfo->button.lockId)
5468 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5469 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5470 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5472 break;
5474 case GAMEOBJECT_TYPE_CHEST: //3
5476 if(goInfo->chest.lockId)
5478 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5479 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5480 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5482 if(goInfo->chest.linkedTrapId) // linked trap
5484 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5486 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5487 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5488 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5490 /* disable check for while
5491 else
5492 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5493 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5496 break;
5498 case GAMEOBJECT_TYPE_TRAP: //6
5500 /* disable check for while
5501 if(goInfo->trap.spellId) // spell
5503 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5504 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5505 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5508 break;
5510 case GAMEOBJECT_TYPE_CHAIR: //7
5511 if(goInfo->chair.height > 2)
5513 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5514 id,goInfo->type,goInfo->chair.height);
5516 // prevent client and server unexpected work
5517 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5519 break;
5520 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5522 if(goInfo->spellFocus.focusId)
5524 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5525 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5526 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5529 if(goInfo->spellFocus.linkedTrapId) // linked trap
5531 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5533 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5534 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5535 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5537 /* disable check for while
5538 else
5539 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5540 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5543 break;
5545 case GAMEOBJECT_TYPE_GOOBER: //10
5547 if(goInfo->goober.pageId) // pageId
5549 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5550 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5551 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5553 /* disable check for while
5554 if(goInfo->goober.spellId) // spell
5556 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5557 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5558 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5561 if(goInfo->goober.linkedTrapId) // linked trap
5563 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5565 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5566 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5567 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5569 /* disable check for while
5570 else
5571 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5572 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5575 break;
5577 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5579 if(goInfo->moTransport.taxiPathId)
5581 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5582 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5583 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5585 break;
5587 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5589 /* disabled
5590 if(goInfo->summoningRitual.spellId)
5592 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5593 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5594 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5597 break;
5599 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5601 if(goInfo->spellcaster.spellId) // spell
5603 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5604 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5605 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5607 break;
5612 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5613 sLog.outString();
5616 void ObjectMgr::LoadExplorationBaseXP()
5618 uint32 count = 0;
5619 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5621 if( !result )
5623 barGoLink bar( 1 );
5625 bar.step();
5627 sLog.outString();
5628 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5629 return;
5632 barGoLink bar( result->GetRowCount() );
5636 bar.step();
5638 Field *fields = result->Fetch();
5639 uint32 level = fields[0].GetUInt32();
5640 uint32 basexp = fields[1].GetUInt32();
5641 mBaseXPTable[level] = basexp;
5642 ++count;
5644 while (result->NextRow());
5646 delete result;
5648 sLog.outString();
5649 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5652 uint32 ObjectMgr::GetBaseXP(uint32 level)
5654 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5657 void ObjectMgr::LoadPetNames()
5659 uint32 count = 0;
5660 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5662 if( !result )
5664 barGoLink bar( 1 );
5666 bar.step();
5668 sLog.outString();
5669 sLog.outString( ">> Loaded %u pet name parts", count );
5670 return;
5673 barGoLink bar( result->GetRowCount() );
5677 bar.step();
5679 Field *fields = result->Fetch();
5680 std::string word = fields[0].GetString();
5681 uint32 entry = fields[1].GetUInt32();
5682 bool half = fields[2].GetBool();
5683 if(half)
5684 PetHalfName1[entry].push_back(word);
5685 else
5686 PetHalfName0[entry].push_back(word);
5687 ++count;
5689 while (result->NextRow());
5690 delete result;
5692 sLog.outString();
5693 sLog.outString( ">> Loaded %u pet name parts", count );
5696 void ObjectMgr::LoadPetNumber()
5698 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5699 if(result)
5701 Field *fields = result->Fetch();
5702 m_hiPetNumber = fields[0].GetUInt32()+1;
5703 delete result;
5706 barGoLink bar( 1 );
5707 bar.step();
5709 sLog.outString();
5710 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5713 std::string ObjectMgr::GeneratePetName(uint32 entry)
5715 std::vector<std::string> & list0 = PetHalfName0[entry];
5716 std::vector<std::string> & list1 = PetHalfName1[entry];
5718 if(list0.empty() || list1.empty())
5720 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5721 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5722 if(!petname)
5723 petname = cinfo->Name;
5724 return std::string(petname);
5727 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5730 uint32 ObjectMgr::GeneratePetNumber()
5732 return ++m_hiPetNumber;
5735 void ObjectMgr::LoadCorpses()
5737 uint32 count = 0;
5738 // 0 1 2 3 4 5 6 7 8 10
5739 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");
5741 if( !result )
5743 barGoLink bar( 1 );
5745 bar.step();
5747 sLog.outString();
5748 sLog.outString( ">> Loaded %u corpses", count );
5749 return;
5752 barGoLink bar( result->GetRowCount() );
5756 bar.step();
5758 Field *fields = result->Fetch();
5760 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5762 Corpse *corpse = new Corpse;
5763 if(!corpse->LoadFromDB(guid,fields))
5765 delete corpse;
5766 continue;
5769 ObjectAccessor::Instance().AddCorpse(corpse);
5771 ++count;
5773 while (result->NextRow());
5774 delete result;
5776 sLog.outString();
5777 sLog.outString( ">> Loaded %u corpses", count );
5780 void ObjectMgr::LoadReputationOnKill()
5782 uint32 count = 0;
5784 // 0 1 2
5785 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5786 // 3 4 5 6 7 8 9
5787 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5788 "FROM creature_onkill_reputation");
5790 if(!result)
5792 barGoLink bar(1);
5794 bar.step();
5796 sLog.outString();
5797 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5798 return;
5801 barGoLink bar(result->GetRowCount());
5805 Field *fields = result->Fetch();
5806 bar.step();
5808 uint32 creature_id = fields[0].GetUInt32();
5810 ReputationOnKillEntry repOnKill;
5811 repOnKill.repfaction1 = fields[1].GetUInt32();
5812 repOnKill.repfaction2 = fields[2].GetUInt32();
5813 repOnKill.is_teamaward1 = fields[3].GetBool();
5814 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5815 repOnKill.repvalue1 = fields[5].GetInt32();
5816 repOnKill.is_teamaward2 = fields[6].GetBool();
5817 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5818 repOnKill.repvalue2 = fields[8].GetInt32();
5819 repOnKill.team_dependent = fields[9].GetUInt8();
5821 if(!GetCreatureTemplate(creature_id))
5823 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5824 continue;
5827 if(repOnKill.repfaction1)
5829 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5830 if(!factionEntry1)
5832 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5833 continue;
5837 if(repOnKill.repfaction2)
5839 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5840 if(!factionEntry2)
5842 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5843 continue;
5847 mRepOnKill[creature_id] = repOnKill;
5849 ++count;
5850 } while (result->NextRow());
5852 delete result;
5854 sLog.outString();
5855 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5858 void ObjectMgr::LoadWeatherZoneChances()
5860 uint32 count = 0;
5862 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5863 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");
5865 if(!result)
5867 barGoLink bar(1);
5869 bar.step();
5871 sLog.outString();
5872 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5873 return;
5876 barGoLink bar(result->GetRowCount());
5880 Field *fields = result->Fetch();
5881 bar.step();
5883 uint32 zone_id = fields[0].GetUInt32();
5885 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5887 for(int season = 0; season < WEATHER_SEASONS; ++season)
5889 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5890 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5891 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5893 if(wzc.data[season].rainChance > 100)
5895 wzc.data[season].rainChance = 25;
5896 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5899 if(wzc.data[season].snowChance > 100)
5901 wzc.data[season].snowChance = 25;
5902 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5905 if(wzc.data[season].stormChance > 100)
5907 wzc.data[season].stormChance = 25;
5908 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5912 ++count;
5913 } while (result->NextRow());
5915 delete result;
5917 sLog.outString();
5918 sLog.outString(">> Loaded %u weather definitions", count);
5921 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5923 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5924 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5925 if(t)
5926 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5929 void ObjectMgr::DeleteCreatureData(uint32 guid)
5931 // remove mapid*cellid -> guid_set map
5932 CreatureData const* data = GetCreatureData(guid);
5933 if(data)
5934 RemoveCreatureFromGrid(guid, data);
5936 mCreatureDataMap.erase(guid);
5939 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5941 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5942 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5943 if(t)
5944 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5947 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5949 RespawnTimes::iterator next;
5951 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5953 next = itr;
5954 ++next;
5956 if(GUID_HIPART(itr->first)==instance)
5957 mGORespawnTimes.erase(itr);
5960 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5962 next = itr;
5963 ++next;
5965 if(GUID_HIPART(itr->first)==instance)
5966 mCreatureRespawnTimes.erase(itr);
5969 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5970 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5973 void ObjectMgr::DeleteGOData(uint32 guid)
5975 // remove mapid*cellid -> guid_set map
5976 GameObjectData const* data = GetGOData(guid);
5977 if(data)
5978 RemoveGameobjectFromGrid(guid, data);
5980 mGameObjectDataMap.erase(guid);
5983 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5985 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5986 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5987 cell_guids.corpses[player_guid] = instance;
5990 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5992 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5993 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5994 cell_guids.corpses.erase(player_guid);
5997 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5999 map.clear(); // need for reload case
6001 uint32 count = 0;
6003 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6005 if(!result)
6007 barGoLink bar(1);
6009 bar.step();
6011 sLog.outString();
6012 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6013 return;
6016 barGoLink bar(result->GetRowCount());
6020 Field *fields = result->Fetch();
6021 bar.step();
6023 uint32 id = fields[0].GetUInt32();
6024 uint32 quest = fields[1].GetUInt32();
6026 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6028 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6029 continue;
6032 map.insert(QuestRelations::value_type(id,quest));
6034 ++count;
6035 } while (result->NextRow());
6037 delete result;
6039 sLog.outString();
6040 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6043 void ObjectMgr::LoadGameobjectQuestRelations()
6045 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6047 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6049 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6050 if(!goInfo)
6051 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6052 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6053 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6057 void ObjectMgr::LoadGameobjectInvolvedRelations()
6059 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6061 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6063 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6064 if(!goInfo)
6065 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6066 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6067 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6071 void ObjectMgr::LoadCreatureQuestRelations()
6073 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6075 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6077 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6078 if(!cInfo)
6079 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6080 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6081 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);
6085 void ObjectMgr::LoadCreatureInvolvedRelations()
6087 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6089 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6091 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6092 if(!cInfo)
6093 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6094 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6095 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);
6099 void ObjectMgr::LoadReservedPlayersNames()
6101 m_ReservedNames.clear(); // need for reload case
6103 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6105 uint32 count = 0;
6107 if( !result )
6109 barGoLink bar( 1 );
6110 bar.step();
6112 sLog.outString();
6113 sLog.outString( ">> Loaded %u reserved player names", count );
6114 return;
6117 barGoLink bar( result->GetRowCount() );
6119 Field* fields;
6122 bar.step();
6123 fields = result->Fetch();
6124 std::string name= fields[0].GetCppString();
6125 if(normalizePlayerName(name))
6127 m_ReservedNames.insert(name);
6128 ++count;
6130 } while ( result->NextRow() );
6132 delete result;
6134 sLog.outString();
6135 sLog.outString( ">> Loaded %u reserved player names", count );
6138 enum LanguageType
6140 LT_BASIC_LATIN = 0x0000,
6141 LT_EXTENDEN_LATIN = 0x0001,
6142 LT_CYRILLIC = 0x0002,
6143 LT_EAST_ASIA = 0x0004,
6144 LT_ANY = 0xFFFF
6147 static LanguageType GetRealmLanguageType(bool create)
6149 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6151 case REALM_ZONE_UNKNOWN: // any language
6152 case REALM_ZONE_DEVELOPMENT:
6153 case REALM_ZONE_TEST_SERVER:
6154 case REALM_ZONE_QA_SERVER:
6155 return LT_ANY;
6156 case REALM_ZONE_UNITED_STATES: // extended-Latin
6157 case REALM_ZONE_OCEANIC:
6158 case REALM_ZONE_LATIN_AMERICA:
6159 case REALM_ZONE_ENGLISH:
6160 case REALM_ZONE_GERMAN:
6161 case REALM_ZONE_FRENCH:
6162 case REALM_ZONE_SPANISH:
6163 return LT_EXTENDEN_LATIN;
6164 case REALM_ZONE_KOREA: // East-Asian
6165 case REALM_ZONE_TAIWAN:
6166 case REALM_ZONE_CHINA:
6167 return LT_EAST_ASIA;
6168 case REALM_ZONE_RUSSIAN: // Cyrillic
6169 return LT_CYRILLIC;
6170 default:
6171 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6175 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6177 if(strictMask==0) // any language, ignore realm
6179 if(isExtendedLatinString(wstr,numericOrSpace))
6180 return true;
6181 if(isCyrillicString(wstr,numericOrSpace))
6182 return true;
6183 if(isEastAsianString(wstr,numericOrSpace))
6184 return true;
6185 return false;
6188 if(strictMask & 0x2) // realm zone specific
6190 LanguageType lt = GetRealmLanguageType(create);
6191 if(lt & LT_EXTENDEN_LATIN)
6192 if(isExtendedLatinString(wstr,numericOrSpace))
6193 return true;
6194 if(lt & LT_CYRILLIC)
6195 if(isCyrillicString(wstr,numericOrSpace))
6196 return true;
6197 if(lt & LT_EAST_ASIA)
6198 if(isEastAsianString(wstr,numericOrSpace))
6199 return true;
6202 if(strictMask & 0x1) // basic Latin
6204 if(isBasicLatinString(wstr,numericOrSpace))
6205 return true;
6208 return false;
6211 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6213 std::wstring wname;
6214 if(!Utf8toWStr(name,wname))
6215 return false;
6217 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6218 return false;
6220 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6222 return isValidString(wname,strictMask,false,create);
6225 bool ObjectMgr::IsValidCharterName( const std::string& name )
6227 std::wstring wname;
6228 if(!Utf8toWStr(name,wname))
6229 return false;
6231 if(wname.size() < 1)
6232 return false;
6234 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6236 return isValidString(wname,strictMask,true);
6239 bool ObjectMgr::IsValidPetName( const std::string& name )
6241 std::wstring wname;
6242 if(!Utf8toWStr(name,wname))
6243 return false;
6245 if(wname.size() < 1)
6246 return false;
6248 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6250 return isValidString(wname,strictMask,false);
6253 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6255 if(loc==LOCALE_enUS)
6256 return -1;
6258 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6259 if(m_LocalForIndex[i]==loc)
6260 return i;
6262 return -1;
6265 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6267 if (i<0 || i>=m_LocalForIndex.size())
6268 return LOCALE_enUS;
6270 return m_LocalForIndex[i];
6273 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6275 if(loc==LOCALE_enUS)
6276 return -1;
6278 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6279 if(m_LocalForIndex[i]==loc)
6280 return i;
6282 m_LocalForIndex.push_back(loc);
6283 return m_LocalForIndex.size()-1;
6286 AchievementCriteriaEntryList const& ObjectMgr::GetAchievementCriteriaByType(AchievementCriteriaTypes type)
6288 return m_AchievementCriteriasByType[type];
6291 void ObjectMgr::LoadAchievementCriteriaList()
6293 for (uint32 entryId = 0; entryId<sAchievementCriteriaStore.GetNumRows(); entryId++)
6295 AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId);
6296 if(!criteria)
6297 continue;
6299 m_AchievementCriteriasByType[criteria->requiredType].push_back(criteria);
6303 void ObjectMgr::LoadBattleMastersEntry()
6305 mBattleMastersMap.clear(); // need for reload case
6307 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6309 uint32 count = 0;
6311 if( !result )
6313 barGoLink bar( 1 );
6314 bar.step();
6316 sLog.outString();
6317 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6318 return;
6321 barGoLink bar( result->GetRowCount() );
6325 ++count;
6326 bar.step();
6328 Field *fields = result->Fetch();
6330 uint32 entry = fields[0].GetUInt32();
6331 uint32 bgTypeId = fields[1].GetUInt32();
6333 mBattleMastersMap[entry] = bgTypeId;
6335 } while( result->NextRow() );
6337 delete result;
6339 sLog.outString();
6340 sLog.outString( ">> Loaded %u battlemaster entries", count );
6343 void ObjectMgr::LoadGameObjectForQuests()
6345 mGameObjectForQuestSet.clear(); // need for reload case
6347 uint32 count = 0;
6349 // collect GO entries for GO that must activated
6350 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6352 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6353 if(!goInfo)
6354 continue;
6356 switch(goInfo->type)
6358 // scan GO chest with loot including quest items
6359 case GAMEOBJECT_TYPE_CHEST:
6361 uint32 loot_id = GameObject::GetLootId(goInfo);
6363 // find quest loot for GO
6364 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6366 mGameObjectForQuestSet.insert(go_entry);
6367 ++count;
6369 break;
6371 case GAMEOBJECT_TYPE_GOOBER:
6373 if(goInfo->goober.questId) //quests objects
6375 mGameObjectForQuestSet.insert(go_entry);
6376 count++;
6378 break;
6380 default:
6381 break;
6385 sLog.outString();
6386 sLog.outString( ">> Loaded %u GameObject for quests", count );
6389 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6391 // cleanup affected map part for reloading case
6392 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6394 if(itr->first >= min_value && itr->first <= max_value)
6396 MangosStringLocaleMap::iterator itr2 = itr;
6397 ++itr;
6398 mMangosStringLocaleMap.erase(itr2);
6400 else
6401 ++itr;
6404 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);
6406 if(!result)
6408 barGoLink bar(1);
6410 bar.step();
6412 sLog.outString("");
6413 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6414 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6415 else
6416 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6417 return false;
6420 uint32 count = 0;
6422 barGoLink bar(result->GetRowCount());
6426 Field *fields = result->Fetch();
6427 bar.step();
6429 int32 entry = fields[0].GetInt32();
6431 if(entry==0)
6433 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6434 continue;
6436 else if(entry < min_value || entry > max_value)
6438 int32 start = min_value > 0 ? min_value : max_value;
6439 int32 end = min_value > 0 ? max_value : min_value;
6440 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6441 continue;
6444 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6446 if(data.Content.size() > 0)
6448 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6449 continue;
6452 data.Content.resize(1);
6453 ++count;
6455 // 0 -> default, idx in to idx+1
6456 data.Content[0] = fields[1].GetCppString();
6458 for(int i = 1; i < MAX_LOCALE; ++i)
6460 std::string str = fields[i+1].GetCppString();
6461 if(!str.empty())
6463 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6464 if(idx >= 0)
6466 // 0 -> default, idx in to idx+1
6467 if(data.Content.size() <= idx+1)
6468 data.Content.resize(idx+2);
6470 data.Content[idx+1] = str;
6474 } while (result->NextRow());
6476 delete result;
6478 sLog.outString();
6479 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6480 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6481 else
6482 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6484 return true;
6487 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6489 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6490 // Content[0] always exist if exist MangosStringLocale
6491 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6493 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6494 return msl->Content[locale_idx+1].c_str();
6495 else
6496 return msl->Content[0].c_str();
6499 if(entry > 0)
6500 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6501 else
6502 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6503 return "<error>";
6506 void ObjectMgr::LoadFishingBaseSkillLevel()
6508 mFishingBaseForArea.clear(); // for reload case
6510 uint32 count = 0;
6511 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6513 if( !result )
6515 barGoLink bar( 1 );
6517 bar.step();
6519 sLog.outString();
6520 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6521 return;
6524 barGoLink bar( result->GetRowCount() );
6528 bar.step();
6530 Field *fields = result->Fetch();
6531 uint32 entry = fields[0].GetUInt32();
6532 int32 skill = fields[1].GetInt32();
6534 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6535 if(!fArea)
6537 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6538 continue;
6541 mFishingBaseForArea[entry] = skill;
6542 ++count;
6544 while (result->NextRow());
6546 delete result;
6548 sLog.outString();
6549 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6552 // Searches for the same condition already in Conditions store
6553 // Returns Id if found, else adds it to Conditions and returns Id
6554 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6556 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6557 for (uint16 i=0; i < mConditions.size(); ++i)
6559 if (lc == mConditions[i])
6560 return i;
6563 mConditions.push_back(lc);
6565 if(mConditions.size() > 0xFFFF)
6567 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6568 return 0;
6571 return mConditions.size() - 1;
6574 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6576 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6578 std::wstring wname;
6579 if(!Utf8toWStr(names.name[i],wname))
6580 return false;
6582 if(mainpart!=GetMainPartOfName(wname,i+1))
6583 return false;
6585 return true;
6588 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6590 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6591 if(i!= mAreaTriggerScripts.end())
6592 return i->second;
6593 return 0;
6596 // Checks if player meets the condition
6597 bool PlayerCondition::Meets(Player const * player) const
6599 if( !player )
6600 return false; // player not present, return false
6602 switch (condition)
6604 case CONDITION_NONE:
6605 return true; // empty condition, always met
6606 case CONDITION_AURA:
6607 return player->HasAura(value1, value2);
6608 case CONDITION_ITEM:
6609 return player->HasItemCount(value1, value2);
6610 case CONDITION_ITEM_EQUIPPED:
6611 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6612 case CONDITION_ZONEID:
6613 return player->GetZoneId() == value1;
6614 case CONDITION_REPUTATION_RANK:
6616 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6617 return faction && player->GetReputationRank(faction) >= value2;
6619 case CONDITION_TEAM:
6620 return player->GetTeam() == value1;
6621 case CONDITION_SKILL:
6622 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6623 case CONDITION_QUESTREWARDED:
6624 return player->GetQuestRewardStatus(value1);
6625 case CONDITION_QUESTTAKEN:
6627 QuestStatus status = player->GetQuestStatus(value1);
6628 return (status == QUEST_STATUS_INCOMPLETE);
6630 case CONDITION_AD_COMMISSION_AURA:
6632 Unit::AuraMap const& auras = player->GetAuras();
6633 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6634 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6635 return true;
6636 return false;
6638 case CONDITION_NO_AURA:
6639 return !player->HasAura(value1, value2);
6640 case CONDITION_ACTIVE_EVENT:
6641 return gameeventmgr.IsActiveEvent(value1);
6642 default:
6643 return false;
6647 // Verification of condition values validity
6648 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6650 if( condition >= MAX_CONDITION) // Wrong condition type
6652 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6653 return false;
6656 switch (condition)
6658 case CONDITION_AURA:
6660 if(!sSpellStore.LookupEntry(value1))
6662 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6663 return false;
6665 if(value2 > 2)
6667 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6668 return false;
6670 break;
6672 case CONDITION_ITEM:
6674 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6675 if(!proto)
6677 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6678 return false;
6680 break;
6682 case CONDITION_ITEM_EQUIPPED:
6684 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6685 if(!proto)
6687 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6688 return false;
6690 break;
6692 case CONDITION_ZONEID:
6694 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6695 if(!areaEntry)
6697 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6698 return false;
6700 if(areaEntry->zone != 0)
6702 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6703 return false;
6705 break;
6707 case CONDITION_REPUTATION_RANK:
6709 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6710 if(!factionEntry)
6712 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6713 return false;
6715 break;
6717 case CONDITION_TEAM:
6719 if (value1 != ALLIANCE && value1 != HORDE)
6721 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6722 return false;
6724 break;
6726 case CONDITION_SKILL:
6728 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6729 if (!pSkill)
6731 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6732 return false;
6734 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6736 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6737 return false;
6739 break;
6741 case CONDITION_QUESTREWARDED:
6742 case CONDITION_QUESTTAKEN:
6744 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6745 if (!Quest)
6747 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6748 return false;
6750 if(value2)
6751 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6752 break;
6754 case CONDITION_AD_COMMISSION_AURA:
6756 if(value1)
6757 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6758 if(value2)
6759 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6760 break;
6762 case CONDITION_NO_AURA:
6764 if(!sSpellStore.LookupEntry(value1))
6766 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6767 return false;
6769 if(value2 > 2)
6771 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6772 return false;
6774 break;
6776 case CONDITION_ACTIVE_EVENT:
6778 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6779 if(value1 >=events.size() || !events[value1].isValid())
6781 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6782 return false;
6784 break;
6787 return true;
6790 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6792 switch(pSkill->categoryId)
6794 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6795 case SKILL_CATEGORY_WEAPON:
6796 if(pSkill->id!=SKILL_FIST_WEAPONS)
6797 return SKILL_RANGE_LEVEL;
6798 else
6799 return SKILL_RANGE_MONO;
6800 case SKILL_CATEGORY_ARMOR:
6801 case SKILL_CATEGORY_CLASS:
6802 if(pSkill->id != SKILL_LOCKPICKING)
6803 return SKILL_RANGE_MONO;
6804 else
6805 return SKILL_RANGE_LEVEL;
6806 case SKILL_CATEGORY_SECONDARY:
6807 case SKILL_CATEGORY_PROFESSION:
6808 // not set skills for professions and racial abilities
6809 if(IsProfessionSkill(pSkill->id))
6810 return SKILL_RANGE_RANK;
6811 else if(racial)
6812 return SKILL_RANGE_NONE;
6813 else
6814 return SKILL_RANGE_MONO;
6815 default:
6816 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6817 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6818 return SKILL_RANGE_NONE;
6822 void ObjectMgr::LoadGameTele()
6824 m_GameTeleMap.clear(); // for reload case
6826 uint32 count = 0;
6827 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6829 if( !result )
6831 barGoLink bar( 1 );
6833 bar.step();
6835 sLog.outString();
6836 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6837 return;
6840 barGoLink bar( result->GetRowCount() );
6844 bar.step();
6846 Field *fields = result->Fetch();
6848 uint32 id = fields[0].GetUInt32();
6850 GameTele gt;
6852 gt.position_x = fields[1].GetFloat();
6853 gt.position_y = fields[2].GetFloat();
6854 gt.position_z = fields[3].GetFloat();
6855 gt.orientation = fields[4].GetFloat();
6856 gt.mapId = fields[5].GetUInt32();
6857 gt.name = fields[6].GetCppString();
6859 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6861 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6862 continue;
6865 if(!Utf8toWStr(gt.name,gt.wnameLow))
6867 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6868 continue;
6871 wstrToLower( gt.wnameLow );
6873 m_GameTeleMap[id] = gt;
6875 ++count;
6877 while (result->NextRow());
6879 delete result;
6881 sLog.outString();
6882 sLog.outString( ">> Loaded %u game tele's", count );
6885 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6887 // explicit name case
6888 std::wstring wname;
6889 if(!Utf8toWStr(name,wname))
6890 return false;
6892 // converting string that we try to find to lower case
6893 wstrToLower( wname );
6895 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6896 const GameTele* alt = NULL;
6897 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6898 if(itr->second.wnameLow == wname)
6899 return &itr->second;
6900 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6901 alt = &itr->second;
6903 return alt;
6906 bool ObjectMgr::AddGameTele(GameTele& tele)
6908 // find max id
6909 uint32 new_id = 0;
6910 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6911 if(itr->first > new_id)
6912 new_id = itr->first;
6914 // use next
6915 ++new_id;
6917 if(!Utf8toWStr(tele.name,tele.wnameLow))
6918 return false;
6920 wstrToLower( tele.wnameLow );
6922 m_GameTeleMap[new_id] = tele;
6924 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')",
6925 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6928 bool ObjectMgr::DeleteGameTele(const std::string& name)
6930 // explicit name case
6931 std::wstring wname;
6932 if(!Utf8toWStr(name,wname))
6933 return false;
6935 // converting string that we try to find to lower case
6936 wstrToLower( wname );
6938 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6940 if(itr->second.wnameLow == wname)
6942 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6943 m_GameTeleMap.erase(itr);
6944 return true;
6948 return false;
6951 void ObjectMgr::LoadTrainerSpell()
6953 // For reload case
6954 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6955 itr->second.Clear();
6956 m_mCacheTrainerSpellMap.clear();
6958 std::set<uint32> skip_trainers;
6960 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6962 if( !result )
6964 barGoLink bar( 1 );
6966 bar.step();
6968 sLog.outString();
6969 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6970 return;
6973 barGoLink bar( result->GetRowCount() );
6975 uint32 count = 0;
6978 bar.step();
6980 Field* fields = result->Fetch();
6982 uint32 entry = fields[0].GetUInt32();
6983 uint32 spell = fields[1].GetUInt32();
6985 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6987 if(!cInfo)
6989 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6990 continue;
6993 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6995 if(skip_trainers.count(entry) == 0)
6997 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6998 skip_trainers.insert(entry);
7000 continue;
7003 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7004 if(!spellinfo)
7006 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7007 continue;
7010 if(!SpellMgr::IsSpellValid(spellinfo))
7012 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7013 continue;
7016 TrainerSpell* pTrainerSpell = new TrainerSpell();
7017 pTrainerSpell->spell = spell;
7018 pTrainerSpell->spellcost = fields[2].GetUInt32();
7019 pTrainerSpell->reqskill = fields[3].GetUInt32();
7020 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
7021 pTrainerSpell->reqlevel = fields[5].GetUInt32();
7023 if(!pTrainerSpell->reqlevel)
7024 pTrainerSpell->reqlevel = spellinfo->spellLevel;
7027 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7029 if(SpellMgr::IsProfessionSpell(spell))
7030 data.trainerType = 2;
7032 data.spellList.push_back(pTrainerSpell);
7033 ++count;
7035 } while (result->NextRow());
7036 delete result;
7038 sLog.outString();
7039 sLog.outString( ">> Loaded Trainers %d", count );
7042 void ObjectMgr::LoadVendors()
7044 // For reload case
7045 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7046 itr->second.Clear();
7047 m_mCacheVendorItemMap.clear();
7049 std::set<uint32> skip_vendors;
7051 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7052 if( !result )
7054 barGoLink bar( 1 );
7056 bar.step();
7058 sLog.outString();
7059 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7060 return;
7063 barGoLink bar( result->GetRowCount() );
7065 uint32 count = 0;
7068 bar.step();
7069 Field* fields = result->Fetch();
7071 uint32 entry = fields[0].GetUInt32();
7072 uint32 item_id = fields[1].GetUInt32();
7073 uint32 maxcount = fields[2].GetUInt32();
7074 uint32 incrtime = fields[3].GetUInt32();
7075 uint32 ExtendedCost = fields[4].GetUInt32();
7077 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7078 continue;
7080 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7082 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7083 ++count;
7085 } while (result->NextRow());
7086 delete result;
7088 sLog.outString();
7089 sLog.outString( ">> Loaded %d Vendors ", count );
7092 void ObjectMgr::LoadNpcTextId()
7095 m_mCacheNpcTextIdMap.clear();
7097 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7098 if( !result )
7100 barGoLink bar( 1 );
7102 bar.step();
7104 sLog.outString();
7105 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7106 return;
7109 barGoLink bar( result->GetRowCount() );
7111 uint32 count = 0;
7112 uint32 guid,textid;
7115 bar.step();
7117 Field* fields = result->Fetch();
7119 guid = fields[0].GetUInt32();
7120 textid = fields[1].GetUInt32();
7122 if (!GetCreatureData(guid))
7124 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7125 continue;
7127 if (!GetGossipText(textid))
7129 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7130 continue;
7133 m_mCacheNpcTextIdMap[guid] = textid ;
7134 ++count;
7136 } while (result->NextRow());
7137 delete result;
7139 sLog.outString();
7140 sLog.outString( ">> Loaded %d NpcTextId ", count );
7143 void ObjectMgr::LoadNpcOptions()
7145 m_mCacheNpcOptionList.clear(); // For reload case
7147 QueryResult *result = WorldDatabase.Query(
7148 // 0 1 2 3 4 5 6 7 8
7149 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7150 "FROM npc_option");
7152 if( !result )
7154 barGoLink bar( 1 );
7156 bar.step();
7158 sLog.outString();
7159 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7160 return;
7163 barGoLink bar( result->GetRowCount() );
7165 uint32 count = 0;
7169 bar.step();
7171 Field* fields = result->Fetch();
7173 GossipOption go;
7174 go.Id = fields[0].GetUInt32();
7175 go.GossipId = fields[1].GetUInt32();
7176 go.NpcFlag = fields[2].GetUInt32();
7177 go.Icon = fields[3].GetUInt32();
7178 go.Action = fields[4].GetUInt32();
7179 go.BoxMoney = fields[5].GetUInt32();
7180 go.Coded = fields[6].GetUInt8()!=0;
7181 go.OptionText = fields[7].GetCppString();
7182 go.BoxText = fields[8].GetCppString();
7184 m_mCacheNpcOptionList.push_back(go);
7186 ++count;
7188 } while (result->NextRow());
7189 delete result;
7191 sLog.outString();
7192 sLog.outString( ">> Loaded %d npc_option entries", count );
7195 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7197 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7198 vList.AddItem(item,maxcount,incrtime,extendedcost);
7200 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7203 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7205 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7206 if(iter == m_mCacheVendorItemMap.end())
7207 return false;
7209 if(!iter->second.FindItem(item))
7210 return false;
7212 iter->second.RemoveItem(item);
7213 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7214 return true;
7217 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7219 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7220 if(!cInfo)
7222 if(pl)
7223 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7224 else
7225 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7226 return false;
7229 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7231 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7233 if(pl)
7234 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7235 else
7236 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7238 if(skip_vendors)
7239 skip_vendors->insert(vendor_entry);
7241 return false;
7244 if(!GetItemPrototype(item_id))
7246 if(pl)
7247 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7248 else
7249 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7250 return false;
7253 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7255 if(pl)
7256 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7257 else
7258 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7259 return false;
7262 if(maxcount > 0 && incrtime == 0)
7264 if(pl)
7265 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7266 else
7267 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7268 return false;
7270 else if(maxcount==0 && incrtime > 0)
7272 if(pl)
7273 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7274 else
7275 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7276 return false;
7279 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7280 if(!vItems)
7281 return true; // later checks for non-empty lists
7283 if(vItems->FindItem(item_id))
7285 if(pl)
7286 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7287 else
7288 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7289 return false;
7292 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7294 if(pl)
7295 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7296 else
7297 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7298 return false;
7301 return true;
7304 void ObjectMgr::LoadScriptNames()
7306 m_scriptNames.push_back("");
7307 QueryResult *result = WorldDatabase.Query(
7308 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7309 "UNION "
7310 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7311 "UNION "
7312 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7313 "UNION "
7314 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7315 "UNION "
7316 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7317 if(result)
7321 m_scriptNames.push_back((*result)[0].GetString());
7322 } while (result->NextRow());
7323 delete result;
7326 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7329 uint32 ObjectMgr::GetScriptId(const char *name)
7331 // use binary search to find the script name in the sorted vector
7332 // assume "" is the first element
7333 if(!name) return 0;
7334 ScriptNameMap::const_iterator itr =
7335 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7336 if(itr == m_scriptNames.end() || *itr != name) return 0;
7337 return itr - m_scriptNames.begin();
7340 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7342 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7344 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7346 if(itrM->second.dataint)
7348 if(!GetMangosStringLocale (itrM->second.dataint))
7349 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7351 if(ids.count(itrM->second.dataint))
7352 ids.erase(itrM->second.dataint);
7358 void ObjectMgr::LoadDbScriptStrings()
7360 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7362 std::set<int32> ids;
7364 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7365 if(GetMangosStringLocale(i))
7366 ids.insert(i);
7368 CheckScripts(sQuestEndScripts,ids);
7369 CheckScripts(sQuestStartScripts,ids);
7370 CheckScripts(sSpellScripts,ids);
7371 CheckScripts(sGameObjectScripts,ids);
7372 CheckScripts(sEventScripts,ids);
7374 WaypointMgr.CheckTextsExistance(ids);
7376 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7377 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7380 // Functions for scripting access
7381 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7383 return objmgr.GetAreaTriggerScriptId(trigger_id);
7386 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7388 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7390 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());
7391 start_value = -1;
7392 end_value = std::numeric_limits<int32>::min();
7395 // for scripting localized strings allowed use _only_ negative entries
7396 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7399 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7401 return objmgr.GetScriptId(name);
7404 ObjectMgr::ScriptNameMap & GetScriptNames()
7406 return objmgr.GetScriptNames();