Updatefields for 3.0.x
[getmangos.git] / src / game / ObjectMgr.cpp
blob29e52ed4b0dd1253f2bda5dbd9910a9e72fab9ee
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
23 #include "Log.h"
24 #include "MapManager.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "WorldSession.h"
30 #include "Group.h"
31 #include "Guild.h"
32 #include "ArenaTeam.h"
33 #include "Transports.h"
34 #include "ProgressBar.h"
35 #include "Policies/SingletonImp.h"
36 #include "Language.h"
37 #include "GameEvent.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
45 INSTANTIATE_SINGLETON_1(ObjectMgr);
47 ScriptMapMap sQuestEndScripts;
48 ScriptMapMap sQuestStartScripts;
49 ScriptMapMap sSpellScripts;
50 ScriptMapMap sGameObjectScripts;
51 ScriptMapMap sEventScripts;
53 bool normalizePlayerName(std::string& name)
55 if(name.empty())
56 return false;
58 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
59 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
61 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
62 return false;
64 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
65 for(size_t i = 1; i < wstr_len; ++i)
66 wstr_buf[i] = wcharToLower(wstr_buf[i]);
68 if(!WStrToUtf8(wstr_buf,wstr_len,name))
69 return false;
71 return true;
74 LanguageDesc lang_description[LANGUAGES_COUNT] =
76 { LANG_ADDON, 0, 0 },
77 { LANG_UNIVERSAL, 0, 0 },
78 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
79 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
80 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
81 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
82 { LANG_COMMON, 668, SKILL_LANG_COMMON },
83 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
84 { LANG_TITAN, 816, SKILL_LANG_TITAN },
85 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
86 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
87 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
88 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
89 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
90 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
91 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
92 { LANG_ZOMBIE, 0, 0 },
93 { LANG_GNOMISH_BINARY, 0, 0 },
94 { LANG_GOBLIN_BINARY, 0, 0 }
97 LanguageDesc const* GetLanguageDescByID(uint32 lang)
99 for(int i = 0; i < LANGUAGES_COUNT; ++i)
101 if(uint32(lang_description[i].lang_id) == lang)
102 return &lang_description[i];
105 return NULL;
108 ObjectMgr::ObjectMgr()
110 m_hiCharGuid = 1;
111 m_hiCreatureGuid = 1;
112 m_hiPetGuid = 1;
113 m_hiItemGuid = 1;
114 m_hiGoGuid = 1;
115 m_hiDoGuid = 1;
116 m_hiCorpseGuid = 1;
118 m_hiPetNumber = 1;
120 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
121 mGuildBankTabPrice[0] = 100;
122 mGuildBankTabPrice[1] = 250;
123 mGuildBankTabPrice[2] = 500;
124 mGuildBankTabPrice[3] = 1000;
125 mGuildBankTabPrice[4] = 2500;
126 mGuildBankTabPrice[5] = 5000;
128 // Only zero condition left, others will be added while loading DB tables
129 mConditions.resize(1);
132 ObjectMgr::~ObjectMgr()
134 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
136 delete i->second;
138 mQuestTemplates.clear( );
140 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
142 delete i->second;
144 mGossipText.clear( );
146 mAreaTriggers.clear();
148 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
150 delete[] i->second;
152 petInfo.clear();
154 // free only if loaded
155 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
156 delete[] playerClassInfo[class_].levelInfo;
158 for (int race = 0; race < MAX_RACES; ++race)
159 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
160 delete[] playerInfo[race][class_].levelInfo;
162 // free group and guild objects
163 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
164 delete (*itr);
165 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
166 delete (*itr);
168 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
169 delete itr->second;
171 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
172 itr->second.Clear();
174 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
175 itr->second.Clear();
178 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
180 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
181 if ((*itr)->GetLeaderGUID() == guid)
182 return *itr;
184 return NULL;
187 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
189 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
190 if ((*itr)->GetId() == GuildId)
191 return *itr;
193 return NULL;
196 Guild * ObjectMgr::GetGuildByName(std::string guildname) const
198 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
199 if ((*itr)->GetName() == guildname)
200 return *itr;
202 return NULL;
205 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
207 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
208 if ((*itr)->GetId() == GuildId)
209 return (*itr)->GetName();
211 return "";
214 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
216 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
217 if( (*itr)->GetLeader() == guid)
218 return *itr;
220 return NULL;
223 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
225 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
226 if ((*itr)->GetId() == ArenaTeamId)
227 return *itr;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
234 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
235 if ((*itr)->GetName() == arenateamname)
236 return *itr;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
243 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
244 if ((*itr)->GetCaptain() == guid)
245 return *itr;
247 return NULL;
250 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
252 switch ( location )
254 case 6: //horde
255 return & mHordeAuctions;
256 break;
257 case 2: //alliance
258 return & mAllianceAuctions;
259 break;
260 default: //neutral
261 return & mNeutralAuctions;
265 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
267 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
268 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
269 else
270 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
273 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
275 float percentance; // in 0..1
276 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
277 percentance = 0.75f;
278 else
279 percentance = 0.15f;
281 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
283 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
286 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
287 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
289 uint32 outbid = (currentBid / 100) * 5;
290 if (!outbid)
291 outbid = 1;
292 return outbid;
295 //does not clear ram
296 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
298 Item *pItem = GetAItem(auction->item_guidlow);
299 if(!pItem)
300 return;
302 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
303 Player *bidder = GetPlayer(bidder_guid);
305 uint32 bidder_accId = 0;
307 // data for gm.log
308 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
310 uint32 bidder_security = 0;
311 std::string bidder_name;
312 if (bidder)
314 bidder_accId = bidder->GetSession()->GetAccountId();
315 bidder_security = bidder->GetSession()->GetSecurity();
316 bidder_name = bidder->GetName();
318 else
320 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
321 bidder_security = accmgr.GetSecurity(bidder_accId);
323 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
325 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
326 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
330 if( bidder_security > SEC_PLAYER )
332 std::string owner_name;
333 if(!GetPlayerNameByGUID(auction->owner,owner_name))
334 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
336 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
338 sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
339 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
342 else if(!bidder)
343 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
345 // receiver exist
346 if(bidder || bidder_accId)
348 std::ostringstream msgAuctionWonSubject;
349 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
351 std::ostringstream msgAuctionWonBody;
352 msgAuctionWonBody.width(16);
353 msgAuctionWonBody << std::right << std::hex << auction->owner;
354 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
355 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
357 //prepare mail data... :
358 uint32 itemTextId = this->CreateItemText( msgAuctionWonBody.str() );
360 // set owner to bidder (to prevent delete item with sender char deleting)
361 // owner in `data` will set at mail receive and item extracting
362 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
363 CharacterDatabase.CommitTransaction();
365 MailItemsInfo mi;
366 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
368 if (bidder)
369 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
370 else
371 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
373 // will delete item or place to receiver mail list
374 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
376 // receiver not exist
377 else
379 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
380 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
381 delete pItem;
385 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
387 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
388 Player *owner = GetPlayer(owner_guid);
390 // owner exist (online or offline)
391 if(owner || GetPlayerAccountIdByGUID(owner_guid))
393 std::ostringstream msgAuctionSalePendingSubject;
394 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
396 std::ostringstream msgAuctionSalePendingBody;
397 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
399 time_t distrTime = time(NULL) + HOUR;
401 msgAuctionSalePendingBody.width(16);
402 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
403 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
404 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
405 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
407 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
409 uint32 itemTextId = this->CreateItemText( msgAuctionSalePendingBody.str() );
411 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
415 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
416 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
418 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
419 Player *owner = GetPlayer(owner_guid);
421 uint32 owner_accId = 0;
422 if(!owner)
423 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
425 // owner exist
426 if(owner || owner_accId)
428 std::ostringstream msgAuctionSuccessfulSubject;
429 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
431 std::ostringstream auctionSuccessfulBody;
432 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
434 auctionSuccessfulBody.width(16);
435 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
436 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
437 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
439 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
441 uint32 itemTextId = this->CreateItemText( auctionSuccessfulBody.str() );
443 uint32 profit = auction->bid + auction->deposit - auctionCut;
445 if (owner)
447 //send auction owner notification, bidder must be current!
448 owner->GetSession()->SendAuctionOwnerNotification( auction );
451 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
455 //does not clear ram
456 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
457 { //return an item in auction to its owner by mail
458 Item *pItem = GetAItem(auction->item_guidlow);
459 if(!pItem)
461 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
462 return;
465 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
466 Player *owner = GetPlayer(owner_guid);
468 uint32 owner_accId = 0;
469 if(!owner)
470 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
472 // owner exist
473 if(owner || owner_accId)
475 std::ostringstream subject;
476 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
478 if ( owner )
479 owner->GetSession()->SendAuctionOwnerNotification( auction );
480 else
481 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
483 MailItemsInfo mi;
484 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
486 // will delete item or place to receiver mail list
487 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
489 // owner not found
490 else
492 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
493 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
494 delete pItem;
498 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
500 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
503 void ObjectMgr::LoadCreatureLocales()
505 mCreatureLocaleMap.clear(); // need for reload case
507 QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,subname_loc1,name_loc2,subname_loc2,name_loc3,subname_loc3,name_loc4,subname_loc4,name_loc5,subname_loc5,name_loc6,subname_loc6,name_loc7,subname_loc7,name_loc8,subname_loc8 FROM locales_creature");
509 if(!result)
511 barGoLink bar(1);
513 bar.step();
515 sLog.outString("");
516 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
517 return;
520 barGoLink bar(result->GetRowCount());
524 Field *fields = result->Fetch();
525 bar.step();
527 uint32 entry = fields[0].GetUInt32();
529 CreatureLocale& data = mCreatureLocaleMap[entry];
531 for(int i = 1; i < MAX_LOCALE; ++i)
533 std::string str = fields[1+2*(i-1)].GetCppString();
534 if(!str.empty())
536 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
537 if(idx >= 0)
539 if(data.Name.size() <= idx)
540 data.Name.resize(idx+1);
542 data.Name[idx] = str;
545 str = fields[1+2*(i-1)+1].GetCppString();
546 if(!str.empty())
548 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
549 if(idx >= 0)
551 if(data.SubName.size() <= idx)
552 data.SubName.resize(idx+1);
554 data.SubName[idx] = str;
558 } while (result->NextRow());
560 delete result;
562 sLog.outString();
563 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
566 void ObjectMgr::LoadCreatureTemplates()
568 sCreatureStorage.Load();
570 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
571 sLog.outString();
573 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
574 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
576 // check data correctness
577 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
579 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
580 if(!cInfo)
581 continue;
583 if(cInfo->HeroicEntry)
585 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
586 if(!heroicInfo)
588 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
589 continue;
592 if(heroicEntries.find(i)!=heroicEntries.end())
594 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
595 continue;
598 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
600 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
601 continue;
604 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
606 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
607 continue;
610 if(cInfo->npcflag != heroicInfo->npcflag)
612 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
613 continue;
616 if(cInfo->classNum != heroicInfo->classNum)
618 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
619 continue;
622 if(cInfo->race != heroicInfo->race)
624 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
625 continue;
628 if(cInfo->trainer_type != heroicInfo->trainer_type)
630 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
631 continue;
634 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
636 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
637 continue;
640 hasHeroicEntries.insert(i);
641 heroicEntries.insert(cInfo->HeroicEntry);
644 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
645 if(!factionTemplate)
646 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
648 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
649 if(!factionTemplate)
650 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
652 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
653 if (!minfo)
654 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
655 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
656 if (!minfo)
657 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
659 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
661 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
662 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
665 if(cInfo->baseattacktime == 0)
666 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
668 if(cInfo->rangeattacktime == 0)
669 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
671 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
672 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
674 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
676 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
677 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
680 if(cInfo->PetSpellDataId)
682 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
683 if(!spellDataId)
684 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
687 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
689 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
690 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
693 if(cInfo->equipmentId > 0) // 0 no equipment
695 if(!GetEquipmentInfo(cInfo->equipmentId))
697 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);
698 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
702 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
703 if(cInfo->scale <= 0.0f)
705 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
706 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
711 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
713 // Now add the auras, format "spellid effectindex spellid effectindex..."
714 char *p,*s;
715 std::vector<int> val;
716 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
717 if(p)
719 while (p[0]!=0)
721 ++p;
722 if (p[0]==' ')
724 val.push_back(atoi(s));
725 s=++p;
728 if (p!=s)
729 val.push_back(atoi(s));
731 // free char* loaded memory
732 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
734 // wrong list
735 if (val.size()%2)
737 addon->auras = NULL;
738 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
739 return;
743 // empty list
744 if(val.empty())
746 addon->auras = NULL;
747 return;
750 // replace by new strucutres array
751 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
753 int i=0;
754 for(int j=0;j<val.size()/2;++j)
756 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
757 cAura.spell_id = (uint32)val[2*j+0];
758 cAura.effect_idx = (uint32)val[2*j+1];
759 if ( cAura.effect_idx > 2 )
761 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);
762 continue;
764 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
765 if (!AdditionalSpellInfo)
767 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
768 continue;
771 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
773 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);
774 continue;
777 ++i;
780 // fill terminator element (after last added)
781 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
782 endAura.spell_id = 0;
783 endAura.effect_idx = 0;
786 void ObjectMgr::LoadCreatureAddons()
788 sCreatureInfoAddonStorage.Load();
790 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
791 sLog.outString();
793 // check data correctness and convert 'auras'
794 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
796 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
797 if(!addon)
798 continue;
800 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
802 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
803 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
806 sCreatureDataAddonStorage.Load();
808 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
809 sLog.outString();
811 // check data correctness and convert 'auras'
812 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
814 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
815 if(!addon)
816 continue;
818 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
820 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
821 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
825 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
827 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
830 void ObjectMgr::LoadEquipmentTemplates()
832 sEquipmentStorage.Load();
834 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
835 sLog.outString();
838 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
840 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
843 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
845 // Load creature model (display id)
846 uint32 display_id;
847 if (!data || data->displayid == 0) // use defaults from the template
849 // DisplayID_A is used if no team is given
850 if (team == HORDE)
851 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
852 else
853 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
855 else // overriden in creature data
856 display_id = data->displayid;
858 return display_id;
861 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
863 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
864 if(!minfo)
865 return NULL;
867 // If a model for another gender exists, 50% chance to use it
868 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
870 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
871 if(!minfo_tmp)
873 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
874 return minfo; // not fatal, just use the previous one
876 else
877 return minfo_tmp;
879 else
880 return minfo;
883 void ObjectMgr::LoadCreatureModelInfo()
885 sCreatureModelStorage.Load();
887 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
888 sLog.outString();
891 void ObjectMgr::LoadCreatures()
893 uint32 count = 0;
894 // 0 1 2 3
895 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
896 // 4 5 6 7 8 9 10 11
897 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
898 // 12 13 14 15 16 17
899 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
900 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
902 if(!result)
904 barGoLink bar(1);
906 bar.step();
908 sLog.outString("");
909 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
910 return;
913 // build single time for check creature data
914 std::set<uint32> heroicCreatures;
915 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
916 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
917 if(cInfo->HeroicEntry)
918 heroicCreatures.insert(cInfo->HeroicEntry);
920 barGoLink bar(result->GetRowCount());
924 Field *fields = result->Fetch();
925 bar.step();
927 uint32 guid = fields[0].GetUInt32();
929 CreatureData& data = mCreatureDataMap[guid];
931 data.id = fields[ 1].GetUInt32();
932 data.mapid = fields[ 2].GetUInt32();
933 data.displayid = fields[ 3].GetUInt32();
934 data.equipmentId = fields[ 4].GetUInt32();
935 data.posX = fields[ 5].GetFloat();
936 data.posY = fields[ 6].GetFloat();
937 data.posZ = fields[ 7].GetFloat();
938 data.orientation = fields[ 8].GetFloat();
939 data.spawntimesecs = fields[ 9].GetUInt32();
940 data.spawndist = fields[10].GetFloat();
941 data.currentwaypoint= fields[11].GetUInt32();
942 data.curhealth = fields[12].GetUInt32();
943 data.curmana = fields[13].GetUInt32();
944 data.is_dead = fields[14].GetBool();
945 data.movementType = fields[15].GetUInt8();
946 data.spawnMask = fields[16].GetUInt8();
947 int16 gameEvent = fields[17].GetInt16();
949 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
950 if(!cInfo)
952 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
953 continue;
956 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
958 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
959 continue;
962 if(data.equipmentId > 0) // -1 no equipment, 0 use default
964 if(!GetEquipmentInfo(data.equipmentId))
966 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);
967 data.equipmentId = -1;
971 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
973 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 );
974 data.curhealth = cInfo->minhealth;
977 if(data.curmana < cInfo->minmana)
979 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 );
980 data.curmana = cInfo->minmana;
983 if(data.spawndist < 0.0f)
985 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
986 data.spawndist = 0.0f;
988 else if(data.movementType == RANDOM_MOTION_TYPE)
990 if(data.spawndist == 0.0f)
992 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 );
993 data.movementType = IDLE_MOTION_TYPE;
996 else if(data.movementType == IDLE_MOTION_TYPE)
998 if(data.spawndist != 0.0f)
1000 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1001 data.spawndist = 0.0f;
1005 if (gameEvent==0) // if not this is to be managed by GameEvent System
1006 AddCreatureToGrid(guid, &data);
1007 ++count;
1009 } while (result->NextRow());
1011 delete result;
1013 sLog.outString();
1014 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1017 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1019 uint8 mask = data->spawnMask;
1020 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1022 if(mask & 1)
1024 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1025 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1027 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1028 cell_guids.creatures.insert(guid);
1033 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1035 uint8 mask = data->spawnMask;
1036 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1038 if(mask & 1)
1040 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1041 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1043 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1044 cell_guids.creatures.erase(guid);
1049 void ObjectMgr::LoadGameobjects()
1051 uint32 count = 0;
1053 // 0 1 2 3 4 5 6
1054 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1055 // 7 8 9 10 11 12 13 14 15
1056 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1057 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1059 if(!result)
1061 barGoLink bar(1);
1063 bar.step();
1065 sLog.outString();
1066 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1067 return;
1070 barGoLink bar(result->GetRowCount());
1074 Field *fields = result->Fetch();
1075 bar.step();
1077 uint32 guid = fields[0].GetUInt32();
1079 GameObjectData& data = mGameObjectDataMap[guid];
1081 data.id = fields[ 1].GetUInt32();
1082 data.mapid = fields[ 2].GetUInt32();
1083 data.posX = fields[ 3].GetFloat();
1084 data.posY = fields[ 4].GetFloat();
1085 data.posZ = fields[ 5].GetFloat();
1086 data.orientation = fields[ 6].GetFloat();
1087 data.rotation0 = fields[ 7].GetFloat();
1088 data.rotation1 = fields[ 8].GetFloat();
1089 data.rotation2 = fields[ 9].GetFloat();
1090 data.rotation3 = fields[10].GetFloat();
1091 data.spawntimesecs = fields[11].GetInt32();
1092 data.animprogress = fields[12].GetUInt32();
1093 data.go_state = fields[13].GetUInt32();
1094 data.spawnMask = fields[14].GetUInt8();
1095 int16 gameEvent = fields[15].GetInt16();
1097 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1098 if(!gInfo)
1100 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1101 continue;
1104 if (gameEvent==0) // if not this is to be managed by GameEvent System
1105 AddGameobjectToGrid(guid, &data);
1106 ++count;
1108 } while (result->NextRow());
1110 delete result;
1112 sLog.outString();
1113 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1116 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1118 uint8 mask = data->spawnMask;
1119 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1121 if(mask & 1)
1123 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1124 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1126 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1127 cell_guids.gameobjects.insert(guid);
1132 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1134 uint8 mask = data->spawnMask;
1135 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1137 if(mask & 1)
1139 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1140 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1142 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1143 cell_guids.gameobjects.erase(guid);
1148 void ObjectMgr::LoadCreatureRespawnTimes()
1150 // remove outdated data
1151 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1153 uint32 count = 0;
1155 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1157 if(!result)
1159 barGoLink bar(1);
1161 bar.step();
1163 sLog.outString();
1164 sLog.outString(">> Loaded 0 creature respawn time.");
1165 return;
1168 barGoLink bar(result->GetRowCount());
1172 Field *fields = result->Fetch();
1173 bar.step();
1175 uint32 loguid = fields[0].GetUInt32();
1176 uint64 respawn_time = fields[1].GetUInt64();
1177 uint32 instance = fields[2].GetUInt32();
1179 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1181 ++count;
1182 } while (result->NextRow());
1184 delete result;
1186 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1187 sLog.outString();
1190 void ObjectMgr::LoadGameobjectRespawnTimes()
1192 // remove outdated data
1193 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1195 uint32 count = 0;
1197 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1199 if(!result)
1201 barGoLink bar(1);
1203 bar.step();
1205 sLog.outString();
1206 sLog.outString(">> Loaded 0 gameobject respawn time.");
1207 return;
1210 barGoLink bar(result->GetRowCount());
1214 Field *fields = result->Fetch();
1215 bar.step();
1217 uint32 loguid = fields[0].GetUInt32();
1218 uint64 respawn_time = fields[1].GetUInt64();
1219 uint32 instance = fields[2].GetUInt32();
1221 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1223 ++count;
1224 } while (result->NextRow());
1226 delete result;
1228 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1229 sLog.outString();
1232 // name must be checked to correctness (if received) before call this function
1233 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1235 uint64 guid = 0;
1237 CharacterDatabase.escape_string(name);
1239 // Player name safe to sending to DB (checked at login) and this function using
1240 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1241 if(result)
1243 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1245 delete result;
1248 return guid;
1251 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1253 // prevent DB access for online player
1254 if(Player* player = GetPlayer(guid))
1256 name = player->GetName();
1257 return true;
1260 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1262 if(result)
1264 name = (*result)[0].GetCppString();
1265 delete result;
1266 return true;
1269 return false;
1272 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1274 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1276 if(result)
1278 uint8 race = (*result)[0].GetUInt8();
1279 delete result;
1280 return Player::TeamForRace(race);
1283 return 0;
1286 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1288 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1289 if(result)
1291 uint32 acc = (*result)[0].GetUInt32();
1292 delete result;
1293 return acc;
1296 return 0;
1299 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(std::string name) const
1301 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1302 if(result)
1304 uint32 acc = (*result)[0].GetUInt32();
1305 delete result;
1306 return acc;
1309 return 0;
1312 void ObjectMgr::LoadAuctions()
1314 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1315 if( !result )
1316 return;
1318 Field *fields = result->Fetch();
1319 uint32 AuctionCount=fields[0].GetUInt32();
1320 delete result;
1322 if(!AuctionCount)
1323 return;
1325 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1326 if( !result )
1327 return;
1329 barGoLink bar( AuctionCount );
1331 AuctionEntry *aItem;
1335 fields = result->Fetch();
1337 bar.step();
1339 aItem = new AuctionEntry;
1340 aItem->Id = fields[0].GetUInt32();
1341 aItem->auctioneer = fields[1].GetUInt32();
1342 aItem->item_guidlow = fields[2].GetUInt32();
1343 aItem->item_template = fields[3].GetUInt32();
1344 aItem->owner = fields[4].GetUInt32();
1345 aItem->buyout = fields[5].GetUInt32();
1346 aItem->time = fields[6].GetUInt32();
1347 aItem->bidder = fields[7].GetUInt32();
1348 aItem->bid = fields[8].GetUInt32();
1349 aItem->startbid = fields[9].GetUInt32();
1350 aItem->deposit = fields[10].GetUInt32();
1351 aItem->location = fields[11].GetUInt8();
1352 //check if sold item exists
1353 if ( this->GetAItem( aItem->item_guidlow ) )
1355 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1357 else
1359 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1360 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1361 delete aItem;
1363 } while (result->NextRow());
1364 delete result;
1366 sLog.outString();
1367 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1368 sLog.outString();
1371 void ObjectMgr::LoadItemLocales()
1373 mItemLocaleMap.clear(); // need for reload case
1375 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");
1377 if(!result)
1379 barGoLink bar(1);
1381 bar.step();
1383 sLog.outString("");
1384 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1385 return;
1388 barGoLink bar(result->GetRowCount());
1392 Field *fields = result->Fetch();
1393 bar.step();
1395 uint32 entry = fields[0].GetUInt32();
1397 ItemLocale& data = mItemLocaleMap[entry];
1399 for(int i = 1; i < MAX_LOCALE; ++i)
1401 std::string str = fields[1+2*(i-1)].GetCppString();
1402 if(!str.empty())
1404 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1405 if(idx >= 0)
1407 if(data.Name.size() <= idx)
1408 data.Name.resize(idx+1);
1410 data.Name[idx] = str;
1414 str = fields[1+2*(i-1)+1].GetCppString();
1415 if(!str.empty())
1417 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1418 if(idx >= 0)
1420 if(data.Description.size() <= idx)
1421 data.Description.resize(idx+1);
1423 data.Description[idx] = str;
1427 } while (result->NextRow());
1429 delete result;
1431 sLog.outString();
1432 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1435 void ObjectMgr::LoadItemPrototypes()
1437 sItemStorage.Load ();
1438 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1439 sLog.outString();
1441 // check data correctness
1442 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1444 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1445 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1446 if(!proto)
1448 /* to many errors, and possible not all items really used in game
1449 if (dbcitem)
1450 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1452 continue;
1455 if(dbcitem)
1457 if(proto->InventoryType != dbcitem->InventoryType)
1459 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1460 // It safe let use InventoryType from DB
1463 if(proto->DisplayInfoID != dbcitem->DisplayId)
1465 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1466 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1468 if(proto->Sheath != dbcitem->Sheath)
1470 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1471 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1474 else
1476 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1479 if(proto->Class >= MAX_ITEM_CLASS)
1481 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1482 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1485 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1487 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1488 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1491 if(proto->Quality >= MAX_ITEM_QUALITY)
1493 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1494 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1497 if(proto->BuyCount <= 0)
1499 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1500 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1503 if(proto->InventoryType >= MAX_INVTYPE)
1505 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1506 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1509 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1511 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1512 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1515 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1517 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1520 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1522 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1525 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1527 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1528 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1531 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1532 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1534 if(proto->RequiredReputationFaction)
1536 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1538 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1539 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1542 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1543 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1545 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1546 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1548 if(proto->Stackable==0)
1550 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1551 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1553 else if(proto->Stackable > 255)
1555 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1556 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1559 for (int j = 0; j < 10; j++)
1561 // for ItemStatValue != 0
1562 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1564 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1565 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1569 for (int j = 0; j < 5; j++)
1571 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1573 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1574 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1578 // special format
1579 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1581 // spell_1
1582 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1584 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);
1585 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1586 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1587 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1588 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1591 // spell_2 have learning spell
1592 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1594 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);
1595 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1596 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1597 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1599 else if(!proto->Spells[1].SpellId)
1601 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1602 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1603 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1605 else
1607 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1608 if(!spellInfo)
1610 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1611 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1612 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1613 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1615 // allowed only in special format
1616 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1618 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1619 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1620 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1621 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1625 // spell_3*,spell_4*,spell_5* is empty
1626 for (int j = 2; j < 5; j++)
1628 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1630 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1631 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1632 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1634 else if(proto->Spells[j].SpellId != 0)
1636 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1637 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1641 // normal spell list
1642 else
1644 for (int j = 0; j < 5; j++)
1646 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1648 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1649 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1650 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1653 if(proto->Spells[j].SpellId)
1655 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1656 if(!spellInfo)
1658 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1659 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1661 // allowed only in special format
1662 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1664 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1665 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1671 if(proto->Bonding >= MAX_BIND_TYPE)
1672 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1674 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1675 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1677 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1678 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1680 if(proto->Sheath >= MAX_SHEATHETYPE)
1682 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1683 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1686 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1688 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1689 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1692 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1694 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1695 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1698 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1700 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1701 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1704 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1705 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1707 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1708 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1710 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1711 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1713 for (int j = 0; j < 3; j++)
1715 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1717 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1718 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1722 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1723 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1725 if(proto->FoodType >= MAX_PET_DIET)
1727 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1728 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1732 // this DBC used currently only for check item templates in DB.
1733 sItemStore.Clear();
1736 void ObjectMgr::LoadAuctionItems()
1738 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1740 if( !result )
1741 return;
1743 barGoLink bar( result->GetRowCount() );
1745 uint32 count = 0;
1747 Field *fields;
1750 bar.step();
1752 fields = result->Fetch();
1753 uint32 item_guid = fields[0].GetUInt32();
1754 uint32 item_template = fields[1].GetUInt32();
1756 ItemPrototype const *proto = GetItemPrototype(item_template);
1758 if(!proto)
1760 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1761 continue;
1764 Item *item = NewItemOrBag(proto);
1766 if(!item->LoadFromDB(item_guid,0))
1768 delete item;
1769 continue;
1771 AddAItem(item);
1773 ++count;
1775 while( result->NextRow() );
1777 delete result;
1779 sLog.outString();
1780 sLog.outString( ">> Loaded %u auction items", count );
1783 void ObjectMgr::LoadPetLevelInfo()
1785 // Loading levels data
1787 // 0 1 2 3 4 5 6 7 8 9
1788 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1790 uint32 count = 0;
1792 if (!result)
1794 barGoLink bar( 1 );
1796 sLog.outString();
1797 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1798 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1799 return;
1802 barGoLink bar( result->GetRowCount() );
1806 Field* fields = result->Fetch();
1808 uint32 creature_id = fields[0].GetUInt32();
1809 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1811 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1812 continue;
1815 uint32 current_level = fields[1].GetUInt32();
1816 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1818 if(current_level > 255) // hardcoded level maximum
1819 sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1820 else
1821 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1822 continue;
1824 else if(current_level < 1)
1826 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1827 continue;
1830 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1832 if(pInfoMapEntry==NULL)
1833 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1835 // data for level 1 stored in [0] array element, ...
1836 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1838 pLevelInfo->health = fields[2].GetUInt16();
1839 pLevelInfo->mana = fields[3].GetUInt16();
1840 pLevelInfo->armor = fields[9].GetUInt16();
1842 for (int i = 0; i < MAX_STATS; i++)
1844 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1847 bar.step();
1848 ++count;
1850 while (result->NextRow());
1852 delete result;
1854 sLog.outString();
1855 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1858 // Fill gaps and check integrity
1859 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1861 PetLevelInfo* pInfo = itr->second;
1863 // fatal error if no level 1 data
1864 if(!pInfo || pInfo[0].health == 0 )
1866 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1867 exit(1);
1870 // fill level gaps
1871 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1873 if(pInfo[level].health == 0)
1875 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1876 pInfo[level] = pInfo[level-1];
1882 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1884 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1885 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1887 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1888 if(itr == petInfo.end())
1889 return NULL;
1891 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1894 void ObjectMgr::LoadPlayerInfo()
1896 // Load playercreate
1898 // 0 1 2 3 4 5 6
1899 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1901 uint32 count = 0;
1903 if (!result)
1905 barGoLink bar( 1 );
1907 sLog.outString();
1908 sLog.outString( ">> Loaded %u player create definitions", count );
1909 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1910 exit(1);
1913 barGoLink bar( result->GetRowCount() );
1917 Field* fields = result->Fetch();
1919 uint32 current_race = fields[0].GetUInt32();
1920 uint32 current_class = fields[1].GetUInt32();
1921 uint32 mapId = fields[2].GetUInt32();
1922 uint32 zoneId = fields[3].GetUInt32();
1923 float positionX = fields[4].GetFloat();
1924 float positionY = fields[5].GetFloat();
1925 float positionZ = fields[6].GetFloat();
1927 if(current_race >= MAX_RACES)
1929 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1930 continue;
1933 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1934 if(!rEntry)
1936 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1937 continue;
1940 if(current_class >= MAX_CLASSES)
1942 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1943 continue;
1946 if(!sChrClassesStore.LookupEntry(current_class))
1948 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1949 continue;
1952 // accept DB data only for valid position (and non instanceable)
1953 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1955 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1956 continue;
1959 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1961 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1962 continue;
1965 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1967 pInfo->mapId = mapId;
1968 pInfo->zoneId = zoneId;
1969 pInfo->positionX = positionX;
1970 pInfo->positionY = positionY;
1971 pInfo->positionZ = positionZ;
1973 pInfo->displayId_m = rEntry->model_m;
1974 pInfo->displayId_f = rEntry->model_f;
1976 bar.step();
1977 ++count;
1979 while (result->NextRow());
1981 delete result;
1983 sLog.outString();
1984 sLog.outString( ">> Loaded %u player create definitions", count );
1987 // Load playercreate items
1989 // 0 1 2 3
1990 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
1992 uint32 count = 0;
1994 if (!result)
1996 barGoLink bar( 1 );
1998 sLog.outString();
1999 sLog.outString( ">> Loaded %u player create items", count );
2000 sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2002 else
2004 barGoLink bar( result->GetRowCount() );
2008 Field* fields = result->Fetch();
2010 uint32 current_race = fields[0].GetUInt32();
2011 if(current_race >= MAX_RACES)
2013 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2014 continue;
2017 uint32 current_class = fields[1].GetUInt32();
2018 if(current_class >= MAX_CLASSES)
2020 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2021 continue;
2024 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2026 uint32 item_id = fields[2].GetUInt32();
2028 if(!GetItemPrototype(item_id))
2030 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);
2031 continue;
2034 uint32 amount = fields[3].GetUInt32();
2036 if(!amount)
2038 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2039 continue;
2042 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2044 bar.step();
2045 ++count;
2047 while(result->NextRow());
2049 delete result;
2051 sLog.outString();
2052 sLog.outString( ">> Loaded %u player create items", count );
2056 // Load playercreate spells
2058 // 0 1 2 3
2059 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2061 uint32 count = 0;
2063 if (!result)
2065 barGoLink bar( 1 );
2067 sLog.outString();
2068 sLog.outString( ">> Loaded %u player create spells", count );
2069 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2071 else
2073 barGoLink bar( result->GetRowCount() );
2077 Field* fields = result->Fetch();
2079 uint32 current_race = fields[0].GetUInt32();
2080 if(current_race >= MAX_RACES)
2082 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2083 continue;
2086 uint32 current_class = fields[1].GetUInt32();
2087 if(current_class >= MAX_CLASSES)
2089 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2090 continue;
2093 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2094 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2096 bar.step();
2097 ++count;
2099 while( result->NextRow() );
2101 delete result;
2103 sLog.outString();
2104 sLog.outString( ">> Loaded %u player create spells", count );
2108 // Load playercreate actions
2110 // 0 1 2 3 4 5
2111 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2113 uint32 count = 0;
2115 if (!result)
2117 barGoLink bar( 1 );
2119 sLog.outString();
2120 sLog.outString( ">> Loaded %u player create actions", count );
2121 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2123 else
2125 barGoLink bar( result->GetRowCount() );
2129 Field* fields = result->Fetch();
2131 uint32 current_race = fields[0].GetUInt32();
2132 if(current_race >= MAX_RACES)
2134 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2135 continue;
2138 uint32 current_class = fields[1].GetUInt32();
2139 if(current_class >= MAX_CLASSES)
2141 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2142 continue;
2145 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2146 pInfo->action[0].push_back(fields[2].GetUInt16());
2147 pInfo->action[1].push_back(fields[3].GetUInt16());
2148 pInfo->action[2].push_back(fields[4].GetUInt16());
2149 pInfo->action[3].push_back(fields[5].GetUInt16());
2151 bar.step();
2152 ++count;
2154 while( result->NextRow() );
2156 delete result;
2158 sLog.outString();
2159 sLog.outString( ">> Loaded %u player create actions", count );
2163 // Loading levels data (class only dependent)
2165 // 0 1 2 3
2166 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2168 uint32 count = 0;
2170 if (!result)
2172 barGoLink bar( 1 );
2174 sLog.outString();
2175 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2176 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2177 exit(1);
2180 barGoLink bar( result->GetRowCount() );
2184 Field* fields = result->Fetch();
2186 uint32 current_class = fields[0].GetUInt32();
2187 if(current_class >= MAX_CLASSES)
2189 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2190 continue;
2193 uint32 current_level = fields[1].GetUInt32();
2194 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2196 if(current_level > 255) // hardcoded level maximum
2197 sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2198 else
2199 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2200 continue;
2203 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2205 if(!pClassInfo->levelInfo)
2206 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2208 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2210 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2211 pClassLevelInfo->basemana = fields[3].GetUInt16();
2213 bar.step();
2214 ++count;
2216 while (result->NextRow());
2218 delete result;
2220 sLog.outString();
2221 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2224 // Fill gaps and check integrity
2225 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2227 // skip non existed classes
2228 if(!sChrClassesStore.LookupEntry(class_))
2229 continue;
2231 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2233 // fatal error if no level 1 data
2234 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2236 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2237 exit(1);
2240 // fill level gaps
2241 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2243 if(pClassInfo->levelInfo[level].basehealth == 0)
2245 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2246 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2251 // Loading levels data (class/race dependent)
2253 // 0 1 2 3 4 5 6 7
2254 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2256 uint32 count = 0;
2258 if (!result)
2260 barGoLink bar( 1 );
2262 sLog.outString();
2263 sLog.outString( ">> Loaded %u level stats definitions", count );
2264 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2265 exit(1);
2268 barGoLink bar( result->GetRowCount() );
2272 Field* fields = result->Fetch();
2274 uint32 current_race = fields[0].GetUInt32();
2275 if(current_race >= MAX_RACES)
2277 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2278 continue;
2281 uint32 current_class = fields[1].GetUInt32();
2282 if(current_class >= MAX_CLASSES)
2284 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2285 continue;
2288 uint32 current_level = fields[2].GetUInt32();
2289 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2291 if(current_level > 255) // hardcoded level maximum
2292 sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2293 else
2294 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2295 continue;
2298 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2300 if(!pInfo->levelInfo)
2301 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2303 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2305 for (int i = 0; i < MAX_STATS; i++)
2307 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2310 bar.step();
2311 ++count;
2313 while (result->NextRow());
2315 delete result;
2317 sLog.outString();
2318 sLog.outString( ">> Loaded %u level stats definitions", count );
2321 // Fill gaps and check integrity
2322 for (int race = 0; race < MAX_RACES; ++race)
2324 // skip non existed races
2325 if(!sChrRacesStore.LookupEntry(race))
2326 continue;
2328 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2330 // skip non existed classes
2331 if(!sChrClassesStore.LookupEntry(class_))
2332 continue;
2334 PlayerInfo* pInfo = &playerInfo[race][class_];
2336 // skip non loaded combinations
2337 if(!pInfo->displayId_m || !pInfo->displayId_f)
2338 continue;
2340 // skip expansion races if not playing with expansion
2341 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2342 continue;
2344 // skip expansion classes if not playing with expansion
2345 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2346 continue;
2348 // fatal error if no level 1 data
2349 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2351 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2352 exit(1);
2355 // fill level gaps
2356 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2358 if(pInfo->levelInfo[level].stats[0] == 0)
2360 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2361 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2368 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2370 if(level < 1 || class_ >= MAX_CLASSES)
2371 return;
2373 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2375 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2376 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2378 *info = pInfo->levelInfo[level-1];
2381 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2383 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2384 return;
2386 PlayerInfo const* pInfo = &playerInfo[race][class_];
2387 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2388 return;
2390 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2391 *info = pInfo->levelInfo[level-1];
2392 else
2393 BuildPlayerLevelInfo(race,class_,level,info);
2396 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2398 // base data (last known level)
2399 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2401 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2403 switch(_class)
2405 case CLASS_WARRIOR:
2406 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2407 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2408 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2409 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2410 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2411 break;
2412 case CLASS_PALADIN:
2413 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2414 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2415 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2416 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2417 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2418 break;
2419 case CLASS_HUNTER:
2420 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2421 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2422 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2423 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2424 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2425 break;
2426 case CLASS_ROGUE:
2427 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2428 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2429 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2430 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2431 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2432 break;
2433 case CLASS_PRIEST:
2434 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2435 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2436 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2437 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2438 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2439 break;
2440 case CLASS_SHAMAN:
2441 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2442 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2443 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2444 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2445 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2446 break;
2447 case CLASS_MAGE:
2448 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2449 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2450 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2451 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2452 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2453 break;
2454 case CLASS_WARLOCK:
2455 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2456 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2457 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2458 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2459 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2460 break;
2461 case CLASS_DRUID:
2462 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2463 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2464 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2465 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2466 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2471 void ObjectMgr::LoadGuilds()
2473 Guild *newguild;
2474 uint32 count = 0;
2476 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2478 if( !result )
2481 barGoLink bar( 1 );
2483 bar.step();
2485 sLog.outString();
2486 sLog.outString( ">> Loaded %u guild definitions", count );
2487 return;
2490 barGoLink bar( result->GetRowCount() );
2494 Field *fields = result->Fetch();
2496 bar.step();
2497 ++count;
2499 newguild = new Guild;
2500 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2502 newguild->Disband();
2503 delete newguild;
2504 continue;
2506 AddGuild(newguild);
2508 }while( result->NextRow() );
2510 delete result;
2512 sLog.outString();
2513 sLog.outString( ">> Loaded %u guild definitions", count );
2516 void ObjectMgr::LoadArenaTeams()
2518 uint32 count = 0;
2520 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2522 if( !result )
2525 barGoLink bar( 1 );
2527 bar.step();
2529 sLog.outString();
2530 sLog.outString( ">> Loaded %u arenateam definitions", count );
2531 return;
2534 barGoLink bar( result->GetRowCount() );
2538 Field *fields = result->Fetch();
2540 bar.step();
2541 ++count;
2543 ArenaTeam *newarenateam = new ArenaTeam;
2544 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2546 delete newarenateam;
2547 continue;
2549 AddArenaTeam(newarenateam);
2550 }while( result->NextRow() );
2552 delete result;
2554 sLog.outString();
2555 sLog.outString( ">> Loaded %u arenateam definitions", count );
2558 void ObjectMgr::LoadGroups()
2560 // -- loading groups --
2561 Group *group = NULL;
2562 uint64 leaderGuid = 0;
2563 uint32 count = 0;
2564 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2565 QueryResult *result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2567 if( !result )
2569 barGoLink bar( 1 );
2571 bar.step();
2573 sLog.outString();
2574 sLog.outString( ">> Loaded %u group definitions", count );
2575 return;
2578 barGoLink bar( result->GetRowCount() );
2582 bar.step();
2583 Field *fields = result->Fetch();
2584 ++count;
2585 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2587 group = new Group;
2588 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2590 group->Disband();
2591 delete group;
2592 continue;
2594 AddGroup(group);
2595 }while( result->NextRow() );
2597 delete result;
2599 sLog.outString();
2600 sLog.outString( ">> Loaded %u group definitions", count );
2602 // -- loading members --
2603 count = 0;
2604 group = NULL;
2605 leaderGuid = 0;
2606 // 0 1 2 3
2607 result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2608 if(!result)
2610 barGoLink bar( 1 );
2611 bar.step();
2613 else
2615 barGoLink bar( result->GetRowCount() );
2618 bar.step();
2619 Field *fields = result->Fetch();
2620 count++;
2621 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2622 if(!group || group->GetLeaderGUID() != leaderGuid)
2624 group = GetGroupByLeader(leaderGuid);
2625 if(!group)
2627 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2628 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2629 continue;
2633 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2635 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2636 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2638 }while( result->NextRow() );
2639 delete result;
2642 // clean groups
2643 // TODO: maybe delete from the DB before loading in this case
2644 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2646 if((*itr)->GetMembersCount() < 2)
2648 (*itr)->Disband();
2649 delete *itr;
2650 mGroupSet.erase(itr++);
2652 else
2653 ++itr;
2656 // -- loading instances --
2657 count = 0;
2658 group = NULL;
2659 leaderGuid = 0;
2660 result = CharacterDatabase.PQuery(
2661 // 0 1 2 3 4 5
2662 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2663 // 6
2664 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2665 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2668 if(!result)
2670 barGoLink bar( 1 );
2671 bar.step();
2673 else
2675 barGoLink bar( result->GetRowCount() );
2678 bar.step();
2679 Field *fields = result->Fetch();
2680 count++;
2681 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2682 if(!group || group->GetLeaderGUID() != leaderGuid)
2684 group = GetGroupByLeader(leaderGuid);
2685 if(!group)
2687 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2688 continue;
2692 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2693 group->BindToInstance(save, fields[3].GetBool(), true);
2694 }while( result->NextRow() );
2695 delete result;
2698 sLog.outString();
2699 sLog.outString( ">> Loaded %u group-instance binds total", count );
2701 sLog.outString();
2702 sLog.outString( ">> Loaded %u group members total", count );
2705 void ObjectMgr::LoadQuests()
2707 // For reload case
2708 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2709 delete itr->second;
2710 mQuestTemplates.clear();
2712 mExclusiveQuestGroups.clear();
2714 // 0 1 2 3 4 5 6 7 8
2715 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2716 // 9 10 11 12 13 14 15 16
2717 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2718 // 17 18 19 20 21 22 23 24 25 26
2719 "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2720 // 27 28 29 30 31 32 33 34 35 36
2721 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2722 // 37 38 39 40 41 42 43 44
2723 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2724 // 45 46 47 48 49 50 51 52 53 54 54 55
2725 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2726 // 57 58 59 60 61 62 63 64
2727 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2728 // 65 66 67 68
2729 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2730 // 69 70 71 72 73 74
2731 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2732 // 75 76 77 78 79 80
2733 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2734 // 81 82 83 84 85 86 87 88
2735 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2736 // 89 90 91 92 93 94 95 96 97 98
2737 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2738 // 99 100 101 102 103 104 105 106 107 108 109
2739 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2740 // 110 111 112 113 114 115 116 117 118 119
2741 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2742 // 120 121
2743 "StartScript, CompleteScript"
2744 " FROM quest_template");
2745 if(result == NULL)
2747 barGoLink bar( 1 );
2748 bar.step();
2750 sLog.outString();
2751 sLog.outString( ">> Loaded 0 quests definitions" );
2752 sLog.outErrorDb("`quest_template` table is empty!");
2753 return;
2756 // create multimap previous quest for each existed quest
2757 // some quests can have many previous maps set by NextQuestId in previous quest
2758 // for example set of race quests can lead to single not race specific quest
2759 barGoLink bar( result->GetRowCount() );
2762 bar.step();
2763 Field *fields = result->Fetch();
2765 Quest * newQuest = new Quest(fields);
2766 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2767 } while( result->NextRow() );
2769 delete result;
2771 // Post processing
2772 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2774 Quest * qinfo = iter->second;
2776 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2778 if( qinfo->GetQuestMethod() >= 3 )
2780 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2783 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2785 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2786 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2787 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2790 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2792 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2794 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2795 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2799 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2801 // at auto-reward can be rewarded only RewChoiceItemId[0]
2802 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2804 if(uint32 id = qinfo->RewChoiceItemId[j])
2806 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2807 qinfo->GetQuestId(),j+1,id,j+1);
2808 // no changes, quest ignore this data
2813 // client quest log visual (area case)
2814 if( qinfo->ZoneOrSort > 0 )
2816 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2818 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2819 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2820 // no changes, quest not dependent from this value but can have problems at client
2823 // client quest log visual (sort case)
2824 if( qinfo->ZoneOrSort < 0 )
2826 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2827 if( !qSort )
2829 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2830 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2831 // 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)
2833 //check SkillOrClass value (class case).
2834 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2836 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2837 if(qinfo->SkillOrClass < 0)
2839 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2840 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2843 //check for proper SkillOrClass value (skill case)
2844 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2846 // skill is positive value in SkillOrClass
2847 if(qinfo->SkillOrClass != skill_id )
2849 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2850 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2851 //override, and force proper value here?
2856 // SkillOrClass (class case)
2857 if( qinfo->SkillOrClass < 0 )
2859 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2861 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2862 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2865 // SkillOrClass (skill case)
2866 if( qinfo->SkillOrClass > 0 )
2868 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2870 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2871 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2875 if( qinfo->RequiredSkillValue )
2877 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2879 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2880 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2881 // no changes, quest can't be done for this requirement
2884 if( qinfo->SkillOrClass <= 0 )
2886 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2887 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2888 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2891 // else Skill quests can have 0 skill level, this is ok
2893 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2895 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2896 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2897 // no changes, quest can't be done for this requirement
2900 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2902 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2903 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2904 // no changes, quest can't be done for this requirement
2907 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2909 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2910 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2911 // no changes, quest can't be done for this requirement
2914 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2916 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2917 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2918 // no changes, quest can't be done for this requirement
2921 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2923 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2924 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2925 // no changes, quest can't be done for this requirement
2928 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2930 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2931 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2932 // warning
2935 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2937 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2938 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2939 // warning
2942 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2944 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2945 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2946 // warning
2949 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2951 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2952 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2953 qinfo->CharTitleId = 0;
2954 // quest can't reward this title
2957 if(qinfo->SrcItemId)
2959 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2961 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2962 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2963 qinfo->SrcItemId = 0; // quest can't be done for this requirement
2965 else if(qinfo->SrcItemCount==0)
2967 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2968 qinfo->GetQuestId(),qinfo->SrcItemId);
2969 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward comptibility with DB
2972 else if(qinfo->SrcItemCount>0)
2974 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
2975 qinfo->GetQuestId(),qinfo->SrcItemCount);
2976 qinfo->SrcItemCount=0; // no quest work changes in fact
2979 if(qinfo->SrcSpell)
2981 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
2982 if(!spellInfo)
2984 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
2985 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
2986 qinfo->SrcSpell = 0; // quest can't be done for this requirement
2988 else if(!SpellMgr::IsSpellValid(spellInfo))
2990 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
2991 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
2992 qinfo->SrcSpell = 0; // quest can't be done for this requirement
2996 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
2998 uint32 id = qinfo->ReqItemId[j];
2999 if(id)
3001 if(qinfo->ReqItemCount[j]==0)
3003 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3004 qinfo->GetQuestId(),j+1,id,j+1);
3005 // no changes, quest can't be done for this requirement
3008 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3010 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3012 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3013 qinfo->GetQuestId(),j+1,id,id);
3014 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3017 else if(qinfo->ReqItemCount[j]>0)
3019 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3020 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3021 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3025 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3027 uint32 id = qinfo->ReqSourceId[j];
3028 if(id)
3030 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3032 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3033 qinfo->GetQuestId(),j+1,id,id);
3034 // no changes, quest can't be done for this requirement
3037 if(!qinfo->ReqSourceCount[j])
3039 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3040 qinfo->GetQuestId(),j+1,id,j+1);
3041 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3044 if(!qinfo->ReqSourceRef[j])
3046 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3047 qinfo->GetQuestId(),j+1,id,j+1);
3048 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3051 else
3053 if(qinfo->ReqSourceCount[j]>0)
3055 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3056 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3057 // no changes, quest ignore this data
3060 if(qinfo->ReqSourceRef[j]>0)
3062 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3063 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3064 // no changes, quest ignore this data
3069 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3071 uint32 ref = qinfo->ReqSourceRef[j];
3072 if(ref)
3074 if(ref > QUEST_OBJECTIVES_COUNT)
3076 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3077 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3078 // no changes, quest can't be done for this requirement
3080 else
3081 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3083 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3084 qinfo->GetQuestId(),j+1,ref,ref,ref);
3085 // no changes, quest can't be done for this requirement
3087 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3089 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3090 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3091 // no changes, quest can't be done for this requirement
3092 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3097 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3099 uint32 id = qinfo->ReqSpell[j];
3100 if(id)
3102 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3103 if(!spellInfo)
3105 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3106 qinfo->GetQuestId(),j+1,id,id);
3107 // no changes, quest can't be done for this requirement
3110 if(!qinfo->ReqCreatureOrGOId[j])
3112 bool found = false;
3113 for(int k = 0; k < 3; ++k)
3115 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3116 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3118 found = true;
3119 break;
3123 if(found)
3125 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3127 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);
3129 // this will prevent quest completing without objective
3130 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3133 else
3135 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.",
3136 qinfo->GetQuestId(),j+1,id,j+1,id);
3137 // no changes, quest can't be done for this requirement
3143 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3145 int32 id = qinfo->ReqCreatureOrGOId[j];
3146 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3148 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3149 qinfo->GetQuestId(),j+1,id,uint32(-id));
3150 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3153 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3155 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3156 qinfo->GetQuestId(),j+1,id,uint32(id));
3157 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3160 if(id)
3162 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3164 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3166 if(!qinfo->ReqCreatureOrGOCount[j])
3168 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3169 qinfo->GetQuestId(),j+1,id,j+1);
3170 // no changes, quest can be incorrectly done, but we already report this
3173 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3175 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3176 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3177 // no changes, quest ignore this data
3181 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3183 uint32 id = qinfo->RewChoiceItemId[j];
3184 if(id)
3186 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3188 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3189 qinfo->GetQuestId(),j+1,id,id);
3190 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3193 if(!qinfo->RewChoiceItemCount[j])
3195 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3196 qinfo->GetQuestId(),j+1,id,j+1);
3197 // no changes, quest can't be done
3200 else if(qinfo->RewChoiceItemCount[j]>0)
3202 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3203 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3204 // no changes, quest ignore this data
3208 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3210 uint32 id = qinfo->RewItemId[j];
3211 if(id)
3213 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3215 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3216 qinfo->GetQuestId(),j+1,id,id);
3217 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3220 if(!qinfo->RewItemCount[j])
3222 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3223 qinfo->GetQuestId(),j+1,id,j+1);
3224 // no changes
3227 else if(qinfo->RewItemCount[j]>0)
3229 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3230 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3231 // no changes, quest ignore this data
3235 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3237 if(qinfo->RewRepFaction[j])
3239 if(!qinfo->RewRepValue[j])
3241 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3242 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3243 // no changes
3246 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3248 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.",
3249 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3250 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3253 else if(qinfo->RewRepValue[j]!=0)
3255 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3256 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3257 // no changes, quest ignore this data
3261 if(qinfo->RewSpell)
3263 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3265 if(!spellInfo)
3267 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3268 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3269 qinfo->RewSpell = 0; // no spell reward will display for this quest
3272 else if(!SpellMgr::IsSpellValid(spellInfo))
3274 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3275 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3276 qinfo->RewSpell = 0; // no spell reward will display for this quest
3281 if(qinfo->RewSpellCast)
3283 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3285 if(!spellInfo)
3287 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3288 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3289 qinfo->RewSpellCast = 0; // no spell will be casted on player
3292 else if(!SpellMgr::IsSpellValid(spellInfo))
3294 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3295 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3296 qinfo->RewSpellCast = 0; // no spell will be casted on player
3301 if(qinfo->RewMailTemplateId)
3303 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3305 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3306 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3307 qinfo->RewMailTemplateId = 0; // no mail will send to player
3308 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3312 if(qinfo->NextQuestInChain)
3314 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3316 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3317 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3318 qinfo->NextQuestInChain = 0;
3320 else
3321 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3324 // fill additional data stores
3325 if(qinfo->PrevQuestId)
3327 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3329 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3331 else
3333 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3337 if(qinfo->NextQuestId)
3339 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3341 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3343 else
3345 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3346 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3350 if(qinfo->ExclusiveGroup)
3351 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3352 if(qinfo->LimitTime)
3353 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3356 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3357 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3359 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3360 if(!spellInfo)
3361 continue;
3363 for(int j = 0; j < 3; ++j)
3365 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3366 continue;
3368 uint32 quest_id = spellInfo->EffectMiscValue[j];
3370 Quest const* quest = GetQuestTemplate(quest_id);
3372 // some quest referenced in spells not exist (outdataed spells)
3373 if(!quest)
3374 continue;
3376 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3378 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);
3380 // this will prevent quest completing without objective
3381 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3386 sLog.outString();
3387 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3390 void ObjectMgr::LoadQuestLocales()
3392 mQuestLocaleMap.clear(); // need for reload case
3394 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3395 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3396 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3397 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3398 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3399 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3400 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3401 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3402 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3403 " FROM locales_quest"
3406 if(!result)
3408 barGoLink bar(1);
3410 bar.step();
3412 sLog.outString("");
3413 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3414 return;
3417 barGoLink bar(result->GetRowCount());
3421 Field *fields = result->Fetch();
3422 bar.step();
3424 uint32 entry = fields[0].GetUInt32();
3426 QuestLocale& data = mQuestLocaleMap[entry];
3428 for(int i = 1; i < MAX_LOCALE; ++i)
3430 std::string str = fields[1+10*(i-1)].GetCppString();
3431 if(!str.empty())
3433 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3434 if(idx >= 0)
3436 if(data.Title.size() <= idx)
3437 data.Title.resize(idx+1);
3439 data.Title[idx] = str;
3442 str = fields[1+10*(i-1)+1].GetCppString();
3443 if(!str.empty())
3445 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3446 if(idx >= 0)
3448 if(data.Details.size() <= idx)
3449 data.Details.resize(idx+1);
3451 data.Details[idx] = str;
3454 str = fields[1+10*(i-1)+2].GetCppString();
3455 if(!str.empty())
3457 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3458 if(idx >= 0)
3460 if(data.Objectives.size() <= idx)
3461 data.Objectives.resize(idx+1);
3463 data.Objectives[idx] = str;
3466 str = fields[1+10*(i-1)+3].GetCppString();
3467 if(!str.empty())
3469 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3470 if(idx >= 0)
3472 if(data.OfferRewardText.size() <= idx)
3473 data.OfferRewardText.resize(idx+1);
3475 data.OfferRewardText[idx] = str;
3478 str = fields[1+10*(i-1)+4].GetCppString();
3479 if(!str.empty())
3481 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3482 if(idx >= 0)
3484 if(data.RequestItemsText.size() <= idx)
3485 data.RequestItemsText.resize(idx+1);
3487 data.RequestItemsText[idx] = str;
3490 str = fields[1+10*(i-1)+5].GetCppString();
3491 if(!str.empty())
3493 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3494 if(idx >= 0)
3496 if(data.EndText.size() <= idx)
3497 data.EndText.resize(idx+1);
3499 data.EndText[idx] = str;
3502 for(int k = 0; k < 4; ++k)
3504 str = fields[1+10*(i-1)+6+k].GetCppString();
3505 if(!str.empty())
3507 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3508 if(idx >= 0)
3510 if(data.ObjectiveText[k].size() <= idx)
3511 data.ObjectiveText[k].resize(idx+1);
3513 data.ObjectiveText[k][idx] = str;
3518 } while (result->NextRow());
3520 delete result;
3522 sLog.outString();
3523 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3526 void ObjectMgr::LoadPetCreateSpells()
3528 QueryResult *result = WorldDatabase.PQuery("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3529 if(!result)
3531 barGoLink bar( 1 );
3532 bar.step();
3534 sLog.outString();
3535 sLog.outString( ">> Loaded 0 pet create spells" );
3536 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3537 return;
3540 uint32 count = 0;
3542 barGoLink bar( result->GetRowCount() );
3544 mPetCreateSpell.clear();
3548 Field *fields = result->Fetch();
3549 bar.step();
3551 uint32 creature_id = fields[0].GetUInt32();
3553 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3554 continue;
3556 PetCreateSpellEntry PetCreateSpell;
3557 for(int i = 0; i < 4; i++)
3559 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3561 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3562 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3565 mPetCreateSpell[creature_id] = PetCreateSpell;
3567 ++count;
3569 while (result->NextRow());
3571 delete result;
3573 sLog.outString();
3574 sLog.outString( ">> Loaded %u pet create spells", count );
3577 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3579 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3580 return;
3582 sLog.outString( "%s :", tablename);
3584 scripts.clear(); // need for reload support
3586 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3588 uint32 count = 0;
3590 if( !result )
3592 barGoLink bar( 1 );
3593 bar.step();
3595 sLog.outString();
3596 sLog.outString( ">> Loaded %u script definitions", count );
3597 return;
3600 barGoLink bar( result->GetRowCount() );
3604 bar.step();
3606 Field *fields = result->Fetch();
3607 ScriptInfo tmp;
3608 tmp.id = fields[0].GetUInt32();
3609 tmp.delay = fields[1].GetUInt32();
3610 tmp.command = fields[2].GetUInt32();
3611 tmp.datalong = fields[3].GetUInt32();
3612 tmp.datalong2 = fields[4].GetUInt32();
3613 tmp.datatext = fields[5].GetCppString();
3614 tmp.x = fields[6].GetFloat();
3615 tmp.y = fields[7].GetFloat();
3616 tmp.z = fields[8].GetFloat();
3617 tmp.o = fields[9].GetFloat();
3619 // generic command args check
3620 switch(tmp.command)
3622 case SCRIPT_COMMAND_TALK:
3624 if(tmp.datalong > 3)
3626 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3627 continue;
3629 break;
3632 case SCRIPT_COMMAND_TELEPORT_TO:
3634 if(!sMapStore.LookupEntry(tmp.datalong))
3636 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3637 continue;
3640 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3642 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);
3643 continue;
3645 break;
3648 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3650 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3652 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);
3653 continue;
3656 if(!GetCreatureTemplate(tmp.datalong))
3658 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3659 continue;
3661 break;
3664 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3666 GameObjectData const* data = GetGOData(tmp.datalong);
3667 if(!data)
3669 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3670 continue;
3673 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3674 if(!info)
3676 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);
3677 continue;
3680 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3681 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3682 info->type==GAMEOBJECT_TYPE_DOOR ||
3683 info->type==GAMEOBJECT_TYPE_BUTTON ||
3684 info->type==GAMEOBJECT_TYPE_TRAP )
3686 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3687 continue;
3689 break;
3691 case SCRIPT_COMMAND_OPEN_DOOR:
3692 case SCRIPT_COMMAND_CLOSE_DOOR:
3694 GameObjectData const* data = GetGOData(tmp.datalong);
3695 if(!data)
3697 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);
3698 continue;
3701 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3702 if(!info)
3704 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);
3705 continue;
3708 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3710 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);
3711 continue;
3714 break;
3716 case SCRIPT_COMMAND_QUEST_EXPLORED:
3718 Quest const* quest = GetQuestTemplate(tmp.datalong);
3719 if(!quest)
3721 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);
3722 continue;
3725 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3727 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);
3729 // this will prevent quest completing without objective
3730 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3732 // continue; - quest objective requiremet set and command can be allowed
3735 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3737 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",tablename,tmp.datalong2,tmp.id);
3738 continue;
3741 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3743 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(DEFAULT_VISIBILITY_DISTANCE));
3744 continue;
3747 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3749 sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(INTERACTION_DISTANCE));
3750 continue;
3753 break;
3756 case SCRIPT_COMMAND_REMOVE_AURA:
3757 case SCRIPT_COMMAND_CAST_SPELL:
3759 if(!sSpellStore.LookupEntry(tmp.datalong))
3761 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",tablename,tmp.datalong,tmp.id);
3762 continue;
3764 break;
3768 if (scripts.find(tmp.id) == scripts.end())
3770 ScriptMap emptyMap;
3771 scripts[tmp.id] = emptyMap;
3773 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3775 ++count;
3776 } while( result->NextRow() );
3778 delete result;
3780 sLog.outString();
3781 sLog.outString( ">> Loaded %u script definitions", count );
3784 void ObjectMgr::LoadGameObjectScripts()
3786 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3788 // check ids
3789 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3791 if(!GetGOData(itr->first))
3792 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3796 void ObjectMgr::LoadQuestEndScripts()
3798 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3800 // check ids
3801 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3803 if(!GetQuestTemplate(itr->first))
3804 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3808 void ObjectMgr::LoadQuestStartScripts()
3810 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3812 // check ids
3813 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3815 if(!GetQuestTemplate(itr->first))
3816 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3820 void ObjectMgr::LoadSpellScripts()
3822 LoadScripts(sSpellScripts, "spell_scripts");
3824 // check ids
3825 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3827 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3829 if(!spellInfo)
3831 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3832 continue;
3835 //check for correct spellEffect
3836 bool found = false;
3837 for(int i=0; i<3; ++i)
3839 // skip empty effects
3840 if( !spellInfo->Effect[i] )
3841 continue;
3843 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3845 found = true;
3846 break;
3850 if(!found)
3851 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3855 void ObjectMgr::LoadEventScripts()
3857 LoadScripts(sEventScripts, "event_scripts");
3859 std::set<uint32> evt_scripts;
3860 // Load all possible script entries from gameobjects
3861 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3863 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3864 if (goInfo)
3866 switch(goInfo->type)
3868 case GAMEOBJECT_TYPE_GOOBER:
3869 if(goInfo->goober.eventId)
3870 evt_scripts.insert(goInfo->goober.eventId);
3871 break;
3872 case GAMEOBJECT_TYPE_CHEST:
3873 if(goInfo->chest.eventId)
3874 evt_scripts.insert(goInfo->chest.eventId);
3875 break;
3876 default:
3877 break;
3881 // Load all possible script entries from spells
3882 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3884 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3885 if (spell)
3887 for(int j=0; j<3; ++j)
3889 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3891 if (spell->EffectMiscValue[j])
3892 evt_scripts.insert(spell->EffectMiscValue[j]);
3897 // Then check if all scripts are in above list of possible script entries
3898 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3900 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3901 if (itr2 == evt_scripts.end())
3902 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not refering to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
3906 void ObjectMgr::LoadItemTexts()
3908 QueryResult *result = CharacterDatabase.PQuery("SELECT id, text FROM item_text");
3910 uint32 count = 0;
3912 if( !result )
3914 barGoLink bar( 1 );
3915 bar.step();
3917 sLog.outString();
3918 sLog.outString( ">> Loaded %u item pages", count );
3919 return;
3922 barGoLink bar( result->GetRowCount() );
3924 Field* fields;
3927 bar.step();
3929 fields = result->Fetch();
3931 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3933 ++count;
3935 } while ( result->NextRow() );
3937 delete result;
3939 sLog.outString();
3940 sLog.outString( ">> Loaded %u item texts", count );
3943 void ObjectMgr::LoadPageTexts()
3945 sPageTextStore.Free(); // for reload case
3947 sPageTextStore.Load();
3948 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3949 sLog.outString();
3951 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3953 // check data correctness
3954 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3955 if(!page)
3956 continue;
3958 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3960 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3961 continue;
3964 // detect circular reference
3965 std::set<uint32> checkedPages;
3966 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
3968 if(!pageItr->Next_Page)
3969 break;
3970 checkedPages.insert(pageItr->Page_ID);
3971 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
3973 std::ostringstream ss;
3974 ss<< "The text page(s) ";
3975 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
3976 ss << *itr << " ";
3977 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
3978 << pageItr->Page_ID <<" to 0";
3979 sLog.outErrorDb(ss.str().c_str());
3980 const_cast<PageText*>(pageItr)->Next_Page = 0;
3981 break;
3987 void ObjectMgr::LoadPageTextLocales()
3989 mPageTextLocaleMap.clear(); // need for reload case
3991 QueryResult *result = WorldDatabase.PQuery("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
3993 if(!result)
3995 barGoLink bar(1);
3997 bar.step();
3999 sLog.outString("");
4000 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4001 return;
4004 barGoLink bar(result->GetRowCount());
4008 Field *fields = result->Fetch();
4009 bar.step();
4011 uint32 entry = fields[0].GetUInt32();
4013 PageTextLocale& data = mPageTextLocaleMap[entry];
4015 for(int i = 1; i < MAX_LOCALE; ++i)
4017 std::string str = fields[i].GetCppString();
4018 if(str.empty())
4019 continue;
4021 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4022 if(idx >= 0)
4024 if(data.Text.size() <= idx)
4025 data.Text.resize(idx+1);
4027 data.Text[idx] = str;
4031 } while (result->NextRow());
4033 delete result;
4035 sLog.outString();
4036 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4039 void ObjectMgr::LoadInstanceTemplate()
4041 sInstanceTemplate.Load();
4043 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4045 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4046 if(!temp) continue;
4047 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4048 if(!entry)
4050 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4051 continue;
4053 else if(!entry->HasResetTime())
4054 continue;
4056 if(temp->reset_delay == 0)
4058 // use defaults from the DBC
4059 if(entry->SupportsHeroicMode())
4061 temp->reset_delay = entry->resetTimeHeroic / DAY;
4063 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4065 temp->reset_delay = entry->resetTimeRaid / DAY;
4069 // the reset_delay must be atleast one day
4070 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4073 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4074 sLog.outString();
4077 void ObjectMgr::AddGossipText(GossipText *pGText)
4079 ASSERT( pGText->Text_ID );
4080 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4081 mGossipText[pGText->Text_ID] = pGText;
4084 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4086 GossipTextMap::const_iterator itr;
4087 for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4089 if(itr->second->Text_ID == Text_ID)
4090 return itr->second;
4092 return NULL;
4095 void ObjectMgr::LoadGossipText()
4097 GossipText *pGText;
4098 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4100 int count = 0;
4101 if( !result )
4103 barGoLink bar( 1 );
4104 bar.step();
4106 sLog.outString();
4107 sLog.outString( ">> Loaded %u npc texts", count );
4108 return;
4111 int cic;
4113 barGoLink bar( result->GetRowCount() );
4117 ++count;
4118 cic = 0;
4120 Field *fields = result->Fetch();
4122 bar.step();
4124 pGText = new GossipText;
4125 pGText->Text_ID = fields[cic++].GetUInt32();
4127 for (int i=0; i< 8; i++)
4129 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4130 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4132 pGText->Options[i].Language = fields[cic++].GetUInt32();
4133 pGText->Options[i].Probability = fields[cic++].GetFloat();
4135 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4136 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4138 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4139 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4141 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4142 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4145 if ( !pGText->Text_ID ) continue;
4146 AddGossipText( pGText );
4148 } while( result->NextRow() );
4150 sLog.outString();
4151 sLog.outString( ">> Loaded %u npc texts", count );
4152 delete result;
4155 void ObjectMgr::LoadNpcTextLocales()
4157 mNpcTextLocaleMap.clear(); // need for reload case
4159 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4160 "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,"
4161 "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,"
4162 "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,"
4163 "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,"
4164 "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,"
4165 "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,"
4166 "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, "
4167 "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 "
4168 " FROM locales_npc_text");
4170 if(!result)
4172 barGoLink bar(1);
4174 bar.step();
4176 sLog.outString("");
4177 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4178 return;
4181 barGoLink bar(result->GetRowCount());
4185 Field *fields = result->Fetch();
4186 bar.step();
4188 uint32 entry = fields[0].GetUInt32();
4190 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4192 for(int i=1; i<MAX_LOCALE; ++i)
4194 for(int j=0; j<8; ++j)
4196 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4197 if(!str0.empty())
4199 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4200 if(idx >= 0)
4202 if(data.Text_0[j].size() <= idx)
4203 data.Text_0[j].resize(idx+1);
4205 data.Text_0[j][idx] = str0;
4208 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4209 if(!str1.empty())
4211 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4212 if(idx >= 0)
4214 if(data.Text_1[j].size() <= idx)
4215 data.Text_1[j].resize(idx+1);
4217 data.Text_1[j][idx] = str1;
4222 } while (result->NextRow());
4224 delete result;
4226 sLog.outString();
4227 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4230 //not very fast function but it is called only once a day, or on starting-up
4231 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4233 time_t basetime = time(NULL);
4234 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4235 //delete all old mails without item and without body immediately, if starting server
4236 if (!serverUp)
4237 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4238 // 0 1 2 3 4 5 6 7 8 9
4239 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);
4240 if ( !result )
4241 return; // any mails need to be returned or deleted
4242 Field *fields;
4243 //std::ostringstream delitems, delmails; //will be here for optimization
4244 //bool deletemail = false, deleteitem = false;
4245 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4246 //delmails << "DELETE FROM mail WHERE id IN ( "
4249 fields = result->Fetch();
4250 Mail *m = new Mail;
4251 m->messageID = fields[0].GetUInt32();
4252 m->messageType = fields[1].GetUInt8();
4253 m->sender = fields[2].GetUInt32();
4254 m->receiver = fields[3].GetUInt32();
4255 m->itemTextId = fields[4].GetUInt32();
4256 bool has_items = fields[5].GetBool();
4257 m->expire_time = (time_t)fields[6].GetUInt64();
4258 m->deliver_time = 0;
4259 m->COD = fields[7].GetUInt32();
4260 m->checked = fields[8].GetUInt32();
4261 m->mailTemplateId = fields[9].GetInt16();
4263 Player *pl = 0;
4264 if (serverUp)
4265 pl = GetPlayer((uint64)m->receiver);
4266 if (pl && pl->m_mailsLoaded)
4267 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4268 //his in mailbox and he has already listed his mails )
4269 delete m;
4270 continue;
4272 //delete or return mail:
4273 if (has_items)
4275 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4276 if(resultItems)
4280 Field *fields2 = resultItems->Fetch();
4282 uint32 item_guid_low = fields2[0].GetUInt32();
4283 uint32 item_template = fields2[1].GetUInt32();
4285 m->AddItem(item_guid_low, item_template);
4287 while (resultItems->NextRow());
4289 delete resultItems;
4291 //if it is mail from AH, it shouldn't be returned, but deleted
4292 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4294 // mail open and then not returned
4295 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4296 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4298 else
4300 //mail will be returned:
4301 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);
4302 delete m;
4303 continue;
4307 if (m->itemTextId)
4308 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4310 //deletemail = true;
4311 //delmails << m->messageID << ", ";
4312 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4313 delete m;
4314 } while (result->NextRow());
4315 delete result;
4318 void ObjectMgr::LoadQuestAreaTriggers()
4320 mQuestAreaTriggerMap.clear(); // need for reload case
4322 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4324 uint32 count = 0;
4326 if( !result )
4328 barGoLink bar( 1 );
4329 bar.step();
4331 sLog.outString();
4332 sLog.outString( ">> Loaded %u quest trigger points", count );
4333 return;
4336 barGoLink bar( result->GetRowCount() );
4340 ++count;
4341 bar.step();
4343 Field *fields = result->Fetch();
4345 uint32 trigger_ID = fields[0].GetUInt32();
4346 uint32 quest_ID = fields[1].GetUInt32();
4348 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4349 if(!atEntry)
4351 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4352 continue;
4355 Quest const* quest = GetQuestTemplate(quest_ID);
4357 if(!quest)
4359 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4360 continue;
4363 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4365 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);
4367 // this will prevent quest completing without objective
4368 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4370 // continue; - quest modified to required obkective and trigger can be allowed.
4373 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4375 } while( result->NextRow() );
4377 delete result;
4379 sLog.outString();
4380 sLog.outString( ">> Loaded %u quest trigger points", count );
4383 void ObjectMgr::LoadTavernAreaTriggers()
4385 mTavernAreaTriggerSet.clear(); // need for reload case
4387 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4389 uint32 count = 0;
4391 if( !result )
4393 barGoLink bar( 1 );
4394 bar.step();
4396 sLog.outString();
4397 sLog.outString( ">> Loaded %u tavern triggers", count );
4398 return;
4401 barGoLink bar( result->GetRowCount() );
4405 ++count;
4406 bar.step();
4408 Field *fields = result->Fetch();
4410 uint32 Trigger_ID = fields[0].GetUInt32();
4412 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4413 if(!atEntry)
4415 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4416 continue;
4419 mTavernAreaTriggerSet.insert(Trigger_ID);
4420 } while( result->NextRow() );
4422 delete result;
4424 sLog.outString();
4425 sLog.outString( ">> Loaded %u tavern triggers", count );
4428 void ObjectMgr::LoadAreaTriggerScripts()
4430 mAreaTriggerScripts.clear(); // need for reload case
4431 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4433 uint32 count = 0;
4435 if( !result )
4437 barGoLink bar( 1 );
4438 bar.step();
4440 sLog.outString();
4441 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4442 return;
4445 barGoLink bar( result->GetRowCount() );
4449 ++count;
4450 bar.step();
4452 Field *fields = result->Fetch();
4454 uint32 Trigger_ID = fields[0].GetUInt32();
4455 std::string scriptName = fields[1].GetCppString();
4457 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4458 if(!atEntry)
4460 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4461 continue;
4463 mAreaTriggerScripts[Trigger_ID] = scriptName;
4464 } while( result->NextRow() );
4466 delete result;
4468 sLog.outString();
4469 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4472 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4474 bool found = false;
4475 float dist;
4476 uint32 id = 0;
4478 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4480 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4481 if(node && node->map_id == mapid)
4483 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4484 if(found)
4486 if(dist2 < dist)
4488 dist = dist2;
4489 id = i;
4492 else
4494 found = true;
4495 dist = dist2;
4496 id = i;
4501 return id;
4504 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4506 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4507 if(src_i==sTaxiPathSetBySource.end())
4509 path = 0;
4510 cost = 0;
4511 return;
4514 TaxiPathSetForSource& pathSet = src_i->second;
4516 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4517 if(dest_i==pathSet.end())
4519 path = 0;
4520 cost = 0;
4521 return;
4524 cost = dest_i->second.price;
4525 path = dest_i->second.ID;
4528 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4530 uint16 mount_entry = 0;
4531 uint16 mount_id = 0;
4533 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4534 if(node)
4536 if (team == ALLIANCE)
4538 mount_entry = node->alliance_mount_type;
4539 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4540 if(ci)
4541 mount_id = ci->DisplayID_A;
4543 if (team == HORDE)
4545 mount_entry = node->horde_mount_type;
4546 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4547 if(ci)
4548 mount_id = ci->DisplayID_H;
4552 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4553 if(!minfo)
4555 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. ",
4556 mount_entry,id,team,mount_id);
4558 return false;
4560 if(minfo->modelid_other_gender!=0)
4561 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4563 return mount_id;
4566 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4568 if(path >= sTaxiPathNodesByPath.size())
4569 return;
4571 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4573 pathnodes.Resize(nodeList.size());
4574 mapIds.resize(nodeList.size());
4576 for(size_t i = 0; i < nodeList.size(); ++i)
4578 pathnodes[ i ].x = nodeList[i].x;
4579 pathnodes[ i ].y = nodeList[i].y;
4580 pathnodes[ i ].z = nodeList[i].z;
4582 mapIds[i] = nodeList[i].mapid;
4586 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4588 if(path >= sTaxiPathNodesByPath.size())
4589 return;
4591 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4593 pathnodes.Resize(nodeList.size());
4595 for(size_t i = 0; i < nodeList.size(); ++i)
4597 pathnodes[ i ].mapid = nodeList[i].mapid;
4598 pathnodes[ i ].x = nodeList[i].x;
4599 pathnodes[ i ].y = nodeList[i].y;
4600 pathnodes[ i ].z = nodeList[i].z;
4601 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4602 pathnodes[ i ].delay = nodeList[i].delay;
4606 void ObjectMgr::LoadGraveyardZones()
4608 mGraveYardMap.clear(); // need for reload case
4610 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4612 uint32 count = 0;
4614 if( !result )
4616 barGoLink bar( 1 );
4617 bar.step();
4619 sLog.outString();
4620 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4621 return;
4624 barGoLink bar( result->GetRowCount() );
4628 ++count;
4629 bar.step();
4631 Field *fields = result->Fetch();
4633 uint32 safeLocId = fields[0].GetUInt32();
4634 uint32 zoneId = fields[1].GetUInt32();
4635 uint32 team = fields[2].GetUInt32();
4637 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4638 if(!entry)
4640 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4641 continue;
4644 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4645 if(!areaEntry)
4647 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4648 continue;
4651 if(areaEntry->zone != 0)
4653 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4654 continue;
4657 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4659 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4660 continue;
4663 if(entry->map_id != areaEntry->mapid && team != 0)
4665 sLog.outErrorDb("Table `game_graveyard_zone` has record for ghost zone (%u) at map %u and graveyard (%u) at map %u for team %u, but in case maps are different, player faction setting is ignored. Use faction 0 instead.",zoneId,areaEntry->mapid, safeLocId, entry->map_id, team);
4666 team = 0;
4669 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4670 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Garveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4671 } while( result->NextRow() );
4673 delete result;
4675 sLog.outString();
4676 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4679 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4681 // search for zone associated closest graveyard
4682 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4684 // Simulate std. algorithm:
4685 // found some graveyard associated to (ghost_zone,ghost_map)
4687 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4688 // then check faction
4689 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4690 // then skip check faction
4691 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4692 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4693 if(graveLow==graveUp)
4695 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4696 return NULL;
4699 bool foundNear = false;
4700 float distNear;
4701 WorldSafeLocsEntry const* entryNear = NULL;
4702 WorldSafeLocsEntry const* entryFar = NULL;
4704 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4706 GraveYardData const& data = itr->second;
4708 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4709 if(!entry)
4711 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4712 continue;
4715 // remember first graveyard at another map and ignore other
4716 if(MapId != entry->map_id)
4718 if(!entryFar)
4719 entryFar = entry;
4720 continue;
4723 // skip enemy faction graveyard at same map (normal area, city, or battleground)
4724 // team == 0 case can be at call from .neargrave
4725 if(data.team != 0 && team != 0 && data.team != team)
4726 continue;
4728 // find now nearest graveyard at same map
4729 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4730 if(foundNear)
4732 if(dist2 < distNear)
4734 distNear = dist2;
4735 entryNear = entry;
4738 else
4740 foundNear = true;
4741 distNear = dist2;
4742 entryNear = entry;
4746 if(entryNear)
4747 return entryNear;
4749 return entryFar;
4752 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4754 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4755 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4757 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4759 if(itr->second.safeLocId==id)
4760 return &itr->second;
4763 return NULL;
4766 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4768 if(FindGraveYardData(id,zoneId))
4769 return false;
4771 // add link to loaded data
4772 GraveYardData data;
4773 data.safeLocId = id;
4774 data.team = team;
4776 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4778 // add link to DB
4779 if(inDB)
4781 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4782 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4785 return true;
4788 void ObjectMgr::LoadAreaTriggerTeleports()
4790 mAreaTriggers.clear(); // need for reload case
4792 uint32 count = 0;
4794 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4795 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");
4796 if( !result )
4799 barGoLink bar( 1 );
4801 bar.step();
4803 sLog.outString();
4804 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4805 return;
4808 barGoLink bar( result->GetRowCount() );
4812 Field *fields = result->Fetch();
4814 bar.step();
4816 ++count;
4818 uint32 Trigger_ID = fields[0].GetUInt32();
4820 AreaTrigger at;
4822 at.requiredLevel = fields[1].GetUInt8();
4823 at.requiredItem = fields[2].GetUInt32();
4824 at.requiredItem2 = fields[3].GetUInt32();
4825 at.heroicKey = fields[4].GetUInt32();
4826 at.heroicKey2 = fields[5].GetUInt32();
4827 at.requiredQuest = fields[6].GetUInt32();
4828 at.requiredFailedText = fields[7].GetCppString();
4829 at.target_mapId = fields[8].GetUInt32();
4830 at.target_X = fields[9].GetFloat();
4831 at.target_Y = fields[10].GetFloat();
4832 at.target_Z = fields[11].GetFloat();
4833 at.target_Orientation = fields[12].GetFloat();
4835 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4836 if(!atEntry)
4838 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4839 continue;
4842 if(at.requiredItem)
4844 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4845 if(!pProto)
4847 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4848 at.requiredItem = 0;
4851 if(at.requiredItem2)
4853 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4854 if(!pProto)
4856 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4857 at.requiredItem2 = 0;
4861 if(at.heroicKey)
4863 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4864 if(!pProto)
4866 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4867 at.heroicKey = 0;
4871 if(at.heroicKey2)
4873 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4874 if(!pProto)
4876 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4877 at.heroicKey2 = 0;
4881 if(at.requiredQuest)
4883 if(!mQuestTemplates[at.requiredQuest])
4885 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4886 at.requiredQuest = 0;
4890 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4891 if(!mapEntry)
4893 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4894 continue;
4897 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4899 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4900 continue;
4903 mAreaTriggers[Trigger_ID] = at;
4905 } while( result->NextRow() );
4907 delete result;
4909 sLog.outString();
4910 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4913 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
4915 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
4916 if(!mapEntry) return NULL;
4917 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
4919 if(itr->second.target_mapId == mapEntry->parent_map)
4921 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
4922 if(atEntry && atEntry->mapid == Map)
4923 return &itr->second;
4926 return NULL;
4929 void ObjectMgr::SetHighestGuids()
4931 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
4932 if( result )
4934 m_hiCharGuid = (*result)[0].GetUInt32()+1;
4936 delete result;
4939 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
4940 if( result )
4942 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
4944 delete result;
4947 result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
4948 if( result )
4950 m_hiPetGuid = (*result)[0].GetUInt32()+1;
4952 delete result;
4955 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
4956 if( result )
4958 m_hiItemGuid = (*result)[0].GetUInt32()+1;
4960 delete result;
4963 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
4964 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
4965 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
4966 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
4967 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
4969 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
4970 if( result )
4972 m_hiGoGuid = (*result)[0].GetUInt32()+1;
4974 delete result;
4977 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
4978 if( result )
4980 m_auctionid = (*result)[0].GetUInt32()+1;
4982 delete result;
4984 else
4986 m_auctionid = 0;
4988 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
4989 if( result )
4991 m_mailid = (*result)[0].GetUInt32()+1;
4993 delete result;
4995 else
4997 m_mailid = 0;
4999 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5000 if( result )
5002 m_ItemTextId = (*result)[0].GetUInt32();
5004 delete result;
5006 else
5007 m_ItemTextId = 0;
5009 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5010 if( result )
5012 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5014 delete result;
5018 uint32 ObjectMgr::GenerateAuctionID()
5020 ++m_auctionid;
5021 if(m_auctionid>=0xFFFFFFFF)
5023 sLog.outError("Auctions ids overflow!! Can't continue, shuting down server. ");
5024 sWorld.m_stopEvent = true;
5026 return m_auctionid;
5029 uint32 ObjectMgr::GenerateMailID()
5031 ++m_mailid;
5032 if(m_mailid>=0xFFFFFFFF)
5034 sLog.outError("Mail ids overflow!! Can't continue, shuting down server. ");
5035 sWorld.m_stopEvent = true;
5037 return m_mailid;
5040 uint32 ObjectMgr::GenerateItemTextID()
5042 ++m_ItemTextId;
5043 if(m_ItemTextId>=0xFFFFFFFF)
5045 sLog.outError("Item text ids overflow!! Can't continue, shuting down server. ");
5046 sWorld.m_stopEvent = true;
5048 return m_ItemTextId;
5051 uint32 ObjectMgr::CreateItemText(std::string text)
5053 uint32 newItemTextId = GenerateItemTextID();
5054 //insert new itempage to container
5055 mItemTexts[ newItemTextId ] = text;
5056 //save new itempage
5057 CharacterDatabase.escape_string(text);
5058 //any Delete query needed, itemTextId is maximum of all ids
5059 std::ostringstream query;
5060 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5061 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5062 return newItemTextId;
5065 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5067 switch(guidhigh)
5069 case HIGHGUID_ITEM:
5070 ++m_hiItemGuid;
5071 if(m_hiItemGuid>=0xFFFFFFFF)
5073 sLog.outError("Item guid overflow!! Can't continue, shuting down server. ");
5074 sWorld.m_stopEvent = true;
5076 return m_hiItemGuid;
5077 case HIGHGUID_UNIT:
5078 ++m_hiCreatureGuid;
5079 if(m_hiCreatureGuid>=0x00FFFFFF)
5081 sLog.outError("Creature guid overflow!! Can't continue, shuting down server. ");
5082 sWorld.m_stopEvent = true;
5084 return m_hiCreatureGuid;
5085 case HIGHGUID_PET:
5086 ++m_hiPetGuid;
5087 if(m_hiPetGuid>=0x00FFFFFF)
5089 sLog.outError("Pet guid overflow!! Can't continue, shuting down server. ");
5090 sWorld.m_stopEvent = true;
5092 return m_hiPetGuid;
5093 case HIGHGUID_PLAYER:
5094 ++m_hiCharGuid;
5095 if(m_hiCharGuid>=0xFFFFFFFF)
5097 sLog.outError("Players guid overflow!! Can't continue, shuting down server. ");
5098 sWorld.m_stopEvent = true;
5100 return m_hiCharGuid;
5101 case HIGHGUID_GAMEOBJECT:
5102 ++m_hiGoGuid;
5103 if(m_hiGoGuid>=0x00FFFFFF)
5105 sLog.outError("Gameobject guid overflow!! Can't continue, shuting down server. ");
5106 sWorld.m_stopEvent = true;
5108 return m_hiGoGuid;
5109 case HIGHGUID_CORPSE:
5110 ++m_hiCorpseGuid;
5111 if(m_hiCorpseGuid>=0xFFFFFFFF)
5113 sLog.outError("Corpse guid overflow!! Can't continue, shuting down server. ");
5114 sWorld.m_stopEvent = true;
5116 return m_hiCorpseGuid;
5117 case HIGHGUID_DYNAMICOBJECT:
5118 ++m_hiDoGuid;
5119 if(m_hiDoGuid>=0xFFFFFFFF)
5121 sLog.outError("DynamicObject guid overflow!! Can't continue, shuting down server. ");
5122 sWorld.m_stopEvent = true;
5124 return m_hiDoGuid;
5125 default:
5126 ASSERT(0);
5129 ASSERT(0);
5130 return 0;
5133 void ObjectMgr::LoadGameObjectLocales()
5135 mGameObjectLocaleMap.clear(); // need for reload case
5137 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5138 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5139 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5140 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5142 if(!result)
5144 barGoLink bar(1);
5146 bar.step();
5148 sLog.outString("");
5149 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5150 return;
5153 barGoLink bar(result->GetRowCount());
5157 Field *fields = result->Fetch();
5158 bar.step();
5160 uint32 entry = fields[0].GetUInt32();
5162 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5164 for(int i = 1; i < MAX_LOCALE; ++i)
5166 std::string str = fields[i].GetCppString();
5167 if(!str.empty())
5169 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5170 if(idx >= 0)
5172 if(data.Name.size() <= idx)
5173 data.Name.resize(idx+1);
5175 data.Name[idx] = str;
5180 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5182 std::string str = fields[i].GetCppString();
5183 if(!str.empty())
5185 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5186 if(idx >= 0)
5188 if(data.CastBarCaption.size() <= idx)
5189 data.CastBarCaption.resize(idx+1);
5191 data.CastBarCaption[idx] = str;
5196 } while (result->NextRow());
5198 delete result;
5200 sLog.outString();
5201 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5204 void ObjectMgr::LoadGameobjectInfo()
5206 sGOStorage.Load();
5208 // some checks
5209 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5211 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5212 if(!goInfo)
5213 continue;
5215 switch(goInfo->type)
5217 case GAMEOBJECT_TYPE_DOOR: //0
5219 if(goInfo->door.lockId)
5221 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5222 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5223 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5225 break;
5227 case GAMEOBJECT_TYPE_BUTTON: //1
5229 if(goInfo->button.lockId)
5231 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5232 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5233 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5235 break;
5237 case GAMEOBJECT_TYPE_CHEST: //3
5239 if(goInfo->chest.lockId)
5241 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5242 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5243 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5245 if(goInfo->chest.linkedTrapId) // linked trap
5247 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5249 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5250 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5251 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5253 /* disable check for while
5254 else
5255 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5256 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5259 break;
5261 case GAMEOBJECT_TYPE_TRAP: //6
5263 /* disable check for while
5264 if(goInfo->trap.spellId) // spell
5266 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5267 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5268 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5271 break;
5273 case GAMEOBJECT_TYPE_CHAIR: //7
5274 if(goInfo->chair.height > 2)
5276 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5277 id,goInfo->type,goInfo->chair.height);
5279 // prevent client and server unexpected work
5280 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5282 break;
5283 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5285 if(goInfo->spellFocus.focusId)
5287 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5288 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5289 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5292 if(goInfo->spellFocus.linkedTrapId) // linked trap
5294 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5296 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5297 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5298 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5300 /* disable check for while
5301 else
5302 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5303 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5306 break;
5308 case GAMEOBJECT_TYPE_GOOBER: //10
5310 if(goInfo->goober.pageId) // pageId
5312 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5313 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5314 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5316 /* disable check for while
5317 if(goInfo->goober.spellId) // spell
5319 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5320 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5321 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5324 if(goInfo->goober.linkedTrapId) // linked trap
5326 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5328 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5329 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5330 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5332 /* disable check for while
5333 else
5334 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5335 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5338 break;
5340 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5342 if(goInfo->moTransport.taxiPathId)
5344 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5345 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5346 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5348 break;
5350 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5352 /* disabled
5353 if(goInfo->summoningRitual.spellId)
5355 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5356 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5357 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5360 break;
5362 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5364 if(goInfo->spellcaster.spellId) // spell
5366 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5367 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5368 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5370 break;
5375 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5376 sLog.outString();
5379 void ObjectMgr::LoadExplorationBaseXP()
5381 uint32 count = 0;
5382 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5384 if( !result )
5386 barGoLink bar( 1 );
5388 bar.step();
5390 sLog.outString();
5391 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5392 return;
5395 barGoLink bar( result->GetRowCount() );
5399 bar.step();
5401 Field *fields = result->Fetch();
5402 uint32 level = fields[0].GetUInt32();
5403 uint32 basexp = fields[1].GetUInt32();
5404 mBaseXPTable[level] = basexp;
5405 ++count;
5407 while (result->NextRow());
5409 delete result;
5411 sLog.outString();
5412 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5415 uint32 ObjectMgr::GetBaseXP(uint32 level)
5417 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5420 void ObjectMgr::LoadPetNames()
5422 uint32 count = 0;
5423 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5425 if( !result )
5427 barGoLink bar( 1 );
5429 bar.step();
5431 sLog.outString();
5432 sLog.outString( ">> Loaded %u pet name parts", count );
5433 return;
5436 barGoLink bar( result->GetRowCount() );
5440 bar.step();
5442 Field *fields = result->Fetch();
5443 std::string word = fields[0].GetString();
5444 uint32 entry = fields[1].GetUInt32();
5445 bool half = fields[2].GetBool();
5446 if(half)
5447 PetHalfName1[entry].push_back(word);
5448 else
5449 PetHalfName0[entry].push_back(word);
5450 ++count;
5452 while (result->NextRow());
5453 delete result;
5455 sLog.outString();
5456 sLog.outString( ">> Loaded %u pet name parts", count );
5459 void ObjectMgr::LoadPetNumber()
5461 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5462 if(result)
5464 Field *fields = result->Fetch();
5465 m_hiPetNumber = fields[0].GetUInt32()+1;
5466 delete result;
5469 barGoLink bar( 1 );
5470 bar.step();
5472 sLog.outString();
5473 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5476 std::string ObjectMgr::GeneratePetName(uint32 entry)
5478 std::vector<std::string> & list0 = PetHalfName0[entry];
5479 std::vector<std::string> & list1 = PetHalfName1[entry];
5481 if(list0.empty() || list1.empty())
5483 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5484 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5485 if(!petname)
5486 petname = cinfo->Name;
5487 return std::string(petname);
5490 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5493 uint32 ObjectMgr::GeneratePetNumber()
5495 return ++m_hiPetNumber;
5498 void ObjectMgr::LoadCorpses()
5500 uint32 count = 0;
5501 // 0 1 2 3 4 5 6 7 8 10
5502 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5504 if( !result )
5506 barGoLink bar( 1 );
5508 bar.step();
5510 sLog.outString();
5511 sLog.outString( ">> Loaded %u corpses", count );
5512 return;
5515 barGoLink bar( result->GetRowCount() );
5519 bar.step();
5521 Field *fields = result->Fetch();
5523 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5525 Corpse *corpse = new Corpse;
5526 if(!corpse->LoadFromDB(guid,fields))
5528 delete corpse;
5529 continue;
5532 ObjectAccessor::Instance().AddCorpse(corpse);
5534 ++count;
5536 while (result->NextRow());
5537 delete result;
5539 sLog.outString();
5540 sLog.outString( ">> Loaded %u corpses", count );
5543 void ObjectMgr::LoadReputationOnKill()
5545 uint32 count = 0;
5547 // 0 1 2
5548 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5549 // 3 4 5 6 7 8 9
5550 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5551 "FROM creature_onkill_reputation");
5553 if(!result)
5555 barGoLink bar(1);
5557 bar.step();
5559 sLog.outString();
5560 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5561 return;
5564 barGoLink bar(result->GetRowCount());
5568 Field *fields = result->Fetch();
5569 bar.step();
5571 uint32 creature_id = fields[0].GetUInt32();
5573 ReputationOnKillEntry repOnKill;
5574 repOnKill.repfaction1 = fields[1].GetUInt32();
5575 repOnKill.repfaction2 = fields[2].GetUInt32();
5576 repOnKill.is_teamaward1 = fields[3].GetBool();
5577 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5578 repOnKill.repvalue1 = fields[5].GetInt32();
5579 repOnKill.is_teamaward2 = fields[6].GetBool();
5580 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5581 repOnKill.repvalue2 = fields[8].GetInt32();
5582 repOnKill.team_dependent = fields[9].GetUInt8();
5584 if(!GetCreatureTemplate(creature_id))
5586 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5587 continue;
5590 if(repOnKill.repfaction1)
5592 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5593 if(!factionEntry1)
5595 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5596 continue;
5600 if(repOnKill.repfaction2)
5602 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5603 if(!factionEntry2)
5605 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5606 continue;
5610 mRepOnKill[creature_id] = repOnKill;
5612 ++count;
5613 } while (result->NextRow());
5615 delete result;
5617 sLog.outString();
5618 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5621 void ObjectMgr::LoadWeatherZoneChances()
5623 uint32 count = 0;
5625 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5626 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");
5628 if(!result)
5630 barGoLink bar(1);
5632 bar.step();
5634 sLog.outString();
5635 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5636 return;
5639 barGoLink bar(result->GetRowCount());
5643 Field *fields = result->Fetch();
5644 bar.step();
5646 uint32 zone_id = fields[0].GetUInt32();
5648 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5650 for(int season = 0; season < WEATHER_SEASONS; ++season)
5652 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5653 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5654 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5656 if(wzc.data[season].rainChance > 100)
5658 wzc.data[season].rainChance = 25;
5659 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5662 if(wzc.data[season].snowChance > 100)
5664 wzc.data[season].snowChance = 25;
5665 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5668 if(wzc.data[season].stormChance > 100)
5670 wzc.data[season].stormChance = 25;
5671 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5675 ++count;
5676 } while (result->NextRow());
5678 delete result;
5680 sLog.outString();
5681 sLog.outString(">> Loaded %u weather definitions", count);
5684 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5686 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5687 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5688 if(t)
5689 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5692 void ObjectMgr::DeleteCreatureData(uint32 guid)
5694 // remove mapid*cellid -> guid_set map
5695 CreatureData const* data = GetCreatureData(guid);
5696 if(data)
5697 RemoveCreatureFromGrid(guid, data);
5699 mCreatureDataMap.erase(guid);
5702 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5704 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5705 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5706 if(t)
5707 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5710 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5712 RespawnTimes::iterator next;
5714 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5716 next = itr;
5717 ++next;
5719 if(GUID_HIPART(itr->first)==instance)
5720 mGORespawnTimes.erase(itr);
5723 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5725 next = itr;
5726 ++next;
5728 if(GUID_HIPART(itr->first)==instance)
5729 mCreatureRespawnTimes.erase(itr);
5732 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5733 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5736 void ObjectMgr::DeleteGOData(uint32 guid)
5738 // remove mapid*cellid -> guid_set map
5739 GameObjectData const* data = GetGOData(guid);
5740 if(data)
5741 RemoveGameobjectFromGrid(guid, data);
5743 mGameObjectDataMap.erase(guid);
5746 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5748 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5749 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5750 cell_guids.corpses[player_guid] = instance;
5753 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5755 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5756 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5757 cell_guids.corpses.erase(player_guid);
5760 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5762 map.clear(); // need for reload case
5764 uint32 count = 0;
5766 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5768 if(!result)
5770 barGoLink bar(1);
5772 bar.step();
5774 sLog.outString();
5775 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5776 return;
5779 barGoLink bar(result->GetRowCount());
5783 Field *fields = result->Fetch();
5784 bar.step();
5786 uint32 id = fields[0].GetUInt32();
5787 uint32 quest = fields[1].GetUInt32();
5789 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5791 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5792 continue;
5795 map.insert(QuestRelations::value_type(id,quest));
5797 ++count;
5798 } while (result->NextRow());
5800 delete result;
5802 sLog.outString();
5803 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5806 void ObjectMgr::LoadGameobjectQuestRelations()
5808 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5810 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5812 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5813 if(!goInfo)
5814 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5815 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5816 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5820 void ObjectMgr::LoadGameobjectInvolvedRelations()
5822 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5824 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5826 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5827 if(!goInfo)
5828 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5829 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5830 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5834 void ObjectMgr::LoadCreatureQuestRelations()
5836 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5838 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5840 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5841 if(!cInfo)
5842 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5843 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5844 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);
5848 void ObjectMgr::LoadCreatureInvolvedRelations()
5850 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
5852 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
5854 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5855 if(!cInfo)
5856 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5857 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5858 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);
5862 void ObjectMgr::LoadReservedPlayersNames()
5864 m_ReservedNames.clear(); // need for reload case
5866 QueryResult *result = WorldDatabase.PQuery("SELECT name FROM reserved_name");
5868 uint32 count = 0;
5870 if( !result )
5872 barGoLink bar( 1 );
5873 bar.step();
5875 sLog.outString();
5876 sLog.outString( ">> Loaded %u reserved player names", count );
5877 return;
5880 barGoLink bar( result->GetRowCount() );
5882 Field* fields;
5885 bar.step();
5886 fields = result->Fetch();
5887 std::string name= fields[0].GetCppString();
5888 if(normalizePlayerName(name))
5890 m_ReservedNames.insert(name);
5891 ++count;
5893 } while ( result->NextRow() );
5895 delete result;
5897 sLog.outString();
5898 sLog.outString( ">> Loaded %u reserved player names", count );
5901 enum LanguageType
5903 LT_BASIC_LATIN = 0x0000,
5904 LT_EXTENDEN_LATIN = 0x0001,
5905 LT_CYRILLIC = 0x0002,
5906 LT_EAST_ASIA = 0x0004,
5907 LT_ANY = 0xFFFF
5910 static LanguageType GetRealmLanguageType(bool create)
5912 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
5914 case REALM_ZONE_UNKNOWN: // any language
5915 case REALM_ZONE_DEVELOPMENT:
5916 case REALM_ZONE_TEST_SERVER:
5917 case REALM_ZONE_QA_SERVER:
5918 return LT_ANY;
5919 case REALM_ZONE_UNITED_STATES: // extended-Latin
5920 case REALM_ZONE_OCEANIC:
5921 case REALM_ZONE_LATIN_AMERICA:
5922 case REALM_ZONE_ENGLISH:
5923 case REALM_ZONE_GERMAN:
5924 case REALM_ZONE_FRENCH:
5925 case REALM_ZONE_SPANISH:
5926 return LT_EXTENDEN_LATIN;
5927 case REALM_ZONE_KOREA: // East-Asian
5928 case REALM_ZONE_TAIWAN:
5929 case REALM_ZONE_CHINA:
5930 return LT_EAST_ASIA;
5931 case REALM_ZONE_RUSSIAN: // Cyrillic
5932 return LT_CYRILLIC;
5933 default:
5934 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
5938 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
5940 if(strictMask==0) // any language, ignore realm
5942 if(isExtendedLatinString(wstr,numericOrSpace))
5943 return true;
5944 if(isCyrillicString(wstr,numericOrSpace))
5945 return true;
5946 if(isEastAsianString(wstr,numericOrSpace))
5947 return true;
5948 return false;
5951 if(strictMask & 0x2) // realm zone specific
5953 LanguageType lt = GetRealmLanguageType(create);
5954 if(lt & LT_EXTENDEN_LATIN)
5955 if(isExtendedLatinString(wstr,numericOrSpace))
5956 return true;
5957 if(lt & LT_CYRILLIC)
5958 if(isCyrillicString(wstr,numericOrSpace))
5959 return true;
5960 if(lt & LT_EAST_ASIA)
5961 if(isEastAsianString(wstr,numericOrSpace))
5962 return true;
5965 if(strictMask & 0x1) // basic latin
5967 if(isBasicLatinString(wstr,numericOrSpace))
5968 return true;
5971 return false;
5974 bool ObjectMgr::IsValidName( std::string name, bool create )
5976 std::wstring wname;
5977 if(!Utf8toWStr(name,wname))
5978 return false;
5980 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
5981 return false;
5983 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
5985 return isValidString(wname,strictMask,false,create);
5988 bool ObjectMgr::IsValidCharterName( std::string name )
5990 std::wstring wname;
5991 if(!Utf8toWStr(name,wname))
5992 return false;
5994 if(wname.size() < 1)
5995 return false;
5997 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
5999 return isValidString(wname,strictMask,true);
6002 bool ObjectMgr::IsValidPetName( std::string name )
6004 std::wstring wname;
6005 if(!Utf8toWStr(name,wname))
6006 return false;
6008 if(wname.size() < 1)
6009 return false;
6011 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6013 return isValidString(wname,strictMask,false);
6016 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6018 if(loc==LOCALE_enUS)
6019 return -1;
6021 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6022 if(m_LocalForIndex[i]==loc)
6023 return i;
6025 return -1;
6028 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6030 if (i<0 || i>=m_LocalForIndex.size())
6031 return LOCALE_enUS;
6033 return m_LocalForIndex[i];
6036 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6038 if(loc==LOCALE_enUS)
6039 return -1;
6041 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6042 if(m_LocalForIndex[i]==loc)
6043 return i;
6045 m_LocalForIndex.push_back(loc);
6046 return m_LocalForIndex.size()-1;
6049 void ObjectMgr::LoadBattleMastersEntry()
6051 mBattleMastersMap.clear(); // need for reload case
6053 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6055 uint32 count = 0;
6057 if( !result )
6059 barGoLink bar( 1 );
6060 bar.step();
6062 sLog.outString();
6063 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6064 return;
6067 barGoLink bar( result->GetRowCount() );
6071 ++count;
6072 bar.step();
6074 Field *fields = result->Fetch();
6076 uint32 entry = fields[0].GetUInt32();
6077 uint32 bgTypeId = fields[1].GetUInt32();
6079 mBattleMastersMap[entry] = bgTypeId;
6081 } while( result->NextRow() );
6083 delete result;
6085 sLog.outString();
6086 sLog.outString( ">> Loaded %u battlemaster entries", count );
6089 void ObjectMgr::LoadGameObjectForQuests()
6091 mGameObjectForQuestSet.clear(); // need for reload case
6093 uint32 count = 0;
6095 // collect GO entries for GO that must activated
6096 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6098 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6099 if(!goInfo)
6100 continue;
6102 switch(goInfo->type)
6104 // scan GO chest with loot including quest items
6105 case GAMEOBJECT_TYPE_CHEST:
6107 uint32 loot_id = GameObject::GetLootId(goInfo);
6109 // find quest loot for GO
6110 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6112 mGameObjectForQuestSet.insert(go_entry);
6113 ++count;
6115 break;
6117 case GAMEOBJECT_TYPE_GOOBER:
6119 if(goInfo->goober.questId) //quests objects
6121 mGameObjectForQuestSet.insert(go_entry);
6122 count++;
6124 break;
6126 default:
6127 break;
6131 sLog.outString();
6132 sLog.outString( ">> Loaded %u GameObject for quests", count );
6135 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6137 // cleanup affected map part for reloading case
6138 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6140 if(itr->first >= min_value && itr->first <= max_value)
6142 MangosStringLocaleMap::iterator itr2 = itr;
6143 ++itr;
6144 mMangosStringLocaleMap.erase(itr2);
6146 else
6147 ++itr;
6150 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);
6152 if(!result)
6154 barGoLink bar(1);
6156 bar.step();
6158 sLog.outString("");
6159 if(min_value > 0) // error only in case internal strings
6160 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6161 else
6162 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6163 return false;
6166 uint32 count = 0;
6168 barGoLink bar(result->GetRowCount());
6172 Field *fields = result->Fetch();
6173 bar.step();
6175 int32 entry = fields[0].GetInt32();
6177 if(entry==0)
6179 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6180 continue;
6182 else if(entry < min_value || entry > max_value)
6184 int32 start = min_value > 0 ? min_value : max_value;
6185 int32 end = min_value > 0 ? max_value : min_value;
6186 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6187 continue;
6190 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6192 if(data.Content.size() > 0)
6194 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6195 continue;
6198 data.Content.resize(1);
6199 ++count;
6201 // 0 -> default, idx in to idx+1
6202 data.Content[0] = fields[1].GetCppString();
6204 for(int i = 1; i < MAX_LOCALE; ++i)
6206 std::string str = fields[i+1].GetCppString();
6207 if(!str.empty())
6209 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6210 if(idx >= 0)
6212 // 0 -> default, idx in to idx+1
6213 if(data.Content.size() <= idx+1)
6214 data.Content.resize(idx+2);
6216 data.Content[idx+1] = str;
6220 } while (result->NextRow());
6222 delete result;
6224 sLog.outString();
6225 if(min_value > 0) // internal mangos strings
6226 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6227 else
6228 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6230 return true;
6233 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6235 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6236 // Content[0] always exist if exist MangosStringLocale
6237 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6239 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6240 return msl->Content[locale_idx+1].c_str();
6241 else
6242 return msl->Content[0].c_str();
6245 if(entry > 0)
6246 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6247 else
6248 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6249 return "<error>";
6252 void ObjectMgr::LoadFishingBaseSkillLevel()
6254 mFishingBaseForArea.clear(); // for relaod case
6256 uint32 count = 0;
6257 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6259 if( !result )
6261 barGoLink bar( 1 );
6263 bar.step();
6265 sLog.outString();
6266 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6267 return;
6270 barGoLink bar( result->GetRowCount() );
6274 bar.step();
6276 Field *fields = result->Fetch();
6277 uint32 entry = fields[0].GetUInt32();
6278 int32 skill = fields[1].GetInt32();
6280 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6281 if(!fArea)
6283 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6284 continue;
6287 mFishingBaseForArea[entry] = skill;
6288 ++count;
6290 while (result->NextRow());
6292 delete result;
6294 sLog.outString();
6295 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6298 // Searches for the same condition already in Conditions store
6299 // Returns Id if found, else adds it to Conditions and returns Id
6300 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6302 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6303 for (uint16 i=0; i < mConditions.size(); ++i)
6305 if (lc == mConditions[i])
6306 return i;
6309 mConditions.push_back(lc);
6311 if(mConditions.size() > 0xFFFF)
6313 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6314 return 0;
6317 return mConditions.size() - 1;
6320 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6322 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6324 std::wstring wname;
6325 if(!Utf8toWStr(names.name[i],wname))
6326 return false;
6328 if(mainpart!=GetMainPartOfName(wname,i+1))
6329 return false;
6331 return true;
6334 const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6336 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6337 if(i!= mAreaTriggerScripts.end())
6338 return i->second.c_str();
6339 return "";
6342 // Checks if player meets the condition
6343 bool PlayerCondition::Meets(Player const * player) const
6345 if( !player )
6346 return false; // player not present, return false
6348 switch (condition)
6350 case CONDITION_NONE:
6351 return true; // empty condition, always met
6352 case CONDITION_AURA:
6353 return player->HasAura(value1, value2);
6354 case CONDITION_ITEM:
6355 return player->HasItemCount(value1, value2);
6356 case CONDITION_ITEM_EQUIPPED:
6357 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6358 case CONDITION_ZONEID:
6359 return player->GetZoneId() == value1;
6360 case CONDITION_REPUTATION_RANK:
6362 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6363 return faction && player->GetReputationRank(faction) >= value2;
6365 case CONDITION_TEAM:
6366 return player->GetTeam() == value1;
6367 case CONDITION_SKILL:
6368 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6369 case CONDITION_QUESTREWARDED:
6370 return player->GetQuestRewardStatus(value1);
6371 case CONDITION_QUESTTAKEN:
6373 QuestStatus status = player->GetQuestStatus(value1);
6374 return (status == QUEST_STATUS_INCOMPLETE);
6376 case CONDITION_AD_COMMISSION_AURA:
6378 Unit::AuraMap const& auras = player->GetAuras();
6379 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6380 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6381 return true;
6382 return false;
6384 default:
6385 return false;
6389 // Verification of condition values validity
6390 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6392 if( condition >= MAX_CONDITION) // Wrong condition type
6394 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6395 return false;
6398 switch (condition)
6400 case CONDITION_AURA:
6402 if(!sSpellStore.LookupEntry(value1))
6404 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6405 return false;
6407 if(value2 > 2)
6409 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6410 return false;
6412 break;
6414 case CONDITION_ITEM:
6416 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6417 if(!proto)
6419 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6420 return false;
6422 break;
6424 case CONDITION_ITEM_EQUIPPED:
6426 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6427 if(!proto)
6429 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6430 return false;
6432 break;
6434 case CONDITION_ZONEID:
6436 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6437 if(!areaEntry)
6439 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6440 return false;
6442 if(areaEntry->zone != 0)
6444 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6445 return false;
6447 break;
6449 case CONDITION_REPUTATION_RANK:
6451 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6452 if(!factionEntry)
6454 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6455 return false;
6457 break;
6459 case CONDITION_TEAM:
6461 if (value1 != ALLIANCE && value1 != HORDE)
6463 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6464 return false;
6466 break;
6468 case CONDITION_SKILL:
6470 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6471 if (!pSkill)
6473 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6474 return false;
6476 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6478 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6479 return false;
6481 break;
6483 case CONDITION_QUESTREWARDED:
6484 case CONDITION_QUESTTAKEN:
6486 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6487 if (!Quest)
6489 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6490 return false;
6492 if(value2)
6493 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6494 break;
6496 case CONDITION_AD_COMMISSION_AURA:
6498 if(value1)
6499 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6500 if(value2)
6501 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6502 break;
6505 return true;
6508 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6510 switch(pSkill->categoryId)
6512 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6513 case SKILL_CATEGORY_WEAPON:
6514 if(pSkill->id!=SKILL_FIST_WEAPONS)
6515 return SKILL_RANGE_LEVEL;
6516 else
6517 return SKILL_RANGE_MONO;
6518 case SKILL_CATEGORY_ARMOR:
6519 case SKILL_CATEGORY_CLASS:
6520 if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6521 return SKILL_RANGE_MONO;
6522 else
6523 return SKILL_RANGE_LEVEL;
6524 case SKILL_CATEGORY_SECONDARY:
6525 case SKILL_CATEGORY_PROFESSION:
6526 // not set skills for professions and racial abilities
6527 if(IsProfessionSkill(pSkill->id))
6528 return SKILL_RANGE_RANK;
6529 else if(racial)
6530 return SKILL_RANGE_NONE;
6531 else
6532 return SKILL_RANGE_MONO;
6533 default:
6534 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6535 case SKILL_CATEGORY_NOT_DISPLAYED: //only GENEREC(DND)
6536 return SKILL_RANGE_NONE;
6540 void ObjectMgr::LoadGameTele()
6542 m_GameTeleMap.clear(); // for relaod case
6544 uint32 count = 0;
6545 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6547 if( !result )
6549 barGoLink bar( 1 );
6551 bar.step();
6553 sLog.outString();
6554 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6555 return;
6558 barGoLink bar( result->GetRowCount() );
6562 bar.step();
6564 Field *fields = result->Fetch();
6566 uint32 id = fields[0].GetUInt32();
6568 GameTele gt;
6570 gt.position_x = fields[1].GetFloat();
6571 gt.position_y = fields[2].GetFloat();
6572 gt.position_z = fields[3].GetFloat();
6573 gt.orientation = fields[4].GetFloat();
6574 gt.mapId = fields[5].GetUInt32();
6575 gt.name = fields[6].GetCppString();
6577 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6579 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6580 continue;
6583 if(!Utf8toWStr(gt.name,gt.wnameLow))
6585 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6586 continue;
6589 wstrToLower( gt.wnameLow );
6591 m_GameTeleMap[id] = gt;
6593 ++count;
6595 while (result->NextRow());
6597 delete result;
6599 sLog.outString();
6600 sLog.outString( ">> Loaded %u game tele's", count );
6603 GameTele const* ObjectMgr::GetGameTele(std::string name) const
6605 // explicit name case
6606 std::wstring wname;
6607 if(!Utf8toWStr(name,wname))
6608 return false;
6610 // converting string that we try to find to lower case
6611 wstrToLower( wname );
6613 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6614 if(itr->second.wnameLow == wname)
6615 return &itr->second;
6617 return NULL;
6620 bool ObjectMgr::AddGameTele(GameTele& tele)
6622 // find max id
6623 uint32 new_id = 0;
6624 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6625 if(itr->first > new_id)
6626 new_id = itr->first;
6628 // use next
6629 ++new_id;
6631 if(!Utf8toWStr(tele.name,tele.wnameLow))
6632 return false;
6634 wstrToLower( tele.wnameLow );
6636 m_GameTeleMap[new_id] = tele;
6638 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')",
6639 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6642 bool ObjectMgr::DeleteGameTele(std::string name)
6644 // explicit name case
6645 std::wstring wname;
6646 if(!Utf8toWStr(name,wname))
6647 return false;
6649 // converting string that we try to find to lower case
6650 wstrToLower( wname );
6652 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6654 if(itr->second.wnameLow == wname)
6656 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6657 m_GameTeleMap.erase(itr);
6658 return true;
6662 return false;
6665 void ObjectMgr::LoadTrainerSpell()
6667 // For reload case
6668 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6669 itr->second.Clear();
6670 m_mCacheTrainerSpellMap.clear();
6672 std::set<uint32> skip_trainers;
6674 QueryResult *result = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6676 if( !result )
6678 barGoLink bar( 1 );
6680 bar.step();
6682 sLog.outString();
6683 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6684 return;
6687 barGoLink bar( result->GetRowCount() );
6689 uint32 count = 0;
6692 bar.step();
6694 Field* fields = result->Fetch();
6696 uint32 entry = fields[0].GetUInt32();
6697 uint32 spell = fields[1].GetUInt32();
6699 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6701 if(!cInfo)
6703 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6704 continue;
6707 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6709 if(skip_trainers.count(entry) == 0)
6711 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6712 skip_trainers.insert(entry);
6714 continue;
6717 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6718 if(!spellinfo)
6720 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6721 continue;
6724 if(!SpellMgr::IsSpellValid(spellinfo))
6726 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6727 continue;
6730 TrainerSpell* pTrainerSpell = new TrainerSpell();
6731 pTrainerSpell->spell = spell;
6732 pTrainerSpell->spellcost = fields[2].GetUInt32();
6733 pTrainerSpell->reqskill = fields[3].GetUInt32();
6734 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6735 pTrainerSpell->reqlevel = fields[5].GetUInt32();
6737 if(!pTrainerSpell->reqlevel)
6738 pTrainerSpell->reqlevel = spellinfo->spellLevel;
6741 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6743 if(SpellMgr::IsProfessionSpell(spell))
6744 data.trainerType = 2;
6746 data.spellList.push_back(pTrainerSpell);
6747 ++count;
6749 } while (result->NextRow());
6750 delete result;
6752 sLog.outString();
6753 sLog.outString( ">> Loaded Trainers %d", count );
6756 void ObjectMgr::LoadVendors()
6758 // For reload case
6759 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6760 itr->second.Clear();
6761 m_mCacheVendorItemMap.clear();
6763 std::set<uint32> skip_vendors;
6765 QueryResult *result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6766 if( !result )
6768 barGoLink bar( 1 );
6770 bar.step();
6772 sLog.outString();
6773 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6774 return;
6777 barGoLink bar( result->GetRowCount() );
6779 uint32 count = 0;
6782 bar.step();
6783 Field* fields = result->Fetch();
6785 uint32 entry = fields[0].GetUInt32();
6786 uint32 item_id = fields[1].GetUInt32();
6787 uint32 maxcount = fields[2].GetUInt32();
6788 uint32 incrtime = fields[3].GetUInt32();
6789 uint32 ExtendedCost = fields[4].GetUInt32();
6791 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6792 continue;
6794 VendorItemData& vList = m_mCacheVendorItemMap[entry];
6796 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
6797 ++count;
6799 } while (result->NextRow());
6800 delete result;
6802 sLog.outString();
6803 sLog.outString( ">> Loaded %d Vendors ", count );
6806 void ObjectMgr::LoadNpcTextId()
6809 m_mCacheNpcTextIdMap.clear();
6811 QueryResult* result = WorldDatabase.PQuery("SELECT npc_guid, textid FROM npc_gossip");
6812 if( !result )
6814 barGoLink bar( 1 );
6816 bar.step();
6818 sLog.outString();
6819 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
6820 return;
6823 barGoLink bar( result->GetRowCount() );
6825 uint32 count = 0;
6826 uint32 guid,textid;
6829 bar.step();
6831 Field* fields = result->Fetch();
6833 guid = fields[0].GetUInt32();
6834 textid = fields[1].GetUInt32();
6836 if (!GetCreatureData(guid))
6838 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
6839 continue;
6841 if (!GetGossipText(textid))
6843 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
6844 continue;
6847 m_mCacheNpcTextIdMap[guid] = textid ;
6848 ++count;
6850 } while (result->NextRow());
6851 delete result;
6853 sLog.outString();
6854 sLog.outString( ">> Loaded %d NpcTextId ", count );
6857 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
6859 VendorItemData& vList = m_mCacheVendorItemMap[entry];
6860 vList.AddItem(item,maxcount,incrtime,extendedcost);
6862 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
6865 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
6867 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
6868 if(iter == m_mCacheVendorItemMap.end())
6869 return false;
6871 if(!iter->second.FindItem(item))
6872 return false;
6874 iter->second.RemoveItem(item);
6875 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
6876 return true;
6879 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
6881 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
6882 if(!cInfo)
6884 if(pl)
6885 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6886 else
6887 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
6888 return false;
6891 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
6893 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
6895 if(pl)
6896 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
6897 else
6898 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
6900 if(skip_vendors)
6901 skip_vendors->insert(vendor_entry);
6903 return false;
6906 if(!GetItemPrototype(item_id))
6908 if(pl)
6909 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
6910 else
6911 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
6912 return false;
6915 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
6917 if(pl)
6918 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
6919 else
6920 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
6921 return false;
6924 if(maxcount > 0 && incrtime == 0)
6926 if(pl)
6927 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
6928 else
6929 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
6930 return false;
6932 else if(maxcount==0 && incrtime > 0)
6934 if(pl)
6935 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
6936 else
6937 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
6938 return false;
6941 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
6942 if(!vItems)
6943 return true; // later checks for non-empty lists
6945 if(vItems->FindItem(item_id))
6947 if(pl)
6948 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
6949 else
6950 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
6951 return false;
6954 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
6956 if(pl)
6957 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
6958 else
6959 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
6960 return false;
6963 return true;
6966 // Functions for scripting access
6967 const char* GetAreaTriggerScriptNameById(uint32 id)
6969 return objmgr.GetAreaTriggerScriptName(id);
6972 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
6974 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
6976 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());
6977 start_value = -1;
6978 end_value = std::numeric_limits<int32>::min();
6981 // for scripting localized strings allowed use _only_ negative entries
6982 return objmgr.LoadMangosStrings(db,table,end_value,start_value);