[9411] More SpellEffectIndex using in apropriate cases
[getmangos.git] / src / game / ObjectMgr.cpp
blob2e20342af1b1414c3d97befae64c9386968e73c3
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
23 #include "Policies/SingletonImp.h"
25 #include "Log.h"
26 #include "MapManager.h"
27 #include "ObjectMgr.h"
28 #include "ObjectDefines.h"
29 #include "SpellMgr.h"
30 #include "UpdateMask.h"
31 #include "World.h"
32 #include "Group.h"
33 #include "Guild.h"
34 #include "ArenaTeam.h"
35 #include "Transports.h"
36 #include "ProgressBar.h"
37 #include "Language.h"
38 #include "GameEventMgr.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
45 #include "WaypointManager.h"
46 #include "GossipDef.h"
48 INSTANTIATE_SINGLETON_1(ObjectMgr);
50 ScriptMapMap sQuestEndScripts;
51 ScriptMapMap sQuestStartScripts;
52 ScriptMapMap sSpellScripts;
53 ScriptMapMap sGameObjectScripts;
54 ScriptMapMap sEventScripts;
55 ScriptMapMap sGossipScripts;
57 bool normalizePlayerName(std::string& name)
59 if(name.empty())
60 return false;
62 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
63 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
65 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
66 return false;
68 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
69 for(size_t i = 1; i < wstr_len; ++i)
70 wstr_buf[i] = wcharToLower(wstr_buf[i]);
72 if(!WStrToUtf8(wstr_buf,wstr_len,name))
73 return false;
75 return true;
78 LanguageDesc lang_description[LANGUAGES_COUNT] =
80 { LANG_ADDON, 0, 0 },
81 { LANG_UNIVERSAL, 0, 0 },
82 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
83 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
84 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
85 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
86 { LANG_COMMON, 668, SKILL_LANG_COMMON },
87 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
88 { LANG_TITAN, 816, SKILL_LANG_TITAN },
89 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
90 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
91 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
92 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
93 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
94 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
95 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
96 { LANG_ZOMBIE, 0, 0 },
97 { LANG_GNOMISH_BINARY, 0, 0 },
98 { LANG_GOBLIN_BINARY, 0, 0 }
101 LanguageDesc const* GetLanguageDescByID(uint32 lang)
103 for(int i = 0; i < LANGUAGES_COUNT; ++i)
105 if(uint32(lang_description[i].lang_id) == lang)
106 return &lang_description[i];
109 return NULL;
112 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
114 if(questStart)
116 // not in expected required quest state
117 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
118 return false;
121 if(questEnd)
123 // not in expected forbidden quest state
124 if(!player || player->GetQuestRewardStatus(questEnd))
125 return false;
128 return true;
131 ObjectMgr::ObjectMgr()
133 m_hiCharGuid = 1;
134 m_hiCreatureGuid = 1;
135 m_hiItemGuid = 1;
136 m_hiGoGuid = 1;
137 m_hiCorpseGuid = 1;
138 m_hiPetNumber = 1;
139 m_ItemTextId = 1;
140 m_mailid = 1;
141 m_equipmentSetGuid = 1;
142 m_guildId = 1;
143 m_arenaTeamId = 1;
144 m_auctionid = 1;
145 m_groupId = 1;
147 // Only zero condition left, others will be added while loading DB tables
148 mConditions.resize(1);
151 ObjectMgr::~ObjectMgr()
153 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
154 delete i->second;
156 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
157 delete[] i->second;
159 // free only if loaded
160 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
161 delete[] playerClassInfo[class_].levelInfo;
163 for (int race = 0; race < MAX_RACES; ++race)
164 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
165 delete[] playerInfo[race][class_].levelInfo;
167 // free group and guild objects
168 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end(); ++itr)
169 delete itr->second;
171 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
172 delete itr->second;
174 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
175 delete itr->second;
177 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
178 itr->second.Clear();
180 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
181 itr->second.Clear();
184 Group* ObjectMgr::GetGroupById(uint32 id) const
186 GroupMap::const_iterator itr = mGroupMap.find(id);
187 if (itr != mGroupMap.end())
188 return itr->second;
190 return NULL;
193 Guild* ObjectMgr::GetGuildById(uint32 GuildId) const
195 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
196 if (itr != mGuildMap.end())
197 return itr->second;
199 return NULL;
202 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
204 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
205 if (itr->second->GetName() == guildname)
206 return itr->second;
208 return NULL;
211 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
213 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
214 if (itr != mGuildMap.end())
215 return itr->second->GetName();
217 return "";
220 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
222 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
223 if (itr->second->GetLeader() == guid)
224 return itr->second;
226 return NULL;
229 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
231 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
232 if (itr != mArenaTeamMap.end())
233 return itr->second;
235 return NULL;
238 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
240 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
241 if (itr->second->GetName() == arenateamname)
242 return itr->second;
244 return NULL;
247 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
249 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
250 if (itr->second->GetCaptain() == guid)
251 return itr->second;
253 return NULL;
256 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
258 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
261 void ObjectMgr::LoadCreatureLocales()
263 mCreatureLocaleMap.clear(); // need for reload case
265 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");
267 if(!result)
269 barGoLink bar(1);
271 bar.step();
273 sLog.outString();
274 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
275 return;
278 barGoLink bar((int)result->GetRowCount());
282 Field *fields = result->Fetch();
283 bar.step();
285 uint32 entry = fields[0].GetUInt32();
287 CreatureLocale& data = mCreatureLocaleMap[entry];
289 for(int i = 1; i < MAX_LOCALE; ++i)
291 std::string str = fields[1+2*(i-1)].GetCppString();
292 if(!str.empty())
294 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
295 if(idx >= 0)
297 if((int32)data.Name.size() <= idx)
298 data.Name.resize(idx+1);
300 data.Name[idx] = str;
303 str = fields[1+2*(i-1)+1].GetCppString();
304 if(!str.empty())
306 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
307 if(idx >= 0)
309 if((int32)data.SubName.size() <= idx)
310 data.SubName.resize(idx+1);
312 data.SubName[idx] = str;
316 } while (result->NextRow());
318 delete result;
320 sLog.outString();
321 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
324 void ObjectMgr::LoadGossipMenuItemsLocales()
326 mGossipMenuItemsLocaleMap.clear(); // need for reload case
328 QueryResult *result = WorldDatabase.Query("SELECT menu_id,id,"
329 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
330 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
331 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
332 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
333 "FROM locales_gossip_menu_option");
335 if(!result)
337 barGoLink bar(1);
339 bar.step();
341 sLog.outString();
342 sLog.outString(">> Loaded 0 gossip_menu_option locale strings. DB table `locales_gossip_menu_option` is empty.");
343 return;
346 barGoLink bar((int)result->GetRowCount());
350 Field *fields = result->Fetch();
351 bar.step();
353 uint16 menuId = fields[0].GetUInt16();
354 uint16 id = fields[1].GetUInt16();
356 GossipMenuItemsLocale& data = mGossipMenuItemsLocaleMap[MAKE_PAIR32(menuId,id)];
358 for(int i = 1; i < MAX_LOCALE; ++i)
360 std::string str = fields[2+2*(i-1)].GetCppString();
361 if(!str.empty())
363 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
364 if(idx >= 0)
366 if((int32)data.OptionText.size() <= idx)
367 data.OptionText.resize(idx+1);
369 data.OptionText[idx] = str;
372 str = fields[2+2*(i-1)+1].GetCppString();
373 if(!str.empty())
375 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
376 if(idx >= 0)
378 if((int32)data.BoxText.size() <= idx)
379 data.BoxText.resize(idx+1);
381 data.BoxText[idx] = str;
385 } while (result->NextRow());
387 delete result;
389 sLog.outString();
390 sLog.outString( ">> Loaded %lu gossip_menu_option locale strings", (unsigned long)mGossipMenuItemsLocaleMap.size() );
393 void ObjectMgr::LoadPointOfInterestLocales()
395 mPointOfInterestLocaleMap.clear(); // need for reload case
397 QueryResult *result = WorldDatabase.Query("SELECT entry,icon_name_loc1,icon_name_loc2,icon_name_loc3,icon_name_loc4,icon_name_loc5,icon_name_loc6,icon_name_loc7,icon_name_loc8 FROM locales_points_of_interest");
399 if(!result)
401 barGoLink bar(1);
403 bar.step();
405 sLog.outString();
406 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
407 return;
410 barGoLink bar((int)result->GetRowCount());
414 Field *fields = result->Fetch();
415 bar.step();
417 uint32 entry = fields[0].GetUInt32();
419 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
421 for(int i = 1; i < MAX_LOCALE; ++i)
423 std::string str = fields[i].GetCppString();
424 if(str.empty())
425 continue;
427 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
428 if(idx >= 0)
430 if((int32)data.IconName.size() <= idx)
431 data.IconName.resize(idx+1);
433 data.IconName[idx] = str;
436 } while (result->NextRow());
438 delete result;
440 sLog.outString();
441 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
444 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
446 template<class D>
447 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
449 dst = D(sObjectMgr.GetScriptId(src));
453 void ObjectMgr::LoadCreatureTemplates()
455 SQLCreatureLoader loader;
456 loader.Load(sCreatureStorage);
458 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
459 sLog.outString();
461 std::set<uint32> difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures
462 std::set<uint32> hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values
464 // check data correctness
465 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
467 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
468 if (!cInfo)
469 continue;
471 bool ok = true; // bool to allow continue outside this loop
472 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
474 if (!cInfo->DifficultyEntry[diff])
475 continue;
476 ok = false; // will be set to true at the end of this loop again
478 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]);
479 if (!difficultyInfo)
481 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u not exist.",
482 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]);
483 continue;
486 if (difficultyEntries[diff].find(i) != difficultyEntries[diff].end())
488 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty %u but have value in `difficulty_entry_%u`.", i, diff + 1, diff + 1);
489 continue;
492 bool ok2 = true;
493 for (uint32 diff2 = 0; diff2 < MAX_DIFFICULTY - 1 && ok2; ++diff2)
495 ok2 = false;
496 if (difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != difficultyEntries[diff2].end())
498 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty %u for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1);
499 continue;
502 if (hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != hasDifficultyEntries[diff2].end())
504 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u have difficulty %u entry also.",
505 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1);
506 continue;
508 ok2 = true;
510 if (!ok2)
511 continue;
513 if (cInfo->unit_class != difficultyInfo->unit_class)
515 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).",
516 i, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class);
517 continue;
520 if (cInfo->npcflag != difficultyInfo->npcflag)
522 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
523 continue;
526 if (cInfo->trainer_class != difficultyInfo->trainer_class)
528 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
529 continue;
532 if (cInfo->trainer_race != difficultyInfo->trainer_race)
534 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
535 continue;
538 if (cInfo->trainer_type != difficultyInfo->trainer_type)
540 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
541 continue;
544 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
546 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
547 continue;
550 if (difficultyInfo->AIName && *difficultyInfo->AIName)
552 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",
553 diff, cInfo->DifficultyEntry[diff], i);
554 continue;
557 if (difficultyInfo->ScriptID)
559 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",
560 diff, cInfo->DifficultyEntry[diff], i);
561 continue;
564 hasDifficultyEntries[diff].insert(i);
565 difficultyEntries[diff].insert(cInfo->DifficultyEntry[diff]);
566 ok = true;
568 if (!ok)
569 continue;
571 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
572 if (!factionTemplate)
573 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
575 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
576 if (!factionTemplate)
577 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
579 // used later for scale
580 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
582 if (cInfo->DisplayID_A[0])
584 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
585 if(!displayEntry)
587 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
588 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
590 else if(!displayScaleEntry)
591 displayScaleEntry = displayEntry;
593 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
594 if (!minfo)
595 sLog.outErrorDb("Creature (Entry: %u) are using modelid_A (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_A[0]);
598 if (cInfo->DisplayID_A[1])
600 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
601 if(!displayEntry)
603 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
604 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
606 else if(!displayScaleEntry)
607 displayScaleEntry = displayEntry;
609 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
610 if (!minfo)
611 sLog.outErrorDb("Creature (Entry: %u) are using modelid_A2 (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_A[1]);
614 if (cInfo->DisplayID_H[0])
616 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
617 if(!displayEntry)
619 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
620 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
622 else if(!displayScaleEntry)
623 displayScaleEntry = displayEntry;
625 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
626 if (!minfo)
627 sLog.outErrorDb("Creature (Entry: %u) are using modelid_H (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_H[0]);
630 if (cInfo->DisplayID_H[1])
632 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
633 if(!displayEntry)
635 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
636 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
638 else if(!displayScaleEntry)
639 displayScaleEntry = displayEntry;
641 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
642 if (!minfo)
643 sLog.outErrorDb("Creature (Entry: %u) are using modelid_H2 (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_H[1]);
646 if (!displayScaleEntry)
647 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid in modelid_A/modelid_A2/modelid_H/modelid_A2", cInfo->Entry);
649 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
651 if(cInfo->KillCredit[k])
653 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
655 sLog.outErrorDb("Creature (Entry: %u) has nonexistent creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
656 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
661 // use below code for 0-checks for unit_class
662 if (/*!cInfo->unit_class ||*/cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
663 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
665 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
667 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
668 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
671 if(cInfo->baseattacktime == 0)
672 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
674 if(cInfo->rangeattacktime == 0)
675 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
677 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
679 sLog.outErrorDb("Creature (Entry: %u) has dynamic flag UNIT_NPC_FLAG_SPELLCLICK (%u) set, it expect to be set by code base at `npc_spellclick_spells` content.",cInfo->Entry,UNIT_NPC_FLAG_SPELLCLICK);
680 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
683 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
684 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
686 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
688 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
689 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
692 // must exist or used hidden but used in data horse case
693 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
695 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
696 const_cast<CreatureInfo*>(cInfo)->family = 0;
699 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
701 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
702 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
705 if(cInfo->PetSpellDataId)
707 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
708 if(!spellDataId)
709 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
712 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
714 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
716 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
717 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
721 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
723 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
724 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
727 if(cInfo->equipmentId > 0) // 0 no equipment
729 if(!GetEquipmentInfo(cInfo->equipmentId))
731 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);
732 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
736 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
737 if(cInfo->scale <= 0.0f)
739 if(displayScaleEntry)
740 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
741 else
742 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
747 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
749 // Now add the auras, format "spellid effectindex spellid effectindex..."
750 char *p,*s;
751 std::vector<int> val;
752 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
753 if(p)
755 while (p[0]!=0)
757 ++p;
758 if (p[0]==' ')
760 val.push_back(atoi(s));
761 s=++p;
764 if (p!=s)
765 val.push_back(atoi(s));
767 // free char* loaded memory
768 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
770 // wrong list
771 if (val.size()%2)
773 addon->auras = NULL;
774 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
775 return;
779 // empty list
780 if(val.empty())
782 addon->auras = NULL;
783 return;
786 // replace by new structures array
787 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
789 uint32 i=0;
790 for(uint32 j = 0; j < val.size()/2; ++j)
792 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
793 cAura.spell_id = uint32(val[2*j+0]);
794 cAura.effect_idx = SpellEffectIndex(val[2*j+1]);
795 if (cAura.effect_idx >= MAX_EFFECT_INDEX)
797 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);
798 continue;
800 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
801 if (!AdditionalSpellInfo)
803 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
804 continue;
807 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
809 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);
810 continue;
813 ++i;
816 // fill terminator element (after last added)
817 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
818 endAura.spell_id = 0;
819 endAura.effect_idx = EFFECT_INDEX_0;
822 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
824 creatureaddons.Load();
826 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
827 sLog.outString();
829 // check data correctness and convert 'auras'
830 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
832 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
833 if(!addon)
834 continue;
836 if (addon->mount)
838 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
840 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
841 const_cast<CreatureDataAddon*>(addon)->mount = 0;
845 if (!sEmotesStore.LookupEntry(addon->emote))
846 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
848 if (addon->splineFlags & (SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3))
850 sLog.outErrorDb("Creature (%s %u) spline flags mask defined in `%s` include forbidden flags (" I32FMT ") that can crash client, cleanup at load.", entryName, addon->guidOrEntry, creatureaddons.GetTableName(), (SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3));
851 const_cast<CreatureDataAddon*>(addon)->splineFlags &= ~(SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3);
854 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
858 void ObjectMgr::LoadCreatureAddons()
860 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
862 // check entry ids
863 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
864 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
865 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
866 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
868 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
870 // check entry ids
871 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
872 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
873 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
874 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
877 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
879 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
882 void ObjectMgr::LoadEquipmentTemplates()
884 sEquipmentStorage.Load();
886 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
888 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
890 if(!eqInfo)
891 continue;
893 for(uint8 j=0; j<3; j++)
895 if(!eqInfo->equipentry[j])
896 continue;
898 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
900 if(!dbcitem)
902 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
903 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
904 continue;
907 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
908 dbcitem->InventoryType != INVTYPE_SHIELD &&
909 dbcitem->InventoryType != INVTYPE_RANGED &&
910 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
911 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
912 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
913 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
914 dbcitem->InventoryType != INVTYPE_THROWN &&
915 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
917 sLog.outErrorDb("Item (entry=%u) in creature_equip_template.equipentry%u for entry = %u is not equipable in a hand, forced to 0.", eqInfo->equipentry[j], j+1, i);
918 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
922 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
923 sLog.outString();
926 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
928 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
931 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
933 // Load creature model (display id)
934 if (data && data->displayid)
935 return data->displayid;
937 // use defaults from the template
938 uint32 display_id;
940 // DisplayID_A is used if no team is given
941 if (team == HORDE)
943 if(cinfo->DisplayID_H[0])
944 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
945 else
946 display_id = cinfo->DisplayID_H[1];
948 if(!display_id)
949 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
951 else
953 if(cinfo->DisplayID_A[0])
954 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
955 else
956 display_id = cinfo->DisplayID_A[1];
958 if(!display_id)
959 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
962 return display_id;
965 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
967 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
968 if(!minfo)
969 return NULL;
971 // If a model for another gender exists, 50% chance to use it
972 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
974 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
975 if(!minfo_tmp)
977 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
978 return minfo; // not fatal, just use the previous one
980 else
981 return minfo_tmp;
983 else
984 return minfo;
987 void ObjectMgr::LoadCreatureModelInfo()
989 sCreatureModelStorage.Load();
991 // post processing
992 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
994 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
995 if (!minfo)
996 continue;
998 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
999 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
1001 if (minfo->gender > GENDER_NONE)
1003 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1004 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1007 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1009 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1010 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1014 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1015 sLog.outString();
1018 void ObjectMgr::LoadCreatures()
1020 uint32 count = 0;
1021 // 0 1 2 3
1022 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1023 // 4 5 6 7 8 9 10 11
1024 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1025 // 12 13 14 15 16 17 18 19
1026 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1027 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1028 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1030 if(!result)
1032 barGoLink bar(1);
1034 bar.step();
1036 sLog.outString();
1037 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1038 return;
1041 // build single time for check creature data
1042 std::set<uint32> difficultyCreatures[MAX_DIFFICULTY - 1];
1043 for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1044 if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1045 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
1046 if (cInfo->DifficultyEntry[diff])
1047 difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]);
1049 // build single time for check spawnmask
1050 std::map<uint32,uint32> spawnMasks;
1051 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1052 if(sMapStore.LookupEntry(i))
1053 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1054 if (GetMapDifficultyData(i,Difficulty(k)))
1055 spawnMasks[i] |= (1 << k);
1057 barGoLink bar((int)result->GetRowCount());
1061 Field *fields = result->Fetch();
1062 bar.step();
1064 uint32 guid = fields[ 0].GetUInt32();
1065 uint32 entry = fields[ 1].GetUInt32();
1067 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1068 if(!cInfo)
1070 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1071 continue;
1074 CreatureData& data = mCreatureDataMap[guid];
1076 data.id = entry;
1077 data.mapid = fields[ 2].GetUInt32();
1078 data.displayid = fields[ 3].GetUInt32();
1079 data.equipmentId = fields[ 4].GetUInt32();
1080 data.posX = fields[ 5].GetFloat();
1081 data.posY = fields[ 6].GetFloat();
1082 data.posZ = fields[ 7].GetFloat();
1083 data.orientation = fields[ 8].GetFloat();
1084 data.spawntimesecs = fields[ 9].GetUInt32();
1085 data.spawndist = fields[10].GetFloat();
1086 data.currentwaypoint= fields[11].GetUInt32();
1087 data.curhealth = fields[12].GetUInt32();
1088 data.curmana = fields[13].GetUInt32();
1089 data.is_dead = fields[14].GetBool();
1090 data.movementType = fields[15].GetUInt8();
1091 data.spawnMask = fields[16].GetUInt8();
1092 data.phaseMask = fields[17].GetUInt16();
1093 int16 gameEvent = fields[18].GetInt16();
1094 int16 PoolId = fields[19].GetInt16();
1096 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1097 if(!mapEntry)
1099 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1100 continue;
1103 if (data.spawnMask & ~spawnMasks[data.mapid])
1104 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that have wrong spawn mask %u including not supported difficulty modes for map (Id: %u).",guid, data.spawnMask, data.mapid );
1106 bool ok = true;
1107 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
1109 if (difficultyCreatures[diff].find(data.id) != difficultyCreatures[diff].end())
1111 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.",
1112 guid, diff + 1, data.id );
1113 ok = false;
1116 if (!ok)
1117 continue;
1119 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1121 if(!GetEquipmentInfo(data.equipmentId))
1123 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);
1124 data.equipmentId = -1;
1128 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1130 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 );
1131 data.curhealth = cInfo->minhealth;
1134 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1136 if(!mapEntry || !mapEntry->IsDungeon())
1137 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`flags_extra` including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.",guid,data.id);
1140 if(data.curmana < cInfo->minmana)
1142 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 );
1143 data.curmana = cInfo->minmana;
1146 if(data.spawndist < 0.0f)
1148 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1149 data.spawndist = 0.0f;
1151 else if(data.movementType == RANDOM_MOTION_TYPE)
1153 if(data.spawndist == 0.0f)
1155 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 );
1156 data.movementType = IDLE_MOTION_TYPE;
1159 else if(data.movementType == IDLE_MOTION_TYPE)
1161 if(data.spawndist != 0.0f)
1163 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1164 data.spawndist = 0.0f;
1168 if(data.phaseMask==0)
1170 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1171 data.phaseMask = 1;
1174 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1175 AddCreatureToGrid(guid, &data);
1177 ++count;
1179 } while (result->NextRow());
1181 delete result;
1183 sLog.outString();
1184 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1187 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1189 uint8 mask = data->spawnMask;
1190 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1192 if(mask & 1)
1194 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1195 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1197 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1198 cell_guids.creatures.insert(guid);
1203 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1205 uint8 mask = data->spawnMask;
1206 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1208 if(mask & 1)
1210 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1211 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1213 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1214 cell_guids.creatures.erase(guid);
1219 void ObjectMgr::LoadGameobjects()
1221 uint32 count = 0;
1223 // 0 1 2 3 4 5 6
1224 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1225 // 7 8 9 10 11 12 13 14 15 16 17
1226 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1227 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1228 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1230 if(!result)
1232 barGoLink bar(1);
1234 bar.step();
1236 sLog.outString();
1237 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1238 return;
1241 // build single time for check spawnmask
1242 std::map<uint32,uint32> spawnMasks;
1243 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1244 if(sMapStore.LookupEntry(i))
1245 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1246 if (GetMapDifficultyData(i,Difficulty(k)))
1247 spawnMasks[i] |= (1 << k);
1249 barGoLink bar((int)result->GetRowCount());
1253 Field *fields = result->Fetch();
1254 bar.step();
1256 uint32 guid = fields[ 0].GetUInt32();
1257 uint32 entry = fields[ 1].GetUInt32();
1259 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1260 if (!gInfo)
1262 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1263 continue;
1266 if(!gInfo->displayId)
1268 switch(gInfo->type)
1270 // can be invisible always and then not req. display id in like case
1271 case GAMEOBJECT_TYPE_TRAP:
1272 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1273 break;
1274 default:
1275 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1276 break;
1279 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1281 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1282 continue;
1285 GameObjectData& data = mGameObjectDataMap[guid];
1287 data.id = entry;
1288 data.mapid = fields[ 2].GetUInt32();
1289 data.posX = fields[ 3].GetFloat();
1290 data.posY = fields[ 4].GetFloat();
1291 data.posZ = fields[ 5].GetFloat();
1292 data.orientation = fields[ 6].GetFloat();
1293 data.rotation0 = fields[ 7].GetFloat();
1294 data.rotation1 = fields[ 8].GetFloat();
1295 data.rotation2 = fields[ 9].GetFloat();
1296 data.rotation3 = fields[10].GetFloat();
1297 data.spawntimesecs = fields[11].GetInt32();
1299 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1300 if(!mapEntry)
1302 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1303 continue;
1306 if (data.spawnMask & ~spawnMasks[data.mapid])
1307 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that have wrong spawn mask %u including not supported difficulty modes for map (Id: %u), skip", guid, data.id, data.spawnMask, data.mapid);
1309 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1311 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1314 data.animprogress = fields[12].GetUInt32();
1316 uint32 go_state = fields[13].GetUInt32();
1317 if (go_state >= MAX_GO_STATE)
1319 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1320 continue;
1322 data.go_state = GOState(go_state);
1324 data.spawnMask = fields[14].GetUInt8();
1325 data.phaseMask = fields[15].GetUInt16();
1326 int16 gameEvent = fields[16].GetInt16();
1327 int16 PoolId = fields[17].GetInt16();
1329 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1331 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1332 continue;
1335 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1337 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1338 continue;
1341 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1343 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1344 continue;
1347 if(data.phaseMask == 0)
1349 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1350 data.phaseMask = 1;
1353 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1354 AddGameobjectToGrid(guid, &data);
1355 ++count;
1357 } while (result->NextRow());
1359 delete result;
1361 sLog.outString();
1362 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1365 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1367 uint8 mask = data->spawnMask;
1368 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1370 if(mask & 1)
1372 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1373 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1375 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1376 cell_guids.gameobjects.insert(guid);
1381 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1383 uint8 mask = data->spawnMask;
1384 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1386 if(mask & 1)
1388 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1389 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1391 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1392 cell_guids.gameobjects.erase(guid);
1397 void ObjectMgr::LoadCreatureRespawnTimes()
1399 // remove outdated data
1400 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1402 uint32 count = 0;
1404 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1406 if(!result)
1408 barGoLink bar(1);
1410 bar.step();
1412 sLog.outString();
1413 sLog.outString(">> Loaded 0 creature respawn time.");
1414 return;
1417 barGoLink bar((int)result->GetRowCount());
1421 Field *fields = result->Fetch();
1422 bar.step();
1424 uint32 loguid = fields[0].GetUInt32();
1425 uint64 respawn_time = fields[1].GetUInt64();
1426 uint32 instance = fields[2].GetUInt32();
1428 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1430 ++count;
1431 } while (result->NextRow());
1433 delete result;
1435 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1436 sLog.outString();
1439 void ObjectMgr::LoadGameobjectRespawnTimes()
1441 // remove outdated data
1442 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1444 uint32 count = 0;
1446 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1448 if(!result)
1450 barGoLink bar(1);
1452 bar.step();
1454 sLog.outString();
1455 sLog.outString(">> Loaded 0 gameobject respawn time.");
1456 return;
1459 barGoLink bar((int)result->GetRowCount());
1463 Field *fields = result->Fetch();
1464 bar.step();
1466 uint32 loguid = fields[0].GetUInt32();
1467 uint64 respawn_time = fields[1].GetUInt64();
1468 uint32 instance = fields[2].GetUInt32();
1470 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1472 ++count;
1473 } while (result->NextRow());
1475 delete result;
1477 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1478 sLog.outString();
1481 // name must be checked to correctness (if received) before call this function
1482 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1484 uint64 guid = 0;
1486 CharacterDatabase.escape_string(name);
1488 // Player name safe to sending to DB (checked at login) and this function using
1489 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1490 if(result)
1492 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1494 delete result;
1497 return guid;
1500 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1502 // prevent DB access for online player
1503 if(Player* player = GetPlayer(guid))
1505 name = player->GetName();
1506 return true;
1509 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1511 if(result)
1513 name = (*result)[0].GetCppString();
1514 delete result;
1515 return true;
1518 return false;
1521 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1523 // prevent DB access for online player
1524 if(Player* player = GetPlayer(guid))
1526 return Player::TeamForRace(player->getRace());
1529 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1531 if(result)
1533 uint8 race = (*result)[0].GetUInt8();
1534 delete result;
1535 return Player::TeamForRace(race);
1538 return 0;
1541 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1543 // prevent DB access for online player
1544 if(Player* player = GetPlayer(guid))
1546 return player->GetSession()->GetAccountId();
1549 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1550 if(result)
1552 uint32 acc = (*result)[0].GetUInt32();
1553 delete result;
1554 return acc;
1557 return 0;
1560 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1562 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1563 if(result)
1565 uint32 acc = (*result)[0].GetUInt32();
1566 delete result;
1567 return acc;
1570 return 0;
1573 void ObjectMgr::LoadItemLocales()
1575 mItemLocaleMap.clear(); // need for reload case
1577 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");
1579 if(!result)
1581 barGoLink bar(1);
1583 bar.step();
1585 sLog.outString();
1586 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1587 return;
1590 barGoLink bar((int)result->GetRowCount());
1594 Field *fields = result->Fetch();
1595 bar.step();
1597 uint32 entry = fields[0].GetUInt32();
1599 ItemLocale& data = mItemLocaleMap[entry];
1601 for(int i = 1; i < MAX_LOCALE; ++i)
1603 std::string str = fields[1+2*(i-1)].GetCppString();
1604 if(!str.empty())
1606 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1607 if(idx >= 0)
1609 if((int32)data.Name.size() <= idx)
1610 data.Name.resize(idx+1);
1612 data.Name[idx] = str;
1616 str = fields[1+2*(i-1)+1].GetCppString();
1617 if(!str.empty())
1619 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1620 if(idx >= 0)
1622 if((int32)data.Description.size() <= idx)
1623 data.Description.resize(idx+1);
1625 data.Description[idx] = str;
1629 } while (result->NextRow());
1631 delete result;
1633 sLog.outString();
1634 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1637 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1639 template<class D>
1640 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1642 dst = D(sObjectMgr.GetScriptId(src));
1646 void ObjectMgr::LoadItemPrototypes()
1648 SQLItemLoader loader;
1649 loader.Load(sItemStorage);
1650 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1651 sLog.outString();
1653 // check data correctness
1654 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1656 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1657 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1658 if(!proto)
1660 /* to many errors, and possible not all items really used in game
1661 if (dbcitem)
1662 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1664 continue;
1667 if(dbcitem)
1669 if(proto->Class != dbcitem->Class)
1671 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1672 // It safe let use Class from DB
1674 /* disabled: have some strange wrong cases for Subclass values.
1675 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1676 if(proto->SubClass != dbcitem->SubClass)
1678 sLog.outErrorDb("Item (Entry: %u) not correct (Class: %u, Sub: %u) pair, must be (Class: %u, Sub: %u) (still using DB value).",i,proto->Class,proto->SubClass,dbcitem->Class,dbcitem->SubClass);
1679 // It safe let use Subclass from DB
1683 if(proto->Unk0 != dbcitem->Unk0)
1685 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1686 // It safe let use Unk0 from DB
1689 if(proto->Material != dbcitem->Material)
1691 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1692 // It safe let use Material from DB
1695 if(proto->InventoryType != dbcitem->InventoryType)
1697 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1698 // It safe let use InventoryType from DB
1701 if(proto->DisplayInfoID != dbcitem->DisplayId)
1703 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1704 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1706 if(proto->Sheath != dbcitem->Sheath)
1708 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1709 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1712 else
1714 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1717 if(proto->Class >= MAX_ITEM_CLASS)
1719 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1720 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1723 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1725 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1726 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1729 if(proto->Quality >= MAX_ITEM_QUALITY)
1731 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1732 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1735 if(proto->BuyCount <= 0)
1737 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1738 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1741 if(proto->InventoryType >= MAX_INVTYPE)
1743 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1744 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1747 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1749 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1750 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1754 // can be used in equip slot, as page read use in inventory, or spell casting at use
1755 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1756 if(!req)
1758 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1760 if(proto->Spells[j].SpellId)
1762 req = true;
1763 break;
1768 if(req)
1770 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1771 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1773 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1774 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1778 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1780 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1781 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1784 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1785 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1787 if(proto->RequiredReputationFaction)
1789 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1791 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1792 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1795 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1796 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1798 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1799 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1801 if(proto->MaxCount < -1)
1803 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1804 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1807 if(proto->Stackable == 0)
1809 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1810 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1812 else if(proto->Stackable < -1)
1814 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1815 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1817 else if(proto->Stackable > 1000)
1819 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1820 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1823 if(proto->ContainerSlots > MAX_BAG_SIZE)
1825 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1826 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1829 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1831 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1832 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1835 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1837 // for ItemStatValue != 0
1838 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1840 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1841 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1844 switch(proto->ItemStat[j].ItemStatType)
1846 case ITEM_MOD_SPELL_HEALING_DONE:
1847 case ITEM_MOD_SPELL_DAMAGE_DONE:
1848 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1849 break;
1850 default:
1851 break;
1855 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1857 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1859 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1860 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1864 // special format
1865 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1867 // spell_1
1868 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1870 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);
1871 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1872 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1873 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1874 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1877 // spell_2 have learning spell
1878 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1880 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);
1881 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1882 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1883 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1885 else if(!proto->Spells[1].SpellId)
1887 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1888 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1889 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1891 else
1893 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1894 if(!spellInfo)
1896 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1897 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1898 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1899 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1901 // allowed only in special format
1902 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1904 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1905 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1906 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1907 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1911 // spell_3*,spell_4*,spell_5* is empty
1912 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1914 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1916 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1917 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1918 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1920 else if(proto->Spells[j].SpellId != 0)
1922 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1923 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1927 // normal spell list
1928 else
1930 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1932 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1934 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1935 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1936 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1938 // on hit can be sued only at weapon
1939 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1941 if(proto->Class != ITEM_CLASS_WEAPON)
1942 sLog.outErrorDb("Item (Entry: %u) isn't weapon (Class: %u) but has on hit spelltrigger_%d (%u), it will not triggered.",i,proto->Class,j+1,proto->Spells[j].SpellTrigger);
1945 if(proto->Spells[j].SpellId)
1947 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1948 if(!spellInfo)
1950 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1951 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1953 // allowed only in special format
1954 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1956 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1957 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1963 if(proto->Bonding >= MAX_BIND_TYPE)
1964 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1966 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1967 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1969 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1970 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1972 if(proto->Sheath >= MAX_SHEATHETYPE)
1974 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1975 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1978 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1980 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1981 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1984 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1986 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1987 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1990 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1992 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1993 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1996 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1997 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1999 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
2000 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
2002 if(proto->BagFamily)
2004 // check bits
2005 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
2007 uint32 mask = 1 << j;
2008 if((proto->BagFamily & mask)==0)
2009 continue;
2011 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
2012 if(!bf)
2014 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2015 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2016 continue;
2019 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2021 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2022 if(!ctEntry)
2024 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2025 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2031 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2032 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2034 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2036 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2038 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2039 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2043 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2044 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2046 if(proto->FoodType >= MAX_PET_DIET)
2048 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2049 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2052 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2054 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2055 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2058 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2060 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2061 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2065 // check some dbc referenced items (avoid duplicate reports)
2066 std::set<uint32> notFoundOutfit;
2067 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
2069 CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i);
2070 if (!entry)
2071 continue;
2073 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
2075 if (entry->ItemId[j] <= 0)
2076 continue;
2078 uint32 item_id = entry->ItemId[j];
2080 if (!GetItemPrototype(item_id))
2081 if (item_id != 40582) // nonexistent item by default but referenced in DBC, skip it from errors
2082 notFoundOutfit.insert(item_id);
2086 for(std::set<uint32>::const_iterator itr = notFoundOutfit.begin(); itr != notFoundOutfit.end(); ++itr)
2087 sLog.outErrorDb("Item (Entry: %u) not exist in `item_template` but referenced in `CharStartOutfit.dbc`", *itr);
2090 void ObjectMgr::LoadItemRequiredTarget()
2092 m_ItemRequiredTarget.clear(); // needed for reload case
2094 uint32 count = 0;
2096 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2098 if (!result)
2100 barGoLink bar(1);
2102 bar.step();
2104 sLog.outString();
2105 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2106 return;
2109 barGoLink bar((int)result->GetRowCount());
2113 Field *fields = result->Fetch();
2114 bar.step();
2116 uint32 uiItemId = fields[0].GetUInt32();
2117 uint32 uiType = fields[1].GetUInt32();
2118 uint32 uiTargetEntry = fields[2].GetUInt32();
2120 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2122 if (!pItemProto)
2124 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2125 continue;
2128 bool bIsItemSpellValid = false;
2130 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2132 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2134 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2135 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2137 SpellScriptTargetBounds bounds = sSpellMgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2138 if (bounds.first != bounds.second)
2139 break;
2141 for (int j = 0; j < MAX_EFFECT_INDEX; ++j)
2143 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2144 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2145 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2146 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2148 bIsItemSpellValid = true;
2149 break;
2152 if (bIsItemSpellValid)
2153 break;
2158 if (!bIsItemSpellValid)
2160 sLog.outErrorDb("Table `item_required_target`: Spell used by item %u does not have implicit target TARGET_CHAIN_DAMAGE(6), TARGET_DUELVSPLAYER(25), already listed in `spell_script_target` or doesn't have item spelltrigger.",uiItemId);
2161 continue;
2164 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2166 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2167 continue;
2170 if (!uiTargetEntry)
2172 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2173 continue;
2176 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2178 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2179 continue;
2182 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2184 ++count;
2185 } while (result->NextRow());
2187 delete result;
2189 sLog.outString();
2190 sLog.outString(">> Loaded %u Item required targets", count);
2193 void ObjectMgr::LoadPetLevelInfo()
2195 // Loading levels data
2197 // 0 1 2 3 4 5 6 7 8 9
2198 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2200 uint32 count = 0;
2202 if (!result)
2204 barGoLink bar( 1 );
2205 bar.step();
2207 sLog.outString();
2208 sLog.outString(">> Loaded %u level pet stats definitions", count);
2209 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2210 return;
2213 barGoLink bar( (int)result->GetRowCount() );
2217 Field* fields = result->Fetch();
2219 uint32 creature_id = fields[0].GetUInt32();
2220 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2222 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2223 continue;
2226 uint32 current_level = fields[1].GetUInt32();
2227 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2229 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2230 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2231 else
2233 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2234 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2236 continue;
2238 else if(current_level < 1)
2240 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2241 continue;
2244 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2246 if(pInfoMapEntry==NULL)
2247 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2249 // data for level 1 stored in [0] array element, ...
2250 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2252 pLevelInfo->health = fields[2].GetUInt16();
2253 pLevelInfo->mana = fields[3].GetUInt16();
2254 pLevelInfo->armor = fields[9].GetUInt16();
2256 for (int i = 0; i < MAX_STATS; i++)
2258 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2261 bar.step();
2262 ++count;
2264 while (result->NextRow());
2266 delete result;
2268 sLog.outString();
2269 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2272 // Fill gaps and check integrity
2273 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2275 PetLevelInfo* pInfo = itr->second;
2277 // fatal error if no level 1 data
2278 if(!pInfo || pInfo[0].health == 0 )
2280 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2281 exit(1);
2284 // fill level gaps
2285 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2287 if(pInfo[level].health == 0)
2289 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2290 pInfo[level] = pInfo[level-1];
2296 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2298 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2299 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2301 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2302 if(itr == petInfo.end())
2303 return NULL;
2305 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2308 void ObjectMgr::LoadPlayerInfo()
2310 // Load playercreate
2312 // 0 1 2 3 4 5 6
2313 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2315 uint32 count = 0;
2317 if (!result)
2319 barGoLink bar( 1 );
2321 sLog.outString();
2322 sLog.outString( ">> Loaded %u player create definitions", count );
2323 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2324 exit(1);
2327 barGoLink bar( (int)result->GetRowCount() );
2331 Field* fields = result->Fetch();
2333 uint32 current_race = fields[0].GetUInt32();
2334 uint32 current_class = fields[1].GetUInt32();
2335 uint32 mapId = fields[2].GetUInt32();
2336 uint32 zoneId = fields[3].GetUInt32();
2337 float positionX = fields[4].GetFloat();
2338 float positionY = fields[5].GetFloat();
2339 float positionZ = fields[6].GetFloat();
2341 if(current_race >= MAX_RACES)
2343 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2344 continue;
2347 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2348 if(!rEntry)
2350 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2351 continue;
2354 if(current_class >= MAX_CLASSES)
2356 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2357 continue;
2360 if(!sChrClassesStore.LookupEntry(current_class))
2362 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2363 continue;
2366 // accept DB data only for valid position (and non instanceable)
2367 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2369 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2370 continue;
2373 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2375 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2376 continue;
2379 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2381 pInfo->mapId = mapId;
2382 pInfo->zoneId = zoneId;
2383 pInfo->positionX = positionX;
2384 pInfo->positionY = positionY;
2385 pInfo->positionZ = positionZ;
2387 pInfo->displayId_m = rEntry->model_m;
2388 pInfo->displayId_f = rEntry->model_f;
2390 bar.step();
2391 ++count;
2393 while (result->NextRow());
2395 delete result;
2397 sLog.outString();
2398 sLog.outString( ">> Loaded %u player create definitions", count );
2401 // Load playercreate items
2403 // 0 1 2 3
2404 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2406 uint32 count = 0;
2408 if (!result)
2410 barGoLink bar( 1 );
2412 bar.step();
2414 sLog.outString();
2415 sLog.outString( ">> Loaded %u custom player create items", count );
2417 else
2419 barGoLink bar( (int)result->GetRowCount() );
2423 Field* fields = result->Fetch();
2425 uint32 current_race = fields[0].GetUInt32();
2426 if(current_race >= MAX_RACES)
2428 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2429 continue;
2432 uint32 current_class = fields[1].GetUInt32();
2433 if(current_class >= MAX_CLASSES)
2435 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2436 continue;
2439 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2441 uint32 item_id = fields[2].GetUInt32();
2443 if(!GetItemPrototype(item_id))
2445 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);
2446 continue;
2449 uint32 amount = fields[3].GetUInt32();
2451 if(!amount)
2453 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2454 continue;
2457 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2459 bar.step();
2460 ++count;
2462 while(result->NextRow());
2464 delete result;
2466 sLog.outString();
2467 sLog.outString( ">> Loaded %u custom player create items", count );
2471 // Load playercreate spells
2473 // 0 1 2
2474 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2476 uint32 count = 0;
2478 if (!result)
2480 barGoLink bar( 1 );
2482 sLog.outString();
2483 sLog.outString( ">> Loaded %u player create spells", count );
2484 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2486 else
2488 barGoLink bar( (int)result->GetRowCount() );
2492 Field* fields = result->Fetch();
2494 uint32 current_race = fields[0].GetUInt32();
2495 if(current_race >= MAX_RACES)
2497 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2498 continue;
2501 uint32 current_class = fields[1].GetUInt32();
2502 if(current_class >= MAX_CLASSES)
2504 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2505 continue;
2508 uint32 spell_id = fields[2].GetUInt32();
2509 if (!sSpellStore.LookupEntry(spell_id))
2511 sLog.outErrorDb("Non existing spell %u in `playercreateinfo_spell` table, ignoring.", spell_id);
2512 continue;
2515 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2516 pInfo->spell.push_back(spell_id);
2518 bar.step();
2519 ++count;
2521 while( result->NextRow() );
2523 delete result;
2525 sLog.outString();
2526 sLog.outString( ">> Loaded %u player create spells", count );
2530 // Load playercreate actions
2532 // 0 1 2 3 4
2533 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2535 uint32 count = 0;
2537 if (!result)
2539 barGoLink bar( 1 );
2541 sLog.outString();
2542 sLog.outString( ">> Loaded %u player create actions", count );
2543 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2545 else
2547 barGoLink bar( (int)result->GetRowCount() );
2551 Field* fields = result->Fetch();
2553 uint32 current_race = fields[0].GetUInt32();
2554 if(current_race >= MAX_RACES)
2556 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2557 continue;
2560 uint32 current_class = fields[1].GetUInt32();
2561 if(current_class >= MAX_CLASSES)
2563 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2564 continue;
2567 uint8 action_button = fields[2].GetUInt8();
2568 uint32 action = fields[3].GetUInt32();
2569 uint8 action_type = fields[4].GetUInt8();
2571 if (!Player::IsActionButtonDataValid(action_button,action,action_type,NULL))
2572 continue;
2574 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2575 pInfo->action.push_back(PlayerCreateInfoAction(action_button,action,action_type));
2577 bar.step();
2578 ++count;
2580 while( result->NextRow() );
2582 delete result;
2584 sLog.outString();
2585 sLog.outString( ">> Loaded %u player create actions", count );
2589 // Loading levels data (class only dependent)
2591 // 0 1 2 3
2592 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2594 uint32 count = 0;
2596 if (!result)
2598 barGoLink bar( 1 );
2600 sLog.outString();
2601 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2602 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2603 exit(1);
2606 barGoLink bar( (int)result->GetRowCount() );
2610 Field* fields = result->Fetch();
2612 uint32 current_class = fields[0].GetUInt32();
2613 if(current_class >= MAX_CLASSES)
2615 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2616 continue;
2619 uint32 current_level = fields[1].GetUInt32();
2620 if(current_level == 0)
2622 sLog.outErrorDb("Wrong level %u in `player_classlevelstats` table, ignoring.",current_level);
2623 continue;
2625 else if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2627 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2628 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2629 else
2631 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2632 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2634 continue;
2637 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2639 if(!pClassInfo->levelInfo)
2640 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2642 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2644 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2645 pClassLevelInfo->basemana = fields[3].GetUInt16();
2647 bar.step();
2648 ++count;
2650 while (result->NextRow());
2652 delete result;
2654 sLog.outString();
2655 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2658 // Fill gaps and check integrity
2659 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2661 // skip non existed classes
2662 if(!sChrClassesStore.LookupEntry(class_))
2663 continue;
2665 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2667 // fatal error if no level 1 data
2668 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2670 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2671 exit(1);
2674 // fill level gaps
2675 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2677 if(pClassInfo->levelInfo[level].basehealth == 0)
2679 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2680 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2685 // Loading levels data (class/race dependent)
2687 // 0 1 2 3 4 5 6 7
2688 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2690 uint32 count = 0;
2692 if (!result)
2694 barGoLink bar( 1 );
2696 sLog.outString();
2697 sLog.outString( ">> Loaded %u level stats definitions", count );
2698 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2699 exit(1);
2702 barGoLink bar( (int)result->GetRowCount() );
2706 Field* fields = result->Fetch();
2708 uint32 current_race = fields[0].GetUInt32();
2709 if(current_race >= MAX_RACES)
2711 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2712 continue;
2715 uint32 current_class = fields[1].GetUInt32();
2716 if(current_class >= MAX_CLASSES)
2718 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2719 continue;
2722 uint32 current_level = fields[2].GetUInt32();
2723 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2725 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2726 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2727 else
2729 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2730 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2732 continue;
2735 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2737 if(!pInfo->levelInfo)
2738 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2740 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2742 for (int i = 0; i < MAX_STATS; i++)
2744 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2747 bar.step();
2748 ++count;
2750 while (result->NextRow());
2752 delete result;
2754 sLog.outString();
2755 sLog.outString( ">> Loaded %u level stats definitions", count );
2758 // Fill gaps and check integrity
2759 for (int race = 0; race < MAX_RACES; ++race)
2761 // skip non existed races
2762 if(!sChrRacesStore.LookupEntry(race))
2763 continue;
2765 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2767 // skip non existed classes
2768 if(!sChrClassesStore.LookupEntry(class_))
2769 continue;
2771 PlayerInfo* pInfo = &playerInfo[race][class_];
2773 // skip non loaded combinations
2774 if(!pInfo->displayId_m || !pInfo->displayId_f)
2775 continue;
2777 // skip expansion races if not playing with expansion
2778 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2779 continue;
2781 // skip expansion classes if not playing with expansion
2782 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2783 continue;
2785 // fatal error if no level 1 data
2786 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2788 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2789 exit(1);
2792 // fill level gaps
2793 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2795 if(pInfo->levelInfo[level].stats[0] == 0)
2797 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2798 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2804 // Loading xp per level data
2806 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
2807 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2808 mPlayerXPperLevel[level] = 0;
2810 // 0 1
2811 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2813 uint32 count = 0;
2815 if (!result)
2817 barGoLink bar( 1 );
2819 sLog.outString();
2820 sLog.outString( ">> Loaded %u xp for level definitions", count );
2821 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2822 exit(1);
2825 barGoLink bar( (int)result->GetRowCount() );
2829 Field* fields = result->Fetch();
2831 uint32 current_level = fields[0].GetUInt32();
2832 uint32 current_xp = fields[1].GetUInt32();
2834 if(current_level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2836 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2837 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2838 else
2840 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2841 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2843 continue;
2845 //PlayerXPperLevel
2846 mPlayerXPperLevel[current_level] = current_xp;
2847 bar.step();
2848 ++count;
2850 while (result->NextRow());
2852 delete result;
2854 sLog.outString();
2855 sLog.outString( ">> Loaded %u xp for level definitions", count );
2858 // fill level gaps
2859 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2861 if( mPlayerXPperLevel[level] == 0)
2863 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2864 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2869 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2871 if(level < 1 || class_ >= MAX_CLASSES)
2872 return;
2874 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2876 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2877 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2879 *info = pInfo->levelInfo[level-1];
2882 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2884 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2885 return;
2887 PlayerInfo const* pInfo = &playerInfo[race][class_];
2888 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2889 return;
2891 if(level <= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2892 *info = pInfo->levelInfo[level-1];
2893 else
2894 BuildPlayerLevelInfo(race,class_,level,info);
2897 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2899 // base data (last known level)
2900 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1];
2902 for(int lvl = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2904 switch(_class)
2906 case CLASS_WARRIOR:
2907 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2908 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2909 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2910 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2911 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2912 break;
2913 case CLASS_PALADIN:
2914 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2915 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2916 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2917 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2918 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2919 break;
2920 case CLASS_HUNTER:
2921 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2922 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2923 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2924 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2925 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2926 break;
2927 case CLASS_ROGUE:
2928 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2929 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2930 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2931 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2932 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2933 break;
2934 case CLASS_PRIEST:
2935 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2936 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2937 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2938 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2939 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2940 break;
2941 case CLASS_SHAMAN:
2942 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2943 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2944 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2945 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2946 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2947 break;
2948 case CLASS_MAGE:
2949 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2950 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2951 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2952 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2953 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2954 break;
2955 case CLASS_WARLOCK:
2956 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2957 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2958 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2959 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2960 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2961 break;
2962 case CLASS_DRUID:
2963 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2964 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2965 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2966 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2967 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2972 void ObjectMgr::LoadGuilds()
2974 Guild *newGuild;
2975 uint32 count = 0;
2977 // 0 1 2 3 4 5 6
2978 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
2979 // 7 8 9 10 11 12
2980 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
2981 "FROM guild ORDER BY guildid ASC");
2983 if( !result )
2986 barGoLink bar( 1 );
2988 bar.step();
2990 sLog.outString();
2991 sLog.outString( ">> Loaded %u guild definitions", count );
2992 return;
2995 // load guild ranks
2996 // 0 1 2 3 4
2997 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
2999 // load guild members
3000 // 0 1 2 3 4 5 6
3001 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
3002 // 7 8 9 10 11 12
3003 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
3004 // 13 14 15 16 17 18
3005 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
3006 // 19 20 21 22 23
3007 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
3008 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
3010 // load guild bank tab rights
3011 // 0 1 2 3 4
3012 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
3014 barGoLink bar( (int)result->GetRowCount() );
3018 //Field *fields = result->Fetch();
3020 bar.step();
3021 ++count;
3023 newGuild = new Guild;
3024 if (!newGuild->LoadGuildFromDB(result) ||
3025 !newGuild->LoadRanksFromDB(guildRanksResult) ||
3026 !newGuild->LoadMembersFromDB(guildMembersResult) ||
3027 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
3028 !newGuild->CheckGuildStructure()
3031 newGuild->Disband();
3032 delete newGuild;
3033 continue;
3035 newGuild->LoadGuildEventLogFromDB();
3036 newGuild->LoadGuildBankEventLogFromDB();
3037 newGuild->LoadGuildBankFromDB();
3038 AddGuild(newGuild);
3039 } while( result->NextRow() );
3041 delete result;
3042 delete guildRanksResult;
3043 delete guildMembersResult;
3044 delete guildBankTabRightsResult;
3046 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
3047 //you can comment these lines if you don't plan to change CONFIG_UINT32_GUILD_EVENT_LOG_COUNT and CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT
3048 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_EVENT_LOG_COUNT));
3049 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT));
3051 sLog.outString();
3052 sLog.outString( ">> Loaded %u guild definitions", count );
3055 void ObjectMgr::LoadArenaTeams()
3057 uint32 count = 0;
3059 // 0 1 2 3 4 5
3060 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3061 // 6 7 8 9 10 11 12 13 14
3062 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3063 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3065 if( !result )
3068 barGoLink bar( 1 );
3070 bar.step();
3072 sLog.outString();
3073 sLog.outString( ">> Loaded %u arenateam definitions", count );
3074 return;
3077 // load arena_team members
3078 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3079 // 0 1 2 3 4 5 6 7 8
3080 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3081 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3083 barGoLink bar( (int)result->GetRowCount() );
3088 bar.step();
3089 ++count;
3091 ArenaTeam *newArenaTeam = new ArenaTeam;
3092 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3093 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3095 newArenaTeam->Disband(NULL);
3096 delete newArenaTeam;
3097 continue;
3099 AddArenaTeam(newArenaTeam);
3100 }while( result->NextRow() );
3102 delete result;
3103 delete arenaTeamMembersResult;
3105 sLog.outString();
3106 sLog.outString( ">> Loaded %u arenateam definitions", count );
3109 void ObjectMgr::LoadGroups()
3111 // -- loading groups --
3112 uint32 count = 0;
3113 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3114 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid, groupId FROM groups");
3116 if (!result)
3118 barGoLink bar( 1 );
3120 bar.step();
3122 sLog.outString();
3123 sLog.outString( ">> Loaded %u group definitions", count );
3124 return;
3127 barGoLink bar( (int)result->GetRowCount() );
3131 bar.step();
3132 Field *fields = result->Fetch();
3133 ++count;
3134 Group *group = new Group;
3135 if (!group->LoadGroupFromDB(fields))
3137 group->Disband();
3138 delete group;
3139 continue;
3141 AddGroup(group);
3142 }while( result->NextRow() );
3144 delete result;
3146 sLog.outString();
3147 sLog.outString( ">> Loaded %u group definitions", count );
3149 // -- loading members --
3150 count = 0;
3151 // 0 1 2 3
3152 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, groupId FROM group_member ORDER BY groupId");
3153 if (!result)
3155 barGoLink bar2( 1 );
3156 bar2.step();
3158 else
3160 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3162 barGoLink bar2( (int)result->GetRowCount() );
3165 bar2.step();
3166 Field *fields = result->Fetch();
3167 count++;
3169 uint32 memberGuidlow = fields[0].GetUInt32();
3170 bool assistent = fields[1].GetBool();
3171 uint8 subgroup = fields[2].GetUInt8();
3172 uint32 groupId = fields[3].GetUInt32();
3173 if (!group || group->GetId() != groupId)
3175 group = GetGroupById(groupId);
3176 if (!group)
3178 sLog.outErrorDb("Incorrect entry in group_member table : no group with Id %d for member %d!", groupId, memberGuidlow);
3179 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3180 continue;
3184 if (!group->LoadMemberFromDB(memberGuidlow, subgroup, assistent))
3186 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group (Id: %u)!", memberGuidlow, GUID_LOPART(group->GetLeaderGUID()), groupId);
3187 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3189 }while( result->NextRow() );
3190 delete result;
3193 // clean groups
3194 // TODO: maybe delete from the DB before loading in this case
3195 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end();)
3197 if (itr->second->GetMembersCount() < 2)
3199 itr->second->Disband();
3200 delete itr->second;
3201 mGroupMap.erase(itr++);
3203 else
3204 ++itr;
3207 // -- loading instances --
3208 count = 0;
3209 result = CharacterDatabase.Query(
3210 // 0 1 2 3 4 5
3211 "SELECT group_instance.leaderGuid, map, instance, permanent, instance.difficulty, resettime, "
3212 // 6
3213 "(SELECT COUNT(*) FROM character_instance WHERE guid = group_instance.leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1), "
3214 // 7
3215 " groups.groupId "
3216 "FROM group_instance LEFT JOIN instance ON instance = id LEFT JOIN groups ON groups.leaderGUID = group_instance.leaderGUID ORDER BY leaderGuid"
3219 if (!result)
3221 barGoLink bar2( 1 );
3222 bar2.step();
3224 else
3226 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3228 barGoLink bar2( (int)result->GetRowCount() );
3231 bar2.step();
3232 Field *fields = result->Fetch();
3233 count++;
3235 uint32 leaderGuidLow = fields[0].GetUInt32();
3236 uint32 mapId = fields[1].GetUInt32();
3237 Difficulty diff = (Difficulty)fields[4].GetUInt8();
3238 uint32 groupId = fields[7].GetUInt32();
3240 if (!group || group->GetId() != groupId)
3242 // find group id in map by leader low guid
3243 group = GetGroupById(groupId);
3244 if (!group)
3246 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", leaderGuidLow);
3247 continue;
3251 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
3252 if (!mapEntry || !mapEntry->IsDungeon())
3254 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", mapId);
3255 continue;
3258 if (diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3260 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff + 1);
3261 diff = REGULAR_DIFFICULTY; // default for both difficaly types
3264 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3265 group->BindToInstance(save, fields[3].GetBool(), true);
3266 }while( result->NextRow() );
3267 delete result;
3270 sLog.outString();
3271 sLog.outString( ">> Loaded %u group-instance binds total", count );
3273 sLog.outString();
3274 sLog.outString( ">> Loaded %u group members total", count );
3277 void ObjectMgr::LoadQuests()
3279 // For reload case
3280 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3281 delete itr->second;
3282 mQuestTemplates.clear();
3284 mExclusiveQuestGroups.clear();
3286 // 0 1 2 3 4 5 6 7 8
3287 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3288 // 9 10 11 12 13 14 15 16
3289 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3290 // 17 18 19 20 21 22 23 24 25
3291 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain,"
3292 // 26 27 28 29
3293 "RewXPId, SrcItemId, SrcItemCount, SrcSpell,"
3294 // 30 31 32 33 34 35 36 37 38 39 40
3295 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, CompletedText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3296 // 41 42 43 44 45 46 47 48 49 50 51 52
3297 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3298 // 53 54 55 56 57 58 59 60
3299 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3300 // 61 62 63 64 65 66 67 68
3301 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3302 // 69 70 71 72
3303 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3304 // 73 74 75 76 77 78
3305 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3306 // 79 80 81 82 83 84
3307 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3308 // 85 86 87 88 89 90 91 92
3309 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3310 // 93 94 95 96 97
3311 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5,"
3312 // 98 99 100 101 102
3313 "RewRepValueId1, RewRepValueId2, RewRepValueId3, RewRepValueId4, RewRepValueId5,"
3314 // 103 104 105 106 107
3315 "RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3316 // 108 109 110 111 112 113
3317 "RewHonorAddition, RewHonorMultiplier, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast,"
3318 // 114 115 116 117 118 119
3319 "RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3320 // 120 121 122 123 124 125 126 127
3321 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3322 // 128 129 130 131 132 133
3323 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3324 // 134 135 136 137
3325 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3326 // 138 139
3327 "StartScript, CompleteScript"
3328 " FROM quest_template");
3329 if(result == NULL)
3331 barGoLink bar( 1 );
3332 bar.step();
3334 sLog.outString();
3335 sLog.outString( ">> Loaded 0 quests definitions" );
3336 sLog.outErrorDb("`quest_template` table is empty!");
3337 return;
3340 // create multimap previous quest for each existed quest
3341 // some quests can have many previous maps set by NextQuestId in previous quest
3342 // for example set of race quests can lead to single not race specific quest
3343 barGoLink bar((int) result->GetRowCount() );
3346 bar.step();
3347 Field *fields = result->Fetch();
3349 Quest * newQuest = new Quest(fields);
3350 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3351 } while( result->NextRow() );
3353 delete result;
3355 // Post processing
3357 std::map<uint32,uint32> usedMailTemplates;
3359 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3361 Quest * qinfo = iter->second;
3363 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3365 if( qinfo->GetQuestMethod() >= 3 )
3367 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3370 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3372 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3373 qinfo->GetQuestId(),qinfo->QuestFlags >> 24,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 24);
3374 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3377 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3379 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3381 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3382 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3386 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3388 // at auto-reward can be rewarded only RewChoiceItemId[0]
3389 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3391 if(uint32 id = qinfo->RewChoiceItemId[j])
3393 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3394 qinfo->GetQuestId(),j+1,id,j+1);
3395 // no changes, quest ignore this data
3400 // client quest log visual (area case)
3401 if( qinfo->ZoneOrSort > 0 )
3403 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3405 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3406 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3407 // no changes, quest not dependent from this value but can have problems at client
3410 // client quest log visual (sort case)
3411 if( qinfo->ZoneOrSort < 0 )
3413 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3414 if( !qSort )
3416 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3417 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3418 // 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)
3420 //check SkillOrClass value (class case).
3421 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3423 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3424 if(qinfo->SkillOrClass < 0)
3426 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3427 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3430 //check for proper SkillOrClass value (skill case)
3431 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3433 // skill is positive value in SkillOrClass
3434 if(qinfo->SkillOrClass != skill_id )
3436 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3437 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3438 //override, and force proper value here?
3443 // SkillOrClass (class case)
3444 if( qinfo->SkillOrClass < 0 )
3446 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3448 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3449 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3452 // SkillOrClass (skill case)
3453 if( qinfo->SkillOrClass > 0 )
3455 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3457 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3458 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3462 if( qinfo->RequiredSkillValue )
3464 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3466 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3467 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3468 // no changes, quest can't be done for this requirement
3471 if( qinfo->SkillOrClass <= 0 )
3473 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3474 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3475 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3478 // else Skill quests can have 0 skill level, this is ok
3480 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3482 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3483 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3484 // no changes, quest can't be done for this requirement
3487 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3489 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3490 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3491 // no changes, quest can't be done for this requirement
3494 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3496 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3497 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3498 // no changes, quest can't be done for this requirement
3501 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3503 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3504 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3505 // no changes, quest can't be done for this requirement
3508 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3510 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3511 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3512 // no changes, quest can't be done for this requirement
3515 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3517 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3518 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3519 // warning
3522 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3524 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3525 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3526 // warning
3529 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3531 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3532 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3533 // warning
3536 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3538 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3539 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3540 qinfo->CharTitleId = 0;
3541 // quest can't reward this title
3544 if(qinfo->SrcItemId)
3546 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3548 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3549 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3550 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3552 else if(qinfo->SrcItemCount==0)
3554 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3555 qinfo->GetQuestId(),qinfo->SrcItemId);
3556 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3559 else if(qinfo->SrcItemCount>0)
3561 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3562 qinfo->GetQuestId(),qinfo->SrcItemCount);
3563 qinfo->SrcItemCount=0; // no quest work changes in fact
3566 if(qinfo->SrcSpell)
3568 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3569 if(!spellInfo)
3571 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3572 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3573 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3575 else if(!SpellMgr::IsSpellValid(spellInfo))
3577 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3578 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3579 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3583 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3585 uint32 id = qinfo->ReqItemId[j];
3586 if(id)
3588 if(qinfo->ReqItemCount[j] == 0)
3590 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3591 qinfo->GetQuestId(), j+1, id, j+1);
3592 // no changes, quest can't be done for this requirement
3595 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3597 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3599 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3600 qinfo->GetQuestId(), j+1, id, id);
3601 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3604 else if(qinfo->ReqItemCount[j] > 0)
3606 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3607 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3608 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3612 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3614 uint32 id = qinfo->ReqSourceId[j];
3615 if(id)
3617 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3619 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3620 qinfo->GetQuestId(),j+1,id,id);
3621 // no changes, quest can't be done for this requirement
3624 else
3626 if(qinfo->ReqSourceCount[j]>0)
3628 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3629 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3630 // no changes, quest ignore this data
3635 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3637 uint32 id = qinfo->ReqSpell[j];
3638 if(id)
3640 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3641 if(!spellInfo)
3643 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3644 qinfo->GetQuestId(),j+1,id,id);
3645 continue;
3648 if(!qinfo->ReqCreatureOrGOId[j])
3650 bool found = false;
3651 for(int k = 0; k < MAX_EFFECT_INDEX; ++k)
3653 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3654 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3656 found = true;
3657 break;
3661 if(found)
3663 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3665 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);
3667 // this will prevent quest completing without objective
3668 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3671 else
3673 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.",
3674 qinfo->GetQuestId(),j+1,id,j+1,id);
3675 // no changes, quest can't be done for this requirement
3681 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3683 int32 id = qinfo->ReqCreatureOrGOId[j];
3684 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3686 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3687 qinfo->GetQuestId(),j+1,id,uint32(-id));
3688 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3691 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3693 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3694 qinfo->GetQuestId(),j+1,id,uint32(id));
3695 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3698 if(id)
3700 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3702 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3704 if(!qinfo->ReqCreatureOrGOCount[j])
3706 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3707 qinfo->GetQuestId(),j+1,id,j+1);
3708 // no changes, quest can be incorrectly done, but we already report this
3711 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3713 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3714 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3715 // no changes, quest ignore this data
3719 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3721 uint32 id = qinfo->RewChoiceItemId[j];
3722 if(id)
3724 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3726 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3727 qinfo->GetQuestId(),j+1,id,id);
3728 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3731 if(!qinfo->RewChoiceItemCount[j])
3733 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3734 qinfo->GetQuestId(),j+1,id,j+1);
3735 // no changes, quest can't be done
3738 else if(qinfo->RewChoiceItemCount[j]>0)
3740 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3741 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3742 // no changes, quest ignore this data
3746 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3748 uint32 id = qinfo->RewItemId[j];
3749 if(id)
3751 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3753 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3754 qinfo->GetQuestId(),j+1,id,id);
3755 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3758 if(!qinfo->RewItemCount[j])
3760 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3761 qinfo->GetQuestId(),j+1,id,j+1);
3762 // no changes
3765 else if(qinfo->RewItemCount[j]>0)
3767 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3768 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3769 // no changes, quest ignore this data
3773 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3775 if (qinfo->RewRepFaction[j])
3777 if (abs(qinfo->RewRepValueId[j]) > 9)
3778 sLog.outErrorDb("Quest %u has RewRepValueId%d = %i but value is not valid.", qinfo->GetQuestId(), j+1, qinfo->RewRepValueId[j]);
3780 if (!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3782 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.",
3783 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j]);
3784 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3787 else if (qinfo->RewRepValue[j] != 0)
3789 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %i.",
3790 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3791 // no changes, quest ignore this data
3795 if(qinfo->RewSpell)
3797 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3799 if(!spellInfo)
3801 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3802 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3803 qinfo->RewSpell = 0; // no spell reward will display for this quest
3805 else if(!SpellMgr::IsSpellValid(spellInfo))
3807 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3808 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3809 qinfo->RewSpell = 0; // no spell reward will display for this quest
3811 else if(GetTalentSpellCost(qinfo->RewSpell))
3813 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3814 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3815 qinfo->RewSpell = 0; // no spell reward will display for this quest
3819 if(qinfo->RewSpellCast)
3821 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3823 if(!spellInfo)
3825 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3826 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3827 qinfo->RewSpellCast = 0; // no spell will be casted on player
3829 else if(!SpellMgr::IsSpellValid(spellInfo))
3831 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3832 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3833 qinfo->RewSpellCast = 0; // no spell will be casted on player
3835 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3837 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3838 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3839 qinfo->RewSpellCast = 0; // no spell will be casted on player
3843 if (qinfo->RewMailTemplateId)
3845 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3847 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3848 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3849 qinfo->RewMailTemplateId = 0; // no mail will send to player
3850 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3852 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3854 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3855 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3856 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3857 qinfo->RewMailTemplateId = 0; // no mail will send to player
3858 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3860 else
3861 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3864 if (qinfo->NextQuestInChain)
3866 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3867 if (qNextItr == mQuestTemplates.end())
3869 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3870 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3871 qinfo->NextQuestInChain = 0;
3873 else
3874 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3877 // fill additional data stores
3878 if (qinfo->PrevQuestId)
3880 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3882 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3884 else
3886 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3890 if(qinfo->NextQuestId)
3892 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3893 if (qNextItr == mQuestTemplates.end())
3895 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3897 else
3899 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3900 qNextItr->second->prevQuests.push_back(signedQuestId);
3904 if(qinfo->ExclusiveGroup)
3905 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3906 if(qinfo->LimitTime)
3907 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3910 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3911 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3913 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3914 if(!spellInfo)
3915 continue;
3917 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
3919 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3920 continue;
3922 uint32 quest_id = spellInfo->EffectMiscValue[j];
3924 Quest const* quest = GetQuestTemplate(quest_id);
3926 // some quest referenced in spells not exist (outdated spells)
3927 if(!quest)
3928 continue;
3930 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3932 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);
3934 // this will prevent quest completing without objective
3935 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3940 sLog.outString();
3941 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3944 void ObjectMgr::LoadQuestLocales()
3946 mQuestLocaleMap.clear(); // need for reload case
3948 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3949 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,CompletedText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3950 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,CompletedText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3951 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,CompletedText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3952 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,CompletedText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3953 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,CompletedText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3954 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,CompletedText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3955 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,CompletedText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3956 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,CompletedText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3957 " FROM locales_quest"
3960 if(!result)
3962 barGoLink bar(1);
3964 bar.step();
3966 sLog.outString();
3967 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3968 return;
3971 barGoLink bar((int)result->GetRowCount());
3975 Field *fields = result->Fetch();
3976 bar.step();
3978 uint32 entry = fields[0].GetUInt32();
3980 QuestLocale& data = mQuestLocaleMap[entry];
3982 for(int i = 1; i < MAX_LOCALE; ++i)
3984 std::string str = fields[1+11*(i-1)].GetCppString();
3985 if(!str.empty())
3987 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3988 if(idx >= 0)
3990 if((int32)data.Title.size() <= idx)
3991 data.Title.resize(idx+1);
3993 data.Title[idx] = str;
3996 str = fields[1+11*(i-1)+1].GetCppString();
3997 if(!str.empty())
3999 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4000 if(idx >= 0)
4002 if((int32)data.Details.size() <= idx)
4003 data.Details.resize(idx+1);
4005 data.Details[idx] = str;
4008 str = fields[1+11*(i-1)+2].GetCppString();
4009 if(!str.empty())
4011 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4012 if(idx >= 0)
4014 if((int32)data.Objectives.size() <= idx)
4015 data.Objectives.resize(idx+1);
4017 data.Objectives[idx] = str;
4020 str = fields[1+11*(i-1)+3].GetCppString();
4021 if(!str.empty())
4023 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4024 if(idx >= 0)
4026 if((int32)data.OfferRewardText.size() <= idx)
4027 data.OfferRewardText.resize(idx+1);
4029 data.OfferRewardText[idx] = str;
4032 str = fields[1+11*(i-1)+4].GetCppString();
4033 if(!str.empty())
4035 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4036 if(idx >= 0)
4038 if((int32)data.RequestItemsText.size() <= idx)
4039 data.RequestItemsText.resize(idx+1);
4041 data.RequestItemsText[idx] = str;
4044 str = fields[1+11*(i-1)+5].GetCppString();
4045 if(!str.empty())
4047 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4048 if(idx >= 0)
4050 if((int32)data.EndText.size() <= idx)
4051 data.EndText.resize(idx+1);
4053 data.EndText[idx] = str;
4056 str = fields[1+11*(i-1)+6].GetCppString();
4057 if(!str.empty())
4059 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4060 if(idx >= 0)
4062 if((int32)data.CompletedText.size() <= idx)
4063 data.CompletedText.resize(idx+1);
4065 data.CompletedText[idx] = str;
4068 for(int k = 0; k < 4; ++k)
4070 str = fields[1+11*(i-1)+7+k].GetCppString();
4071 if(!str.empty())
4073 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4074 if(idx >= 0)
4076 if((int32)data.ObjectiveText[k].size() <= idx)
4077 data.ObjectiveText[k].resize(idx+1);
4079 data.ObjectiveText[k][idx] = str;
4084 } while (result->NextRow());
4086 delete result;
4088 sLog.outString();
4089 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4092 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4094 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4095 return;
4097 sLog.outString( "%s :", tablename);
4099 scripts.clear(); // need for reload support
4101 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
4103 uint32 count = 0;
4105 if( !result )
4107 barGoLink bar( 1 );
4108 bar.step();
4110 sLog.outString();
4111 sLog.outString( ">> Loaded %u script definitions", count );
4112 return;
4115 barGoLink bar( (int)result->GetRowCount() );
4119 bar.step();
4121 Field *fields = result->Fetch();
4122 ScriptInfo tmp;
4123 tmp.id = fields[0].GetUInt32();
4124 tmp.delay = fields[1].GetUInt32();
4125 tmp.command = fields[2].GetUInt32();
4126 tmp.datalong = fields[3].GetUInt32();
4127 tmp.datalong2 = fields[4].GetUInt32();
4128 tmp.dataint = fields[5].GetInt32();
4129 tmp.x = fields[6].GetFloat();
4130 tmp.y = fields[7].GetFloat();
4131 tmp.z = fields[8].GetFloat();
4132 tmp.o = fields[9].GetFloat();
4134 // generic command args check
4135 switch(tmp.command)
4137 case SCRIPT_COMMAND_TALK:
4139 if(tmp.datalong > 3)
4141 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4142 continue;
4144 if(tmp.dataint==0)
4146 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4147 continue;
4149 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4151 sLog.outErrorDb("Table `%s` has out of range text id (dataint = %i expected %u-%u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID,tmp.id);
4152 continue;
4155 // if(!GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4156 break;
4159 case SCRIPT_COMMAND_EMOTE:
4161 if(!sEmotesStore.LookupEntry(tmp.datalong))
4163 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4164 continue;
4166 break;
4169 case SCRIPT_COMMAND_TELEPORT_TO:
4171 if(!sMapStore.LookupEntry(tmp.datalong))
4173 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4174 continue;
4177 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4179 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);
4180 continue;
4182 break;
4185 case SCRIPT_COMMAND_KILL_CREDIT:
4187 if (!GetCreatureTemplate(tmp.datalong))
4189 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u",tablename,tmp.datalong,tmp.id);
4190 continue;
4192 break;
4195 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4197 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4199 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);
4200 continue;
4203 if(!GetCreatureTemplate(tmp.datalong))
4205 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4206 continue;
4208 break;
4211 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4213 GameObjectData const* data = GetGOData(tmp.datalong);
4214 if(!data)
4216 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4217 continue;
4220 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4221 if(!info)
4223 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);
4224 continue;
4227 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4228 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4229 info->type==GAMEOBJECT_TYPE_DOOR ||
4230 info->type==GAMEOBJECT_TYPE_BUTTON ||
4231 info->type==GAMEOBJECT_TYPE_TRAP )
4233 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4234 continue;
4236 break;
4238 case SCRIPT_COMMAND_OPEN_DOOR:
4239 case SCRIPT_COMMAND_CLOSE_DOOR:
4241 GameObjectData const* data = GetGOData(tmp.datalong);
4242 if(!data)
4244 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);
4245 continue;
4248 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4249 if(!info)
4251 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);
4252 continue;
4255 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4257 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);
4258 continue;
4261 break;
4263 case SCRIPT_COMMAND_QUEST_EXPLORED:
4265 Quest const* quest = GetQuestTemplate(tmp.datalong);
4266 if(!quest)
4268 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);
4269 continue;
4272 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4274 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);
4276 // this will prevent quest completing without objective
4277 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4279 // continue; - quest objective requirement set and command can be allowed
4282 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4284 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",
4285 tablename,tmp.datalong2,tmp.id);
4286 continue;
4289 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4291 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %f or 0 for disable distance check",
4292 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4293 continue;
4296 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4298 sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %f or 0 for disable distance check",
4299 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4300 continue;
4303 break;
4306 case SCRIPT_COMMAND_REMOVE_AURA:
4308 if(!sSpellStore.LookupEntry(tmp.datalong))
4310 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4311 tablename,tmp.datalong,tmp.id);
4312 continue;
4314 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4316 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4317 tablename,tmp.datalong2,tmp.id);
4318 continue;
4320 break;
4322 case SCRIPT_COMMAND_CAST_SPELL:
4324 if(!sSpellStore.LookupEntry(tmp.datalong))
4326 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4327 tablename,tmp.datalong,tmp.id);
4328 continue;
4330 if(tmp.datalong2 & ~0x3) // 2 bits
4332 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4333 tablename,tmp.datalong2,tmp.id);
4334 continue;
4336 break;
4340 if (scripts.find(tmp.id) == scripts.end())
4342 ScriptMap emptyMap;
4343 scripts[tmp.id] = emptyMap;
4345 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4347 ++count;
4348 } while( result->NextRow() );
4350 delete result;
4352 sLog.outString();
4353 sLog.outString( ">> Loaded %u script definitions", count );
4356 void ObjectMgr::LoadGameObjectScripts()
4358 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4360 // check ids
4361 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4363 if(!GetGOData(itr->first))
4364 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4368 void ObjectMgr::LoadQuestEndScripts()
4370 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4372 // check ids
4373 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4375 if(!GetQuestTemplate(itr->first))
4376 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4380 void ObjectMgr::LoadQuestStartScripts()
4382 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4384 // check ids
4385 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4387 if(!GetQuestTemplate(itr->first))
4388 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4392 void ObjectMgr::LoadSpellScripts()
4394 LoadScripts(sSpellScripts, "spell_scripts");
4396 // check ids
4397 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4399 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4401 if(!spellInfo)
4403 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4404 continue;
4407 //check for correct spellEffect
4408 bool found = false;
4409 for(int i=0; i<3; ++i)
4411 // skip empty effects
4412 if( !spellInfo->Effect[i] )
4413 continue;
4415 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4417 found = true;
4418 break;
4422 if(!found)
4423 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4427 void ObjectMgr::LoadEventScripts()
4429 LoadScripts(sEventScripts, "event_scripts");
4431 std::set<uint32> evt_scripts;
4432 // Load all possible script entries from gameobjects
4433 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4435 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4436 if (goInfo)
4438 switch(goInfo->type)
4440 case GAMEOBJECT_TYPE_GOOBER:
4441 if (goInfo->goober.eventId)
4442 evt_scripts.insert(goInfo->goober.eventId);
4443 break;
4444 case GAMEOBJECT_TYPE_CHEST:
4445 if (goInfo->chest.eventId)
4446 evt_scripts.insert(goInfo->chest.eventId);
4447 break;
4448 case GAMEOBJECT_TYPE_CAMERA:
4449 if (goInfo->camera.eventID)
4450 evt_scripts.insert(goInfo->camera.eventID);
4451 default:
4452 break;
4456 // Load all possible script entries from spells
4457 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4459 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4460 if (spell)
4462 for(int j=0; j<3; ++j)
4464 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4466 if (spell->EffectMiscValue[j])
4467 evt_scripts.insert(spell->EffectMiscValue[j]);
4472 // Then check if all scripts are in above list of possible script entries
4473 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4475 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4476 if (itr2 == evt_scripts.end())
4477 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect %u",
4478 itr->first, SPELL_EFFECT_SEND_EVENT);
4482 void ObjectMgr::LoadGossipScripts()
4484 LoadScripts(sGossipScripts, "gossip_scripts");
4486 // checks are done in LoadGossipMenuItems
4489 void ObjectMgr::LoadItemTexts()
4491 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4493 uint32 count = 0;
4495 if( !result )
4497 barGoLink bar( 1 );
4498 bar.step();
4500 sLog.outString();
4501 sLog.outString( ">> Loaded %u item pages", count );
4502 return;
4505 barGoLink bar( (int)result->GetRowCount() );
4507 Field* fields;
4510 bar.step();
4512 fields = result->Fetch();
4514 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4516 ++count;
4518 } while ( result->NextRow() );
4520 delete result;
4522 sLog.outString();
4523 sLog.outString( ">> Loaded %u item texts", count );
4526 void ObjectMgr::LoadPageTexts()
4528 sPageTextStore.Free(); // for reload case
4530 sPageTextStore.Load();
4531 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4532 sLog.outString();
4534 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4536 // check data correctness
4537 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4538 if(!page)
4539 continue;
4541 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4543 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4544 continue;
4547 // detect circular reference
4548 std::set<uint32> checkedPages;
4549 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4551 if(!pageItr->Next_Page)
4552 break;
4553 checkedPages.insert(pageItr->Page_ID);
4554 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4556 std::ostringstream ss;
4557 ss<< "The text page(s) ";
4558 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4559 ss << *itr << " ";
4560 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4561 << pageItr->Page_ID <<" to 0";
4562 sLog.outErrorDb("%s", ss.str().c_str());
4563 const_cast<PageText*>(pageItr)->Next_Page = 0;
4564 break;
4570 void ObjectMgr::LoadPageTextLocales()
4572 mPageTextLocaleMap.clear(); // need for reload case
4574 QueryResult *result = WorldDatabase.Query("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4576 if(!result)
4578 barGoLink bar(1);
4580 bar.step();
4582 sLog.outString();
4583 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4584 return;
4587 barGoLink bar((int)result->GetRowCount());
4591 Field *fields = result->Fetch();
4592 bar.step();
4594 uint32 entry = fields[0].GetUInt32();
4596 PageTextLocale& data = mPageTextLocaleMap[entry];
4598 for(int i = 1; i < MAX_LOCALE; ++i)
4600 std::string str = fields[i].GetCppString();
4601 if(str.empty())
4602 continue;
4604 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4605 if(idx >= 0)
4607 if((int32)data.Text.size() <= idx)
4608 data.Text.resize(idx+1);
4610 data.Text[idx] = str;
4614 } while (result->NextRow());
4616 delete result;
4618 sLog.outString();
4619 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4622 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4624 template<class D>
4625 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4627 dst = D(sObjectMgr.GetScriptId(src));
4631 void ObjectMgr::LoadInstanceTemplate()
4633 SQLInstanceLoader loader;
4634 loader.Load(sInstanceTemplate);
4636 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4638 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4639 if(!temp)
4640 continue;
4642 if(!MapManager::IsValidMAP(temp->map))
4643 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4645 if(!MapManager::IsValidMapCoord(temp->parent,temp->startLocX,temp->startLocY,temp->startLocZ,temp->startLocO))
4647 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad parent entrance coordinates for map id %d template!", temp->map);
4648 temp->parent = 0; // will have wrong continent 0 parent, at least existed
4652 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4653 sLog.outString();
4656 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4658 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4659 if(itr != mGossipText.end())
4660 return &itr->second;
4661 return NULL;
4664 void ObjectMgr::LoadGossipText()
4666 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4668 int count = 0;
4669 if( !result )
4671 barGoLink bar( 1 );
4672 bar.step();
4674 sLog.outString();
4675 sLog.outString( ">> Loaded %u npc texts", count );
4676 return;
4679 int cic;
4681 barGoLink bar( (int)result->GetRowCount() );
4685 ++count;
4686 cic = 0;
4688 Field *fields = result->Fetch();
4690 bar.step();
4692 uint32 Text_ID = fields[cic++].GetUInt32();
4693 if(!Text_ID)
4695 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4696 continue;
4699 GossipText& gText = mGossipText[Text_ID];
4701 for (int i=0; i< 8; i++)
4703 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4704 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4706 gText.Options[i].Language = fields[cic++].GetUInt32();
4707 gText.Options[i].Probability = fields[cic++].GetFloat();
4709 for(int j=0; j < 3; ++j)
4711 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4712 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4715 } while( result->NextRow() );
4717 sLog.outString();
4718 sLog.outString( ">> Loaded %u npc texts", count );
4719 delete result;
4722 void ObjectMgr::LoadNpcTextLocales()
4724 mNpcTextLocaleMap.clear(); // need for reload case
4726 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4727 "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,"
4728 "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,"
4729 "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,"
4730 "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,"
4731 "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,"
4732 "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,"
4733 "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, "
4734 "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 "
4735 " FROM locales_npc_text");
4737 if(!result)
4739 barGoLink bar(1);
4741 bar.step();
4743 sLog.outString();
4744 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4745 return;
4748 barGoLink bar((int)result->GetRowCount());
4752 Field *fields = result->Fetch();
4753 bar.step();
4755 uint32 entry = fields[0].GetUInt32();
4757 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4759 for(int i=1; i<MAX_LOCALE; ++i)
4761 for(int j=0; j<8; ++j)
4763 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4764 if(!str0.empty())
4766 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4767 if(idx >= 0)
4769 if((int32)data.Text_0[j].size() <= idx)
4770 data.Text_0[j].resize(idx+1);
4772 data.Text_0[j][idx] = str0;
4775 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4776 if(!str1.empty())
4778 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4779 if(idx >= 0)
4781 if((int32)data.Text_1[j].size() <= idx)
4782 data.Text_1[j].resize(idx+1);
4784 data.Text_1[j][idx] = str1;
4789 } while (result->NextRow());
4791 delete result;
4793 sLog.outString();
4794 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4797 //not very fast function but it is called only once a day, or on starting-up
4798 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4800 time_t basetime = time(NULL);
4801 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4802 //delete all old mails without item and without body immediately, if starting server
4803 if (!serverUp)
4804 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4805 // 0 1 2 3 4 5 6 7 8 9
4806 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime);
4807 if ( !result )
4809 barGoLink bar(1);
4810 bar.step();
4811 sLog.outString();
4812 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4813 return; // any mails need to be returned or deleted
4816 //std::ostringstream delitems, delmails; //will be here for optimization
4817 //bool deletemail = false, deleteitem = false;
4818 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4819 //delmails << "DELETE FROM mail WHERE id IN ( "
4821 barGoLink bar( (int)result->GetRowCount() );
4822 uint32 count = 0;
4823 Field *fields;
4827 bar.step();
4829 fields = result->Fetch();
4830 Mail *m = new Mail;
4831 m->messageID = fields[0].GetUInt32();
4832 m->messageType = fields[1].GetUInt8();
4833 m->sender = fields[2].GetUInt32();
4834 m->receiver = fields[3].GetUInt32();
4835 m->itemTextId = fields[4].GetUInt32();
4836 bool has_items = fields[5].GetBool();
4837 m->expire_time = (time_t)fields[6].GetUInt64();
4838 m->deliver_time = 0;
4839 m->COD = fields[7].GetUInt32();
4840 m->checked = fields[8].GetUInt32();
4841 m->mailTemplateId = fields[9].GetInt16();
4843 Player *pl = 0;
4844 if (serverUp)
4845 pl = GetPlayer((uint64)m->receiver);
4846 if (pl)
4847 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4848 //his in mailbox and he has already listed his mails )
4849 delete m;
4850 continue;
4852 //delete or return mail:
4853 if (has_items)
4855 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4856 if(resultItems)
4860 Field *fields2 = resultItems->Fetch();
4862 uint32 item_guid_low = fields2[0].GetUInt32();
4863 uint32 item_template = fields2[1].GetUInt32();
4865 m->AddItem(item_guid_low, item_template);
4867 while (resultItems->NextRow());
4869 delete resultItems;
4871 //if it is mail from AH, it shouldn't be returned, but deleted
4872 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4874 // mail open and then not returned
4875 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4876 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4878 else
4880 //mail will be returned:
4881 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4882 delete m;
4883 continue;
4887 if (m->itemTextId)
4888 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4890 //deletemail = true;
4891 //delmails << m->messageID << ", ";
4892 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4893 delete m;
4894 ++count;
4895 } while (result->NextRow());
4896 delete result;
4898 sLog.outString();
4899 sLog.outString( ">> Loaded %u mails", count );
4902 void ObjectMgr::LoadQuestAreaTriggers()
4904 mQuestAreaTriggerMap.clear(); // need for reload case
4906 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4908 uint32 count = 0;
4910 if( !result )
4912 barGoLink bar( 1 );
4913 bar.step();
4915 sLog.outString();
4916 sLog.outString( ">> Loaded %u quest trigger points", count );
4917 return;
4920 barGoLink bar((int) result->GetRowCount() );
4924 ++count;
4925 bar.step();
4927 Field *fields = result->Fetch();
4929 uint32 trigger_ID = fields[0].GetUInt32();
4930 uint32 quest_ID = fields[1].GetUInt32();
4932 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4933 if(!atEntry)
4935 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4936 continue;
4939 Quest const* quest = GetQuestTemplate(quest_ID);
4941 if(!quest)
4943 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4944 continue;
4947 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4949 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);
4951 // this will prevent quest completing without objective
4952 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4954 // continue; - quest modified to required objective and trigger can be allowed.
4957 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4959 } while( result->NextRow() );
4961 delete result;
4963 sLog.outString();
4964 sLog.outString( ">> Loaded %u quest trigger points", count );
4967 void ObjectMgr::LoadTavernAreaTriggers()
4969 mTavernAreaTriggerSet.clear(); // need for reload case
4971 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4973 uint32 count = 0;
4975 if( !result )
4977 barGoLink bar( 1 );
4978 bar.step();
4980 sLog.outString();
4981 sLog.outString( ">> Loaded %u tavern triggers", count );
4982 return;
4985 barGoLink bar( (int)result->GetRowCount() );
4989 ++count;
4990 bar.step();
4992 Field *fields = result->Fetch();
4994 uint32 Trigger_ID = fields[0].GetUInt32();
4996 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4997 if(!atEntry)
4999 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5000 continue;
5003 mTavernAreaTriggerSet.insert(Trigger_ID);
5004 } while( result->NextRow() );
5006 delete result;
5008 sLog.outString();
5009 sLog.outString( ">> Loaded %u tavern triggers", count );
5012 void ObjectMgr::LoadAreaTriggerScripts()
5014 mAreaTriggerScripts.clear(); // need for reload case
5015 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
5017 uint32 count = 0;
5019 if( !result )
5021 barGoLink bar( 1 );
5022 bar.step();
5024 sLog.outString();
5025 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5026 return;
5029 barGoLink bar( (int)result->GetRowCount() );
5033 ++count;
5034 bar.step();
5036 Field *fields = result->Fetch();
5038 uint32 Trigger_ID = fields[0].GetUInt32();
5039 const char *scriptName = fields[1].GetString();
5041 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5042 if(!atEntry)
5044 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5045 continue;
5047 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
5048 } while( result->NextRow() );
5050 delete result;
5052 sLog.outString();
5053 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5056 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
5058 bool found = false;
5059 float dist;
5060 uint32 id = 0;
5062 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
5064 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
5065 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
5066 continue;
5068 uint8 field = (uint8)((i - 1) / 32);
5069 uint32 submask = 1<<((i-1)%32);
5071 // skip not taxi network nodes
5072 if((sTaxiNodesMask[field] & submask)==0)
5073 continue;
5075 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5076 if(found)
5078 if(dist2 < dist)
5080 dist = dist2;
5081 id = i;
5084 else
5086 found = true;
5087 dist = dist2;
5088 id = i;
5092 return id;
5095 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5097 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5098 if(src_i==sTaxiPathSetBySource.end())
5100 path = 0;
5101 cost = 0;
5102 return;
5105 TaxiPathSetForSource& pathSet = src_i->second;
5107 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5108 if(dest_i==pathSet.end())
5110 path = 0;
5111 cost = 0;
5112 return;
5115 cost = dest_i->second.price;
5116 path = dest_i->second.ID;
5119 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5121 uint16 mount_entry = 0;
5123 // select mount creature id
5124 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5125 if(node)
5127 if (team == ALLIANCE)
5129 mount_entry = node->MountCreatureID[1];
5130 if(!mount_entry && allowed_alt_team)
5131 mount_entry = node->MountCreatureID[0];
5133 else if (team == HORDE)
5135 mount_entry = node->MountCreatureID[0];
5137 if(!mount_entry && allowed_alt_team)
5138 mount_entry = node->MountCreatureID[1];
5142 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5143 if (!mount_info)
5144 return 0;
5146 uint16 mount_id = ChooseDisplayId(team,mount_info);
5147 if (!mount_id)
5148 return 0;
5150 CreatureModelInfo const *minfo = GetCreatureModelRandomGender(mount_id);
5151 if (minfo)
5152 mount_id = minfo->modelid;
5154 return mount_id;
5157 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5159 if(path >= sTaxiPathNodesByPath.size())
5160 return;
5162 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5164 pathnodes.Resize(nodeList.size());
5165 mapIds.resize(nodeList.size());
5167 for(size_t i = 0; i < nodeList.size(); ++i)
5169 pathnodes[ i ].x = nodeList[i].x;
5170 pathnodes[ i ].y = nodeList[i].y;
5171 pathnodes[ i ].z = nodeList[i].z;
5173 mapIds[i] = nodeList[i].mapid;
5177 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5179 if(path >= sTaxiPathNodesByPath.size())
5180 return;
5182 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5184 pathnodes.Resize(nodeList.size());
5186 for(size_t i = 0; i < nodeList.size(); ++i)
5188 pathnodes[ i ].mapid = nodeList[i].mapid;
5189 pathnodes[ i ].x = nodeList[i].x;
5190 pathnodes[ i ].y = nodeList[i].y;
5191 pathnodes[ i ].z = nodeList[i].z;
5192 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5193 pathnodes[ i ].delay = nodeList[i].delay;
5197 void ObjectMgr::LoadGraveyardZones()
5199 mGraveYardMap.clear(); // need for reload case
5201 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5203 uint32 count = 0;
5205 if( !result )
5207 barGoLink bar( 1 );
5208 bar.step();
5210 sLog.outString();
5211 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5212 return;
5215 barGoLink bar( (int)result->GetRowCount() );
5219 ++count;
5220 bar.step();
5222 Field *fields = result->Fetch();
5224 uint32 safeLocId = fields[0].GetUInt32();
5225 uint32 zoneId = fields[1].GetUInt32();
5226 uint32 team = fields[2].GetUInt32();
5228 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5229 if(!entry)
5231 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5232 continue;
5235 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5236 if(!areaEntry)
5238 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5239 continue;
5242 if(areaEntry->zone != 0)
5244 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5245 continue;
5248 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5250 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5251 continue;
5254 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5255 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5256 } while( result->NextRow() );
5258 delete result;
5260 sLog.outString();
5261 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5264 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5266 // search for zone associated closest graveyard
5267 uint32 zoneId = sMapMgr.GetZoneId(MapId,x,y,z);
5269 // Simulate std. algorithm:
5270 // found some graveyard associated to (ghost_zone,ghost_map)
5272 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5273 // then check faction
5274 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5275 // then check faction
5276 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5277 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5278 if(graveLow==graveUp)
5280 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5281 return NULL;
5284 // at corpse map
5285 bool foundNear = false;
5286 float distNear;
5287 WorldSafeLocsEntry const* entryNear = NULL;
5289 // at entrance map for corpse map
5290 bool foundEntr = false;
5291 float distEntr;
5292 WorldSafeLocsEntry const* entryEntr = NULL;
5294 // some where other
5295 WorldSafeLocsEntry const* entryFar = NULL;
5297 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5299 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5301 GraveYardData const& data = itr->second;
5303 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5304 if(!entry)
5306 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5307 continue;
5310 // skip enemy faction graveyard
5311 // team == 0 case can be at call from .neargrave
5312 if(data.team != 0 && team != 0 && data.team != team)
5313 continue;
5315 // find now nearest graveyard at other map
5316 if(MapId != entry->map_id)
5318 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5319 if (!mapEntry ||
5320 mapEntry->entrance_map < 0 ||
5321 mapEntry->entrance_map != entry->map_id ||
5322 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5324 // not have any corrdinates for check distance anyway
5325 entryFar = entry;
5326 continue;
5329 // at entrance map calculate distance (2D);
5330 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5331 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5332 if(foundEntr)
5334 if(dist2 < distEntr)
5336 distEntr = dist2;
5337 entryEntr = entry;
5340 else
5342 foundEntr = true;
5343 distEntr = dist2;
5344 entryEntr = entry;
5347 // find now nearest graveyard at same map
5348 else
5350 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5351 if(foundNear)
5353 if(dist2 < distNear)
5355 distNear = dist2;
5356 entryNear = entry;
5359 else
5361 foundNear = true;
5362 distNear = dist2;
5363 entryNear = entry;
5368 if(entryNear)
5369 return entryNear;
5371 if(entryEntr)
5372 return entryEntr;
5374 return entryFar;
5377 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5379 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5380 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5382 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5384 if(itr->second.safeLocId==id)
5385 return &itr->second;
5388 return NULL;
5391 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5393 if(FindGraveYardData(id,zoneId))
5394 return false;
5396 // add link to loaded data
5397 GraveYardData data;
5398 data.safeLocId = id;
5399 data.team = team;
5401 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5403 // add link to DB
5404 if(inDB)
5406 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5407 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5410 return true;
5413 void ObjectMgr::LoadAreaTriggerTeleports()
5415 mAreaTriggers.clear(); // need for reload case
5417 uint32 count = 0;
5419 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5420 QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_quest_done_heroic, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
5421 if( !result )
5424 barGoLink bar( 1 );
5426 bar.step();
5428 sLog.outString();
5429 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5430 return;
5433 barGoLink bar( (int)result->GetRowCount() );
5437 Field *fields = result->Fetch();
5439 bar.step();
5441 ++count;
5443 uint32 Trigger_ID = fields[0].GetUInt32();
5445 AreaTrigger at;
5447 at.requiredLevel = fields[1].GetUInt8();
5448 at.requiredItem = fields[2].GetUInt32();
5449 at.requiredItem2 = fields[3].GetUInt32();
5450 at.heroicKey = fields[4].GetUInt32();
5451 at.heroicKey2 = fields[5].GetUInt32();
5452 at.requiredQuest = fields[6].GetUInt32();
5453 at.requiredQuestHeroic = fields[7].GetUInt32();
5454 at.requiredFailedText = fields[8].GetCppString();
5455 at.target_mapId = fields[9].GetUInt32();
5456 at.target_X = fields[10].GetFloat();
5457 at.target_Y = fields[11].GetFloat();
5458 at.target_Z = fields[12].GetFloat();
5459 at.target_Orientation = fields[13].GetFloat();
5461 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5462 if(!atEntry)
5464 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5465 continue;
5468 if(at.requiredItem)
5470 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5471 if(!pProto)
5473 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5474 at.requiredItem = 0;
5477 if(at.requiredItem2)
5479 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5480 if(!pProto)
5482 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5483 at.requiredItem2 = 0;
5487 if(at.heroicKey)
5489 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5490 if(!pProto)
5492 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5493 at.heroicKey = 0;
5497 if(at.heroicKey2)
5499 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5500 if(!pProto)
5502 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5503 at.heroicKey2 = 0;
5507 if(at.requiredQuest)
5509 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5510 if(qReqItr == mQuestTemplates.end())
5512 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5513 at.requiredQuest = 0;
5517 if(at.requiredQuestHeroic)
5519 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5520 if(qReqItr == mQuestTemplates.end())
5522 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5523 at.requiredQuestHeroic = 0;
5527 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5528 if(!mapEntry)
5530 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5531 continue;
5534 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5536 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5537 continue;
5540 mAreaTriggers[Trigger_ID] = at;
5542 } while( result->NextRow() );
5544 delete result;
5546 sLog.outString();
5547 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5551 * Searches for the areatrigger which teleports players out of the given map
5553 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5555 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5556 if(!mapEntry) return NULL;
5557 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5559 if(itr->second.target_mapId == mapEntry->entrance_map)
5561 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5562 if(atEntry && atEntry->mapid == Map)
5563 return &itr->second;
5566 return NULL;
5570 * Searches for the areatrigger which teleports players to the given map
5572 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5574 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5576 if(itr->second.target_mapId == Map)
5578 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5579 if(atEntry)
5580 return &itr->second;
5583 return NULL;
5586 void ObjectMgr::PackGroupIds()
5588 // this routine renumbers groups in such a way so they start from 1 and go up
5590 // obtain set of all groups
5591 std::set<uint32> groupIds;
5593 // all valid ids are in the instance table
5594 // any associations to ids not in this table are assumed to be
5595 // cleaned already in CleanupInstances
5596 QueryResult *result = CharacterDatabase.Query("SELECT groupId FROM groups");
5597 if( result )
5601 Field *fields = result->Fetch();
5603 uint32 id = fields[0].GetUInt32();
5605 if (id == 0)
5607 CharacterDatabase.PExecute("DELETE FROM groups WHERE groupId = '%u'", id);
5608 CharacterDatabase.PExecute("DELETE FROM group_member WHERE groupId = '%u'", id);
5609 continue;
5612 groupIds.insert(id);
5614 while (result->NextRow());
5615 delete result;
5618 barGoLink bar( groupIds.size() + 1);
5619 bar.step();
5621 uint32 groupId = 1;
5622 // we do assume std::set is sorted properly on integer value
5623 for (std::set<uint32>::iterator i = groupIds.begin(); i != groupIds.end(); ++i)
5625 if (*i != groupId)
5627 // remap group id
5628 CharacterDatabase.PExecute("UPDATE groups SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5629 CharacterDatabase.PExecute("UPDATE group_member SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5632 ++groupId;
5633 bar.step();
5636 m_groupId = groupId;
5638 sLog.outString( ">> Group Ids remapped, next group id is %u", groupId );
5639 sLog.outString();
5642 void ObjectMgr::SetHighestGuids()
5644 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5645 if( result )
5647 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5648 delete result;
5651 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5652 if( result )
5654 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5655 delete result;
5658 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5659 if( result )
5661 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5662 delete result;
5665 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5666 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5667 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5668 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5669 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5671 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5672 if( result )
5674 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5675 delete result;
5678 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5679 if( result )
5681 m_auctionid = (*result)[0].GetUInt32()+1;
5682 delete result;
5685 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5686 if( result )
5688 m_mailid = (*result)[0].GetUInt32()+1;
5689 delete result;
5692 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5693 if( result )
5695 m_ItemTextId = (*result)[0].GetUInt32()+1;
5696 delete result;
5699 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5700 if( result )
5702 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5703 delete result;
5706 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5707 if (result)
5709 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5710 delete result;
5713 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5714 if (result)
5716 m_equipmentSetGuid = (*result)[0].GetUInt64()+1;
5717 delete result;
5720 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5721 if (result)
5723 m_guildId = (*result)[0].GetUInt32()+1;
5724 delete result;
5727 result = CharacterDatabase.Query( "SELECT MAX(groupId) FROM groups" );
5728 if (result)
5730 m_groupId = (*result)[0].GetUInt32()+1;
5731 delete result;
5735 uint32 ObjectMgr::GenerateArenaTeamId()
5737 if(m_arenaTeamId>=0xFFFFFFFE)
5739 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5740 World::StopNow(ERROR_EXIT_CODE);
5742 return m_arenaTeamId++;
5745 uint32 ObjectMgr::GenerateAuctionID()
5747 if(m_auctionid>=0xFFFFFFFE)
5749 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5750 World::StopNow(ERROR_EXIT_CODE);
5752 return m_auctionid++;
5755 uint64 ObjectMgr::GenerateEquipmentSetGuid()
5757 if(m_equipmentSetGuid>=0xFFFFFFFFFFFFFFFEll)
5759 sLog.outError("EquipmentSet guid overflow!! Can't continue, shutting down server. ");
5760 World::StopNow(ERROR_EXIT_CODE);
5762 return m_equipmentSetGuid++;
5765 uint32 ObjectMgr::GenerateGuildId()
5767 if(m_guildId>=0xFFFFFFFE)
5769 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5770 World::StopNow(ERROR_EXIT_CODE);
5772 return m_guildId++;
5775 uint32 ObjectMgr::GenerateGroupId()
5777 if(m_groupId>=0xFFFFFFFE)
5779 sLog.outError("Group ids overflow!! Can't continue, shutting down server. ");
5780 World::StopNow(ERROR_EXIT_CODE);
5782 return m_groupId++;
5785 uint32 ObjectMgr::GenerateMailID()
5787 if(m_mailid>=0xFFFFFFFE)
5789 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5790 World::StopNow(ERROR_EXIT_CODE);
5792 return m_mailid++;
5795 uint32 ObjectMgr::GenerateItemTextID()
5797 if(m_ItemTextId>=0xFFFFFFFE)
5799 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5800 World::StopNow(ERROR_EXIT_CODE);
5802 return m_ItemTextId++;
5805 uint32 ObjectMgr::CreateItemText(std::string text)
5807 uint32 newItemTextId = GenerateItemTextID();
5808 //insert new itempage to container
5809 mItemTexts[ newItemTextId ] = text;
5810 //save new itempage
5811 CharacterDatabase.escape_string(text);
5812 //any Delete query needed, itemTextId is maximum of all ids
5813 std::ostringstream query;
5814 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5815 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5816 return newItemTextId;
5819 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5821 switch(guidhigh)
5823 case HIGHGUID_ITEM:
5824 if(m_hiItemGuid>=0xFFFFFFFE)
5826 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5827 World::StopNow(ERROR_EXIT_CODE);
5829 return m_hiItemGuid++;
5830 case HIGHGUID_UNIT:
5831 if(m_hiCreatureGuid>=0x00FFFFFE)
5833 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5834 World::StopNow(ERROR_EXIT_CODE);
5836 return m_hiCreatureGuid++;
5837 case HIGHGUID_PLAYER:
5838 if(m_hiCharGuid>=0xFFFFFFFE)
5840 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5841 World::StopNow(ERROR_EXIT_CODE);
5843 return m_hiCharGuid++;
5844 case HIGHGUID_GAMEOBJECT:
5845 if(m_hiGoGuid>=0x00FFFFFE)
5847 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5848 World::StopNow(ERROR_EXIT_CODE);
5850 return m_hiGoGuid++;
5851 case HIGHGUID_CORPSE:
5852 if(m_hiCorpseGuid>=0xFFFFFFFE)
5854 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5855 World::StopNow(ERROR_EXIT_CODE);
5857 return m_hiCorpseGuid++;
5858 default:
5859 ASSERT(0);
5862 ASSERT(0);
5863 return 0;
5866 void ObjectMgr::LoadGameObjectLocales()
5868 mGameObjectLocaleMap.clear(); // need for reload case
5870 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5871 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5872 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5873 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5875 if(!result)
5877 barGoLink bar(1);
5879 bar.step();
5881 sLog.outString();
5882 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5883 return;
5886 barGoLink bar((int)result->GetRowCount());
5890 Field *fields = result->Fetch();
5891 bar.step();
5893 uint32 entry = fields[0].GetUInt32();
5895 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5897 for(int i = 1; i < MAX_LOCALE; ++i)
5899 std::string str = fields[i].GetCppString();
5900 if(!str.empty())
5902 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5903 if(idx >= 0)
5905 if((int32)data.Name.size() <= idx)
5906 data.Name.resize(idx+1);
5908 data.Name[idx] = str;
5913 for(int i = 1; i < MAX_LOCALE; ++i)
5915 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5916 if(!str.empty())
5918 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5919 if(idx >= 0)
5921 if((int32)data.CastBarCaption.size() <= idx)
5922 data.CastBarCaption.resize(idx+1);
5924 data.CastBarCaption[idx] = str;
5929 } while (result->NextRow());
5931 delete result;
5933 sLog.outString();
5934 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5937 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5939 template<class D>
5940 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5942 dst = D(sObjectMgr.GetScriptId(src));
5946 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5948 if (sLockStore.LookupEntry(dataN))
5949 return;
5951 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5952 goInfo->id,goInfo->type,N,dataN,dataN);
5955 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5957 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5959 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5960 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5961 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5963 /* disable check for while (too many error reports baout not existed in trap templates
5964 else
5965 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5966 goInfo->id,goInfo->type,N,dataN,dataN);
5970 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5972 if (sSpellStore.LookupEntry(dataN))
5973 return;
5975 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5976 goInfo->id,goInfo->type,N,dataN,dataN);
5979 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5981 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5982 return;
5984 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5985 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5987 // prevent client and server unexpected work
5988 const_cast<uint32&>(dataN) = 0;
5991 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5993 // 0/1 correct values
5994 if (dataN <= 1)
5995 return;
5997 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5998 goInfo->id,goInfo->type,N,dataN);
6001 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
6003 // 0/1 correct values
6004 if (dataN <= 1)
6005 return;
6007 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
6008 goInfo->id,goInfo->type,N,dataN);
6011 void ObjectMgr::LoadGameobjectInfo()
6013 SQLGameObjectLoader loader;
6014 loader.Load(sGOStorage);
6016 // some checks
6017 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
6019 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
6020 if (!goInfo)
6021 continue;
6023 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
6025 switch(goInfo->type)
6027 case GAMEOBJECT_TYPE_DOOR: //0
6029 if (goInfo->door.lockId)
6030 CheckGOLockId(goInfo,goInfo->door.lockId,1);
6031 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
6032 break;
6034 case GAMEOBJECT_TYPE_BUTTON: //1
6036 if (goInfo->button.lockId)
6037 CheckGOLockId(goInfo,goInfo->button.lockId,1);
6038 if (goInfo->button.linkedTrapId) // linked trap
6039 CheckGOLinkedTrapId(goInfo,goInfo->button.linkedTrapId,3);
6040 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
6041 break;
6043 case GAMEOBJECT_TYPE_QUESTGIVER: //2
6045 if (goInfo->questgiver.lockId)
6046 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
6047 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
6048 break;
6050 case GAMEOBJECT_TYPE_CHEST: //3
6052 if (goInfo->chest.lockId)
6053 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
6055 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
6057 if (goInfo->chest.linkedTrapId) // linked trap
6058 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
6059 break;
6061 case GAMEOBJECT_TYPE_TRAP: //6
6063 if (goInfo->trap.lockId)
6064 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
6065 /* disable check for while, too many not existed spells
6066 if (goInfo->trap.spellId) // spell
6067 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
6069 break;
6071 case GAMEOBJECT_TYPE_CHAIR: //7
6072 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
6073 break;
6074 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
6076 if (goInfo->spellFocus.focusId)
6078 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
6079 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
6080 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
6083 if (goInfo->spellFocus.linkedTrapId) // linked trap
6084 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
6085 break;
6087 case GAMEOBJECT_TYPE_GOOBER: //10
6089 if (goInfo->goober.lockId)
6090 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
6092 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
6094 if (goInfo->goober.pageId) // pageId
6096 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
6097 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
6098 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
6100 /* disable check for while, too many not existed spells
6101 if (goInfo->goober.spellId) // spell
6102 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
6104 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
6105 if (goInfo->goober.linkedTrapId) // linked trap
6106 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
6107 break;
6109 case GAMEOBJECT_TYPE_AREADAMAGE: //12
6111 if (goInfo->areadamage.lockId)
6112 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
6113 break;
6115 case GAMEOBJECT_TYPE_CAMERA: //13
6117 if (goInfo->camera.lockId)
6118 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
6119 break;
6121 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
6123 if (goInfo->moTransport.taxiPathId)
6125 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
6126 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
6127 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
6129 break;
6131 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
6133 /* disable check for while, too many not existed spells
6134 // always must have spell
6135 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
6137 break;
6139 case GAMEOBJECT_TYPE_SPELLCASTER: //22
6141 // always must have spell
6142 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
6143 break;
6145 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6147 if (goInfo->flagstand.lockId)
6148 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6149 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6150 break;
6152 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6154 if (goInfo->fishinghole.lockId)
6155 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6156 break;
6158 case GAMEOBJECT_TYPE_FLAGDROP: //26
6160 if (goInfo->flagdrop.lockId)
6161 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6162 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6163 break;
6165 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6166 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6167 break;
6171 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6172 sLog.outString();
6175 void ObjectMgr::LoadExplorationBaseXP()
6177 uint32 count = 0;
6178 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6180 if( !result )
6182 barGoLink bar( 1 );
6184 bar.step();
6186 sLog.outString();
6187 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6188 return;
6191 barGoLink bar( (int)result->GetRowCount() );
6195 bar.step();
6197 Field *fields = result->Fetch();
6198 uint32 level = fields[0].GetUInt32();
6199 uint32 basexp = fields[1].GetUInt32();
6200 mBaseXPTable[level] = basexp;
6201 ++count;
6203 while (result->NextRow());
6205 delete result;
6207 sLog.outString();
6208 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6211 uint32 ObjectMgr::GetBaseXP(uint32 level) const
6213 BaseXPMap::const_iterator itr = mBaseXPTable.find(level);
6214 return itr != mBaseXPTable.end() ? itr->second : 0;
6217 uint32 ObjectMgr::GetXPForLevel(uint32 level) const
6219 if (level < mPlayerXPperLevel.size())
6220 return mPlayerXPperLevel[level];
6221 return 0;
6224 void ObjectMgr::LoadPetNames()
6226 uint32 count = 0;
6227 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6229 if( !result )
6231 barGoLink bar( 1 );
6233 bar.step();
6235 sLog.outString();
6236 sLog.outString( ">> Loaded %u pet name parts", count );
6237 return;
6240 barGoLink bar( (int)result->GetRowCount() );
6244 bar.step();
6246 Field *fields = result->Fetch();
6247 std::string word = fields[0].GetString();
6248 uint32 entry = fields[1].GetUInt32();
6249 bool half = fields[2].GetBool();
6250 if(half)
6251 PetHalfName1[entry].push_back(word);
6252 else
6253 PetHalfName0[entry].push_back(word);
6254 ++count;
6256 while (result->NextRow());
6257 delete result;
6259 sLog.outString();
6260 sLog.outString( ">> Loaded %u pet name parts", count );
6263 void ObjectMgr::LoadPetNumber()
6265 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6266 if(result)
6268 Field *fields = result->Fetch();
6269 m_hiPetNumber = fields[0].GetUInt32()+1;
6270 delete result;
6273 barGoLink bar( 1 );
6274 bar.step();
6276 sLog.outString();
6277 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
6280 std::string ObjectMgr::GeneratePetName(uint32 entry)
6282 std::vector<std::string> & list0 = PetHalfName0[entry];
6283 std::vector<std::string> & list1 = PetHalfName1[entry];
6285 if(list0.empty() || list1.empty())
6287 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6288 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6289 if(!petname)
6290 petname = cinfo->Name;
6291 return std::string(petname);
6294 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6297 uint32 ObjectMgr::GeneratePetNumber()
6299 return ++m_hiPetNumber;
6302 void ObjectMgr::LoadCorpses()
6304 uint32 count = 0;
6305 // 0 1 2 3 4 5 6 7 8 10
6306 QueryResult *result = CharacterDatabase.Query("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
6308 if( !result )
6310 barGoLink bar( 1 );
6312 bar.step();
6314 sLog.outString();
6315 sLog.outString( ">> Loaded %u corpses", count );
6316 return;
6319 barGoLink bar( (int)result->GetRowCount() );
6323 bar.step();
6325 Field *fields = result->Fetch();
6327 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6329 Corpse *corpse = new Corpse;
6330 if(!corpse->LoadFromDB(guid,fields))
6332 delete corpse;
6333 continue;
6336 sObjectAccessor.AddCorpse(corpse);
6338 ++count;
6340 while (result->NextRow());
6341 delete result;
6343 sLog.outString();
6344 sLog.outString( ">> Loaded %u corpses", count );
6347 void ObjectMgr::LoadReputationOnKill()
6349 uint32 count = 0;
6351 // 0 1 2
6352 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6353 // 3 4 5 6 7 8 9
6354 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6355 "FROM creature_onkill_reputation");
6357 if(!result)
6359 barGoLink bar(1);
6361 bar.step();
6363 sLog.outString();
6364 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6365 return;
6368 barGoLink bar((int)result->GetRowCount());
6372 Field *fields = result->Fetch();
6373 bar.step();
6375 uint32 creature_id = fields[0].GetUInt32();
6377 ReputationOnKillEntry repOnKill;
6378 repOnKill.repfaction1 = fields[1].GetUInt32();
6379 repOnKill.repfaction2 = fields[2].GetUInt32();
6380 repOnKill.is_teamaward1 = fields[3].GetBool();
6381 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6382 repOnKill.repvalue1 = fields[5].GetInt32();
6383 repOnKill.is_teamaward2 = fields[6].GetBool();
6384 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6385 repOnKill.repvalue2 = fields[8].GetInt32();
6386 repOnKill.team_dependent = fields[9].GetUInt8();
6388 if(!GetCreatureTemplate(creature_id))
6390 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6391 continue;
6394 if(repOnKill.repfaction1)
6396 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6397 if(!factionEntry1)
6399 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6400 continue;
6404 if(repOnKill.repfaction2)
6406 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6407 if(!factionEntry2)
6409 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6410 continue;
6414 mRepOnKill[creature_id] = repOnKill;
6416 ++count;
6417 } while (result->NextRow());
6419 delete result;
6421 sLog.outString();
6422 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6425 void ObjectMgr::LoadPointsOfInterest()
6427 mPointsOfInterest.clear(); // need for reload case
6429 uint32 count = 0;
6431 // 0 1 2 3 4 5
6432 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6434 if(!result)
6436 barGoLink bar(1);
6438 bar.step();
6440 sLog.outString();
6441 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6442 return;
6445 barGoLink bar((int)result->GetRowCount());
6449 Field *fields = result->Fetch();
6450 bar.step();
6452 uint32 point_id = fields[0].GetUInt32();
6454 PointOfInterest POI;
6455 POI.x = fields[1].GetFloat();
6456 POI.y = fields[2].GetFloat();
6457 POI.icon = fields[3].GetUInt32();
6458 POI.flags = fields[4].GetUInt32();
6459 POI.data = fields[5].GetUInt32();
6460 POI.icon_name = fields[6].GetCppString();
6462 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6464 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6465 continue;
6468 mPointsOfInterest[point_id] = POI;
6470 ++count;
6471 } while (result->NextRow());
6473 delete result;
6475 sLog.outString();
6476 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6479 void ObjectMgr::LoadQuestPOI()
6481 mQuestPOIMap.clear(); // need for reload case
6483 uint32 count = 0;
6485 // 0 1 2 3 4 5 6
6486 QueryResult *result = WorldDatabase.Query("SELECT questId, objIndex, mapId, unk1, unk2, unk3, unk4 FROM quest_poi");
6488 if(!result)
6490 barGoLink bar(1);
6492 bar.step();
6494 sLog.outString();
6495 sLog.outErrorDb(">> Loaded 0 quest POI definitions. DB table `quest_poi` is empty.");
6496 return;
6499 barGoLink bar((int)result->GetRowCount());
6503 Field *fields = result->Fetch();
6504 bar.step();
6506 uint32 questId = fields[0].GetUInt32();
6507 int32 objIndex = fields[1].GetInt32();
6508 uint32 mapId = fields[2].GetUInt32();
6509 uint32 unk1 = fields[3].GetUInt32();
6510 uint32 unk2 = fields[4].GetUInt32();
6511 uint32 unk3 = fields[5].GetUInt32();
6512 uint32 unk4 = fields[6].GetUInt32();
6514 QuestPOI POI(objIndex, mapId, unk1, unk2, unk3, unk4);
6516 QueryResult *points = WorldDatabase.PQuery("SELECT x, y FROM quest_poi_points WHERE questId='%u' AND objIndex='%i'", questId, objIndex);
6518 if(points)
6522 Field *pointFields = points->Fetch();
6523 int32 x = pointFields[0].GetInt32();
6524 int32 y = pointFields[1].GetInt32();
6525 QuestPOIPoint point(x, y);
6526 POI.points.push_back(point);
6527 } while (points->NextRow());
6529 delete points;
6532 mQuestPOIMap[questId].push_back(POI);
6534 ++count;
6535 } while (result->NextRow());
6537 delete result;
6539 sLog.outString();
6540 sLog.outString(">> Loaded %u quest POI definitions", count);
6543 void ObjectMgr::LoadNPCSpellClickSpells()
6545 uint32 count = 0;
6547 mSpellClickInfoMap.clear();
6548 // 0 1 2 3 4 5
6549 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6551 if(!result)
6553 barGoLink bar(1);
6555 bar.step();
6557 sLog.outString();
6558 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6559 return;
6562 barGoLink bar((int)result->GetRowCount());
6566 Field *fields = result->Fetch();
6567 bar.step();
6569 uint32 npc_entry = fields[0].GetUInt32();
6570 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6571 if (!cInfo)
6573 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6574 continue;
6577 uint32 spellid = fields[1].GetUInt32();
6578 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6579 if (!spellinfo)
6581 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6582 continue;
6585 uint32 quest_start = fields[2].GetUInt32();
6587 // quest might be 0 to enable spellclick independent of any quest
6588 if (quest_start)
6590 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6592 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6593 continue;
6598 bool quest_start_active = fields[3].GetBool();
6600 uint32 quest_end = fields[4].GetUInt32();
6601 // quest might be 0 to enable spellclick active infinity after start quest
6602 if (quest_end)
6604 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6606 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6607 continue;
6612 uint8 castFlags = fields[5].GetUInt8();
6613 SpellClickInfo info;
6614 info.spellId = spellid;
6615 info.questStart = quest_start;
6616 info.questStartCanActive = quest_start_active;
6617 info.questEnd = quest_end;
6618 info.castFlags = castFlags;
6619 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6621 // mark creature template as spell clickable
6622 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6624 ++count;
6625 } while (result->NextRow());
6627 delete result;
6629 sLog.outString();
6630 sLog.outString(">> Loaded %u spellclick definitions", count);
6633 void ObjectMgr::LoadWeatherZoneChances()
6635 uint32 count = 0;
6637 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6638 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");
6640 if(!result)
6642 barGoLink bar(1);
6644 bar.step();
6646 sLog.outString();
6647 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6648 return;
6651 barGoLink bar((int)result->GetRowCount());
6655 Field *fields = result->Fetch();
6656 bar.step();
6658 uint32 zone_id = fields[0].GetUInt32();
6660 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6662 for(int season = 0; season < WEATHER_SEASONS; ++season)
6664 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6665 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6666 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6668 if(wzc.data[season].rainChance > 100)
6670 wzc.data[season].rainChance = 25;
6671 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6674 if(wzc.data[season].snowChance > 100)
6676 wzc.data[season].snowChance = 25;
6677 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6680 if(wzc.data[season].stormChance > 100)
6682 wzc.data[season].stormChance = 25;
6683 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6687 ++count;
6688 } while (result->NextRow());
6690 delete result;
6692 sLog.outString();
6693 sLog.outString(">> Loaded %u weather definitions", count);
6696 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6698 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6699 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6700 if(t)
6701 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6704 void ObjectMgr::DeleteCreatureData(uint32 guid)
6706 // remove mapid*cellid -> guid_set map
6707 CreatureData const* data = GetCreatureData(guid);
6708 if(data)
6709 RemoveCreatureFromGrid(guid, data);
6711 mCreatureDataMap.erase(guid);
6714 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6716 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6717 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6718 if(t)
6719 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6722 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6724 RespawnTimes::iterator next;
6726 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6728 next = itr;
6729 ++next;
6731 if(GUID_HIPART(itr->first)==instance)
6732 mGORespawnTimes.erase(itr);
6735 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6737 next = itr;
6738 ++next;
6740 if(GUID_HIPART(itr->first)==instance)
6741 mCreatureRespawnTimes.erase(itr);
6744 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6745 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6748 void ObjectMgr::DeleteGOData(uint32 guid)
6750 // remove mapid*cellid -> guid_set map
6751 GameObjectData const* data = GetGOData(guid);
6752 if(data)
6753 RemoveGameobjectFromGrid(guid, data);
6755 mGameObjectDataMap.erase(guid);
6758 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6760 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6761 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6762 cell_guids.corpses[player_guid] = instance;
6765 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6767 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6768 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6769 cell_guids.corpses.erase(player_guid);
6772 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6774 map.clear(); // need for reload case
6776 uint32 count = 0;
6778 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6780 if(!result)
6782 barGoLink bar(1);
6784 bar.step();
6786 sLog.outString();
6787 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6788 return;
6791 barGoLink bar((int)result->GetRowCount());
6795 Field *fields = result->Fetch();
6796 bar.step();
6798 uint32 id = fields[0].GetUInt32();
6799 uint32 quest = fields[1].GetUInt32();
6801 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6803 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6804 continue;
6807 map.insert(QuestRelations::value_type(id,quest));
6809 ++count;
6810 } while (result->NextRow());
6812 delete result;
6814 sLog.outString();
6815 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6818 void ObjectMgr::LoadGameobjectQuestRelations()
6820 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6822 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6824 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6825 if(!goInfo)
6826 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6827 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6828 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6832 void ObjectMgr::LoadGameobjectInvolvedRelations()
6834 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6836 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6838 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6839 if(!goInfo)
6840 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6841 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6842 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6846 void ObjectMgr::LoadCreatureQuestRelations()
6848 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6850 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6852 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6853 if(!cInfo)
6854 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6855 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6856 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);
6860 void ObjectMgr::LoadCreatureInvolvedRelations()
6862 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6864 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6866 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6867 if(!cInfo)
6868 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6869 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6870 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);
6874 void ObjectMgr::LoadReservedPlayersNames()
6876 m_ReservedNames.clear(); // need for reload case
6878 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6880 uint32 count = 0;
6882 if( !result )
6884 barGoLink bar( 1 );
6885 bar.step();
6887 sLog.outString();
6888 sLog.outString( ">> Loaded %u reserved player names", count );
6889 return;
6892 barGoLink bar((int) result->GetRowCount() );
6894 Field* fields;
6897 bar.step();
6898 fields = result->Fetch();
6899 std::string name= fields[0].GetCppString();
6901 std::wstring wstr;
6902 if(!Utf8toWStr (name,wstr))
6904 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6905 continue;
6908 wstrToLower(wstr);
6910 m_ReservedNames.insert(wstr);
6911 ++count;
6912 } while ( result->NextRow() );
6914 delete result;
6916 sLog.outString();
6917 sLog.outString( ">> Loaded %u reserved player names", count );
6920 bool ObjectMgr::IsReservedName( const std::string& name ) const
6922 std::wstring wstr;
6923 if(!Utf8toWStr (name,wstr))
6924 return false;
6926 wstrToLower(wstr);
6928 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6931 enum LanguageType
6933 LT_BASIC_LATIN = 0x0000,
6934 LT_EXTENDEN_LATIN = 0x0001,
6935 LT_CYRILLIC = 0x0002,
6936 LT_EAST_ASIA = 0x0004,
6937 LT_ANY = 0xFFFF
6940 static LanguageType GetRealmLanguageType(bool create)
6942 switch(sWorld.getConfig(CONFIG_UINT32_REALM_ZONE))
6944 case REALM_ZONE_UNKNOWN: // any language
6945 case REALM_ZONE_DEVELOPMENT:
6946 case REALM_ZONE_TEST_SERVER:
6947 case REALM_ZONE_QA_SERVER:
6948 return LT_ANY;
6949 case REALM_ZONE_UNITED_STATES: // extended-Latin
6950 case REALM_ZONE_OCEANIC:
6951 case REALM_ZONE_LATIN_AMERICA:
6952 case REALM_ZONE_ENGLISH:
6953 case REALM_ZONE_GERMAN:
6954 case REALM_ZONE_FRENCH:
6955 case REALM_ZONE_SPANISH:
6956 return LT_EXTENDEN_LATIN;
6957 case REALM_ZONE_KOREA: // East-Asian
6958 case REALM_ZONE_TAIWAN:
6959 case REALM_ZONE_CHINA:
6960 return LT_EAST_ASIA;
6961 case REALM_ZONE_RUSSIAN: // Cyrillic
6962 return LT_CYRILLIC;
6963 default:
6964 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6968 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6970 if(strictMask==0) // any language, ignore realm
6972 if(isExtendedLatinString(wstr,numericOrSpace))
6973 return true;
6974 if(isCyrillicString(wstr,numericOrSpace))
6975 return true;
6976 if(isEastAsianString(wstr,numericOrSpace))
6977 return true;
6978 return false;
6981 if(strictMask & 0x2) // realm zone specific
6983 LanguageType lt = GetRealmLanguageType(create);
6984 if(lt & LT_EXTENDEN_LATIN)
6985 if(isExtendedLatinString(wstr,numericOrSpace))
6986 return true;
6987 if(lt & LT_CYRILLIC)
6988 if(isCyrillicString(wstr,numericOrSpace))
6989 return true;
6990 if(lt & LT_EAST_ASIA)
6991 if(isEastAsianString(wstr,numericOrSpace))
6992 return true;
6995 if(strictMask & 0x1) // basic Latin
6997 if(isBasicLatinString(wstr,numericOrSpace))
6998 return true;
7001 return false;
7004 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
7006 std::wstring wname;
7007 if(!Utf8toWStr(name,wname))
7008 return CHAR_NAME_INVALID_CHARACTER;
7010 if(wname.size() > MAX_PLAYER_NAME)
7011 return CHAR_NAME_TOO_LONG;
7013 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PLAYER_NAME);
7014 if(wname.size() < minName)
7015 return CHAR_NAME_TOO_SHORT;
7017 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PLAYER_NAMES);
7018 if(!isValidString(wname,strictMask,false,create))
7019 return CHAR_NAME_MIXED_LANGUAGES;
7021 return CHAR_NAME_SUCCESS;
7024 bool ObjectMgr::IsValidCharterName( const std::string& name )
7026 std::wstring wname;
7027 if(!Utf8toWStr(name,wname))
7028 return false;
7030 if(wname.size() > MAX_CHARTER_NAME)
7031 return false;
7033 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_CHARTER_NAME);
7034 if(wname.size() < minName)
7035 return false;
7037 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_CHARTER_NAMES);
7039 return isValidString(wname,strictMask,true);
7042 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
7044 std::wstring wname;
7045 if(!Utf8toWStr(name,wname))
7046 return PET_NAME_INVALID;
7048 if(wname.size() > MAX_PET_NAME)
7049 return PET_NAME_TOO_LONG;
7051 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PET_NAME);
7052 if(wname.size() < minName)
7053 return PET_NAME_TOO_SHORT;
7055 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PET_NAMES);
7056 if(!isValidString(wname,strictMask,false))
7057 return PET_NAME_MIXED_LANGUAGES;
7059 return PET_NAME_SUCCESS;
7062 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
7064 if(loc==LOCALE_enUS)
7065 return -1;
7067 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7068 if(m_LocalForIndex[i]==loc)
7069 return i;
7071 return -1;
7074 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
7076 if (i<0 || i>=(int32)m_LocalForIndex.size())
7077 return LOCALE_enUS;
7079 return m_LocalForIndex[i];
7082 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
7084 if(loc==LOCALE_enUS)
7085 return -1;
7087 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7088 if(m_LocalForIndex[i]==loc)
7089 return i;
7091 m_LocalForIndex.push_back(loc);
7092 return m_LocalForIndex.size()-1;
7095 void ObjectMgr::LoadGameObjectForQuests()
7097 mGameObjectForQuestSet.clear(); // need for reload case
7099 if( !sGOStorage.MaxEntry )
7101 barGoLink bar( 1 );
7102 bar.step();
7103 sLog.outString();
7104 sLog.outString( ">> Loaded 0 GameObjects for quests" );
7105 return;
7108 barGoLink bar( sGOStorage.MaxEntry - 1 );
7109 uint32 count = 0;
7111 // collect GO entries for GO that must activated
7112 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
7114 bar.step();
7115 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
7116 if(!goInfo)
7117 continue;
7119 switch(goInfo->type)
7121 // scan GO chest with loot including quest items
7122 case GAMEOBJECT_TYPE_CHEST:
7124 uint32 loot_id = goInfo->GetLootId();
7126 // find quest loot for GO
7127 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
7129 mGameObjectForQuestSet.insert(go_entry);
7130 ++count;
7132 break;
7134 case GAMEOBJECT_TYPE_GOOBER:
7136 if(goInfo->goober.questId) //quests objects
7138 mGameObjectForQuestSet.insert(go_entry);
7139 count++;
7141 break;
7143 default:
7144 break;
7148 sLog.outString();
7149 sLog.outString( ">> Loaded %u GameObjects for quests", count );
7152 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
7154 int32 start_value = min_value;
7155 int32 end_value = max_value;
7156 // some string can have negative indexes range
7157 if (start_value < 0)
7159 if (end_value >= start_value)
7161 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7162 return false;
7165 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
7166 std::swap(start_value,end_value);
7167 ++start_value;
7168 ++end_value;
7170 else
7172 if (start_value >= end_value)
7174 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7175 return false;
7179 // cleanup affected map part for reloading case
7180 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
7182 if (itr->first >= start_value && itr->first < end_value)
7183 mMangosStringLocaleMap.erase(itr++);
7184 else
7185 ++itr;
7188 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);
7190 if (!result)
7192 barGoLink bar(1);
7194 bar.step();
7196 sLog.outString();
7197 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
7198 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
7199 else
7200 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
7201 return false;
7204 uint32 count = 0;
7206 barGoLink bar((int)result->GetRowCount());
7210 Field *fields = result->Fetch();
7211 bar.step();
7213 int32 entry = fields[0].GetInt32();
7215 if (entry==0)
7217 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7218 continue;
7220 else if (entry < start_value || entry >= end_value)
7222 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7223 continue;
7226 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7228 if (data.Content.size() > 0)
7230 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7231 continue;
7234 data.Content.resize(1);
7235 ++count;
7237 // 0 -> default, idx in to idx+1
7238 data.Content[0] = fields[1].GetCppString();
7240 for(int i = 1; i < MAX_LOCALE; ++i)
7242 std::string str = fields[i+1].GetCppString();
7243 if (!str.empty())
7245 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7246 if (idx >= 0)
7248 // 0 -> default, idx in to idx+1
7249 if ((int32)data.Content.size() <= idx+1)
7250 data.Content.resize(idx+2);
7252 data.Content[idx+1] = str;
7256 } while (result->NextRow());
7258 delete result;
7260 sLog.outString();
7261 if (min_value == MIN_MANGOS_STRING_ID)
7262 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7263 else
7264 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7266 return true;
7269 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7271 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7272 // Content[0] always exist if exist MangosStringLocale
7273 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7275 if((int32)msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7276 return msl->Content[locale_idx+1].c_str();
7277 else
7278 return msl->Content[0].c_str();
7281 if(entry > 0)
7282 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7283 else
7284 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7285 return "<error>";
7288 void ObjectMgr::LoadFishingBaseSkillLevel()
7290 mFishingBaseForArea.clear(); // for reload case
7292 uint32 count = 0;
7293 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7295 if( !result )
7297 barGoLink bar( 1 );
7299 bar.step();
7301 sLog.outString();
7302 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7303 return;
7306 barGoLink bar((int) result->GetRowCount() );
7310 bar.step();
7312 Field *fields = result->Fetch();
7313 uint32 entry = fields[0].GetUInt32();
7314 int32 skill = fields[1].GetInt32();
7316 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7317 if(!fArea)
7319 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7320 continue;
7323 mFishingBaseForArea[entry] = skill;
7324 ++count;
7326 while (result->NextRow());
7328 delete result;
7330 sLog.outString();
7331 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7334 // Searches for the same condition already in Conditions store
7335 // Returns Id if found, else adds it to Conditions and returns Id
7336 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7338 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7339 for (uint16 i=0; i < mConditions.size(); ++i)
7341 if (lc == mConditions[i])
7342 return i;
7345 mConditions.push_back(lc);
7347 if(mConditions.size() > 0xFFFF)
7349 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7350 return 0;
7353 return mConditions.size() - 1;
7356 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7358 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7360 std::wstring wname;
7361 if(!Utf8toWStr(names.name[i],wname))
7362 return false;
7364 if(mainpart!=GetMainPartOfName(wname,i+1))
7365 return false;
7367 return true;
7370 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7372 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7373 if(i!= mAreaTriggerScripts.end())
7374 return i->second;
7375 return 0;
7378 // Checks if player meets the condition
7379 bool PlayerCondition::Meets(Player const * player) const
7381 if( !player )
7382 return false; // player not present, return false
7384 switch (condition)
7386 case CONDITION_NONE:
7387 return true; // empty condition, always met
7388 case CONDITION_AURA:
7389 return player->HasAura(value1, SpellEffectIndex(value2));
7390 case CONDITION_ITEM:
7391 return player->HasItemCount(value1, value2);
7392 case CONDITION_ITEM_EQUIPPED:
7393 return player->HasItemOrGemWithIdEquipped(value1,1);
7394 case CONDITION_ZONEID:
7395 return player->GetZoneId() == value1;
7396 case CONDITION_REPUTATION_RANK:
7398 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7399 return faction && player->GetReputationMgr().GetRank(faction) >= ReputationRank(value2);
7401 case CONDITION_TEAM:
7402 return player->GetTeam() == value1;
7403 case CONDITION_SKILL:
7404 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7405 case CONDITION_QUESTREWARDED:
7406 return player->GetQuestRewardStatus(value1);
7407 case CONDITION_QUESTTAKEN:
7409 QuestStatus status = player->GetQuestStatus(value1);
7410 return (status == QUEST_STATUS_INCOMPLETE);
7412 case CONDITION_AD_COMMISSION_AURA:
7414 Unit::AuraMap const& auras = player->GetAuras();
7415 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7416 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7417 return true;
7418 return false;
7420 case CONDITION_NO_AURA:
7421 return !player->HasAura(value1, SpellEffectIndex(value2));
7422 case CONDITION_ACTIVE_EVENT:
7423 return sGameEventMgr.IsActiveEvent(value1);
7424 case CONDITION_AREA_FLAG:
7426 if (AreaTableEntry const *pAreaEntry = GetAreaEntryByAreaID(player->GetAreaId()))
7428 if ((!value1 || (pAreaEntry->flags & value1)) && (!value2 || !(pAreaEntry->flags & value2)))
7429 return true;
7431 return false;
7433 case CONDITION_RACE_CLASS:
7434 if ((!value1 || (player->getRaceMask() & value1)) && (!value2 || (player->getClassMask() & value2)))
7435 return true;
7436 return false;
7437 case CONDITION_LEVEL:
7439 switch(value2)
7441 case 0: return player->getLevel() == value1;
7442 case 1: return player->getLevel() >= value1;
7443 case 2: return player->getLevel() <= value1;
7445 return false;
7447 default:
7448 return false;
7452 // Verification of condition values validity
7453 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7455 if( condition >= MAX_CONDITION) // Wrong condition type
7457 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7458 return false;
7461 switch (condition)
7463 case CONDITION_AURA:
7465 if(!sSpellStore.LookupEntry(value1))
7467 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7468 return false;
7470 if(value2 >= MAX_EFFECT_INDEX)
7472 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7473 return false;
7475 break;
7477 case CONDITION_ITEM:
7479 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7480 if(!proto)
7482 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7483 return false;
7485 break;
7487 case CONDITION_ITEM_EQUIPPED:
7489 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7490 if(!proto)
7492 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7493 return false;
7495 break;
7497 case CONDITION_ZONEID:
7499 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7500 if(!areaEntry)
7502 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7503 return false;
7505 if(areaEntry->zone != 0)
7507 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7508 return false;
7510 break;
7512 case CONDITION_REPUTATION_RANK:
7514 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7515 if(!factionEntry)
7517 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7518 return false;
7520 break;
7522 case CONDITION_TEAM:
7524 if (value1 != ALLIANCE && value1 != HORDE)
7526 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7527 return false;
7529 break;
7531 case CONDITION_SKILL:
7533 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7534 if (!pSkill)
7536 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7537 return false;
7539 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7541 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7542 return false;
7544 break;
7546 case CONDITION_QUESTREWARDED:
7547 case CONDITION_QUESTTAKEN:
7549 Quest const *Quest = sObjectMgr.GetQuestTemplate(value1);
7550 if (!Quest)
7552 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7553 return false;
7555 if(value2)
7556 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7557 break;
7559 case CONDITION_AD_COMMISSION_AURA:
7561 if(value1)
7562 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7563 if(value2)
7564 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7565 break;
7567 case CONDITION_NO_AURA:
7569 if(!sSpellStore.LookupEntry(value1))
7571 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7572 return false;
7574 if(value2 > MAX_EFFECT_INDEX)
7576 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7577 return false;
7579 break;
7581 case CONDITION_ACTIVE_EVENT:
7583 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
7584 if(value1 >=events.size() || !events[value1].isValid())
7586 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7587 return false;
7589 break;
7591 case CONDITION_AREA_FLAG:
7593 if (!value1 && !value2)
7595 sLog.outErrorDb("Area flag condition has both values like 0, skipped");
7596 return false;
7598 break;
7600 case CONDITION_RACE_CLASS:
7602 if (!value1 && !value2)
7604 sLog.outErrorDb("Race_class condition has both values like 0, skipped");
7605 return false;
7608 if (value1 && !(value1 & RACEMASK_ALL_PLAYABLE))
7610 sLog.outErrorDb("Race_class condition has invalid player class %u, skipped", value1);
7611 return false;
7614 if (value2 && !(value2 & CLASSMASK_ALL_PLAYABLE))
7616 sLog.outErrorDb("Race_class condition has invalid race mask %u, skipped", value2);
7617 return false;
7619 break;
7621 case CONDITION_LEVEL:
7623 if (!value1 || value1 > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
7625 sLog.outErrorDb("Level condition has invalid level %u, skipped", value1);
7626 return false;
7629 if (value2 > 2)
7631 sLog.outErrorDb("Level condition has invalid argument %u (must be 0..2), skipped", value2);
7632 return false;
7635 break;
7637 case CONDITION_NONE:
7638 break;
7640 return true;
7643 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7645 switch(pSkill->categoryId)
7647 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7648 case SKILL_CATEGORY_WEAPON:
7649 if(pSkill->id!=SKILL_FIST_WEAPONS)
7650 return SKILL_RANGE_LEVEL;
7651 else
7652 return SKILL_RANGE_MONO;
7653 case SKILL_CATEGORY_ARMOR:
7654 case SKILL_CATEGORY_CLASS:
7655 if(pSkill->id != SKILL_LOCKPICKING)
7656 return SKILL_RANGE_MONO;
7657 else
7658 return SKILL_RANGE_LEVEL;
7659 case SKILL_CATEGORY_SECONDARY:
7660 case SKILL_CATEGORY_PROFESSION:
7661 // not set skills for professions and racial abilities
7662 if(IsProfessionSkill(pSkill->id))
7663 return SKILL_RANGE_RANK;
7664 else if(racial)
7665 return SKILL_RANGE_NONE;
7666 else
7667 return SKILL_RANGE_MONO;
7668 default:
7669 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7670 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7671 return SKILL_RANGE_NONE;
7675 void ObjectMgr::LoadGameTele()
7677 m_GameTeleMap.clear(); // for reload case
7679 uint32 count = 0;
7680 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7682 if( !result )
7684 barGoLink bar( 1 );
7686 bar.step();
7688 sLog.outString();
7689 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7690 return;
7693 barGoLink bar( (int)result->GetRowCount() );
7697 bar.step();
7699 Field *fields = result->Fetch();
7701 uint32 id = fields[0].GetUInt32();
7703 GameTele gt;
7705 gt.position_x = fields[1].GetFloat();
7706 gt.position_y = fields[2].GetFloat();
7707 gt.position_z = fields[3].GetFloat();
7708 gt.orientation = fields[4].GetFloat();
7709 gt.mapId = fields[5].GetUInt32();
7710 gt.name = fields[6].GetCppString();
7712 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7714 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7715 continue;
7718 if(!Utf8toWStr(gt.name,gt.wnameLow))
7720 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7721 continue;
7724 wstrToLower( gt.wnameLow );
7726 m_GameTeleMap[id] = gt;
7728 ++count;
7730 while (result->NextRow());
7731 delete result;
7733 sLog.outString();
7734 sLog.outString( ">> Loaded %u GameTeleports", count );
7737 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7739 // explicit name case
7740 std::wstring wname;
7741 if(!Utf8toWStr(name,wname))
7742 return false;
7744 // converting string that we try to find to lower case
7745 wstrToLower( wname );
7747 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7748 const GameTele* alt = NULL;
7749 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7750 if(itr->second.wnameLow == wname)
7751 return &itr->second;
7752 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7753 alt = &itr->second;
7755 return alt;
7758 bool ObjectMgr::AddGameTele(GameTele& tele)
7760 // find max id
7761 uint32 new_id = 0;
7762 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7763 if(itr->first > new_id)
7764 new_id = itr->first;
7766 // use next
7767 ++new_id;
7769 if(!Utf8toWStr(tele.name,tele.wnameLow))
7770 return false;
7772 wstrToLower( tele.wnameLow );
7774 m_GameTeleMap[new_id] = tele;
7776 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')",
7777 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7780 bool ObjectMgr::DeleteGameTele(const std::string& name)
7782 // explicit name case
7783 std::wstring wname;
7784 if(!Utf8toWStr(name,wname))
7785 return false;
7787 // converting string that we try to find to lower case
7788 wstrToLower( wname );
7790 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7792 if(itr->second.wnameLow == wname)
7794 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7795 m_GameTeleMap.erase(itr);
7796 return true;
7800 return false;
7803 void ObjectMgr::LoadMailLevelRewards()
7805 m_mailLevelRewardMap.clear(); // for reload case
7807 uint32 count = 0;
7808 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7810 if( !result )
7812 barGoLink bar( 1 );
7814 bar.step();
7816 sLog.outString();
7817 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7818 return;
7821 barGoLink bar((int) result->GetRowCount() );
7825 bar.step();
7827 Field *fields = result->Fetch();
7829 uint8 level = fields[0].GetUInt8();
7830 uint32 raceMask = fields[1].GetUInt32();
7831 uint32 mailTemplateId = fields[2].GetUInt32();
7832 uint32 senderEntry = fields[3].GetUInt32();
7834 if(level > MAX_LEVEL)
7836 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7837 continue;
7840 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7842 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7843 continue;
7846 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7848 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7849 continue;
7852 if(!GetCreatureTemplateStore(senderEntry))
7854 sLog.outErrorDb("Table `mail_level_reward` have not existed sender creature entry (%u) for level %u that invalid not include any player races, ignoring.",senderEntry,level);
7855 continue;
7858 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7860 ++count;
7862 while (result->NextRow());
7863 delete result;
7865 sLog.outString();
7866 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7869 void ObjectMgr::LoadTrainerSpell()
7871 // For reload case
7872 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7873 itr->second.Clear();
7874 m_mCacheTrainerSpellMap.clear();
7876 std::set<uint32> skip_trainers;
7878 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7880 if( !result )
7882 barGoLink bar( 1 );
7884 bar.step();
7886 sLog.outString();
7887 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7888 return;
7891 barGoLink bar( (int)result->GetRowCount() );
7893 std::set<uint32> talentIds;
7895 uint32 count = 0;
7898 bar.step();
7900 Field* fields = result->Fetch();
7902 uint32 entry = fields[0].GetUInt32();
7903 uint32 spell = fields[1].GetUInt32();
7905 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7907 if(!cInfo)
7909 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7910 continue;
7913 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7915 if (skip_trainers.find(entry) == skip_trainers.end())
7917 sLog.outErrorDb("Table `npc_trainer` have data for creature (Entry: %u) without trainer flag, ignore", entry);
7918 skip_trainers.insert(entry);
7920 continue;
7923 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7924 if(!spellinfo)
7926 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7927 continue;
7930 if(!SpellMgr::IsSpellValid(spellinfo))
7932 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7933 continue;
7936 if(GetTalentSpellCost(spell))
7938 if (talentIds.find(spell) == talentIds.end())
7940 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7941 talentIds.insert(spell);
7943 continue;
7946 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7948 TrainerSpell& trainerSpell = data.spellList[spell];
7949 trainerSpell.spell = spell;
7950 trainerSpell.spellCost = fields[2].GetUInt32();
7951 trainerSpell.reqSkill = fields[3].GetUInt32();
7952 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7953 trainerSpell.reqLevel = fields[5].GetUInt32();
7955 if(!trainerSpell.reqLevel)
7956 trainerSpell.reqLevel = spellinfo->spellLevel;
7958 // calculate learned spell for profession case when stored cast-spell
7959 trainerSpell.learnedSpell = spell;
7960 for(int i = 0; i <3; ++i)
7962 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7963 continue;
7964 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7966 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7967 break;
7971 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7972 data.trainerType = 2;
7974 ++count;
7976 } while (result->NextRow());
7977 delete result;
7979 sLog.outString();
7980 sLog.outString( ">> Loaded %d Trainers", count );
7983 void ObjectMgr::LoadVendors()
7985 // For reload case
7986 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7987 itr->second.Clear();
7988 m_mCacheVendorItemMap.clear();
7990 std::set<uint32> skip_vendors;
7992 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7993 if( !result )
7995 barGoLink bar( 1 );
7997 bar.step();
7999 sLog.outString();
8000 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
8001 return;
8004 barGoLink bar( (int)result->GetRowCount() );
8006 uint32 count = 0;
8009 bar.step();
8010 Field* fields = result->Fetch();
8012 uint32 entry = fields[0].GetUInt32();
8013 uint32 item_id = fields[1].GetUInt32();
8014 uint32 maxcount = fields[2].GetUInt32();
8015 uint32 incrtime = fields[3].GetUInt32();
8016 uint32 ExtendedCost = fields[4].GetUInt32();
8018 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
8019 continue;
8021 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8023 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
8024 ++count;
8026 } while (result->NextRow());
8027 delete result;
8029 sLog.outString();
8030 sLog.outString( ">> Loaded %d Vendors ", count );
8033 void ObjectMgr::LoadNpcTextId()
8036 m_mCacheNpcTextIdMap.clear();
8038 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
8039 if( !result )
8041 barGoLink bar( 1 );
8043 bar.step();
8045 sLog.outString();
8046 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
8047 return;
8050 barGoLink bar((int) result->GetRowCount() );
8052 uint32 count = 0;
8053 uint32 guid,textid;
8056 bar.step();
8058 Field* fields = result->Fetch();
8060 guid = fields[0].GetUInt32();
8061 textid = fields[1].GetUInt32();
8063 if (!GetCreatureData(guid))
8065 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
8066 continue;
8068 if (!GetGossipText(textid))
8070 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
8071 continue;
8074 m_mCacheNpcTextIdMap[guid] = textid ;
8075 ++count;
8077 } while (result->NextRow());
8078 delete result;
8080 sLog.outString();
8081 sLog.outString( ">> Loaded %d NpcTextId ", count );
8084 void ObjectMgr::LoadGossipMenu()
8086 m_mGossipMenusMap.clear();
8088 QueryResult* result = WorldDatabase.Query("SELECT entry, text_id, "
8089 "cond_1, cond_1_val_1, cond_1_val_2, cond_2, cond_2_val_1, cond_2_val_2 FROM gossip_menu");
8091 if (!result)
8093 barGoLink bar(1);
8095 bar.step();
8097 sLog.outString();
8098 sLog.outErrorDb(">> Loaded gossip_menu, table is empty!");
8099 return;
8102 barGoLink bar( (int)result->GetRowCount() );
8104 uint32 count = 0;
8108 bar.step();
8110 Field* fields = result->Fetch();
8112 GossipMenus gMenu;
8114 gMenu.entry = fields[0].GetUInt32();
8115 gMenu.text_id = fields[1].GetUInt32();
8117 ConditionType cond_1 = (ConditionType)fields[2].GetUInt32();
8118 uint32 cond_1_val_1 = fields[3].GetUInt32();
8119 uint32 cond_1_val_2 = fields[4].GetUInt32();
8120 ConditionType cond_2 = (ConditionType)fields[5].GetUInt32();
8121 uint32 cond_2_val_1 = fields[6].GetUInt32();
8122 uint32 cond_2_val_2 = fields[7].GetUInt32();
8124 if (!GetGossipText(gMenu.text_id))
8126 sLog.outErrorDb("Table gossip_menu entry %u are using non-existing text_id %u", gMenu.entry, gMenu.text_id);
8127 continue;
8130 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8132 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 1 for id %u", gMenu.entry, gMenu.text_id);
8133 continue;
8136 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8138 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 2 for id %u", gMenu.entry, gMenu.text_id);
8139 continue;
8142 gMenu.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8143 gMenu.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8145 m_mGossipMenusMap.insert(GossipMenusMap::value_type(gMenu.entry, gMenu));
8147 ++count;
8149 while(result->NextRow());
8151 delete result;
8153 sLog.outString();
8154 sLog.outString( ">> Loaded %u gossip_menu entries", count);
8157 void ObjectMgr::LoadGossipMenuItems()
8159 m_mGossipMenuItemsMap.clear();
8161 QueryResult *result = WorldDatabase.Query(
8162 "SELECT menu_id, id, option_icon, option_text, option_id, npc_option_npcflag, "
8163 "action_menu_id, action_poi_id, action_script_id, box_coded, box_money, box_text, "
8164 "cond_1, cond_1_val_1, cond_1_val_2, "
8165 "cond_2, cond_2_val_1, cond_2_val_2, "
8166 "cond_3, cond_3_val_1, cond_3_val_2 "
8167 "FROM gossip_menu_option");
8169 if (!result)
8171 barGoLink bar(1);
8173 bar.step();
8175 sLog.outString();
8176 sLog.outErrorDb(">> Loaded gossip_menu_option, table is empty!");
8177 return;
8180 barGoLink bar((int)result->GetRowCount());
8182 uint32 count = 0;
8184 std::set<uint32> gossipScriptSet;
8186 for(ScriptMapMap::const_iterator itr = sGossipScripts.begin(); itr != sGossipScripts.end(); ++itr)
8187 gossipScriptSet.insert(itr->first);
8191 bar.step();
8193 Field* fields = result->Fetch();
8195 GossipMenuItems gMenuItem;
8197 gMenuItem.menu_id = fields[0].GetUInt32();
8198 gMenuItem.id = fields[1].GetUInt32();
8199 gMenuItem.option_icon = fields[2].GetUInt8();
8200 gMenuItem.option_text = fields[3].GetCppString();
8201 gMenuItem.option_id = fields[4].GetUInt32();
8202 gMenuItem.npc_option_npcflag = fields[5].GetUInt32();
8203 gMenuItem.action_menu_id = fields[6].GetUInt32();
8204 gMenuItem.action_poi_id = fields[7].GetUInt32();
8205 gMenuItem.action_script_id = fields[8].GetUInt32();
8206 gMenuItem.box_coded = fields[9].GetUInt8() != 0;
8207 gMenuItem.box_money = fields[10].GetUInt32();
8208 gMenuItem.box_text = fields[11].GetCppString();
8210 ConditionType cond_1 = (ConditionType)fields[12].GetUInt32();
8211 uint32 cond_1_val_1 = fields[13].GetUInt32();
8212 uint32 cond_1_val_2 = fields[14].GetUInt32();
8213 ConditionType cond_2 = (ConditionType)fields[15].GetUInt32();
8214 uint32 cond_2_val_1 = fields[16].GetUInt32();
8215 uint32 cond_2_val_2 = fields[17].GetUInt32();
8216 ConditionType cond_3 = (ConditionType)fields[18].GetUInt32();
8217 uint32 cond_3_val_1 = fields[19].GetUInt32();
8218 uint32 cond_3_val_2 = fields[20].GetUInt32();
8220 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8222 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 1 for id %u", gMenuItem.menu_id, gMenuItem.id);
8223 continue;
8225 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8227 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 2 for id %u", gMenuItem.menu_id, gMenuItem.id);
8228 continue;
8230 if (!PlayerCondition::IsValid(cond_3, cond_3_val_1, cond_3_val_2))
8232 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 3 for id %u", gMenuItem.menu_id, gMenuItem.id);
8233 continue;
8236 if (gMenuItem.option_icon >= GOSSIP_ICON_MAX)
8238 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u has unknown icon id %u. Replacing with GOSSIP_ICON_CHAT", gMenuItem.menu_id, gMenuItem.id, gMenuItem.option_icon);
8239 gMenuItem.option_icon = GOSSIP_ICON_CHAT;
8242 if (gMenuItem.option_id == GOSSIP_OPTION_NONE)
8243 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u use option id GOSSIP_OPTION_NONE. Option will never be used", gMenuItem.menu_id, gMenuItem.id);
8245 if (gMenuItem.option_id >= GOSSIP_OPTION_MAX)
8246 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u has unknown option id %u. Option will not be used", gMenuItem.menu_id, gMenuItem.id, gMenuItem.option_id);
8248 if (gMenuItem.action_poi_id && !GetPointOfInterest(gMenuItem.action_poi_id))
8250 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u use non-existing action_poi_id %u, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_poi_id);
8251 gMenuItem.action_poi_id = 0;
8254 if (gMenuItem.action_script_id)
8256 if (gMenuItem.option_id != GOSSIP_OPTION_GOSSIP)
8258 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u have action_script_id %u but option_id is not GOSSIP_OPTION_GOSSIP, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_script_id);
8259 continue;
8262 if (sGossipScripts.find(gMenuItem.action_script_id) == sGossipScripts.end())
8264 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u have action_script_id %u that does not exist in `gossip_scripts`, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_script_id);
8265 continue;
8268 gossipScriptSet.erase(gMenuItem.action_script_id);
8271 gMenuItem.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8272 gMenuItem.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8273 gMenuItem.cond_3 = GetConditionId(cond_3, cond_3_val_1, cond_3_val_2);
8275 m_mGossipMenuItemsMap.insert(GossipMenuItemsMap::value_type(gMenuItem.menu_id, gMenuItem));
8277 ++count;
8280 while(result->NextRow());
8282 delete result;
8284 if (!gossipScriptSet.empty())
8286 for(std::set<uint32>::const_iterator itr = gossipScriptSet.begin(); itr != gossipScriptSet.end(); ++itr)
8287 sLog.outErrorDb("Table `gossip_scripts` contain unused script, id %u.", *itr);
8290 sLog.outString();
8291 sLog.outString(">> Loaded %u gossip_menu_option entries", count);
8294 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
8296 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8297 vList.AddItem(item,maxcount,incrtime,extendedcost);
8299 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
8302 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
8304 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
8305 if(iter == m_mCacheVendorItemMap.end())
8306 return false;
8308 if(!iter->second.FindItem(item))
8309 return false;
8311 iter->second.RemoveItem(item);
8312 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
8313 return true;
8316 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
8318 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
8319 if(!cInfo)
8321 if(pl)
8322 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8323 else
8324 sLog.outErrorDb("Table `npc_vendor` has data for nonexistent creature (Entry: %u), ignoring", vendor_entry);
8325 return false;
8328 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
8330 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
8332 if(pl)
8333 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8334 else
8335 sLog.outErrorDb("Table `npc_vendor` has data for creature (Entry: %u) without vendor flag, ignoring", vendor_entry);
8337 if(skip_vendors)
8338 skip_vendors->insert(vendor_entry);
8340 return false;
8343 if(!GetItemPrototype(item_id))
8345 if(pl)
8346 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
8347 else
8348 sLog.outErrorDb("Table `npc_vendor` for vendor (Entry: %u) contain nonexistent item (%u), ignoring",vendor_entry,item_id);
8349 return false;
8352 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
8354 if(pl)
8355 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
8356 else
8357 sLog.outErrorDb("Table `npc_vendor` contain item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignoring",item_id,ExtendedCost,vendor_entry);
8358 return false;
8361 if(maxcount > 0 && incrtime == 0)
8363 if(pl)
8364 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
8365 else
8366 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignoring", maxcount, item_id, vendor_entry);
8367 return false;
8369 else if(maxcount==0 && incrtime > 0)
8371 if(pl)
8372 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
8373 else
8374 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignoring", item_id, vendor_entry);
8375 return false;
8378 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
8379 if(!vItems)
8380 return true; // later checks for non-empty lists
8382 if(vItems->FindItem(item_id))
8384 if(pl)
8385 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
8386 else
8387 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignoring", item_id, vendor_entry);
8388 return false;
8391 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
8393 if(pl)
8394 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
8395 else
8396 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignoring", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
8397 return false;
8400 return true;
8403 void ObjectMgr::LoadScriptNames()
8405 m_scriptNames.push_back("");
8406 QueryResult *result = WorldDatabase.Query(
8407 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
8408 "UNION "
8409 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
8410 "UNION "
8411 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
8412 "UNION "
8413 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
8414 "UNION "
8415 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
8417 if( !result )
8419 barGoLink bar( 1 );
8420 bar.step();
8421 sLog.outString();
8422 sLog.outErrorDb(">> Loaded empty set of Script Names!");
8423 return;
8426 barGoLink bar( (int)result->GetRowCount() );
8427 uint32 count = 0;
8431 bar.step();
8432 m_scriptNames.push_back((*result)[0].GetString());
8433 ++count;
8434 } while (result->NextRow());
8435 delete result;
8437 std::sort(m_scriptNames.begin(), m_scriptNames.end());
8438 sLog.outString();
8439 sLog.outString( ">> Loaded %d Script Names", count );
8442 uint32 ObjectMgr::GetScriptId(const char *name)
8444 // use binary search to find the script name in the sorted vector
8445 // assume "" is the first element
8446 if(!name) return 0;
8447 ScriptNameMap::const_iterator itr =
8448 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8449 if(itr == m_scriptNames.end() || *itr != name) return 0;
8450 return uint32(itr - m_scriptNames.begin());
8453 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
8455 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8457 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8459 switch(itrM->second.command)
8461 case SCRIPT_COMMAND_TALK:
8463 if(!GetMangosStringLocale (itrM->second.dataint))
8464 sLog.outErrorDb( "Table `db_script_string` is missing string id %u, used in database script id %u.", itrM->second.dataint, itrMM->first);
8466 if (ids.find(itrM->second.dataint) != ids.end())
8467 ids.erase(itrM->second.dataint);
8474 void ObjectMgr::LoadDbScriptStrings()
8476 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8478 std::set<int32> ids;
8480 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8481 if(GetMangosStringLocale(i))
8482 ids.insert(i);
8484 CheckScripts(sQuestEndScripts,ids);
8485 CheckScripts(sQuestStartScripts,ids);
8486 CheckScripts(sSpellScripts,ids);
8487 CheckScripts(sGameObjectScripts,ids);
8488 CheckScripts(sEventScripts,ids);
8489 CheckScripts(sGossipScripts,ids);
8491 sWaypointMgr.CheckTextsExistance(ids);
8493 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8494 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8497 void ObjectMgr::AddGuild( Guild* guild )
8499 mGuildMap[guild->GetId()] = guild ;
8502 void ObjectMgr::RemoveGuild( uint32 Id )
8504 mGuildMap.erase(Id);
8507 void ObjectMgr::AddGroup( Group* group )
8509 mGroupMap[group->GetId()] = group ;
8512 void ObjectMgr::RemoveGroup( Group* group )
8514 mGroupMap.erase(group->GetId());
8517 void ObjectMgr::AddArenaTeam( ArenaTeam* arenaTeam )
8519 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
8522 void ObjectMgr::RemoveArenaTeam( uint32 Id )
8524 mArenaTeamMap.erase(Id);
8527 // Functions for scripting access
8528 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8530 return sObjectMgr.GetAreaTriggerScriptId(trigger_id);
8533 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8535 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8536 // start/end reversed for negative values
8537 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8539 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8540 return false;
8543 return sObjectMgr.LoadMangosStrings(db,table,start_value,end_value);
8546 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8548 return sObjectMgr.GetScriptId(name);
8551 ObjectMgr::ScriptNameMap & GetScriptNames()
8553 return sObjectMgr.GetScriptNames();
8556 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8558 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8561 Quest const* GetQuestTemplateStore(uint32 entry)
8563 return sObjectMgr.GetQuestTemplate(entry);