[9581] Fixed apply damage reduction to melee/ranged damage.
[getmangos.git] / src / game / ObjectMgr.cpp
blobb6997b746ebbe9a00910d102d26f08f06443a38f
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 "ObjectGuid.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 #include <limits>
50 INSTANTIATE_SINGLETON_1(ObjectMgr);
52 ScriptMapMap sQuestEndScripts;
53 ScriptMapMap sQuestStartScripts;
54 ScriptMapMap sSpellScripts;
55 ScriptMapMap sGameObjectScripts;
56 ScriptMapMap sEventScripts;
57 ScriptMapMap sGossipScripts;
59 bool normalizePlayerName(std::string& name)
61 if(name.empty())
62 return false;
64 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
65 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
67 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
68 return false;
70 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
71 for(size_t i = 1; i < wstr_len; ++i)
72 wstr_buf[i] = wcharToLower(wstr_buf[i]);
74 if(!WStrToUtf8(wstr_buf,wstr_len,name))
75 return false;
77 return true;
80 LanguageDesc lang_description[LANGUAGES_COUNT] =
82 { LANG_ADDON, 0, 0 },
83 { LANG_UNIVERSAL, 0, 0 },
84 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
85 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
86 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
87 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
88 { LANG_COMMON, 668, SKILL_LANG_COMMON },
89 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
90 { LANG_TITAN, 816, SKILL_LANG_TITAN },
91 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
92 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
93 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
94 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
95 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
96 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
97 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
98 { LANG_ZOMBIE, 0, 0 },
99 { LANG_GNOMISH_BINARY, 0, 0 },
100 { LANG_GOBLIN_BINARY, 0, 0 }
103 LanguageDesc const* GetLanguageDescByID(uint32 lang)
105 for(int i = 0; i < LANGUAGES_COUNT; ++i)
107 if(uint32(lang_description[i].lang_id) == lang)
108 return &lang_description[i];
111 return NULL;
114 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
116 if(questStart)
118 // not in expected required quest state
119 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
120 return false;
123 if(questEnd)
125 // not in expected forbidden quest state
126 if(!player || player->GetQuestRewardStatus(questEnd))
127 return false;
130 return true;
133 template<typename T>
134 T IdGenerator<T>::Generate()
136 if (m_nextGuid >= std::numeric_limits<T>::max()-1)
138 sLog.outError("%s guid overflow!! Can't continue, shutting down server. ",m_name);
139 World::StopNow(ERROR_EXIT_CODE);
141 return m_nextGuid++;
144 template uint32 IdGenerator<uint32>::Generate();
145 template uint64 IdGenerator<uint64>::Generate();
147 ObjectMgr::ObjectMgr() :
148 m_ArenaTeamIds("Arena team ids"),
149 m_AuctionIds("Auction ids"),
150 m_EquipmentSetIds("Equipment set ids"),
151 m_GuildIds("Guild ids"),
152 m_ItemTextIds("Item text ids"),
153 m_MailIds("Mail ids"),
154 m_PetNumbers("Pet numbers"),
155 m_GroupIds("Group ids")
157 // Only zero condition left, others will be added while loading DB tables
158 mConditions.resize(1);
161 ObjectMgr::~ObjectMgr()
163 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
164 delete i->second;
166 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
167 delete[] i->second;
169 // free only if loaded
170 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
171 delete[] playerClassInfo[class_].levelInfo;
173 for (int race = 0; race < MAX_RACES; ++race)
174 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
175 delete[] playerInfo[race][class_].levelInfo;
177 // free group and guild objects
178 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end(); ++itr)
179 delete itr->second;
181 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
182 delete itr->second;
184 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
185 delete itr->second;
187 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
188 itr->second.Clear();
190 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
191 itr->second.Clear();
194 Group* ObjectMgr::GetGroupById(uint32 id) const
196 GroupMap::const_iterator itr = mGroupMap.find(id);
197 if (itr != mGroupMap.end())
198 return itr->second;
200 return NULL;
203 Guild* ObjectMgr::GetGuildById(uint32 GuildId) const
205 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
206 if (itr != mGuildMap.end())
207 return itr->second;
209 return NULL;
212 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
214 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
215 if (itr->second->GetName() == guildname)
216 return itr->second;
218 return NULL;
221 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
223 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
224 if (itr != mGuildMap.end())
225 return itr->second->GetName();
227 return "";
230 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
232 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
233 if (itr->second->GetLeader() == guid)
234 return itr->second;
236 return NULL;
239 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
241 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
242 if (itr != mArenaTeamMap.end())
243 return itr->second;
245 return NULL;
248 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
250 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
251 if (itr->second->GetName() == arenateamname)
252 return itr->second;
254 return NULL;
257 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
259 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
260 if (itr->second->GetCaptain() == guid)
261 return itr->second;
263 return NULL;
266 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
268 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
271 void ObjectMgr::LoadCreatureLocales()
273 mCreatureLocaleMap.clear(); // need for reload case
275 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");
277 if(!result)
279 barGoLink bar(1);
281 bar.step();
283 sLog.outString();
284 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
285 return;
288 barGoLink bar((int)result->GetRowCount());
292 Field *fields = result->Fetch();
293 bar.step();
295 uint32 entry = fields[0].GetUInt32();
297 CreatureLocale& data = mCreatureLocaleMap[entry];
299 for(int i = 1; i < MAX_LOCALE; ++i)
301 std::string str = fields[1+2*(i-1)].GetCppString();
302 if(!str.empty())
304 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
305 if(idx >= 0)
307 if((int32)data.Name.size() <= idx)
308 data.Name.resize(idx+1);
310 data.Name[idx] = str;
313 str = fields[1+2*(i-1)+1].GetCppString();
314 if(!str.empty())
316 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
317 if(idx >= 0)
319 if((int32)data.SubName.size() <= idx)
320 data.SubName.resize(idx+1);
322 data.SubName[idx] = str;
326 } while (result->NextRow());
328 delete result;
330 sLog.outString();
331 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
334 void ObjectMgr::LoadGossipMenuItemsLocales()
336 mGossipMenuItemsLocaleMap.clear(); // need for reload case
338 QueryResult *result = WorldDatabase.Query("SELECT menu_id,id,"
339 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
340 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
341 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
342 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
343 "FROM locales_gossip_menu_option");
345 if(!result)
347 barGoLink bar(1);
349 bar.step();
351 sLog.outString();
352 sLog.outString(">> Loaded 0 gossip_menu_option locale strings. DB table `locales_gossip_menu_option` is empty.");
353 return;
356 barGoLink bar((int)result->GetRowCount());
360 Field *fields = result->Fetch();
361 bar.step();
363 uint16 menuId = fields[0].GetUInt16();
364 uint16 id = fields[1].GetUInt16();
366 GossipMenuItemsLocale& data = mGossipMenuItemsLocaleMap[MAKE_PAIR32(menuId,id)];
368 for(int i = 1; i < MAX_LOCALE; ++i)
370 std::string str = fields[2+2*(i-1)].GetCppString();
371 if(!str.empty())
373 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
374 if(idx >= 0)
376 if((int32)data.OptionText.size() <= idx)
377 data.OptionText.resize(idx+1);
379 data.OptionText[idx] = str;
382 str = fields[2+2*(i-1)+1].GetCppString();
383 if(!str.empty())
385 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
386 if(idx >= 0)
388 if((int32)data.BoxText.size() <= idx)
389 data.BoxText.resize(idx+1);
391 data.BoxText[idx] = str;
395 } while (result->NextRow());
397 delete result;
399 sLog.outString();
400 sLog.outString( ">> Loaded %lu gossip_menu_option locale strings", (unsigned long)mGossipMenuItemsLocaleMap.size() );
403 void ObjectMgr::LoadPointOfInterestLocales()
405 mPointOfInterestLocaleMap.clear(); // need for reload case
407 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");
409 if(!result)
411 barGoLink bar(1);
413 bar.step();
415 sLog.outString();
416 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
417 return;
420 barGoLink bar((int)result->GetRowCount());
424 Field *fields = result->Fetch();
425 bar.step();
427 uint32 entry = fields[0].GetUInt32();
429 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
431 for(int i = 1; i < MAX_LOCALE; ++i)
433 std::string str = fields[i].GetCppString();
434 if(str.empty())
435 continue;
437 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
438 if(idx >= 0)
440 if((int32)data.IconName.size() <= idx)
441 data.IconName.resize(idx+1);
443 data.IconName[idx] = str;
446 } while (result->NextRow());
448 delete result;
450 sLog.outString();
451 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
454 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
456 template<class D>
457 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
459 dst = D(sObjectMgr.GetScriptId(src));
463 void ObjectMgr::LoadCreatureTemplates()
465 SQLCreatureLoader loader;
466 loader.Load(sCreatureStorage);
468 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
469 sLog.outString();
471 std::set<uint32> difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures
472 std::set<uint32> hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values
474 // check data correctness
475 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
477 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
478 if (!cInfo)
479 continue;
481 bool ok = true; // bool to allow continue outside this loop
482 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
484 if (!cInfo->DifficultyEntry[diff])
485 continue;
486 ok = false; // will be set to true at the end of this loop again
488 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]);
489 if (!difficultyInfo)
491 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u not exist.",
492 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]);
493 continue;
496 if (difficultyEntries[diff].find(i) != difficultyEntries[diff].end())
498 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty %u but have value in `difficulty_entry_%u`.", i, diff + 1, diff + 1);
499 continue;
502 bool ok2 = true;
503 for (uint32 diff2 = 0; diff2 < MAX_DIFFICULTY - 1 && ok2; ++diff2)
505 ok2 = false;
506 if (difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != difficultyEntries[diff2].end())
508 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty %u for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1);
509 continue;
512 if (hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != hasDifficultyEntries[diff2].end())
514 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u have difficulty %u entry also.",
515 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1);
516 continue;
518 ok2 = true;
520 if (!ok2)
521 continue;
523 if (cInfo->unit_class != difficultyInfo->unit_class)
525 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).",
526 i, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class);
527 continue;
530 if (cInfo->npcflag != difficultyInfo->npcflag)
532 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
533 continue;
536 if (cInfo->trainer_class != difficultyInfo->trainer_class)
538 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
539 continue;
542 if (cInfo->trainer_race != difficultyInfo->trainer_race)
544 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
545 continue;
548 if (cInfo->trainer_type != difficultyInfo->trainer_type)
550 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
551 continue;
554 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
556 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
557 continue;
560 if (difficultyInfo->AIName && *difficultyInfo->AIName)
562 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",
563 diff, cInfo->DifficultyEntry[diff], i);
564 continue;
567 if (difficultyInfo->ScriptID)
569 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",
570 diff, cInfo->DifficultyEntry[diff], i);
571 continue;
574 hasDifficultyEntries[diff].insert(i);
575 difficultyEntries[diff].insert(cInfo->DifficultyEntry[diff]);
576 ok = true;
578 if (!ok)
579 continue;
581 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
582 if (!factionTemplate)
583 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
585 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
586 if (!factionTemplate)
587 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
589 // used later for scale
590 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
592 if (cInfo->DisplayID_A[0])
594 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
595 if(!displayEntry)
597 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
598 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
600 else if(!displayScaleEntry)
601 displayScaleEntry = displayEntry;
603 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
604 if (!minfo)
605 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]);
608 if (cInfo->DisplayID_A[1])
610 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
611 if(!displayEntry)
613 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
614 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
616 else if(!displayScaleEntry)
617 displayScaleEntry = displayEntry;
619 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
620 if (!minfo)
621 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]);
624 if (cInfo->DisplayID_H[0])
626 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
627 if(!displayEntry)
629 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
630 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
632 else if(!displayScaleEntry)
633 displayScaleEntry = displayEntry;
635 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
636 if (!minfo)
637 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]);
640 if (cInfo->DisplayID_H[1])
642 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
643 if(!displayEntry)
645 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
646 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
648 else if(!displayScaleEntry)
649 displayScaleEntry = displayEntry;
651 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
652 if (!minfo)
653 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]);
656 if (!displayScaleEntry)
657 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid in modelid_A/modelid_A2/modelid_H/modelid_A2", cInfo->Entry);
659 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
661 if(cInfo->KillCredit[k])
663 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
665 sLog.outErrorDb("Creature (Entry: %u) has nonexistent creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
666 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
671 // use below code for 0-checks for unit_class
672 if (/*!cInfo->unit_class ||*/cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
673 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
675 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
677 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
678 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
681 if(cInfo->baseattacktime == 0)
682 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
684 if(cInfo->rangeattacktime == 0)
685 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
687 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
689 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);
690 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
693 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
694 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
696 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
698 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
699 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
702 // must exist or used hidden but used in data horse case
703 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
705 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
706 const_cast<CreatureInfo*>(cInfo)->family = 0;
709 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
711 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
712 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
715 if(cInfo->PetSpellDataId)
717 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
718 if(!spellDataId)
719 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
722 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
724 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
726 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
727 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
731 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
733 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
734 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
737 if(cInfo->equipmentId > 0) // 0 no equipment
739 if(!GetEquipmentInfo(cInfo->equipmentId))
741 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);
742 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
746 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
747 if(cInfo->scale <= 0.0f)
749 if(displayScaleEntry)
750 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
751 else
752 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
757 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
759 // Now add the auras, format "spellid effectindex spellid effectindex..."
760 char *p,*s;
761 std::vector<int> val;
762 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
763 if(p)
765 while (p[0]!=0)
767 ++p;
768 if (p[0]==' ')
770 val.push_back(atoi(s));
771 s=++p;
774 if (p!=s)
775 val.push_back(atoi(s));
777 // free char* loaded memory
778 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
780 // wrong list
781 if (val.size()%2)
783 addon->auras = NULL;
784 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
785 return;
789 // empty list
790 if(val.empty())
792 addon->auras = NULL;
793 return;
796 // replace by new structures array
797 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
799 uint32 i=0;
800 for(uint32 j = 0; j < val.size()/2; ++j)
802 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
803 cAura.spell_id = uint32(val[2*j+0]);
804 cAura.effect_idx = SpellEffectIndex(val[2*j+1]);
805 if (cAura.effect_idx >= MAX_EFFECT_INDEX)
807 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);
808 continue;
810 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
811 if (!AdditionalSpellInfo)
813 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
814 continue;
817 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
819 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);
820 continue;
823 ++i;
826 // fill terminator element (after last added)
827 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
828 endAura.spell_id = 0;
829 endAura.effect_idx = EFFECT_INDEX_0;
832 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
834 creatureaddons.Load();
836 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
837 sLog.outString();
839 // check data correctness and convert 'auras'
840 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
842 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
843 if(!addon)
844 continue;
846 if (addon->mount)
848 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
850 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
851 const_cast<CreatureDataAddon*>(addon)->mount = 0;
855 if (!sEmotesStore.LookupEntry(addon->emote))
856 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
858 if (addon->splineFlags & (SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3))
860 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));
861 const_cast<CreatureDataAddon*>(addon)->splineFlags &= ~(SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3);
864 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
868 void ObjectMgr::LoadCreatureAddons()
870 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
872 // check entry ids
873 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
874 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
875 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
876 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
878 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
880 // check entry ids
881 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
882 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
883 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
884 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
887 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
889 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
892 void ObjectMgr::LoadEquipmentTemplates()
894 sEquipmentStorage.Load();
896 for(uint32 i=0; i < sEquipmentStorage.MaxEntry; ++i)
898 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
900 if (!eqInfo)
901 continue;
903 for(uint8 j = 0; j < 3; ++j)
905 if (!eqInfo->equipentry[j])
906 continue;
908 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
910 if (!dbcitem)
912 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
913 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
914 continue;
917 if (dbcitem->InventoryType != INVTYPE_WEAPON &&
918 dbcitem->InventoryType != INVTYPE_SHIELD &&
919 dbcitem->InventoryType != INVTYPE_RANGED &&
920 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
921 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
922 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
923 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
924 dbcitem->InventoryType != INVTYPE_THROWN &&
925 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
927 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);
928 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
932 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
933 sLog.outString();
936 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
938 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
941 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
943 // Load creature model (display id)
944 if (data && data->displayid)
945 return data->displayid;
947 // use defaults from the template
948 uint32 display_id;
950 // DisplayID_A is used if no team is given
951 if (team == HORDE)
953 if(cinfo->DisplayID_H[0])
954 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
955 else
956 display_id = cinfo->DisplayID_H[1];
958 if(!display_id)
959 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
961 else
963 if(cinfo->DisplayID_A[0])
964 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
965 else
966 display_id = cinfo->DisplayID_A[1];
968 if(!display_id)
969 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
972 return display_id;
975 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
977 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
978 if(!minfo)
979 return NULL;
981 // If a model for another gender exists, 50% chance to use it
982 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
984 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
985 if(!minfo_tmp)
987 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
988 return minfo; // not fatal, just use the previous one
990 else
991 return minfo_tmp;
993 else
994 return minfo;
997 void ObjectMgr::LoadCreatureModelInfo()
999 sCreatureModelStorage.Load();
1001 // post processing
1002 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
1004 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
1005 if (!minfo)
1006 continue;
1008 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
1009 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
1011 if (minfo->gender > GENDER_NONE)
1013 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1014 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1017 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1019 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1020 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1024 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1025 sLog.outString();
1028 void ObjectMgr::LoadCreatures()
1030 uint32 count = 0;
1031 // 0 1 2 3
1032 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1033 // 4 5 6 7 8 9 10 11
1034 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1035 // 12 13 14 15 16 17 18 19
1036 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1037 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1038 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1040 if(!result)
1042 barGoLink bar(1);
1044 bar.step();
1046 sLog.outString();
1047 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1048 return;
1051 // build single time for check creature data
1052 std::set<uint32> difficultyCreatures[MAX_DIFFICULTY - 1];
1053 for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1054 if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1055 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
1056 if (cInfo->DifficultyEntry[diff])
1057 difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]);
1059 // build single time for check spawnmask
1060 std::map<uint32,uint32> spawnMasks;
1061 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1062 if(sMapStore.LookupEntry(i))
1063 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1064 if (GetMapDifficultyData(i,Difficulty(k)))
1065 spawnMasks[i] |= (1 << k);
1067 barGoLink bar((int)result->GetRowCount());
1071 Field *fields = result->Fetch();
1072 bar.step();
1074 uint32 guid = fields[ 0].GetUInt32();
1075 uint32 entry = fields[ 1].GetUInt32();
1077 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1078 if(!cInfo)
1080 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1081 continue;
1084 CreatureData& data = mCreatureDataMap[guid];
1086 data.id = entry;
1087 data.mapid = fields[ 2].GetUInt32();
1088 data.displayid = fields[ 3].GetUInt32();
1089 data.equipmentId = fields[ 4].GetUInt32();
1090 data.posX = fields[ 5].GetFloat();
1091 data.posY = fields[ 6].GetFloat();
1092 data.posZ = fields[ 7].GetFloat();
1093 data.orientation = fields[ 8].GetFloat();
1094 data.spawntimesecs = fields[ 9].GetUInt32();
1095 data.spawndist = fields[10].GetFloat();
1096 data.currentwaypoint= fields[11].GetUInt32();
1097 data.curhealth = fields[12].GetUInt32();
1098 data.curmana = fields[13].GetUInt32();
1099 data.is_dead = fields[14].GetBool();
1100 data.movementType = fields[15].GetUInt8();
1101 data.spawnMask = fields[16].GetUInt8();
1102 data.phaseMask = fields[17].GetUInt16();
1103 int16 gameEvent = fields[18].GetInt16();
1104 int16 PoolId = fields[19].GetInt16();
1106 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1107 if(!mapEntry)
1109 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1110 continue;
1113 if (data.spawnMask & ~spawnMasks[data.mapid])
1114 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 );
1116 bool ok = true;
1117 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
1119 if (difficultyCreatures[diff].find(data.id) != difficultyCreatures[diff].end())
1121 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.",
1122 guid, diff + 1, data.id );
1123 ok = false;
1126 if (!ok)
1127 continue;
1129 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1131 if(!GetEquipmentInfo(data.equipmentId))
1133 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);
1134 data.equipmentId = -1;
1138 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1140 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 );
1141 data.curhealth = cInfo->minhealth;
1144 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1146 if(!mapEntry || !mapEntry->IsDungeon())
1147 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);
1150 if(data.curmana < cInfo->minmana)
1152 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 );
1153 data.curmana = cInfo->minmana;
1156 if(data.spawndist < 0.0f)
1158 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1159 data.spawndist = 0.0f;
1161 else if(data.movementType == RANDOM_MOTION_TYPE)
1163 if(data.spawndist == 0.0f)
1165 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 );
1166 data.movementType = IDLE_MOTION_TYPE;
1169 else if(data.movementType == IDLE_MOTION_TYPE)
1171 if(data.spawndist != 0.0f)
1173 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1174 data.spawndist = 0.0f;
1178 if(data.phaseMask==0)
1180 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1181 data.phaseMask = 1;
1184 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1185 AddCreatureToGrid(guid, &data);
1187 ++count;
1189 } while (result->NextRow());
1191 delete result;
1193 sLog.outString();
1194 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1197 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1199 uint8 mask = data->spawnMask;
1200 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1202 if(mask & 1)
1204 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1205 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1207 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1208 cell_guids.creatures.insert(guid);
1213 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1215 uint8 mask = data->spawnMask;
1216 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1218 if(mask & 1)
1220 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1221 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1223 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1224 cell_guids.creatures.erase(guid);
1229 void ObjectMgr::LoadGameobjects()
1231 uint32 count = 0;
1233 // 0 1 2 3 4 5 6
1234 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1235 // 7 8 9 10 11 12 13 14 15 16 17
1236 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1237 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1238 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1240 if(!result)
1242 barGoLink bar(1);
1244 bar.step();
1246 sLog.outString();
1247 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1248 return;
1251 // build single time for check spawnmask
1252 std::map<uint32,uint32> spawnMasks;
1253 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1254 if(sMapStore.LookupEntry(i))
1255 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1256 if (GetMapDifficultyData(i,Difficulty(k)))
1257 spawnMasks[i] |= (1 << k);
1259 barGoLink bar((int)result->GetRowCount());
1263 Field *fields = result->Fetch();
1264 bar.step();
1266 uint32 guid = fields[ 0].GetUInt32();
1267 uint32 entry = fields[ 1].GetUInt32();
1269 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1270 if (!gInfo)
1272 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1273 continue;
1276 if(!gInfo->displayId)
1278 switch(gInfo->type)
1280 // can be invisible always and then not req. display id in like case
1281 case GAMEOBJECT_TYPE_TRAP:
1282 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1283 break;
1284 default:
1285 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1286 break;
1289 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1291 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1292 continue;
1295 GameObjectData& data = mGameObjectDataMap[guid];
1297 data.id = entry;
1298 data.mapid = fields[ 2].GetUInt32();
1299 data.posX = fields[ 3].GetFloat();
1300 data.posY = fields[ 4].GetFloat();
1301 data.posZ = fields[ 5].GetFloat();
1302 data.orientation = fields[ 6].GetFloat();
1303 data.rotation0 = fields[ 7].GetFloat();
1304 data.rotation1 = fields[ 8].GetFloat();
1305 data.rotation2 = fields[ 9].GetFloat();
1306 data.rotation3 = fields[10].GetFloat();
1307 data.spawntimesecs = fields[11].GetInt32();
1309 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1310 if(!mapEntry)
1312 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1313 continue;
1316 if (data.spawnMask & ~spawnMasks[data.mapid])
1317 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);
1319 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1321 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1324 data.animprogress = fields[12].GetUInt32();
1326 uint32 go_state = fields[13].GetUInt32();
1327 if (go_state >= MAX_GO_STATE)
1329 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1330 continue;
1332 data.go_state = GOState(go_state);
1334 data.spawnMask = fields[14].GetUInt8();
1335 data.phaseMask = fields[15].GetUInt16();
1336 int16 gameEvent = fields[16].GetInt16();
1337 int16 PoolId = fields[17].GetInt16();
1339 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1341 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1342 continue;
1345 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1347 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1348 continue;
1351 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1353 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1354 continue;
1357 if(data.phaseMask == 0)
1359 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1360 data.phaseMask = 1;
1363 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1364 AddGameobjectToGrid(guid, &data);
1365 ++count;
1367 } while (result->NextRow());
1369 delete result;
1371 sLog.outString();
1372 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1375 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1377 uint8 mask = data->spawnMask;
1378 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1380 if(mask & 1)
1382 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1383 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1385 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1386 cell_guids.gameobjects.insert(guid);
1391 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1393 uint8 mask = data->spawnMask;
1394 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1396 if(mask & 1)
1398 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1399 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1401 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1402 cell_guids.gameobjects.erase(guid);
1407 void ObjectMgr::LoadCreatureRespawnTimes()
1409 // remove outdated data
1410 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1412 uint32 count = 0;
1414 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1416 if(!result)
1418 barGoLink bar(1);
1420 bar.step();
1422 sLog.outString();
1423 sLog.outString(">> Loaded 0 creature respawn time.");
1424 return;
1427 barGoLink bar((int)result->GetRowCount());
1431 Field *fields = result->Fetch();
1432 bar.step();
1434 uint32 loguid = fields[0].GetUInt32();
1435 uint64 respawn_time = fields[1].GetUInt64();
1436 uint32 instance = fields[2].GetUInt32();
1438 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1440 ++count;
1441 } while (result->NextRow());
1443 delete result;
1445 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1446 sLog.outString();
1449 void ObjectMgr::LoadGameobjectRespawnTimes()
1451 // remove outdated data
1452 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1454 uint32 count = 0;
1456 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1458 if(!result)
1460 barGoLink bar(1);
1462 bar.step();
1464 sLog.outString();
1465 sLog.outString(">> Loaded 0 gameobject respawn time.");
1466 return;
1469 barGoLink bar((int)result->GetRowCount());
1473 Field *fields = result->Fetch();
1474 bar.step();
1476 uint32 loguid = fields[0].GetUInt32();
1477 uint64 respawn_time = fields[1].GetUInt64();
1478 uint32 instance = fields[2].GetUInt32();
1480 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1482 ++count;
1483 } while (result->NextRow());
1485 delete result;
1487 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1488 sLog.outString();
1491 // name must be checked to correctness (if received) before call this function
1492 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1494 uint64 guid = 0;
1496 CharacterDatabase.escape_string(name);
1498 // Player name safe to sending to DB (checked at login) and this function using
1499 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1500 if(result)
1502 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1504 delete result;
1507 return guid;
1510 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1512 // prevent DB access for online player
1513 if(Player* player = GetPlayer(guid))
1515 name = player->GetName();
1516 return true;
1519 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1521 if(result)
1523 name = (*result)[0].GetCppString();
1524 delete result;
1525 return true;
1528 return false;
1531 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1533 // prevent DB access for online player
1534 if(Player* player = GetPlayer(guid))
1536 return Player::TeamForRace(player->getRace());
1539 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1541 if(result)
1543 uint8 race = (*result)[0].GetUInt8();
1544 delete result;
1545 return Player::TeamForRace(race);
1548 return 0;
1551 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1553 // prevent DB access for online player
1554 if(Player* player = GetPlayer(guid))
1556 return player->GetSession()->GetAccountId();
1559 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1560 if(result)
1562 uint32 acc = (*result)[0].GetUInt32();
1563 delete result;
1564 return acc;
1567 return 0;
1570 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1572 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1573 if(result)
1575 uint32 acc = (*result)[0].GetUInt32();
1576 delete result;
1577 return acc;
1580 return 0;
1583 void ObjectMgr::LoadItemLocales()
1585 mItemLocaleMap.clear(); // need for reload case
1587 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");
1589 if(!result)
1591 barGoLink bar(1);
1593 bar.step();
1595 sLog.outString();
1596 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1597 return;
1600 barGoLink bar((int)result->GetRowCount());
1604 Field *fields = result->Fetch();
1605 bar.step();
1607 uint32 entry = fields[0].GetUInt32();
1609 ItemLocale& data = mItemLocaleMap[entry];
1611 for(int i = 1; i < MAX_LOCALE; ++i)
1613 std::string str = fields[1+2*(i-1)].GetCppString();
1614 if(!str.empty())
1616 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1617 if(idx >= 0)
1619 if((int32)data.Name.size() <= idx)
1620 data.Name.resize(idx+1);
1622 data.Name[idx] = str;
1626 str = fields[1+2*(i-1)+1].GetCppString();
1627 if(!str.empty())
1629 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1630 if(idx >= 0)
1632 if((int32)data.Description.size() <= idx)
1633 data.Description.resize(idx+1);
1635 data.Description[idx] = str;
1639 } while (result->NextRow());
1641 delete result;
1643 sLog.outString();
1644 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1647 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1649 template<class D>
1650 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1652 dst = D(sObjectMgr.GetScriptId(src));
1656 void ObjectMgr::LoadItemPrototypes()
1658 SQLItemLoader loader;
1659 loader.Load(sItemStorage);
1660 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1661 sLog.outString();
1663 // check data correctness
1664 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1666 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1667 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1668 if(!proto)
1670 /* to many errors, and possible not all items really used in game
1671 if (dbcitem)
1672 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1674 continue;
1677 if(dbcitem)
1679 if(proto->Class != dbcitem->Class)
1681 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1682 // It safe let use Class from DB
1684 /* disabled: have some strange wrong cases for Subclass values.
1685 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1686 if(proto->SubClass != dbcitem->SubClass)
1688 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);
1689 // It safe let use Subclass from DB
1693 if(proto->Unk0 != dbcitem->Unk0)
1695 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1696 // It safe let use Unk0 from DB
1699 if(proto->Material != dbcitem->Material)
1701 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1702 // It safe let use Material from DB
1705 if(proto->InventoryType != dbcitem->InventoryType)
1707 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1708 // It safe let use InventoryType from DB
1711 if(proto->DisplayInfoID != dbcitem->DisplayId)
1713 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1714 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1716 if(proto->Sheath != dbcitem->Sheath)
1718 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1719 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1722 else
1724 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1727 if(proto->Class >= MAX_ITEM_CLASS)
1729 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1730 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1733 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1735 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1736 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1739 if(proto->Quality >= MAX_ITEM_QUALITY)
1741 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1742 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1745 if(proto->BuyCount <= 0)
1747 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1748 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1751 if(proto->InventoryType >= MAX_INVTYPE)
1753 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1754 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1757 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1759 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1760 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1764 // can be used in equip slot, as page read use in inventory, or spell casting at use
1765 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1766 if(!req)
1768 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1770 if(proto->Spells[j].SpellId)
1772 req = true;
1773 break;
1778 if(req)
1780 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1781 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1783 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1784 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1788 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1790 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1791 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1794 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1795 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1797 if(proto->RequiredReputationFaction)
1799 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1801 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1802 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1805 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1806 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1808 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1809 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1811 if(proto->MaxCount < -1)
1813 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1814 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1817 if(proto->Stackable == 0)
1819 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1820 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1822 else if(proto->Stackable < -1)
1824 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1825 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1827 else if(proto->Stackable > 1000)
1829 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1830 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1833 if(proto->ContainerSlots > MAX_BAG_SIZE)
1835 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1836 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1839 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1841 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1842 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1845 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1847 // for ItemStatValue != 0
1848 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1850 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1851 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1854 switch(proto->ItemStat[j].ItemStatType)
1856 case ITEM_MOD_SPELL_HEALING_DONE:
1857 case ITEM_MOD_SPELL_DAMAGE_DONE:
1858 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1859 break;
1860 default:
1861 break;
1865 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1867 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1869 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1870 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1874 // special format
1875 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1877 // spell_1
1878 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1880 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);
1881 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1882 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1883 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1884 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1887 // spell_2 have learning spell
1888 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1890 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);
1891 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1892 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1893 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1895 else if(!proto->Spells[1].SpellId)
1897 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1898 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1899 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1901 else
1903 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1904 if(!spellInfo)
1906 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1907 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1908 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1909 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1911 // allowed only in special format
1912 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1914 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1915 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1916 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1917 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1921 // spell_3*,spell_4*,spell_5* is empty
1922 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1924 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1926 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1927 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1928 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1930 else if(proto->Spells[j].SpellId != 0)
1932 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1933 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1937 // normal spell list
1938 else
1940 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1942 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1944 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1945 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1946 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1948 // on hit can be sued only at weapon
1949 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1951 if(proto->Class != ITEM_CLASS_WEAPON)
1952 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);
1955 if(proto->Spells[j].SpellId)
1957 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1958 if(!spellInfo)
1960 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1961 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1963 // allowed only in special format
1964 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1966 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1967 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1973 if(proto->Bonding >= MAX_BIND_TYPE)
1974 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1976 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1977 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1979 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1980 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1982 if(proto->Sheath >= MAX_SHEATHETYPE)
1984 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1985 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1988 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1990 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1991 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1994 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1996 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1997 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
2000 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
2002 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
2003 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
2006 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
2007 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
2009 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
2010 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
2012 if(proto->BagFamily)
2014 // check bits
2015 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
2017 uint32 mask = 1 << j;
2018 if((proto->BagFamily & mask)==0)
2019 continue;
2021 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
2022 if(!bf)
2024 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2025 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2026 continue;
2029 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2031 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2032 if(!ctEntry)
2034 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2035 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2041 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2042 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2044 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2046 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2048 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2049 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2053 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2054 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2056 if(proto->FoodType >= MAX_PET_DIET)
2058 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2059 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2062 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2064 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2065 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2068 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2070 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2071 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2074 if(proto->NonConsumable)
2076 if (proto->NonConsumable > 1)
2078 sLog.outErrorDb("Item (Entry: %u) has wrong NonConsumable (%u), must be 0..1",i,proto->NonConsumable);
2079 const_cast<ItemPrototype*>(proto)->NonConsumable = 1;
2082 bool can_be_need = false;
2083 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
2085 if(proto->Spells[j].SpellCharges < 0)
2087 can_be_need = true;
2088 break;
2092 if (!can_be_need)
2094 sLog.outErrorDb("Item (Entry: %u) has redundant NonConsumable (%u), item not have negative charges",i,proto->NonConsumable);
2095 const_cast<ItemPrototype*>(proto)->NonConsumable = 0;
2100 // check some dbc referenced items (avoid duplicate reports)
2101 std::set<uint32> notFoundOutfit;
2102 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
2104 CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i);
2105 if (!entry)
2106 continue;
2108 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
2110 if (entry->ItemId[j] <= 0)
2111 continue;
2113 uint32 item_id = entry->ItemId[j];
2115 if (!GetItemPrototype(item_id))
2116 if (item_id != 40582) // nonexistent item by default but referenced in DBC, skip it from errors
2117 notFoundOutfit.insert(item_id);
2121 for(std::set<uint32>::const_iterator itr = notFoundOutfit.begin(); itr != notFoundOutfit.end(); ++itr)
2122 sLog.outErrorDb("Item (Entry: %u) not exist in `item_template` but referenced in `CharStartOutfit.dbc`", *itr);
2125 void ObjectMgr::LoadItemRequiredTarget()
2127 m_ItemRequiredTarget.clear(); // needed for reload case
2129 uint32 count = 0;
2131 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2133 if (!result)
2135 barGoLink bar(1);
2137 bar.step();
2139 sLog.outString();
2140 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2141 return;
2144 barGoLink bar((int)result->GetRowCount());
2148 Field *fields = result->Fetch();
2149 bar.step();
2151 uint32 uiItemId = fields[0].GetUInt32();
2152 uint32 uiType = fields[1].GetUInt32();
2153 uint32 uiTargetEntry = fields[2].GetUInt32();
2155 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2157 if (!pItemProto)
2159 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2160 continue;
2163 bool bIsItemSpellValid = false;
2165 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2167 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2169 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2170 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2172 SpellScriptTargetBounds bounds = sSpellMgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2173 if (bounds.first != bounds.second)
2174 break;
2176 for (int j = 0; j < MAX_EFFECT_INDEX; ++j)
2178 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2179 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2180 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2181 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2183 bIsItemSpellValid = true;
2184 break;
2187 if (bIsItemSpellValid)
2188 break;
2193 if (!bIsItemSpellValid)
2195 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);
2196 continue;
2199 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2201 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2202 continue;
2205 if (!uiTargetEntry)
2207 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2208 continue;
2211 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2213 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2214 continue;
2217 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2219 ++count;
2220 } while (result->NextRow());
2222 delete result;
2224 sLog.outString();
2225 sLog.outString(">> Loaded %u Item required targets", count);
2228 void ObjectMgr::LoadPetLevelInfo()
2230 // Loading levels data
2232 // 0 1 2 3 4 5 6 7 8 9
2233 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2235 uint32 count = 0;
2237 if (!result)
2239 barGoLink bar( 1 );
2240 bar.step();
2242 sLog.outString();
2243 sLog.outString(">> Loaded %u level pet stats definitions", count);
2244 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2245 return;
2248 barGoLink bar( (int)result->GetRowCount() );
2252 Field* fields = result->Fetch();
2254 uint32 creature_id = fields[0].GetUInt32();
2255 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2257 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2258 continue;
2261 uint32 current_level = fields[1].GetUInt32();
2262 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2264 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2265 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2266 else
2268 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2269 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2271 continue;
2273 else if(current_level < 1)
2275 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2276 continue;
2279 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2281 if(pInfoMapEntry==NULL)
2282 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2284 // data for level 1 stored in [0] array element, ...
2285 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2287 pLevelInfo->health = fields[2].GetUInt16();
2288 pLevelInfo->mana = fields[3].GetUInt16();
2289 pLevelInfo->armor = fields[9].GetUInt16();
2291 for (int i = 0; i < MAX_STATS; i++)
2293 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2296 bar.step();
2297 ++count;
2299 while (result->NextRow());
2301 delete result;
2303 sLog.outString();
2304 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2307 // Fill gaps and check integrity
2308 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2310 PetLevelInfo* pInfo = itr->second;
2312 // fatal error if no level 1 data
2313 if(!pInfo || pInfo[0].health == 0 )
2315 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2316 exit(1);
2319 // fill level gaps
2320 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2322 if(pInfo[level].health == 0)
2324 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2325 pInfo[level] = pInfo[level-1];
2331 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2333 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2334 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2336 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2337 if(itr == petInfo.end())
2338 return NULL;
2340 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2343 void ObjectMgr::LoadPlayerInfo()
2345 // Load playercreate
2347 // 0 1 2 3 4 5 6
2348 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2350 uint32 count = 0;
2352 if (!result)
2354 barGoLink bar( 1 );
2356 sLog.outString();
2357 sLog.outString( ">> Loaded %u player create definitions", count );
2358 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2359 exit(1);
2362 barGoLink bar( (int)result->GetRowCount() );
2366 Field* fields = result->Fetch();
2368 uint32 current_race = fields[0].GetUInt32();
2369 uint32 current_class = fields[1].GetUInt32();
2370 uint32 mapId = fields[2].GetUInt32();
2371 uint32 areaId = fields[3].GetUInt32();
2372 float positionX = fields[4].GetFloat();
2373 float positionY = fields[5].GetFloat();
2374 float positionZ = fields[6].GetFloat();
2376 if(current_race >= MAX_RACES)
2378 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2379 continue;
2382 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2383 if(!rEntry)
2385 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2386 continue;
2389 if(current_class >= MAX_CLASSES)
2391 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2392 continue;
2395 if(!sChrClassesStore.LookupEntry(current_class))
2397 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2398 continue;
2401 // accept DB data only for valid position (and non instanceable)
2402 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2404 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2405 continue;
2408 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2410 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2411 continue;
2414 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2416 pInfo->mapId = mapId;
2417 pInfo->areaId = areaId;
2418 pInfo->positionX = positionX;
2419 pInfo->positionY = positionY;
2420 pInfo->positionZ = positionZ;
2422 pInfo->displayId_m = rEntry->model_m;
2423 pInfo->displayId_f = rEntry->model_f;
2425 bar.step();
2426 ++count;
2428 while (result->NextRow());
2430 delete result;
2432 sLog.outString();
2433 sLog.outString( ">> Loaded %u player create definitions", count );
2436 // Load playercreate items
2438 // 0 1 2 3
2439 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2441 uint32 count = 0;
2443 if (!result)
2445 barGoLink bar( 1 );
2447 bar.step();
2449 sLog.outString();
2450 sLog.outString( ">> Loaded %u custom player create items", count );
2452 else
2454 barGoLink bar( (int)result->GetRowCount() );
2458 Field* fields = result->Fetch();
2460 uint32 current_race = fields[0].GetUInt32();
2461 if(current_race >= MAX_RACES)
2463 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2464 continue;
2467 uint32 current_class = fields[1].GetUInt32();
2468 if(current_class >= MAX_CLASSES)
2470 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2471 continue;
2474 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2476 uint32 item_id = fields[2].GetUInt32();
2478 if(!GetItemPrototype(item_id))
2480 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);
2481 continue;
2484 uint32 amount = fields[3].GetUInt32();
2486 if(!amount)
2488 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2489 continue;
2492 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2494 bar.step();
2495 ++count;
2497 while(result->NextRow());
2499 delete result;
2501 sLog.outString();
2502 sLog.outString( ">> Loaded %u custom player create items", count );
2506 // Load playercreate spells
2508 // 0 1 2
2509 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2511 uint32 count = 0;
2513 if (!result)
2515 barGoLink bar( 1 );
2517 sLog.outString();
2518 sLog.outString( ">> Loaded %u player create spells", count );
2519 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2521 else
2523 barGoLink bar( (int)result->GetRowCount() );
2527 Field* fields = result->Fetch();
2529 uint32 current_race = fields[0].GetUInt32();
2530 if(current_race >= MAX_RACES)
2532 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2533 continue;
2536 uint32 current_class = fields[1].GetUInt32();
2537 if(current_class >= MAX_CLASSES)
2539 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2540 continue;
2543 uint32 spell_id = fields[2].GetUInt32();
2544 if (!sSpellStore.LookupEntry(spell_id))
2546 sLog.outErrorDb("Non existing spell %u in `playercreateinfo_spell` table, ignoring.", spell_id);
2547 continue;
2550 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2551 pInfo->spell.push_back(spell_id);
2553 bar.step();
2554 ++count;
2556 while( result->NextRow() );
2558 delete result;
2560 sLog.outString();
2561 sLog.outString( ">> Loaded %u player create spells", count );
2565 // Load playercreate actions
2567 // 0 1 2 3 4
2568 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2570 uint32 count = 0;
2572 if (!result)
2574 barGoLink bar( 1 );
2576 sLog.outString();
2577 sLog.outString( ">> Loaded %u player create actions", count );
2578 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2580 else
2582 barGoLink bar( (int)result->GetRowCount() );
2586 Field* fields = result->Fetch();
2588 uint32 current_race = fields[0].GetUInt32();
2589 if(current_race >= MAX_RACES)
2591 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2592 continue;
2595 uint32 current_class = fields[1].GetUInt32();
2596 if(current_class >= MAX_CLASSES)
2598 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2599 continue;
2602 uint8 action_button = fields[2].GetUInt8();
2603 uint32 action = fields[3].GetUInt32();
2604 uint8 action_type = fields[4].GetUInt8();
2606 if (!Player::IsActionButtonDataValid(action_button,action,action_type,NULL))
2607 continue;
2609 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2610 pInfo->action.push_back(PlayerCreateInfoAction(action_button,action,action_type));
2612 bar.step();
2613 ++count;
2615 while( result->NextRow() );
2617 delete result;
2619 sLog.outString();
2620 sLog.outString( ">> Loaded %u player create actions", count );
2624 // Loading levels data (class only dependent)
2626 // 0 1 2 3
2627 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2629 uint32 count = 0;
2631 if (!result)
2633 barGoLink bar( 1 );
2635 sLog.outString();
2636 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2637 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2638 exit(1);
2641 barGoLink bar( (int)result->GetRowCount() );
2645 Field* fields = result->Fetch();
2647 uint32 current_class = fields[0].GetUInt32();
2648 if(current_class >= MAX_CLASSES)
2650 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2651 continue;
2654 uint32 current_level = fields[1].GetUInt32();
2655 if(current_level == 0)
2657 sLog.outErrorDb("Wrong level %u in `player_classlevelstats` table, ignoring.",current_level);
2658 continue;
2660 else if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2662 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2663 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2664 else
2666 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2667 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2669 continue;
2672 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2674 if(!pClassInfo->levelInfo)
2675 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2677 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2679 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2680 pClassLevelInfo->basemana = fields[3].GetUInt16();
2682 bar.step();
2683 ++count;
2685 while (result->NextRow());
2687 delete result;
2689 sLog.outString();
2690 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2693 // Fill gaps and check integrity
2694 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2696 // skip non existed classes
2697 if(!sChrClassesStore.LookupEntry(class_))
2698 continue;
2700 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2702 // fatal error if no level 1 data
2703 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2705 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2706 exit(1);
2709 // fill level gaps
2710 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2712 if(pClassInfo->levelInfo[level].basehealth == 0)
2714 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2715 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2720 // Loading levels data (class/race dependent)
2722 // 0 1 2 3 4 5 6 7
2723 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2725 uint32 count = 0;
2727 if (!result)
2729 barGoLink bar( 1 );
2731 sLog.outString();
2732 sLog.outString( ">> Loaded %u level stats definitions", count );
2733 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2734 exit(1);
2737 barGoLink bar( (int)result->GetRowCount() );
2741 Field* fields = result->Fetch();
2743 uint32 current_race = fields[0].GetUInt32();
2744 if(current_race >= MAX_RACES)
2746 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2747 continue;
2750 uint32 current_class = fields[1].GetUInt32();
2751 if(current_class >= MAX_CLASSES)
2753 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2754 continue;
2757 uint32 current_level = fields[2].GetUInt32();
2758 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2760 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2761 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2762 else
2764 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2765 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2767 continue;
2770 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2772 if(!pInfo->levelInfo)
2773 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2775 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2777 for (int i = 0; i < MAX_STATS; i++)
2779 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2782 bar.step();
2783 ++count;
2785 while (result->NextRow());
2787 delete result;
2789 sLog.outString();
2790 sLog.outString( ">> Loaded %u level stats definitions", count );
2793 // Fill gaps and check integrity
2794 for (int race = 0; race < MAX_RACES; ++race)
2796 // skip non existed races
2797 if(!sChrRacesStore.LookupEntry(race))
2798 continue;
2800 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2802 // skip non existed classes
2803 if(!sChrClassesStore.LookupEntry(class_))
2804 continue;
2806 PlayerInfo* pInfo = &playerInfo[race][class_];
2808 // skip non loaded combinations
2809 if(!pInfo->displayId_m || !pInfo->displayId_f)
2810 continue;
2812 // skip expansion races if not playing with expansion
2813 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2814 continue;
2816 // skip expansion classes if not playing with expansion
2817 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2818 continue;
2820 // fatal error if no level 1 data
2821 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2823 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2824 exit(1);
2827 // fill level gaps
2828 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2830 if(pInfo->levelInfo[level].stats[0] == 0)
2832 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2833 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2839 // Loading xp per level data
2841 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
2842 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2843 mPlayerXPperLevel[level] = 0;
2845 // 0 1
2846 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2848 uint32 count = 0;
2850 if (!result)
2852 barGoLink bar( 1 );
2854 sLog.outString();
2855 sLog.outString( ">> Loaded %u xp for level definitions", count );
2856 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2857 exit(1);
2860 barGoLink bar( (int)result->GetRowCount() );
2864 Field* fields = result->Fetch();
2866 uint32 current_level = fields[0].GetUInt32();
2867 uint32 current_xp = fields[1].GetUInt32();
2869 if(current_level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2871 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2872 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2873 else
2875 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2876 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2878 continue;
2880 //PlayerXPperLevel
2881 mPlayerXPperLevel[current_level] = current_xp;
2882 bar.step();
2883 ++count;
2885 while (result->NextRow());
2887 delete result;
2889 sLog.outString();
2890 sLog.outString( ">> Loaded %u xp for level definitions", count );
2893 // fill level gaps
2894 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2896 if( mPlayerXPperLevel[level] == 0)
2898 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2899 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2904 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2906 if(level < 1 || class_ >= MAX_CLASSES)
2907 return;
2909 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2911 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2912 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2914 *info = pInfo->levelInfo[level-1];
2917 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2919 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2920 return;
2922 PlayerInfo const* pInfo = &playerInfo[race][class_];
2923 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2924 return;
2926 if(level <= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2927 *info = pInfo->levelInfo[level-1];
2928 else
2929 BuildPlayerLevelInfo(race,class_,level,info);
2932 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2934 // base data (last known level)
2935 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1];
2937 for(int lvl = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2939 switch(_class)
2941 case CLASS_WARRIOR:
2942 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2943 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2944 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2945 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2946 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2947 break;
2948 case CLASS_PALADIN:
2949 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2950 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2951 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2952 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2953 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2954 break;
2955 case CLASS_HUNTER:
2956 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2957 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2958 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2959 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2960 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2961 break;
2962 case CLASS_ROGUE:
2963 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2964 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2965 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2966 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2967 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2968 break;
2969 case CLASS_PRIEST:
2970 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2971 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2972 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2973 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2974 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2975 break;
2976 case CLASS_SHAMAN:
2977 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2978 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2979 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2980 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2981 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2982 break;
2983 case CLASS_MAGE:
2984 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2985 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2986 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2987 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2988 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2989 break;
2990 case CLASS_WARLOCK:
2991 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2992 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2993 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2994 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2995 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2996 break;
2997 case CLASS_DRUID:
2998 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2999 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
3000 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
3001 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
3002 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
3007 void ObjectMgr::LoadGuilds()
3009 Guild *newGuild;
3010 uint32 count = 0;
3012 // 0 1 2 3 4 5 6
3013 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
3014 // 7 8 9 10 11 12
3015 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
3016 "FROM guild ORDER BY guildid ASC");
3018 if( !result )
3021 barGoLink bar( 1 );
3023 bar.step();
3025 sLog.outString();
3026 sLog.outString( ">> Loaded %u guild definitions", count );
3027 return;
3030 // load guild ranks
3031 // 0 1 2 3 4
3032 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
3034 // load guild members
3035 // 0 1 2 3 4 5 6
3036 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
3037 // 7 8 9 10 11 12
3038 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
3039 // 13 14 15 16 17 18
3040 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
3041 // 19 20 21 22 23
3042 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
3043 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
3045 // load guild bank tab rights
3046 // 0 1 2 3 4
3047 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
3049 barGoLink bar( (int)result->GetRowCount() );
3053 //Field *fields = result->Fetch();
3055 bar.step();
3056 ++count;
3058 newGuild = new Guild;
3059 if (!newGuild->LoadGuildFromDB(result) ||
3060 !newGuild->LoadRanksFromDB(guildRanksResult) ||
3061 !newGuild->LoadMembersFromDB(guildMembersResult) ||
3062 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
3063 !newGuild->CheckGuildStructure()
3066 newGuild->Disband();
3067 delete newGuild;
3068 continue;
3070 newGuild->LoadGuildEventLogFromDB();
3071 newGuild->LoadGuildBankEventLogFromDB();
3072 newGuild->LoadGuildBankFromDB();
3073 AddGuild(newGuild);
3074 } while( result->NextRow() );
3076 delete result;
3077 delete guildRanksResult;
3078 delete guildMembersResult;
3079 delete guildBankTabRightsResult;
3081 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
3082 //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
3083 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_EVENT_LOG_COUNT));
3084 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT));
3086 sLog.outString();
3087 sLog.outString( ">> Loaded %u guild definitions", count );
3090 void ObjectMgr::LoadArenaTeams()
3092 uint32 count = 0;
3094 // 0 1 2 3 4 5
3095 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3096 // 6 7 8 9 10 11 12 13 14
3097 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3098 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3100 if( !result )
3103 barGoLink bar( 1 );
3105 bar.step();
3107 sLog.outString();
3108 sLog.outString( ">> Loaded %u arenateam definitions", count );
3109 return;
3112 // load arena_team members
3113 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3114 // 0 1 2 3 4 5 6 7 8
3115 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3116 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3118 barGoLink bar( (int)result->GetRowCount() );
3123 bar.step();
3124 ++count;
3126 ArenaTeam *newArenaTeam = new ArenaTeam;
3127 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3128 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3130 newArenaTeam->Disband(NULL);
3131 delete newArenaTeam;
3132 continue;
3134 AddArenaTeam(newArenaTeam);
3135 }while( result->NextRow() );
3137 delete result;
3138 delete arenaTeamMembersResult;
3140 sLog.outString();
3141 sLog.outString( ">> Loaded %u arenateam definitions", count );
3144 void ObjectMgr::LoadGroups()
3146 // -- loading groups --
3147 uint32 count = 0;
3148 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3149 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");
3151 if (!result)
3153 barGoLink bar( 1 );
3155 bar.step();
3157 sLog.outString();
3158 sLog.outString( ">> Loaded %u group definitions", count );
3159 return;
3162 barGoLink bar( (int)result->GetRowCount() );
3166 bar.step();
3167 Field *fields = result->Fetch();
3168 ++count;
3169 Group *group = new Group;
3170 if (!group->LoadGroupFromDB(fields))
3172 group->Disband();
3173 delete group;
3174 continue;
3176 AddGroup(group);
3177 }while( result->NextRow() );
3179 delete result;
3181 sLog.outString();
3182 sLog.outString( ">> Loaded %u group definitions", count );
3184 // -- loading members --
3185 count = 0;
3186 // 0 1 2 3
3187 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, groupId FROM group_member ORDER BY groupId");
3188 if (!result)
3190 barGoLink bar2( 1 );
3191 bar2.step();
3193 else
3195 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3197 barGoLink bar2( (int)result->GetRowCount() );
3200 bar2.step();
3201 Field *fields = result->Fetch();
3202 count++;
3204 uint32 memberGuidlow = fields[0].GetUInt32();
3205 bool assistent = fields[1].GetBool();
3206 uint8 subgroup = fields[2].GetUInt8();
3207 uint32 groupId = fields[3].GetUInt32();
3208 if (!group || group->GetId() != groupId)
3210 group = GetGroupById(groupId);
3211 if (!group)
3213 sLog.outErrorDb("Incorrect entry in group_member table : no group with Id %d for member %d!", groupId, memberGuidlow);
3214 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3215 continue;
3219 if (!group->LoadMemberFromDB(memberGuidlow, subgroup, assistent))
3221 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);
3222 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3224 }while( result->NextRow() );
3225 delete result;
3228 // clean groups
3229 // TODO: maybe delete from the DB before loading in this case
3230 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end();)
3232 if (itr->second->GetMembersCount() < 2)
3234 itr->second->Disband();
3235 delete itr->second;
3236 mGroupMap.erase(itr++);
3238 else
3239 ++itr;
3242 // -- loading instances --
3243 count = 0;
3244 result = CharacterDatabase.Query(
3245 // 0 1 2 3 4 5
3246 "SELECT group_instance.leaderGuid, map, instance, permanent, instance.difficulty, resettime, "
3247 // 6
3248 "(SELECT COUNT(*) FROM character_instance WHERE guid = group_instance.leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1), "
3249 // 7
3250 " groups.groupId "
3251 "FROM group_instance LEFT JOIN instance ON instance = id LEFT JOIN groups ON groups.leaderGUID = group_instance.leaderGUID ORDER BY leaderGuid"
3254 if (!result)
3256 barGoLink bar2( 1 );
3257 bar2.step();
3259 else
3261 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3263 barGoLink bar2( (int)result->GetRowCount() );
3266 bar2.step();
3267 Field *fields = result->Fetch();
3268 count++;
3270 uint32 leaderGuidLow = fields[0].GetUInt32();
3271 uint32 mapId = fields[1].GetUInt32();
3272 Difficulty diff = (Difficulty)fields[4].GetUInt8();
3273 uint32 groupId = fields[7].GetUInt32();
3275 if (!group || group->GetId() != groupId)
3277 // find group id in map by leader low guid
3278 group = GetGroupById(groupId);
3279 if (!group)
3281 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", leaderGuidLow);
3282 continue;
3286 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
3287 if (!mapEntry || !mapEntry->IsDungeon())
3289 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", mapId);
3290 continue;
3293 if (diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3295 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff + 1);
3296 diff = REGULAR_DIFFICULTY; // default for both difficaly types
3299 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3300 group->BindToInstance(save, fields[3].GetBool(), true);
3301 }while( result->NextRow() );
3302 delete result;
3305 sLog.outString();
3306 sLog.outString( ">> Loaded %u group-instance binds total", count );
3308 sLog.outString();
3309 sLog.outString( ">> Loaded %u group members total", count );
3312 void ObjectMgr::LoadQuests()
3314 // For reload case
3315 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3316 delete itr->second;
3317 mQuestTemplates.clear();
3319 mExclusiveQuestGroups.clear();
3321 // 0 1 2 3 4 5 6 7 8
3322 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3323 // 9 10 11 12 13 14 15 16
3324 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3325 // 17 18 19 20 21 22 23 24 25
3326 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain,"
3327 // 26 27 28 29
3328 "RewXPId, SrcItemId, SrcItemCount, SrcSpell,"
3329 // 30 31 32 33 34 35 36 37 38 39 40
3330 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, CompletedText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3331 // 41 42 43 44 45 46 47 48 49 50 51 52
3332 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3333 // 53 54 55 56 57 58 59 60
3334 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3335 // 61 62 63 64 65 66 67 68
3336 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3337 // 69 70 71 72
3338 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3339 // 73 74 75 76 77 78
3340 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3341 // 79 80 81 82 83 84
3342 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3343 // 85 86 87 88 89 90 91 92
3344 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3345 // 93 94 95 96 97
3346 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5,"
3347 // 98 99 100 101 102
3348 "RewRepValueId1, RewRepValueId2, RewRepValueId3, RewRepValueId4, RewRepValueId5,"
3349 // 103 104 105 106 107
3350 "RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3351 // 108 109 110 111 112 113
3352 "RewHonorAddition, RewHonorMultiplier, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast,"
3353 // 114 115 116 117 118 119
3354 "RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3355 // 120 121 122 123 124 125 126 127
3356 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3357 // 128 129 130 131 132 133
3358 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3359 // 134 135 136 137
3360 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3361 // 138 139
3362 "StartScript, CompleteScript"
3363 " FROM quest_template");
3364 if(result == NULL)
3366 barGoLink bar( 1 );
3367 bar.step();
3369 sLog.outString();
3370 sLog.outString( ">> Loaded 0 quests definitions" );
3371 sLog.outErrorDb("`quest_template` table is empty!");
3372 return;
3375 // create multimap previous quest for each existed quest
3376 // some quests can have many previous maps set by NextQuestId in previous quest
3377 // for example set of race quests can lead to single not race specific quest
3378 barGoLink bar((int) result->GetRowCount() );
3381 bar.step();
3382 Field *fields = result->Fetch();
3384 Quest * newQuest = new Quest(fields);
3385 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3386 } while( result->NextRow() );
3388 delete result;
3390 // Post processing
3392 std::map<uint32,uint32> usedMailTemplates;
3394 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3396 Quest * qinfo = iter->second;
3398 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3400 if( qinfo->GetQuestMethod() >= 3 )
3402 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3405 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3407 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3408 qinfo->GetQuestId(),qinfo->QuestFlags >> 24,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 24);
3409 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3412 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3414 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3416 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3417 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3421 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3423 // at auto-reward can be rewarded only RewChoiceItemId[0]
3424 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3426 if(uint32 id = qinfo->RewChoiceItemId[j])
3428 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3429 qinfo->GetQuestId(),j+1,id,j+1);
3430 // no changes, quest ignore this data
3435 // client quest log visual (area case)
3436 if( qinfo->ZoneOrSort > 0 )
3438 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3440 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3441 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3442 // no changes, quest not dependent from this value but can have problems at client
3445 // client quest log visual (sort case)
3446 if( qinfo->ZoneOrSort < 0 )
3448 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3449 if( !qSort )
3451 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3452 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3453 // 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)
3455 //check SkillOrClass value (class case).
3456 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3458 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3459 if(qinfo->SkillOrClass < 0)
3461 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3462 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3465 //check for proper SkillOrClass value (skill case)
3466 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3468 // skill is positive value in SkillOrClass
3469 if(qinfo->SkillOrClass != skill_id )
3471 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3472 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3473 //override, and force proper value here?
3478 // SkillOrClass (class case)
3479 if( qinfo->SkillOrClass < 0 )
3481 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3483 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3484 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3487 // SkillOrClass (skill case)
3488 if( qinfo->SkillOrClass > 0 )
3490 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3492 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3493 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3497 if( qinfo->RequiredSkillValue )
3499 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3501 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3502 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3503 // no changes, quest can't be done for this requirement
3506 if( qinfo->SkillOrClass <= 0 )
3508 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3509 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3510 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3513 // else Skill quests can have 0 skill level, this is ok
3515 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3517 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3518 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3519 // no changes, quest can't be done for this requirement
3522 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3524 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3525 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3526 // no changes, quest can't be done for this requirement
3529 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3531 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3532 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3533 // no changes, quest can't be done for this requirement
3536 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3538 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3539 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3540 // no changes, quest can't be done for this requirement
3543 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3545 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3546 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3547 // no changes, quest can't be done for this requirement
3550 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3552 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3553 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3554 // warning
3557 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3559 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3560 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3561 // warning
3564 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3566 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3567 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3568 // warning
3571 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3573 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3574 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3575 qinfo->CharTitleId = 0;
3576 // quest can't reward this title
3579 if(qinfo->SrcItemId)
3581 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3583 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3584 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3585 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3587 else if(qinfo->SrcItemCount==0)
3589 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3590 qinfo->GetQuestId(),qinfo->SrcItemId);
3591 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3594 else if(qinfo->SrcItemCount>0)
3596 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3597 qinfo->GetQuestId(),qinfo->SrcItemCount);
3598 qinfo->SrcItemCount=0; // no quest work changes in fact
3601 if(qinfo->SrcSpell)
3603 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3604 if(!spellInfo)
3606 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3607 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3608 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3610 else if(!SpellMgr::IsSpellValid(spellInfo))
3612 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3613 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3614 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3618 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3620 uint32 id = qinfo->ReqItemId[j];
3621 if(id)
3623 if(qinfo->ReqItemCount[j] == 0)
3625 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3626 qinfo->GetQuestId(), j+1, id, j+1);
3627 // no changes, quest can't be done for this requirement
3630 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3632 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3634 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3635 qinfo->GetQuestId(), j+1, id, id);
3636 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3639 else if(qinfo->ReqItemCount[j] > 0)
3641 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3642 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3643 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3647 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3649 uint32 id = qinfo->ReqSourceId[j];
3650 if(id)
3652 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3654 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3655 qinfo->GetQuestId(),j+1,id,id);
3656 // no changes, quest can't be done for this requirement
3659 else
3661 if(qinfo->ReqSourceCount[j]>0)
3663 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3664 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3665 // no changes, quest ignore this data
3670 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3672 uint32 id = qinfo->ReqSpell[j];
3673 if(id)
3675 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3676 if(!spellInfo)
3678 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3679 qinfo->GetQuestId(),j+1,id,id);
3680 continue;
3683 if(!qinfo->ReqCreatureOrGOId[j])
3685 bool found = false;
3686 for(int k = 0; k < MAX_EFFECT_INDEX; ++k)
3688 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3689 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3691 found = true;
3692 break;
3696 if(found)
3698 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3700 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);
3702 // this will prevent quest completing without objective
3703 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3706 else
3708 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.",
3709 qinfo->GetQuestId(),j+1,id,j+1,id);
3710 // no changes, quest can't be done for this requirement
3716 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3718 int32 id = qinfo->ReqCreatureOrGOId[j];
3719 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3721 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3722 qinfo->GetQuestId(),j+1,id,uint32(-id));
3723 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3726 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3728 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3729 qinfo->GetQuestId(),j+1,id,uint32(id));
3730 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3733 if(id)
3735 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3737 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3739 if(!qinfo->ReqCreatureOrGOCount[j])
3741 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3742 qinfo->GetQuestId(),j+1,id,j+1);
3743 // no changes, quest can be incorrectly done, but we already report this
3746 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3748 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3749 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3750 // no changes, quest ignore this data
3754 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3756 uint32 id = qinfo->RewChoiceItemId[j];
3757 if(id)
3759 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3761 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3762 qinfo->GetQuestId(),j+1,id,id);
3763 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3766 if(!qinfo->RewChoiceItemCount[j])
3768 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3769 qinfo->GetQuestId(),j+1,id,j+1);
3770 // no changes, quest can't be done
3773 else if(qinfo->RewChoiceItemCount[j]>0)
3775 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3776 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3777 // no changes, quest ignore this data
3781 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3783 uint32 id = qinfo->RewItemId[j];
3784 if(id)
3786 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3788 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3789 qinfo->GetQuestId(),j+1,id,id);
3790 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3793 if(!qinfo->RewItemCount[j])
3795 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3796 qinfo->GetQuestId(),j+1,id,j+1);
3797 // no changes
3800 else if(qinfo->RewItemCount[j]>0)
3802 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3803 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3804 // no changes, quest ignore this data
3808 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3810 if (qinfo->RewRepFaction[j])
3812 if (abs(qinfo->RewRepValueId[j]) > 9)
3813 sLog.outErrorDb("Quest %u has RewRepValueId%d = %i but value is not valid.", qinfo->GetQuestId(), j+1, qinfo->RewRepValueId[j]);
3815 if (!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3817 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.",
3818 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j]);
3819 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3822 else if (qinfo->RewRepValue[j] != 0)
3824 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %i.",
3825 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3826 // no changes, quest ignore this data
3830 if(qinfo->RewSpell)
3832 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3834 if(!spellInfo)
3836 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3837 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3838 qinfo->RewSpell = 0; // no spell reward will display for this quest
3840 else if(!SpellMgr::IsSpellValid(spellInfo))
3842 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3843 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3844 qinfo->RewSpell = 0; // no spell reward will display for this quest
3846 else if(GetTalentSpellCost(qinfo->RewSpell))
3848 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3849 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3850 qinfo->RewSpell = 0; // no spell reward will display for this quest
3854 if(qinfo->RewSpellCast)
3856 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3858 if(!spellInfo)
3860 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3861 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3862 qinfo->RewSpellCast = 0; // no spell will be casted on player
3864 else if(!SpellMgr::IsSpellValid(spellInfo))
3866 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3867 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3868 qinfo->RewSpellCast = 0; // no spell will be casted on player
3870 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3872 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3873 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3874 qinfo->RewSpellCast = 0; // no spell will be casted on player
3878 if (qinfo->RewMailTemplateId)
3880 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3882 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3883 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3884 qinfo->RewMailTemplateId = 0; // no mail will send to player
3885 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3887 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3889 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3890 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3891 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3892 qinfo->RewMailTemplateId = 0; // no mail will send to player
3893 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3895 else
3896 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3899 if (qinfo->NextQuestInChain)
3901 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3902 if (qNextItr == mQuestTemplates.end())
3904 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3905 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3906 qinfo->NextQuestInChain = 0;
3908 else
3909 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3912 // fill additional data stores
3913 if (qinfo->PrevQuestId)
3915 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3917 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3919 else
3921 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3925 if(qinfo->NextQuestId)
3927 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3928 if (qNextItr == mQuestTemplates.end())
3930 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3932 else
3934 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3935 qNextItr->second->prevQuests.push_back(signedQuestId);
3939 if(qinfo->ExclusiveGroup)
3940 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3941 if(qinfo->LimitTime)
3942 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3945 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3946 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3948 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3949 if(!spellInfo)
3950 continue;
3952 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
3954 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3955 continue;
3957 uint32 quest_id = spellInfo->EffectMiscValue[j];
3959 Quest const* quest = GetQuestTemplate(quest_id);
3961 // some quest referenced in spells not exist (outdated spells)
3962 if(!quest)
3963 continue;
3965 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3967 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);
3969 // this will prevent quest completing without objective
3970 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3975 sLog.outString();
3976 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3979 void ObjectMgr::LoadQuestLocales()
3981 mQuestLocaleMap.clear(); // need for reload case
3983 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3984 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,CompletedText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3985 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,CompletedText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3986 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,CompletedText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3987 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,CompletedText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3988 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,CompletedText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3989 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,CompletedText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3990 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,CompletedText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3991 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,CompletedText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3992 " FROM locales_quest"
3995 if(!result)
3997 barGoLink bar(1);
3999 bar.step();
4001 sLog.outString();
4002 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
4003 return;
4006 barGoLink bar((int)result->GetRowCount());
4010 Field *fields = result->Fetch();
4011 bar.step();
4013 uint32 entry = fields[0].GetUInt32();
4015 QuestLocale& data = mQuestLocaleMap[entry];
4017 for(int i = 1; i < MAX_LOCALE; ++i)
4019 std::string str = fields[1+11*(i-1)].GetCppString();
4020 if(!str.empty())
4022 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4023 if(idx >= 0)
4025 if((int32)data.Title.size() <= idx)
4026 data.Title.resize(idx+1);
4028 data.Title[idx] = str;
4031 str = fields[1+11*(i-1)+1].GetCppString();
4032 if(!str.empty())
4034 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4035 if(idx >= 0)
4037 if((int32)data.Details.size() <= idx)
4038 data.Details.resize(idx+1);
4040 data.Details[idx] = str;
4043 str = fields[1+11*(i-1)+2].GetCppString();
4044 if(!str.empty())
4046 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4047 if(idx >= 0)
4049 if((int32)data.Objectives.size() <= idx)
4050 data.Objectives.resize(idx+1);
4052 data.Objectives[idx] = str;
4055 str = fields[1+11*(i-1)+3].GetCppString();
4056 if(!str.empty())
4058 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4059 if(idx >= 0)
4061 if((int32)data.OfferRewardText.size() <= idx)
4062 data.OfferRewardText.resize(idx+1);
4064 data.OfferRewardText[idx] = str;
4067 str = fields[1+11*(i-1)+4].GetCppString();
4068 if(!str.empty())
4070 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4071 if(idx >= 0)
4073 if((int32)data.RequestItemsText.size() <= idx)
4074 data.RequestItemsText.resize(idx+1);
4076 data.RequestItemsText[idx] = str;
4079 str = fields[1+11*(i-1)+5].GetCppString();
4080 if(!str.empty())
4082 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4083 if(idx >= 0)
4085 if((int32)data.EndText.size() <= idx)
4086 data.EndText.resize(idx+1);
4088 data.EndText[idx] = str;
4091 str = fields[1+11*(i-1)+6].GetCppString();
4092 if(!str.empty())
4094 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4095 if(idx >= 0)
4097 if((int32)data.CompletedText.size() <= idx)
4098 data.CompletedText.resize(idx+1);
4100 data.CompletedText[idx] = str;
4103 for(int k = 0; k < 4; ++k)
4105 str = fields[1+11*(i-1)+7+k].GetCppString();
4106 if(!str.empty())
4108 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4109 if(idx >= 0)
4111 if((int32)data.ObjectiveText[k].size() <= idx)
4112 data.ObjectiveText[k].resize(idx+1);
4114 data.ObjectiveText[k][idx] = str;
4119 } while (result->NextRow());
4121 delete result;
4123 sLog.outString();
4124 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4127 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4129 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4130 return;
4132 sLog.outString( "%s :", tablename);
4134 scripts.clear(); // need for reload support
4136 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
4138 uint32 count = 0;
4140 if( !result )
4142 barGoLink bar( 1 );
4143 bar.step();
4145 sLog.outString();
4146 sLog.outString( ">> Loaded %u script definitions", count );
4147 return;
4150 barGoLink bar( (int)result->GetRowCount() );
4154 bar.step();
4156 Field *fields = result->Fetch();
4157 ScriptInfo tmp;
4158 tmp.id = fields[0].GetUInt32();
4159 tmp.delay = fields[1].GetUInt32();
4160 tmp.command = fields[2].GetUInt32();
4161 tmp.datalong = fields[3].GetUInt32();
4162 tmp.datalong2 = fields[4].GetUInt32();
4163 tmp.dataint = fields[5].GetInt32();
4164 tmp.x = fields[6].GetFloat();
4165 tmp.y = fields[7].GetFloat();
4166 tmp.z = fields[8].GetFloat();
4167 tmp.o = fields[9].GetFloat();
4169 // generic command args check
4170 switch(tmp.command)
4172 case SCRIPT_COMMAND_TALK:
4174 if(tmp.datalong > 3)
4176 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4177 continue;
4179 if(tmp.dataint==0)
4181 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4182 continue;
4184 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4186 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);
4187 continue;
4190 // if(!GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4191 break;
4194 case SCRIPT_COMMAND_EMOTE:
4196 if(!sEmotesStore.LookupEntry(tmp.datalong))
4198 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4199 continue;
4201 break;
4204 case SCRIPT_COMMAND_TELEPORT_TO:
4206 if(!sMapStore.LookupEntry(tmp.datalong))
4208 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4209 continue;
4212 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4214 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);
4215 continue;
4217 break;
4220 case SCRIPT_COMMAND_KILL_CREDIT:
4222 if (!GetCreatureTemplate(tmp.datalong))
4224 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u",tablename,tmp.datalong,tmp.id);
4225 continue;
4227 break;
4230 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4232 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4234 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);
4235 continue;
4238 if(!GetCreatureTemplate(tmp.datalong))
4240 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4241 continue;
4243 break;
4246 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4248 GameObjectData const* data = GetGOData(tmp.datalong);
4249 if(!data)
4251 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4252 continue;
4255 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4256 if(!info)
4258 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);
4259 continue;
4262 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4263 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4264 info->type==GAMEOBJECT_TYPE_DOOR ||
4265 info->type==GAMEOBJECT_TYPE_BUTTON ||
4266 info->type==GAMEOBJECT_TYPE_TRAP )
4268 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4269 continue;
4271 break;
4273 case SCRIPT_COMMAND_OPEN_DOOR:
4274 case SCRIPT_COMMAND_CLOSE_DOOR:
4276 GameObjectData const* data = GetGOData(tmp.datalong);
4277 if(!data)
4279 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);
4280 continue;
4283 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4284 if(!info)
4286 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);
4287 continue;
4290 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4292 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);
4293 continue;
4296 break;
4298 case SCRIPT_COMMAND_QUEST_EXPLORED:
4300 Quest const* quest = GetQuestTemplate(tmp.datalong);
4301 if(!quest)
4303 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);
4304 continue;
4307 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4309 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);
4311 // this will prevent quest completing without objective
4312 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4314 // continue; - quest objective requirement set and command can be allowed
4317 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4319 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",
4320 tablename,tmp.datalong2,tmp.id);
4321 continue;
4324 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4326 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",
4327 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4328 continue;
4331 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4333 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",
4334 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4335 continue;
4338 break;
4341 case SCRIPT_COMMAND_REMOVE_AURA:
4343 if(!sSpellStore.LookupEntry(tmp.datalong))
4345 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4346 tablename,tmp.datalong,tmp.id);
4347 continue;
4349 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4351 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4352 tablename,tmp.datalong2,tmp.id);
4353 continue;
4355 break;
4357 case SCRIPT_COMMAND_CAST_SPELL:
4359 if(!sSpellStore.LookupEntry(tmp.datalong))
4361 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4362 tablename,tmp.datalong,tmp.id);
4363 continue;
4365 if(tmp.datalong2 & ~0x3) // 2 bits
4367 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4368 tablename,tmp.datalong2,tmp.id);
4369 continue;
4371 break;
4373 case SCRIPT_COMMAND_CREATE_ITEM:
4375 if (!GetItemPrototype(tmp.datalong))
4377 sLog.outErrorDb("Table `%s` has nonexistent item (entry: %u) in SCRIPT_COMMAND_CREATE_ITEM for script id %u",
4378 tablename, tmp.datalong, tmp.id);
4379 continue;
4381 if (!tmp.datalong2)
4383 sLog.outErrorDb("Table `%s` SCRIPT_COMMAND_CREATE_ITEM but amount is %u for script id %u",
4384 tablename, tmp.datalong2, tmp.id);
4385 continue;
4387 break;
4389 case SCRIPT_COMMAND_DESPAWN_SELF:
4391 // for later, we might consider despawn by database guid, and define in datalong2 as option to despawn self.
4392 break;
4396 if (scripts.find(tmp.id) == scripts.end())
4398 ScriptMap emptyMap;
4399 scripts[tmp.id] = emptyMap;
4401 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4403 ++count;
4404 } while( result->NextRow() );
4406 delete result;
4408 sLog.outString();
4409 sLog.outString( ">> Loaded %u script definitions", count );
4412 void ObjectMgr::LoadGameObjectScripts()
4414 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4416 // check ids
4417 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4419 if(!GetGOData(itr->first))
4420 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4424 void ObjectMgr::LoadQuestEndScripts()
4426 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4428 // check ids
4429 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4431 if(!GetQuestTemplate(itr->first))
4432 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4436 void ObjectMgr::LoadQuestStartScripts()
4438 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4440 // check ids
4441 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4443 if(!GetQuestTemplate(itr->first))
4444 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4448 void ObjectMgr::LoadSpellScripts()
4450 LoadScripts(sSpellScripts, "spell_scripts");
4452 // check ids
4453 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4455 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4457 if(!spellInfo)
4459 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4460 continue;
4463 //check for correct spellEffect
4464 bool found = false;
4465 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
4467 // skip empty effects
4468 if (!spellInfo->Effect[i])
4469 continue;
4471 if (spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT)
4473 found = true;
4474 break;
4478 if (!found)
4479 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4483 void ObjectMgr::LoadEventScripts()
4485 LoadScripts(sEventScripts, "event_scripts");
4487 std::set<uint32> evt_scripts;
4488 // Load all possible script entries from gameobjects
4489 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4491 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4492 if (goInfo)
4494 switch(goInfo->type)
4496 case GAMEOBJECT_TYPE_GOOBER:
4497 if (goInfo->goober.eventId)
4498 evt_scripts.insert(goInfo->goober.eventId);
4499 break;
4500 case GAMEOBJECT_TYPE_CHEST:
4501 if (goInfo->chest.eventId)
4502 evt_scripts.insert(goInfo->chest.eventId);
4503 break;
4504 case GAMEOBJECT_TYPE_CAMERA:
4505 if (goInfo->camera.eventID)
4506 evt_scripts.insert(goInfo->camera.eventID);
4507 default:
4508 break;
4512 // Load all possible script entries from spells
4513 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4515 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4516 if (spell)
4518 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
4520 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4522 if (spell->EffectMiscValue[j])
4523 evt_scripts.insert(spell->EffectMiscValue[j]);
4528 // Then check if all scripts are in above list of possible script entries
4529 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4531 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4532 if (itr2 == evt_scripts.end())
4533 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",
4534 itr->first, SPELL_EFFECT_SEND_EVENT);
4538 void ObjectMgr::LoadGossipScripts()
4540 LoadScripts(sGossipScripts, "gossip_scripts");
4542 // checks are done in LoadGossipMenuItems
4545 void ObjectMgr::LoadItemTexts()
4547 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4549 uint32 count = 0;
4551 if( !result )
4553 barGoLink bar( 1 );
4554 bar.step();
4556 sLog.outString();
4557 sLog.outString( ">> Loaded %u item pages", count );
4558 return;
4561 barGoLink bar( (int)result->GetRowCount() );
4563 Field* fields;
4566 bar.step();
4568 fields = result->Fetch();
4570 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4572 ++count;
4574 } while ( result->NextRow() );
4576 delete result;
4578 sLog.outString();
4579 sLog.outString( ">> Loaded %u item texts", count );
4582 void ObjectMgr::LoadPageTexts()
4584 sPageTextStore.Free(); // for reload case
4586 sPageTextStore.Load();
4587 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4588 sLog.outString();
4590 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4592 // check data correctness
4593 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4594 if(!page)
4595 continue;
4597 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4599 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4600 continue;
4603 // detect circular reference
4604 std::set<uint32> checkedPages;
4605 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4607 if(!pageItr->Next_Page)
4608 break;
4609 checkedPages.insert(pageItr->Page_ID);
4610 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4612 std::ostringstream ss;
4613 ss<< "The text page(s) ";
4614 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4615 ss << *itr << " ";
4616 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4617 << pageItr->Page_ID <<" to 0";
4618 sLog.outErrorDb("%s", ss.str().c_str());
4619 const_cast<PageText*>(pageItr)->Next_Page = 0;
4620 break;
4626 void ObjectMgr::LoadPageTextLocales()
4628 mPageTextLocaleMap.clear(); // need for reload case
4630 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");
4632 if(!result)
4634 barGoLink bar(1);
4636 bar.step();
4638 sLog.outString();
4639 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4640 return;
4643 barGoLink bar((int)result->GetRowCount());
4647 Field *fields = result->Fetch();
4648 bar.step();
4650 uint32 entry = fields[0].GetUInt32();
4652 PageTextLocale& data = mPageTextLocaleMap[entry];
4654 for(int i = 1; i < MAX_LOCALE; ++i)
4656 std::string str = fields[i].GetCppString();
4657 if(str.empty())
4658 continue;
4660 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4661 if(idx >= 0)
4663 if((int32)data.Text.size() <= idx)
4664 data.Text.resize(idx+1);
4666 data.Text[idx] = str;
4670 } while (result->NextRow());
4672 delete result;
4674 sLog.outString();
4675 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4678 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4680 template<class D>
4681 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4683 dst = D(sObjectMgr.GetScriptId(src));
4687 void ObjectMgr::LoadInstanceTemplate()
4689 SQLInstanceLoader loader;
4690 loader.Load(sInstanceTemplate);
4692 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4694 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4695 if(!temp)
4696 continue;
4698 if(!MapManager::IsValidMAP(temp->map))
4699 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4701 if(!MapManager::IsValidMapCoord(temp->parent,temp->startLocX,temp->startLocY,temp->startLocZ,temp->startLocO))
4703 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad parent entrance coordinates for map id %d template!", temp->map);
4704 temp->parent = 0; // will have wrong continent 0 parent, at least existed
4708 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4709 sLog.outString();
4712 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4714 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4715 if(itr != mGossipText.end())
4716 return &itr->second;
4717 return NULL;
4720 void ObjectMgr::LoadGossipText()
4722 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4724 int count = 0;
4725 if( !result )
4727 barGoLink bar( 1 );
4728 bar.step();
4730 sLog.outString();
4731 sLog.outString( ">> Loaded %u npc texts", count );
4732 return;
4735 int cic;
4737 barGoLink bar( (int)result->GetRowCount() );
4741 ++count;
4742 cic = 0;
4744 Field *fields = result->Fetch();
4746 bar.step();
4748 uint32 Text_ID = fields[cic++].GetUInt32();
4749 if(!Text_ID)
4751 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4752 continue;
4755 GossipText& gText = mGossipText[Text_ID];
4757 for (int i=0; i< 8; i++)
4759 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4760 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4762 gText.Options[i].Language = fields[cic++].GetUInt32();
4763 gText.Options[i].Probability = fields[cic++].GetFloat();
4765 for(int j=0; j < 3; ++j)
4767 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4768 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4771 } while( result->NextRow() );
4773 sLog.outString();
4774 sLog.outString( ">> Loaded %u npc texts", count );
4775 delete result;
4778 void ObjectMgr::LoadNpcTextLocales()
4780 mNpcTextLocaleMap.clear(); // need for reload case
4782 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4783 "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,"
4784 "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,"
4785 "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,"
4786 "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,"
4787 "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,"
4788 "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,"
4789 "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, "
4790 "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 "
4791 " FROM locales_npc_text");
4793 if(!result)
4795 barGoLink bar(1);
4797 bar.step();
4799 sLog.outString();
4800 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4801 return;
4804 barGoLink bar((int)result->GetRowCount());
4808 Field *fields = result->Fetch();
4809 bar.step();
4811 uint32 entry = fields[0].GetUInt32();
4813 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4815 for(int i=1; i<MAX_LOCALE; ++i)
4817 for(int j=0; j<8; ++j)
4819 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4820 if(!str0.empty())
4822 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4823 if(idx >= 0)
4825 if((int32)data.Text_0[j].size() <= idx)
4826 data.Text_0[j].resize(idx+1);
4828 data.Text_0[j][idx] = str0;
4831 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4832 if(!str1.empty())
4834 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4835 if(idx >= 0)
4837 if((int32)data.Text_1[j].size() <= idx)
4838 data.Text_1[j].resize(idx+1);
4840 data.Text_1[j][idx] = str1;
4845 } while (result->NextRow());
4847 delete result;
4849 sLog.outString();
4850 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4853 //not very fast function but it is called only once a day, or on starting-up
4854 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4856 time_t basetime = time(NULL);
4857 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4858 //delete all old mails without item and without body immediately, if starting server
4859 if (!serverUp)
4860 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4861 // 0 1 2 3 4 5 6 7 8 9
4862 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);
4863 if ( !result )
4865 barGoLink bar(1);
4866 bar.step();
4867 sLog.outString();
4868 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4869 return; // any mails need to be returned or deleted
4872 //std::ostringstream delitems, delmails; //will be here for optimization
4873 //bool deletemail = false, deleteitem = false;
4874 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4875 //delmails << "DELETE FROM mail WHERE id IN ( "
4877 barGoLink bar( (int)result->GetRowCount() );
4878 uint32 count = 0;
4879 Field *fields;
4883 bar.step();
4885 fields = result->Fetch();
4886 Mail *m = new Mail;
4887 m->messageID = fields[0].GetUInt32();
4888 m->messageType = fields[1].GetUInt8();
4889 m->sender = fields[2].GetUInt32();
4890 m->receiver = fields[3].GetUInt32();
4891 m->itemTextId = fields[4].GetUInt32();
4892 bool has_items = fields[5].GetBool();
4893 m->expire_time = (time_t)fields[6].GetUInt64();
4894 m->deliver_time = 0;
4895 m->COD = fields[7].GetUInt32();
4896 m->checked = fields[8].GetUInt32();
4897 m->mailTemplateId = fields[9].GetInt16();
4899 Player *pl = 0;
4900 if (serverUp)
4901 pl = GetPlayer((uint64)m->receiver);
4902 if (pl)
4903 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4904 //his in mailbox and he has already listed his mails )
4905 delete m;
4906 continue;
4908 //delete or return mail:
4909 if (has_items)
4911 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4912 if(resultItems)
4916 Field *fields2 = resultItems->Fetch();
4918 uint32 item_guid_low = fields2[0].GetUInt32();
4919 uint32 item_template = fields2[1].GetUInt32();
4921 m->AddItem(item_guid_low, item_template);
4923 while (resultItems->NextRow());
4925 delete resultItems;
4927 //if it is mail from AH, it shouldn't be returned, but deleted
4928 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4930 // mail open and then not returned
4931 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4932 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4934 else
4936 //mail will be returned:
4937 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);
4938 delete m;
4939 continue;
4943 if (m->itemTextId)
4944 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4946 //deletemail = true;
4947 //delmails << m->messageID << ", ";
4948 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4949 delete m;
4950 ++count;
4951 } while (result->NextRow());
4952 delete result;
4954 sLog.outString();
4955 sLog.outString( ">> Loaded %u mails", count );
4958 void ObjectMgr::LoadQuestAreaTriggers()
4960 mQuestAreaTriggerMap.clear(); // need for reload case
4962 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4964 uint32 count = 0;
4966 if( !result )
4968 barGoLink bar( 1 );
4969 bar.step();
4971 sLog.outString();
4972 sLog.outString( ">> Loaded %u quest trigger points", count );
4973 return;
4976 barGoLink bar((int) result->GetRowCount() );
4980 ++count;
4981 bar.step();
4983 Field *fields = result->Fetch();
4985 uint32 trigger_ID = fields[0].GetUInt32();
4986 uint32 quest_ID = fields[1].GetUInt32();
4988 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4989 if(!atEntry)
4991 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4992 continue;
4995 Quest const* quest = GetQuestTemplate(quest_ID);
4997 if(!quest)
4999 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
5000 continue;
5003 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
5005 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);
5007 // this will prevent quest completing without objective
5008 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
5010 // continue; - quest modified to required objective and trigger can be allowed.
5013 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
5015 } while( result->NextRow() );
5017 delete result;
5019 sLog.outString();
5020 sLog.outString( ">> Loaded %u quest trigger points", count );
5023 void ObjectMgr::LoadTavernAreaTriggers()
5025 mTavernAreaTriggerSet.clear(); // need for reload case
5027 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
5029 uint32 count = 0;
5031 if( !result )
5033 barGoLink bar( 1 );
5034 bar.step();
5036 sLog.outString();
5037 sLog.outString( ">> Loaded %u tavern triggers", count );
5038 return;
5041 barGoLink bar( (int)result->GetRowCount() );
5045 ++count;
5046 bar.step();
5048 Field *fields = result->Fetch();
5050 uint32 Trigger_ID = fields[0].GetUInt32();
5052 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5053 if(!atEntry)
5055 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5056 continue;
5059 mTavernAreaTriggerSet.insert(Trigger_ID);
5060 } while( result->NextRow() );
5062 delete result;
5064 sLog.outString();
5065 sLog.outString( ">> Loaded %u tavern triggers", count );
5068 void ObjectMgr::LoadAreaTriggerScripts()
5070 mAreaTriggerScripts.clear(); // need for reload case
5071 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
5073 uint32 count = 0;
5075 if( !result )
5077 barGoLink bar( 1 );
5078 bar.step();
5080 sLog.outString();
5081 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5082 return;
5085 barGoLink bar( (int)result->GetRowCount() );
5089 ++count;
5090 bar.step();
5092 Field *fields = result->Fetch();
5094 uint32 Trigger_ID = fields[0].GetUInt32();
5095 const char *scriptName = fields[1].GetString();
5097 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5098 if(!atEntry)
5100 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5101 continue;
5103 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
5104 } while( result->NextRow() );
5106 delete result;
5108 sLog.outString();
5109 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5112 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
5114 bool found = false;
5115 float dist;
5116 uint32 id = 0;
5118 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
5120 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
5121 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
5122 continue;
5124 uint8 field = (uint8)((i - 1) / 32);
5125 uint32 submask = 1<<((i-1)%32);
5127 // skip not taxi network nodes
5128 if((sTaxiNodesMask[field] & submask)==0)
5129 continue;
5131 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5132 if(found)
5134 if(dist2 < dist)
5136 dist = dist2;
5137 id = i;
5140 else
5142 found = true;
5143 dist = dist2;
5144 id = i;
5148 return id;
5151 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5153 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5154 if(src_i==sTaxiPathSetBySource.end())
5156 path = 0;
5157 cost = 0;
5158 return;
5161 TaxiPathSetForSource& pathSet = src_i->second;
5163 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5164 if(dest_i==pathSet.end())
5166 path = 0;
5167 cost = 0;
5168 return;
5171 cost = dest_i->second.price;
5172 path = dest_i->second.ID;
5175 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5177 uint16 mount_entry = 0;
5179 // select mount creature id
5180 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5181 if(node)
5183 if (team == ALLIANCE)
5185 mount_entry = node->MountCreatureID[1];
5186 if(!mount_entry && allowed_alt_team)
5187 mount_entry = node->MountCreatureID[0];
5189 else if (team == HORDE)
5191 mount_entry = node->MountCreatureID[0];
5193 if(!mount_entry && allowed_alt_team)
5194 mount_entry = node->MountCreatureID[1];
5198 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5199 if (!mount_info)
5200 return 0;
5202 uint16 mount_id = ChooseDisplayId(team,mount_info);
5203 if (!mount_id)
5204 return 0;
5206 CreatureModelInfo const *minfo = GetCreatureModelRandomGender(mount_id);
5207 if (minfo)
5208 mount_id = minfo->modelid;
5210 return mount_id;
5213 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5215 if(path >= sTaxiPathNodesByPath.size())
5216 return;
5218 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5220 pathnodes.Resize(nodeList.size());
5221 mapIds.resize(nodeList.size());
5223 for(size_t i = 0; i < nodeList.size(); ++i)
5225 pathnodes[ i ].x = nodeList[i].x;
5226 pathnodes[ i ].y = nodeList[i].y;
5227 pathnodes[ i ].z = nodeList[i].z;
5229 mapIds[i] = nodeList[i].mapid;
5233 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5235 if(path >= sTaxiPathNodesByPath.size())
5236 return;
5238 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5240 pathnodes.Resize(nodeList.size());
5242 for(size_t i = 0; i < nodeList.size(); ++i)
5244 pathnodes[ i ].mapid = nodeList[i].mapid;
5245 pathnodes[ i ].x = nodeList[i].x;
5246 pathnodes[ i ].y = nodeList[i].y;
5247 pathnodes[ i ].z = nodeList[i].z;
5248 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5249 pathnodes[ i ].delay = nodeList[i].delay;
5253 void ObjectMgr::LoadGraveyardZones()
5255 mGraveYardMap.clear(); // need for reload case
5257 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5259 uint32 count = 0;
5261 if( !result )
5263 barGoLink bar( 1 );
5264 bar.step();
5266 sLog.outString();
5267 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5268 return;
5271 barGoLink bar( (int)result->GetRowCount() );
5275 ++count;
5276 bar.step();
5278 Field *fields = result->Fetch();
5280 uint32 safeLocId = fields[0].GetUInt32();
5281 uint32 zoneId = fields[1].GetUInt32();
5282 uint32 team = fields[2].GetUInt32();
5284 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5285 if(!entry)
5287 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5288 continue;
5291 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5292 if(!areaEntry)
5294 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5295 continue;
5298 if(areaEntry->zone != 0)
5300 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5301 continue;
5304 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5306 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5307 continue;
5310 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5311 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5312 } while( result->NextRow() );
5314 delete result;
5316 sLog.outString();
5317 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5320 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5322 // search for zone associated closest graveyard
5323 uint32 zoneId = sMapMgr.GetZoneId(MapId,x,y,z);
5325 // Simulate std. algorithm:
5326 // found some graveyard associated to (ghost_zone,ghost_map)
5328 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5329 // then check faction
5330 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5331 // then check faction
5332 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5333 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5334 if(graveLow==graveUp)
5336 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5337 return NULL;
5340 // at corpse map
5341 bool foundNear = false;
5342 float distNear;
5343 WorldSafeLocsEntry const* entryNear = NULL;
5345 // at entrance map for corpse map
5346 bool foundEntr = false;
5347 float distEntr;
5348 WorldSafeLocsEntry const* entryEntr = NULL;
5350 // some where other
5351 WorldSafeLocsEntry const* entryFar = NULL;
5353 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5355 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5357 GraveYardData const& data = itr->second;
5359 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5360 if(!entry)
5362 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5363 continue;
5366 // skip enemy faction graveyard
5367 // team == 0 case can be at call from .neargrave
5368 if(data.team != 0 && team != 0 && data.team != team)
5369 continue;
5371 // find now nearest graveyard at other map
5372 if(MapId != entry->map_id)
5374 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5375 if (!mapEntry ||
5376 mapEntry->entrance_map < 0 ||
5377 mapEntry->entrance_map != entry->map_id ||
5378 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5380 // not have any corrdinates for check distance anyway
5381 entryFar = entry;
5382 continue;
5385 // at entrance map calculate distance (2D);
5386 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5387 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5388 if(foundEntr)
5390 if(dist2 < distEntr)
5392 distEntr = dist2;
5393 entryEntr = entry;
5396 else
5398 foundEntr = true;
5399 distEntr = dist2;
5400 entryEntr = entry;
5403 // find now nearest graveyard at same map
5404 else
5406 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5407 if(foundNear)
5409 if(dist2 < distNear)
5411 distNear = dist2;
5412 entryNear = entry;
5415 else
5417 foundNear = true;
5418 distNear = dist2;
5419 entryNear = entry;
5424 if(entryNear)
5425 return entryNear;
5427 if(entryEntr)
5428 return entryEntr;
5430 return entryFar;
5433 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5435 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5436 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5438 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5440 if(itr->second.safeLocId==id)
5441 return &itr->second;
5444 return NULL;
5447 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5449 if(FindGraveYardData(id,zoneId))
5450 return false;
5452 // add link to loaded data
5453 GraveYardData data;
5454 data.safeLocId = id;
5455 data.team = team;
5457 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5459 // add link to DB
5460 if(inDB)
5462 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5463 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5466 return true;
5469 void ObjectMgr::LoadAreaTriggerTeleports()
5471 mAreaTriggers.clear(); // need for reload case
5473 uint32 count = 0;
5475 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5476 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");
5477 if( !result )
5480 barGoLink bar( 1 );
5482 bar.step();
5484 sLog.outString();
5485 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5486 return;
5489 barGoLink bar( (int)result->GetRowCount() );
5493 Field *fields = result->Fetch();
5495 bar.step();
5497 ++count;
5499 uint32 Trigger_ID = fields[0].GetUInt32();
5501 AreaTrigger at;
5503 at.requiredLevel = fields[1].GetUInt8();
5504 at.requiredItem = fields[2].GetUInt32();
5505 at.requiredItem2 = fields[3].GetUInt32();
5506 at.heroicKey = fields[4].GetUInt32();
5507 at.heroicKey2 = fields[5].GetUInt32();
5508 at.requiredQuest = fields[6].GetUInt32();
5509 at.requiredQuestHeroic = fields[7].GetUInt32();
5510 at.requiredFailedText = fields[8].GetCppString();
5511 at.target_mapId = fields[9].GetUInt32();
5512 at.target_X = fields[10].GetFloat();
5513 at.target_Y = fields[11].GetFloat();
5514 at.target_Z = fields[12].GetFloat();
5515 at.target_Orientation = fields[13].GetFloat();
5517 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5518 if(!atEntry)
5520 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5521 continue;
5524 if(at.requiredItem)
5526 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5527 if(!pProto)
5529 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5530 at.requiredItem = 0;
5533 if(at.requiredItem2)
5535 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5536 if(!pProto)
5538 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5539 at.requiredItem2 = 0;
5543 if(at.heroicKey)
5545 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5546 if(!pProto)
5548 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5549 at.heroicKey = 0;
5553 if(at.heroicKey2)
5555 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5556 if(!pProto)
5558 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5559 at.heroicKey2 = 0;
5563 if(at.requiredQuest)
5565 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5566 if(qReqItr == mQuestTemplates.end())
5568 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5569 at.requiredQuest = 0;
5573 if(at.requiredQuestHeroic)
5575 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5576 if(qReqItr == mQuestTemplates.end())
5578 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5579 at.requiredQuestHeroic = 0;
5583 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5584 if(!mapEntry)
5586 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5587 continue;
5590 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5592 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5593 continue;
5596 mAreaTriggers[Trigger_ID] = at;
5598 } while( result->NextRow() );
5600 delete result;
5602 sLog.outString();
5603 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5607 * Searches for the areatrigger which teleports players out of the given map
5609 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5611 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5612 if(!mapEntry) return NULL;
5613 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5615 if(itr->second.target_mapId == mapEntry->entrance_map)
5617 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5618 if(atEntry && atEntry->mapid == Map)
5619 return &itr->second;
5622 return NULL;
5626 * Searches for the areatrigger which teleports players to the given map
5628 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5630 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5632 if(itr->second.target_mapId == Map)
5634 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5635 if(atEntry)
5636 return &itr->second;
5639 return NULL;
5642 void ObjectMgr::PackGroupIds()
5644 // this routine renumbers groups in such a way so they start from 1 and go up
5646 // obtain set of all groups
5647 std::set<uint32> groupIds;
5649 // all valid ids are in the instance table
5650 // any associations to ids not in this table are assumed to be
5651 // cleaned already in CleanupInstances
5652 QueryResult *result = CharacterDatabase.Query("SELECT groupId FROM groups");
5653 if( result )
5657 Field *fields = result->Fetch();
5659 uint32 id = fields[0].GetUInt32();
5661 if (id == 0)
5663 CharacterDatabase.PExecute("DELETE FROM groups WHERE groupId = '%u'", id);
5664 CharacterDatabase.PExecute("DELETE FROM group_member WHERE groupId = '%u'", id);
5665 continue;
5668 groupIds.insert(id);
5670 while (result->NextRow());
5671 delete result;
5674 barGoLink bar( groupIds.size() + 1);
5675 bar.step();
5677 uint32 groupId = 1;
5678 // we do assume std::set is sorted properly on integer value
5679 for (std::set<uint32>::iterator i = groupIds.begin(); i != groupIds.end(); ++i)
5681 if (*i != groupId)
5683 // remap group id
5684 CharacterDatabase.PExecute("UPDATE groups SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5685 CharacterDatabase.PExecute("UPDATE group_member SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5688 ++groupId;
5689 bar.step();
5692 m_GroupIds.Set(groupId);
5694 sLog.outString( ">> Group Ids remapped, next group id is %u", groupId );
5695 sLog.outString();
5698 void ObjectMgr::SetHighestGuids()
5700 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5701 if( result )
5703 m_CharGuids.Set((*result)[0].GetUInt32()+1);
5704 delete result;
5707 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5708 if( result )
5710 m_CreatureGuids.Set((*result)[0].GetUInt32()+1);
5711 delete result;
5714 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5715 if( result )
5717 m_ItemGuids.Set((*result)[0].GetUInt32()+1);
5718 delete result;
5721 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5722 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5723 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5724 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5725 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5727 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5728 if( result )
5730 m_GameobjectGuids.Set((*result)[0].GetUInt32()+1);
5731 delete result;
5734 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5735 if( result )
5737 m_AuctionIds.Set((*result)[0].GetUInt32()+1);
5738 delete result;
5741 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5742 if( result )
5744 m_MailIds.Set((*result)[0].GetUInt32()+1);
5745 delete result;
5748 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5749 if( result )
5751 m_ItemTextIds.Set((*result)[0].GetUInt32()+1);
5752 delete result;
5755 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5756 if( result )
5758 m_CorpseGuids.Set((*result)[0].GetUInt32()+1);
5759 delete result;
5762 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5763 if (result)
5765 m_ArenaTeamIds.Set((*result)[0].GetUInt32()+1);
5766 delete result;
5769 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5770 if (result)
5772 m_EquipmentSetIds.Set((*result)[0].GetUInt64()+1);
5773 delete result;
5776 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5777 if (result)
5779 m_GuildIds.Set((*result)[0].GetUInt32()+1);
5780 delete result;
5783 result = CharacterDatabase.Query( "SELECT MAX(groupId) FROM groups" );
5784 if (result)
5786 m_GroupIds.Set((*result)[0].GetUInt32()+1);
5787 delete result;
5791 uint32 ObjectMgr::CreateItemText(std::string text)
5793 uint32 newItemTextId = GenerateItemTextID();
5794 //insert new itempage to container
5795 mItemTexts[ newItemTextId ] = text;
5796 //save new itempage
5797 CharacterDatabase.escape_string(text);
5798 //any Delete query needed, itemTextId is maximum of all ids
5799 std::ostringstream query;
5800 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5801 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5802 return newItemTextId;
5805 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5807 switch(guidhigh)
5809 case HIGHGUID_ITEM:
5810 return m_ItemGuids.Generate();
5811 case HIGHGUID_UNIT:
5812 return m_CreatureGuids.Generate();
5813 case HIGHGUID_PLAYER:
5814 return m_CharGuids.Generate();
5815 case HIGHGUID_GAMEOBJECT:
5816 return m_GameobjectGuids.Generate();
5817 case HIGHGUID_CORPSE:
5818 return m_CorpseGuids.Generate();
5819 default:
5820 ASSERT(0);
5823 ASSERT(0);
5824 return 0;
5827 void ObjectMgr::LoadGameObjectLocales()
5829 mGameObjectLocaleMap.clear(); // need for reload case
5831 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5832 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5833 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5834 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5836 if(!result)
5838 barGoLink bar(1);
5840 bar.step();
5842 sLog.outString();
5843 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5844 return;
5847 barGoLink bar((int)result->GetRowCount());
5851 Field *fields = result->Fetch();
5852 bar.step();
5854 uint32 entry = fields[0].GetUInt32();
5856 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5858 for(int i = 1; i < MAX_LOCALE; ++i)
5860 std::string str = fields[i].GetCppString();
5861 if(!str.empty())
5863 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5864 if(idx >= 0)
5866 if((int32)data.Name.size() <= idx)
5867 data.Name.resize(idx+1);
5869 data.Name[idx] = str;
5874 for(int i = 1; i < MAX_LOCALE; ++i)
5876 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5877 if(!str.empty())
5879 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5880 if(idx >= 0)
5882 if((int32)data.CastBarCaption.size() <= idx)
5883 data.CastBarCaption.resize(idx+1);
5885 data.CastBarCaption[idx] = str;
5890 } while (result->NextRow());
5892 delete result;
5894 sLog.outString();
5895 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5898 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5900 template<class D>
5901 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5903 dst = D(sObjectMgr.GetScriptId(src));
5907 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5909 if (sLockStore.LookupEntry(dataN))
5910 return;
5912 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5913 goInfo->id,goInfo->type,N,dataN,dataN);
5916 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5918 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5920 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5921 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5922 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5924 /* disable check for while (too many error reports baout not existed in trap templates
5925 else
5926 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5927 goInfo->id,goInfo->type,N,dataN,dataN);
5931 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5933 if (sSpellStore.LookupEntry(dataN))
5934 return;
5936 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5937 goInfo->id,goInfo->type,N,dataN,dataN);
5940 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5942 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5943 return;
5945 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5946 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5948 // prevent client and server unexpected work
5949 const_cast<uint32&>(dataN) = 0;
5952 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5954 // 0/1 correct values
5955 if (dataN <= 1)
5956 return;
5958 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5959 goInfo->id,goInfo->type,N,dataN);
5962 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5964 // 0/1 correct values
5965 if (dataN <= 1)
5966 return;
5968 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5969 goInfo->id,goInfo->type,N,dataN);
5972 void ObjectMgr::LoadGameobjectInfo()
5974 SQLGameObjectLoader loader;
5975 loader.Load(sGOStorage);
5977 // some checks
5978 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5980 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5981 if (!goInfo)
5982 continue;
5984 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5986 switch(goInfo->type)
5988 case GAMEOBJECT_TYPE_DOOR: //0
5990 if (goInfo->door.lockId)
5991 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5992 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5993 break;
5995 case GAMEOBJECT_TYPE_BUTTON: //1
5997 if (goInfo->button.lockId)
5998 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5999 if (goInfo->button.linkedTrapId) // linked trap
6000 CheckGOLinkedTrapId(goInfo,goInfo->button.linkedTrapId,3);
6001 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
6002 break;
6004 case GAMEOBJECT_TYPE_QUESTGIVER: //2
6006 if (goInfo->questgiver.lockId)
6007 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
6008 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
6009 break;
6011 case GAMEOBJECT_TYPE_CHEST: //3
6013 if (goInfo->chest.lockId)
6014 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
6016 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
6018 if (goInfo->chest.linkedTrapId) // linked trap
6019 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
6020 break;
6022 case GAMEOBJECT_TYPE_TRAP: //6
6024 if (goInfo->trap.lockId)
6025 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
6026 /* disable check for while, too many not existed spells
6027 if (goInfo->trap.spellId) // spell
6028 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
6030 break;
6032 case GAMEOBJECT_TYPE_CHAIR: //7
6033 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
6034 break;
6035 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
6037 if (goInfo->spellFocus.focusId)
6039 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
6040 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
6041 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
6044 if (goInfo->spellFocus.linkedTrapId) // linked trap
6045 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
6046 break;
6048 case GAMEOBJECT_TYPE_GOOBER: //10
6050 if (goInfo->goober.lockId)
6051 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
6053 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
6055 if (goInfo->goober.pageId) // pageId
6057 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
6058 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
6059 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
6061 /* disable check for while, too many not existed spells
6062 if (goInfo->goober.spellId) // spell
6063 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
6065 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
6066 if (goInfo->goober.linkedTrapId) // linked trap
6067 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
6068 break;
6070 case GAMEOBJECT_TYPE_AREADAMAGE: //12
6072 if (goInfo->areadamage.lockId)
6073 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
6074 break;
6076 case GAMEOBJECT_TYPE_CAMERA: //13
6078 if (goInfo->camera.lockId)
6079 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
6080 break;
6082 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
6084 if (goInfo->moTransport.taxiPathId)
6086 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
6087 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
6088 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
6090 break;
6092 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
6094 /* disable check for while, too many not existed spells
6095 // always must have spell
6096 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
6098 break;
6100 case GAMEOBJECT_TYPE_SPELLCASTER: //22
6102 // always must have spell
6103 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
6104 break;
6106 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6108 if (goInfo->flagstand.lockId)
6109 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6110 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6111 break;
6113 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6115 if (goInfo->fishinghole.lockId)
6116 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6117 break;
6119 case GAMEOBJECT_TYPE_FLAGDROP: //26
6121 if (goInfo->flagdrop.lockId)
6122 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6123 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6124 break;
6126 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6127 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6128 break;
6132 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6133 sLog.outString();
6136 void ObjectMgr::LoadExplorationBaseXP()
6138 uint32 count = 0;
6139 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6141 if( !result )
6143 barGoLink bar( 1 );
6145 bar.step();
6147 sLog.outString();
6148 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6149 return;
6152 barGoLink bar( (int)result->GetRowCount() );
6156 bar.step();
6158 Field *fields = result->Fetch();
6159 uint32 level = fields[0].GetUInt32();
6160 uint32 basexp = fields[1].GetUInt32();
6161 mBaseXPTable[level] = basexp;
6162 ++count;
6164 while (result->NextRow());
6166 delete result;
6168 sLog.outString();
6169 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6172 uint32 ObjectMgr::GetBaseXP(uint32 level) const
6174 BaseXPMap::const_iterator itr = mBaseXPTable.find(level);
6175 return itr != mBaseXPTable.end() ? itr->second : 0;
6178 uint32 ObjectMgr::GetXPForLevel(uint32 level) const
6180 if (level < mPlayerXPperLevel.size())
6181 return mPlayerXPperLevel[level];
6182 return 0;
6185 void ObjectMgr::LoadPetNames()
6187 uint32 count = 0;
6188 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6190 if( !result )
6192 barGoLink bar( 1 );
6194 bar.step();
6196 sLog.outString();
6197 sLog.outString( ">> Loaded %u pet name parts", count );
6198 return;
6201 barGoLink bar( (int)result->GetRowCount() );
6205 bar.step();
6207 Field *fields = result->Fetch();
6208 std::string word = fields[0].GetString();
6209 uint32 entry = fields[1].GetUInt32();
6210 bool half = fields[2].GetBool();
6211 if(half)
6212 PetHalfName1[entry].push_back(word);
6213 else
6214 PetHalfName0[entry].push_back(word);
6215 ++count;
6217 while (result->NextRow());
6218 delete result;
6220 sLog.outString();
6221 sLog.outString( ">> Loaded %u pet name parts", count );
6224 void ObjectMgr::LoadPetNumber()
6226 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6227 if(result)
6229 Field *fields = result->Fetch();
6230 m_PetNumbers.Set(fields[0].GetUInt32()+1);
6231 delete result;
6234 barGoLink bar( 1 );
6235 bar.step();
6237 sLog.outString();
6238 sLog.outString( ">> Loaded the max pet number: %d", m_PetNumbers.GetNextAfterMaxUsed()-1);
6241 std::string ObjectMgr::GeneratePetName(uint32 entry)
6243 std::vector<std::string> & list0 = PetHalfName0[entry];
6244 std::vector<std::string> & list1 = PetHalfName1[entry];
6246 if(list0.empty() || list1.empty())
6248 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6249 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6250 if(!petname)
6251 petname = cinfo->Name;
6252 return std::string(petname);
6255 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6258 void ObjectMgr::LoadCorpses()
6260 uint32 count = 0;
6261 // 0 1 2 3 4 5 6 7 8 10
6262 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");
6264 if( !result )
6266 barGoLink bar( 1 );
6268 bar.step();
6270 sLog.outString();
6271 sLog.outString( ">> Loaded %u corpses", count );
6272 return;
6275 barGoLink bar( (int)result->GetRowCount() );
6279 bar.step();
6281 Field *fields = result->Fetch();
6283 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6285 Corpse *corpse = new Corpse;
6286 if(!corpse->LoadFromDB(guid,fields))
6288 delete corpse;
6289 continue;
6292 sObjectAccessor.AddCorpse(corpse);
6294 ++count;
6296 while (result->NextRow());
6297 delete result;
6299 sLog.outString();
6300 sLog.outString( ">> Loaded %u corpses", count );
6303 void ObjectMgr::LoadReputationOnKill()
6305 uint32 count = 0;
6307 // 0 1 2
6308 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6309 // 3 4 5 6 7 8 9
6310 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6311 "FROM creature_onkill_reputation");
6313 if(!result)
6315 barGoLink bar(1);
6317 bar.step();
6319 sLog.outString();
6320 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6321 return;
6324 barGoLink bar((int)result->GetRowCount());
6328 Field *fields = result->Fetch();
6329 bar.step();
6331 uint32 creature_id = fields[0].GetUInt32();
6333 ReputationOnKillEntry repOnKill;
6334 repOnKill.repfaction1 = fields[1].GetUInt32();
6335 repOnKill.repfaction2 = fields[2].GetUInt32();
6336 repOnKill.is_teamaward1 = fields[3].GetBool();
6337 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6338 repOnKill.repvalue1 = fields[5].GetInt32();
6339 repOnKill.is_teamaward2 = fields[6].GetBool();
6340 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6341 repOnKill.repvalue2 = fields[8].GetInt32();
6342 repOnKill.team_dependent = fields[9].GetUInt8();
6344 if(!GetCreatureTemplate(creature_id))
6346 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6347 continue;
6350 if(repOnKill.repfaction1)
6352 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6353 if(!factionEntry1)
6355 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6356 continue;
6360 if(repOnKill.repfaction2)
6362 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6363 if(!factionEntry2)
6365 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6366 continue;
6370 mRepOnKill[creature_id] = repOnKill;
6372 ++count;
6373 } while (result->NextRow());
6375 delete result;
6377 sLog.outString();
6378 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6381 void ObjectMgr::LoadPointsOfInterest()
6383 mPointsOfInterest.clear(); // need for reload case
6385 uint32 count = 0;
6387 // 0 1 2 3 4 5
6388 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6390 if(!result)
6392 barGoLink bar(1);
6394 bar.step();
6396 sLog.outString();
6397 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6398 return;
6401 barGoLink bar((int)result->GetRowCount());
6405 Field *fields = result->Fetch();
6406 bar.step();
6408 uint32 point_id = fields[0].GetUInt32();
6410 PointOfInterest POI;
6411 POI.x = fields[1].GetFloat();
6412 POI.y = fields[2].GetFloat();
6413 POI.icon = fields[3].GetUInt32();
6414 POI.flags = fields[4].GetUInt32();
6415 POI.data = fields[5].GetUInt32();
6416 POI.icon_name = fields[6].GetCppString();
6418 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6420 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6421 continue;
6424 mPointsOfInterest[point_id] = POI;
6426 ++count;
6427 } while (result->NextRow());
6429 delete result;
6431 sLog.outString();
6432 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6435 void ObjectMgr::LoadQuestPOI()
6437 mQuestPOIMap.clear(); // need for reload case
6439 uint32 count = 0;
6441 // 0 1 2 3 4 5 6
6442 QueryResult *result = WorldDatabase.Query("SELECT questId, objIndex, mapId, unk1, unk2, unk3, unk4 FROM quest_poi");
6444 if(!result)
6446 barGoLink bar(1);
6448 bar.step();
6450 sLog.outString();
6451 sLog.outErrorDb(">> Loaded 0 quest POI definitions. DB table `quest_poi` is empty.");
6452 return;
6455 barGoLink bar((int)result->GetRowCount());
6459 Field *fields = result->Fetch();
6460 bar.step();
6462 uint32 questId = fields[0].GetUInt32();
6463 int32 objIndex = fields[1].GetInt32();
6464 uint32 mapId = fields[2].GetUInt32();
6465 uint32 unk1 = fields[3].GetUInt32();
6466 uint32 unk2 = fields[4].GetUInt32();
6467 uint32 unk3 = fields[5].GetUInt32();
6468 uint32 unk4 = fields[6].GetUInt32();
6470 QuestPOI POI(objIndex, mapId, unk1, unk2, unk3, unk4);
6472 QueryResult *points = WorldDatabase.PQuery("SELECT x, y FROM quest_poi_points WHERE questId='%u' AND objIndex='%i'", questId, objIndex);
6474 if(points)
6478 Field *pointFields = points->Fetch();
6479 int32 x = pointFields[0].GetInt32();
6480 int32 y = pointFields[1].GetInt32();
6481 QuestPOIPoint point(x, y);
6482 POI.points.push_back(point);
6483 } while (points->NextRow());
6485 delete points;
6488 mQuestPOIMap[questId].push_back(POI);
6490 ++count;
6491 } while (result->NextRow());
6493 delete result;
6495 sLog.outString();
6496 sLog.outString(">> Loaded %u quest POI definitions", count);
6499 void ObjectMgr::LoadNPCSpellClickSpells()
6501 uint32 count = 0;
6503 mSpellClickInfoMap.clear();
6504 // 0 1 2 3 4 5
6505 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6507 if(!result)
6509 barGoLink bar(1);
6511 bar.step();
6513 sLog.outString();
6514 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6515 return;
6518 barGoLink bar((int)result->GetRowCount());
6522 Field *fields = result->Fetch();
6523 bar.step();
6525 uint32 npc_entry = fields[0].GetUInt32();
6526 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6527 if (!cInfo)
6529 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6530 continue;
6533 uint32 spellid = fields[1].GetUInt32();
6534 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6535 if (!spellinfo)
6537 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6538 continue;
6541 uint32 quest_start = fields[2].GetUInt32();
6543 // quest might be 0 to enable spellclick independent of any quest
6544 if (quest_start)
6546 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6548 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6549 continue;
6554 bool quest_start_active = fields[3].GetBool();
6556 uint32 quest_end = fields[4].GetUInt32();
6557 // quest might be 0 to enable spellclick active infinity after start quest
6558 if (quest_end)
6560 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6562 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6563 continue;
6568 uint8 castFlags = fields[5].GetUInt8();
6569 SpellClickInfo info;
6570 info.spellId = spellid;
6571 info.questStart = quest_start;
6572 info.questStartCanActive = quest_start_active;
6573 info.questEnd = quest_end;
6574 info.castFlags = castFlags;
6575 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6577 // mark creature template as spell clickable
6578 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6580 ++count;
6581 } while (result->NextRow());
6583 delete result;
6585 sLog.outString();
6586 sLog.outString(">> Loaded %u spellclick definitions", count);
6589 void ObjectMgr::LoadWeatherZoneChances()
6591 uint32 count = 0;
6593 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6594 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");
6596 if(!result)
6598 barGoLink bar(1);
6600 bar.step();
6602 sLog.outString();
6603 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6604 return;
6607 barGoLink bar((int)result->GetRowCount());
6611 Field *fields = result->Fetch();
6612 bar.step();
6614 uint32 zone_id = fields[0].GetUInt32();
6616 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6618 for(int season = 0; season < WEATHER_SEASONS; ++season)
6620 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6621 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6622 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6624 if(wzc.data[season].rainChance > 100)
6626 wzc.data[season].rainChance = 25;
6627 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6630 if(wzc.data[season].snowChance > 100)
6632 wzc.data[season].snowChance = 25;
6633 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6636 if(wzc.data[season].stormChance > 100)
6638 wzc.data[season].stormChance = 25;
6639 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6643 ++count;
6644 } while (result->NextRow());
6646 delete result;
6648 sLog.outString();
6649 sLog.outString(">> Loaded %u weather definitions", count);
6652 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6654 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6655 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6656 if(t)
6657 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6660 void ObjectMgr::DeleteCreatureData(uint32 guid)
6662 // remove mapid*cellid -> guid_set map
6663 CreatureData const* data = GetCreatureData(guid);
6664 if(data)
6665 RemoveCreatureFromGrid(guid, data);
6667 mCreatureDataMap.erase(guid);
6670 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6672 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6673 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6674 if(t)
6675 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6678 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6680 RespawnTimes::iterator next;
6682 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6684 next = itr;
6685 ++next;
6687 if(GUID_HIPART(itr->first)==instance)
6688 mGORespawnTimes.erase(itr);
6691 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6693 next = itr;
6694 ++next;
6696 if(GUID_HIPART(itr->first)==instance)
6697 mCreatureRespawnTimes.erase(itr);
6700 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6701 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6704 void ObjectMgr::DeleteGOData(uint32 guid)
6706 // remove mapid*cellid -> guid_set map
6707 GameObjectData const* data = GetGOData(guid);
6708 if(data)
6709 RemoveGameobjectFromGrid(guid, data);
6711 mGameObjectDataMap.erase(guid);
6714 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6716 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6717 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6718 cell_guids.corpses[player_guid] = instance;
6721 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6723 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6724 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6725 cell_guids.corpses.erase(player_guid);
6728 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6730 map.clear(); // need for reload case
6732 uint32 count = 0;
6734 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6736 if(!result)
6738 barGoLink bar(1);
6740 bar.step();
6742 sLog.outString();
6743 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6744 return;
6747 barGoLink bar((int)result->GetRowCount());
6751 Field *fields = result->Fetch();
6752 bar.step();
6754 uint32 id = fields[0].GetUInt32();
6755 uint32 quest = fields[1].GetUInt32();
6757 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6759 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6760 continue;
6763 map.insert(QuestRelations::value_type(id,quest));
6765 ++count;
6766 } while (result->NextRow());
6768 delete result;
6770 sLog.outString();
6771 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6774 void ObjectMgr::LoadGameobjectQuestRelations()
6776 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6778 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6780 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6781 if(!goInfo)
6782 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6783 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6784 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6788 void ObjectMgr::LoadGameobjectInvolvedRelations()
6790 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6792 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6794 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6795 if(!goInfo)
6796 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6797 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6798 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6802 void ObjectMgr::LoadCreatureQuestRelations()
6804 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6806 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6808 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6809 if(!cInfo)
6810 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6811 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6812 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);
6816 void ObjectMgr::LoadCreatureInvolvedRelations()
6818 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6820 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6822 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6823 if(!cInfo)
6824 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6825 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6826 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);
6830 void ObjectMgr::LoadReservedPlayersNames()
6832 m_ReservedNames.clear(); // need for reload case
6834 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6836 uint32 count = 0;
6838 if( !result )
6840 barGoLink bar( 1 );
6841 bar.step();
6843 sLog.outString();
6844 sLog.outString( ">> Loaded %u reserved player names", count );
6845 return;
6848 barGoLink bar((int) result->GetRowCount() );
6850 Field* fields;
6853 bar.step();
6854 fields = result->Fetch();
6855 std::string name= fields[0].GetCppString();
6857 std::wstring wstr;
6858 if(!Utf8toWStr (name,wstr))
6860 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6861 continue;
6864 wstrToLower(wstr);
6866 m_ReservedNames.insert(wstr);
6867 ++count;
6868 } while ( result->NextRow() );
6870 delete result;
6872 sLog.outString();
6873 sLog.outString( ">> Loaded %u reserved player names", count );
6876 bool ObjectMgr::IsReservedName( const std::string& name ) const
6878 std::wstring wstr;
6879 if(!Utf8toWStr (name,wstr))
6880 return false;
6882 wstrToLower(wstr);
6884 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6887 enum LanguageType
6889 LT_BASIC_LATIN = 0x0000,
6890 LT_EXTENDEN_LATIN = 0x0001,
6891 LT_CYRILLIC = 0x0002,
6892 LT_EAST_ASIA = 0x0004,
6893 LT_ANY = 0xFFFF
6896 static LanguageType GetRealmLanguageType(bool create)
6898 switch(sWorld.getConfig(CONFIG_UINT32_REALM_ZONE))
6900 case REALM_ZONE_UNKNOWN: // any language
6901 case REALM_ZONE_DEVELOPMENT:
6902 case REALM_ZONE_TEST_SERVER:
6903 case REALM_ZONE_QA_SERVER:
6904 return LT_ANY;
6905 case REALM_ZONE_UNITED_STATES: // extended-Latin
6906 case REALM_ZONE_OCEANIC:
6907 case REALM_ZONE_LATIN_AMERICA:
6908 case REALM_ZONE_ENGLISH:
6909 case REALM_ZONE_GERMAN:
6910 case REALM_ZONE_FRENCH:
6911 case REALM_ZONE_SPANISH:
6912 return LT_EXTENDEN_LATIN;
6913 case REALM_ZONE_KOREA: // East-Asian
6914 case REALM_ZONE_TAIWAN:
6915 case REALM_ZONE_CHINA:
6916 return LT_EAST_ASIA;
6917 case REALM_ZONE_RUSSIAN: // Cyrillic
6918 return LT_CYRILLIC;
6919 default:
6920 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6924 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6926 if(strictMask==0) // any language, ignore realm
6928 if(isExtendedLatinString(wstr,numericOrSpace))
6929 return true;
6930 if(isCyrillicString(wstr,numericOrSpace))
6931 return true;
6932 if(isEastAsianString(wstr,numericOrSpace))
6933 return true;
6934 return false;
6937 if(strictMask & 0x2) // realm zone specific
6939 LanguageType lt = GetRealmLanguageType(create);
6940 if(lt & LT_EXTENDEN_LATIN)
6941 if(isExtendedLatinString(wstr,numericOrSpace))
6942 return true;
6943 if(lt & LT_CYRILLIC)
6944 if(isCyrillicString(wstr,numericOrSpace))
6945 return true;
6946 if(lt & LT_EAST_ASIA)
6947 if(isEastAsianString(wstr,numericOrSpace))
6948 return true;
6951 if(strictMask & 0x1) // basic Latin
6953 if(isBasicLatinString(wstr,numericOrSpace))
6954 return true;
6957 return false;
6960 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6962 std::wstring wname;
6963 if(!Utf8toWStr(name,wname))
6964 return CHAR_NAME_INVALID_CHARACTER;
6966 if(wname.size() > MAX_PLAYER_NAME)
6967 return CHAR_NAME_TOO_LONG;
6969 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PLAYER_NAME);
6970 if(wname.size() < minName)
6971 return CHAR_NAME_TOO_SHORT;
6973 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PLAYER_NAMES);
6974 if(!isValidString(wname,strictMask,false,create))
6975 return CHAR_NAME_MIXED_LANGUAGES;
6977 return CHAR_NAME_SUCCESS;
6980 bool ObjectMgr::IsValidCharterName( const std::string& name )
6982 std::wstring wname;
6983 if(!Utf8toWStr(name,wname))
6984 return false;
6986 if(wname.size() > MAX_CHARTER_NAME)
6987 return false;
6989 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_CHARTER_NAME);
6990 if(wname.size() < minName)
6991 return false;
6993 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_CHARTER_NAMES);
6995 return isValidString(wname,strictMask,true);
6998 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
7000 std::wstring wname;
7001 if(!Utf8toWStr(name,wname))
7002 return PET_NAME_INVALID;
7004 if(wname.size() > MAX_PET_NAME)
7005 return PET_NAME_TOO_LONG;
7007 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PET_NAME);
7008 if(wname.size() < minName)
7009 return PET_NAME_TOO_SHORT;
7011 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PET_NAMES);
7012 if(!isValidString(wname,strictMask,false))
7013 return PET_NAME_MIXED_LANGUAGES;
7015 return PET_NAME_SUCCESS;
7018 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
7020 if(loc==LOCALE_enUS)
7021 return -1;
7023 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7024 if(m_LocalForIndex[i]==loc)
7025 return i;
7027 return -1;
7030 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
7032 if (i<0 || i>=(int32)m_LocalForIndex.size())
7033 return LOCALE_enUS;
7035 return m_LocalForIndex[i];
7038 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
7040 if(loc==LOCALE_enUS)
7041 return -1;
7043 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7044 if(m_LocalForIndex[i]==loc)
7045 return i;
7047 m_LocalForIndex.push_back(loc);
7048 return m_LocalForIndex.size()-1;
7051 void ObjectMgr::LoadGameObjectForQuests()
7053 mGameObjectForQuestSet.clear(); // need for reload case
7055 if( !sGOStorage.MaxEntry )
7057 barGoLink bar( 1 );
7058 bar.step();
7059 sLog.outString();
7060 sLog.outString( ">> Loaded 0 GameObjects for quests" );
7061 return;
7064 barGoLink bar( sGOStorage.MaxEntry - 1 );
7065 uint32 count = 0;
7067 // collect GO entries for GO that must activated
7068 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
7070 bar.step();
7071 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
7072 if(!goInfo)
7073 continue;
7075 switch(goInfo->type)
7077 // scan GO chest with loot including quest items
7078 case GAMEOBJECT_TYPE_CHEST:
7080 uint32 loot_id = goInfo->GetLootId();
7082 // find quest loot for GO
7083 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
7085 mGameObjectForQuestSet.insert(go_entry);
7086 ++count;
7088 break;
7090 case GAMEOBJECT_TYPE_GOOBER:
7092 if(goInfo->goober.questId) //quests objects
7094 mGameObjectForQuestSet.insert(go_entry);
7095 count++;
7097 break;
7099 default:
7100 break;
7104 sLog.outString();
7105 sLog.outString( ">> Loaded %u GameObjects for quests", count );
7108 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
7110 int32 start_value = min_value;
7111 int32 end_value = max_value;
7112 // some string can have negative indexes range
7113 if (start_value < 0)
7115 if (end_value >= start_value)
7117 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7118 return false;
7121 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
7122 std::swap(start_value,end_value);
7123 ++start_value;
7124 ++end_value;
7126 else
7128 if (start_value >= end_value)
7130 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7131 return false;
7135 // cleanup affected map part for reloading case
7136 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
7138 if (itr->first >= start_value && itr->first < end_value)
7139 mMangosStringLocaleMap.erase(itr++);
7140 else
7141 ++itr;
7144 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);
7146 if (!result)
7148 barGoLink bar(1);
7150 bar.step();
7152 sLog.outString();
7153 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
7154 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
7155 else
7156 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
7157 return false;
7160 uint32 count = 0;
7162 barGoLink bar((int)result->GetRowCount());
7166 Field *fields = result->Fetch();
7167 bar.step();
7169 int32 entry = fields[0].GetInt32();
7171 if (entry==0)
7173 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7174 continue;
7176 else if (entry < start_value || entry >= end_value)
7178 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7179 continue;
7182 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7184 if (data.Content.size() > 0)
7186 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7187 continue;
7190 data.Content.resize(1);
7191 ++count;
7193 // 0 -> default, idx in to idx+1
7194 data.Content[0] = fields[1].GetCppString();
7196 for(int i = 1; i < MAX_LOCALE; ++i)
7198 std::string str = fields[i+1].GetCppString();
7199 if (!str.empty())
7201 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7202 if (idx >= 0)
7204 // 0 -> default, idx in to idx+1
7205 if ((int32)data.Content.size() <= idx+1)
7206 data.Content.resize(idx+2);
7208 data.Content[idx+1] = str;
7212 } while (result->NextRow());
7214 delete result;
7216 sLog.outString();
7217 if (min_value == MIN_MANGOS_STRING_ID)
7218 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7219 else
7220 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7222 return true;
7225 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7227 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7228 // Content[0] always exist if exist MangosStringLocale
7229 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7231 if((int32)msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7232 return msl->Content[locale_idx+1].c_str();
7233 else
7234 return msl->Content[0].c_str();
7237 if(entry > 0)
7238 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7239 else
7240 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7241 return "<error>";
7244 void ObjectMgr::LoadFishingBaseSkillLevel()
7246 mFishingBaseForArea.clear(); // for reload case
7248 uint32 count = 0;
7249 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7251 if( !result )
7253 barGoLink bar( 1 );
7255 bar.step();
7257 sLog.outString();
7258 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7259 return;
7262 barGoLink bar((int) result->GetRowCount() );
7266 bar.step();
7268 Field *fields = result->Fetch();
7269 uint32 entry = fields[0].GetUInt32();
7270 int32 skill = fields[1].GetInt32();
7272 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7273 if(!fArea)
7275 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7276 continue;
7279 mFishingBaseForArea[entry] = skill;
7280 ++count;
7282 while (result->NextRow());
7284 delete result;
7286 sLog.outString();
7287 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7290 // Searches for the same condition already in Conditions store
7291 // Returns Id if found, else adds it to Conditions and returns Id
7292 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7294 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7295 for (uint16 i=0; i < mConditions.size(); ++i)
7297 if (lc == mConditions[i])
7298 return i;
7301 mConditions.push_back(lc);
7303 if(mConditions.size() > 0xFFFF)
7305 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7306 return 0;
7309 return mConditions.size() - 1;
7312 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7314 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7316 std::wstring wname;
7317 if(!Utf8toWStr(names.name[i],wname))
7318 return false;
7320 if(mainpart!=GetMainPartOfName(wname,i+1))
7321 return false;
7323 return true;
7326 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7328 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7329 if(i!= mAreaTriggerScripts.end())
7330 return i->second;
7331 return 0;
7334 // Checks if player meets the condition
7335 bool PlayerCondition::Meets(Player const * player) const
7337 if( !player )
7338 return false; // player not present, return false
7340 switch (condition)
7342 case CONDITION_NONE:
7343 return true; // empty condition, always met
7344 case CONDITION_AURA:
7345 return player->HasAura(value1, SpellEffectIndex(value2));
7346 case CONDITION_ITEM:
7347 return player->HasItemCount(value1, value2);
7348 case CONDITION_ITEM_EQUIPPED:
7349 return player->HasItemOrGemWithIdEquipped(value1,1);
7350 case CONDITION_ZONEID:
7351 return player->GetZoneId() == value1;
7352 case CONDITION_REPUTATION_RANK:
7354 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7355 return faction && player->GetReputationMgr().GetRank(faction) >= ReputationRank(value2);
7357 case CONDITION_TEAM:
7358 return player->GetTeam() == value1;
7359 case CONDITION_SKILL:
7360 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7361 case CONDITION_QUESTREWARDED:
7362 return player->GetQuestRewardStatus(value1);
7363 case CONDITION_QUESTTAKEN:
7365 QuestStatus status = player->GetQuestStatus(value1);
7366 return (status == QUEST_STATUS_INCOMPLETE);
7368 case CONDITION_AD_COMMISSION_AURA:
7370 Unit::AuraMap const& auras = player->GetAuras();
7371 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7372 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7373 return true;
7374 return false;
7376 case CONDITION_NO_AURA:
7377 return !player->HasAura(value1, SpellEffectIndex(value2));
7378 case CONDITION_ACTIVE_EVENT:
7379 return sGameEventMgr.IsActiveEvent(value1);
7380 case CONDITION_AREA_FLAG:
7382 if (AreaTableEntry const *pAreaEntry = GetAreaEntryByAreaID(player->GetAreaId()))
7384 if ((!value1 || (pAreaEntry->flags & value1)) && (!value2 || !(pAreaEntry->flags & value2)))
7385 return true;
7387 return false;
7389 case CONDITION_RACE_CLASS:
7390 if ((!value1 || (player->getRaceMask() & value1)) && (!value2 || (player->getClassMask() & value2)))
7391 return true;
7392 return false;
7393 case CONDITION_LEVEL:
7395 switch(value2)
7397 case 0: return player->getLevel() == value1;
7398 case 1: return player->getLevel() >= value1;
7399 case 2: return player->getLevel() <= value1;
7401 return false;
7403 case CONDITION_NOITEM:
7404 return !player->HasItemCount(value1, value2);
7405 default:
7406 return false;
7410 // Verification of condition values validity
7411 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7413 if( condition >= MAX_CONDITION) // Wrong condition type
7415 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7416 return false;
7419 switch (condition)
7421 case CONDITION_AURA:
7423 if(!sSpellStore.LookupEntry(value1))
7425 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7426 return false;
7428 if(value2 >= MAX_EFFECT_INDEX)
7430 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7431 return false;
7433 break;
7435 case CONDITION_ITEM:
7436 case CONDITION_NOITEM:
7438 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7439 if(!proto)
7441 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7442 return false;
7445 if(value2 < 1)
7447 sLog.outErrorDb("Item condition useless with count < 1, skipped");
7448 return false;
7450 break;
7452 case CONDITION_ITEM_EQUIPPED:
7454 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7455 if(!proto)
7457 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7458 return false;
7460 break;
7462 case CONDITION_ZONEID:
7464 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7465 if(!areaEntry)
7467 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7468 return false;
7470 if(areaEntry->zone != 0)
7472 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7473 return false;
7475 break;
7477 case CONDITION_REPUTATION_RANK:
7479 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7480 if(!factionEntry)
7482 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7483 return false;
7485 break;
7487 case CONDITION_TEAM:
7489 if (value1 != ALLIANCE && value1 != HORDE)
7491 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7492 return false;
7494 break;
7496 case CONDITION_SKILL:
7498 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7499 if (!pSkill)
7501 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7502 return false;
7504 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7506 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7507 return false;
7509 break;
7511 case CONDITION_QUESTREWARDED:
7512 case CONDITION_QUESTTAKEN:
7514 Quest const *Quest = sObjectMgr.GetQuestTemplate(value1);
7515 if (!Quest)
7517 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7518 return false;
7520 if(value2)
7521 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7522 break;
7524 case CONDITION_AD_COMMISSION_AURA:
7526 if(value1)
7527 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7528 if(value2)
7529 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7530 break;
7532 case CONDITION_NO_AURA:
7534 if(!sSpellStore.LookupEntry(value1))
7536 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7537 return false;
7539 if(value2 > MAX_EFFECT_INDEX)
7541 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7542 return false;
7544 break;
7546 case CONDITION_ACTIVE_EVENT:
7548 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
7549 if(value1 >=events.size() || !events[value1].isValid())
7551 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7552 return false;
7554 break;
7556 case CONDITION_AREA_FLAG:
7558 if (!value1 && !value2)
7560 sLog.outErrorDb("Area flag condition has both values like 0, skipped");
7561 return false;
7563 break;
7565 case CONDITION_RACE_CLASS:
7567 if (!value1 && !value2)
7569 sLog.outErrorDb("Race_class condition has both values like 0, skipped");
7570 return false;
7573 if (value1 && !(value1 & RACEMASK_ALL_PLAYABLE))
7575 sLog.outErrorDb("Race_class condition has invalid player class %u, skipped", value1);
7576 return false;
7579 if (value2 && !(value2 & CLASSMASK_ALL_PLAYABLE))
7581 sLog.outErrorDb("Race_class condition has invalid race mask %u, skipped", value2);
7582 return false;
7584 break;
7586 case CONDITION_LEVEL:
7588 if (!value1 || value1 > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
7590 sLog.outErrorDb("Level condition has invalid level %u, skipped", value1);
7591 return false;
7594 if (value2 > 2)
7596 sLog.outErrorDb("Level condition has invalid argument %u (must be 0..2), skipped", value2);
7597 return false;
7600 break;
7602 case CONDITION_NONE:
7603 break;
7605 return true;
7608 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7610 switch(pSkill->categoryId)
7612 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7613 case SKILL_CATEGORY_WEAPON:
7614 if(pSkill->id!=SKILL_FIST_WEAPONS)
7615 return SKILL_RANGE_LEVEL;
7616 else
7617 return SKILL_RANGE_MONO;
7618 case SKILL_CATEGORY_ARMOR:
7619 case SKILL_CATEGORY_CLASS:
7620 if(pSkill->id != SKILL_LOCKPICKING)
7621 return SKILL_RANGE_MONO;
7622 else
7623 return SKILL_RANGE_LEVEL;
7624 case SKILL_CATEGORY_SECONDARY:
7625 case SKILL_CATEGORY_PROFESSION:
7626 // not set skills for professions and racial abilities
7627 if(IsProfessionSkill(pSkill->id))
7628 return SKILL_RANGE_RANK;
7629 else if(racial)
7630 return SKILL_RANGE_NONE;
7631 else
7632 return SKILL_RANGE_MONO;
7633 default:
7634 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7635 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7636 return SKILL_RANGE_NONE;
7640 void ObjectMgr::LoadGameTele()
7642 m_GameTeleMap.clear(); // for reload case
7644 uint32 count = 0;
7645 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7647 if( !result )
7649 barGoLink bar( 1 );
7651 bar.step();
7653 sLog.outString();
7654 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7655 return;
7658 barGoLink bar( (int)result->GetRowCount() );
7662 bar.step();
7664 Field *fields = result->Fetch();
7666 uint32 id = fields[0].GetUInt32();
7668 GameTele gt;
7670 gt.position_x = fields[1].GetFloat();
7671 gt.position_y = fields[2].GetFloat();
7672 gt.position_z = fields[3].GetFloat();
7673 gt.orientation = fields[4].GetFloat();
7674 gt.mapId = fields[5].GetUInt32();
7675 gt.name = fields[6].GetCppString();
7677 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7679 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7680 continue;
7683 if(!Utf8toWStr(gt.name,gt.wnameLow))
7685 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7686 continue;
7689 wstrToLower( gt.wnameLow );
7691 m_GameTeleMap[id] = gt;
7693 ++count;
7695 while (result->NextRow());
7696 delete result;
7698 sLog.outString();
7699 sLog.outString( ">> Loaded %u GameTeleports", count );
7702 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7704 // explicit name case
7705 std::wstring wname;
7706 if(!Utf8toWStr(name,wname))
7707 return false;
7709 // converting string that we try to find to lower case
7710 wstrToLower( wname );
7712 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7713 const GameTele* alt = NULL;
7714 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7715 if(itr->second.wnameLow == wname)
7716 return &itr->second;
7717 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7718 alt = &itr->second;
7720 return alt;
7723 bool ObjectMgr::AddGameTele(GameTele& tele)
7725 // find max id
7726 uint32 new_id = 0;
7727 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7728 if(itr->first > new_id)
7729 new_id = itr->first;
7731 // use next
7732 ++new_id;
7734 if(!Utf8toWStr(tele.name,tele.wnameLow))
7735 return false;
7737 wstrToLower( tele.wnameLow );
7739 m_GameTeleMap[new_id] = tele;
7741 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')",
7742 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7745 bool ObjectMgr::DeleteGameTele(const std::string& name)
7747 // explicit name case
7748 std::wstring wname;
7749 if(!Utf8toWStr(name,wname))
7750 return false;
7752 // converting string that we try to find to lower case
7753 wstrToLower( wname );
7755 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7757 if(itr->second.wnameLow == wname)
7759 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7760 m_GameTeleMap.erase(itr);
7761 return true;
7765 return false;
7768 void ObjectMgr::LoadMailLevelRewards()
7770 m_mailLevelRewardMap.clear(); // for reload case
7772 uint32 count = 0;
7773 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7775 if( !result )
7777 barGoLink bar( 1 );
7779 bar.step();
7781 sLog.outString();
7782 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7783 return;
7786 barGoLink bar((int) result->GetRowCount() );
7790 bar.step();
7792 Field *fields = result->Fetch();
7794 uint8 level = fields[0].GetUInt8();
7795 uint32 raceMask = fields[1].GetUInt32();
7796 uint32 mailTemplateId = fields[2].GetUInt32();
7797 uint32 senderEntry = fields[3].GetUInt32();
7799 if(level > MAX_LEVEL)
7801 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7802 continue;
7805 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7807 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7808 continue;
7811 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7813 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7814 continue;
7817 if(!GetCreatureTemplateStore(senderEntry))
7819 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);
7820 continue;
7823 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7825 ++count;
7827 while (result->NextRow());
7828 delete result;
7830 sLog.outString();
7831 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7834 void ObjectMgr::LoadTrainerSpell()
7836 // For reload case
7837 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7838 itr->second.Clear();
7839 m_mCacheTrainerSpellMap.clear();
7841 std::set<uint32> skip_trainers;
7843 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7845 if( !result )
7847 barGoLink bar( 1 );
7849 bar.step();
7851 sLog.outString();
7852 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7853 return;
7856 barGoLink bar( (int)result->GetRowCount() );
7858 std::set<uint32> talentIds;
7860 uint32 count = 0;
7863 bar.step();
7865 Field* fields = result->Fetch();
7867 uint32 entry = fields[0].GetUInt32();
7868 uint32 spell = fields[1].GetUInt32();
7870 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7872 if(!cInfo)
7874 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7875 continue;
7878 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7880 if (skip_trainers.find(entry) == skip_trainers.end())
7882 sLog.outErrorDb("Table `npc_trainer` have data for creature (Entry: %u) without trainer flag, ignore", entry);
7883 skip_trainers.insert(entry);
7885 continue;
7888 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7889 if(!spellinfo)
7891 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7892 continue;
7895 if(!SpellMgr::IsSpellValid(spellinfo))
7897 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7898 continue;
7901 if(GetTalentSpellCost(spell))
7903 if (talentIds.find(spell) == talentIds.end())
7905 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7906 talentIds.insert(spell);
7908 continue;
7911 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7913 TrainerSpell& trainerSpell = data.spellList[spell];
7914 trainerSpell.spell = spell;
7915 trainerSpell.spellCost = fields[2].GetUInt32();
7916 trainerSpell.reqSkill = fields[3].GetUInt32();
7917 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7918 trainerSpell.reqLevel = fields[5].GetUInt32();
7920 if(!trainerSpell.reqLevel)
7921 trainerSpell.reqLevel = spellinfo->spellLevel;
7923 // calculate learned spell for profession case when stored cast-spell
7924 trainerSpell.learnedSpell = spell;
7925 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
7927 if (spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7928 continue;
7929 if (SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7931 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7932 break;
7936 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7937 data.trainerType = 2;
7939 ++count;
7941 } while (result->NextRow());
7942 delete result;
7944 sLog.outString();
7945 sLog.outString( ">> Loaded %d Trainers", count );
7948 void ObjectMgr::LoadVendors()
7950 // For reload case
7951 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7952 itr->second.Clear();
7953 m_mCacheVendorItemMap.clear();
7955 std::set<uint32> skip_vendors;
7957 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7958 if( !result )
7960 barGoLink bar( 1 );
7962 bar.step();
7964 sLog.outString();
7965 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7966 return;
7969 barGoLink bar( (int)result->GetRowCount() );
7971 uint32 count = 0;
7974 bar.step();
7975 Field* fields = result->Fetch();
7977 uint32 entry = fields[0].GetUInt32();
7978 uint32 item_id = fields[1].GetUInt32();
7979 uint32 maxcount = fields[2].GetUInt32();
7980 uint32 incrtime = fields[3].GetUInt32();
7981 uint32 ExtendedCost = fields[4].GetUInt32();
7983 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7984 continue;
7986 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7988 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7989 ++count;
7991 } while (result->NextRow());
7992 delete result;
7994 sLog.outString();
7995 sLog.outString( ">> Loaded %d Vendors ", count );
7998 void ObjectMgr::LoadNpcTextId()
8001 m_mCacheNpcTextIdMap.clear();
8003 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
8004 if( !result )
8006 barGoLink bar( 1 );
8008 bar.step();
8010 sLog.outString();
8011 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
8012 return;
8015 barGoLink bar((int) result->GetRowCount() );
8017 uint32 count = 0;
8018 uint32 guid,textid;
8021 bar.step();
8023 Field* fields = result->Fetch();
8025 guid = fields[0].GetUInt32();
8026 textid = fields[1].GetUInt32();
8028 if (!GetCreatureData(guid))
8030 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
8031 continue;
8033 if (!GetGossipText(textid))
8035 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
8036 continue;
8039 m_mCacheNpcTextIdMap[guid] = textid ;
8040 ++count;
8042 } while (result->NextRow());
8043 delete result;
8045 sLog.outString();
8046 sLog.outString( ">> Loaded %d NpcTextId ", count );
8049 void ObjectMgr::LoadGossipMenu()
8051 m_mGossipMenusMap.clear();
8053 QueryResult* result = WorldDatabase.Query("SELECT entry, text_id, "
8054 "cond_1, cond_1_val_1, cond_1_val_2, cond_2, cond_2_val_1, cond_2_val_2 FROM gossip_menu");
8056 if (!result)
8058 barGoLink bar(1);
8060 bar.step();
8062 sLog.outString();
8063 sLog.outErrorDb(">> Loaded gossip_menu, table is empty!");
8064 return;
8067 barGoLink bar( (int)result->GetRowCount() );
8069 uint32 count = 0;
8073 bar.step();
8075 Field* fields = result->Fetch();
8077 GossipMenus gMenu;
8079 gMenu.entry = fields[0].GetUInt32();
8080 gMenu.text_id = fields[1].GetUInt32();
8082 ConditionType cond_1 = (ConditionType)fields[2].GetUInt32();
8083 uint32 cond_1_val_1 = fields[3].GetUInt32();
8084 uint32 cond_1_val_2 = fields[4].GetUInt32();
8085 ConditionType cond_2 = (ConditionType)fields[5].GetUInt32();
8086 uint32 cond_2_val_1 = fields[6].GetUInt32();
8087 uint32 cond_2_val_2 = fields[7].GetUInt32();
8089 if (!GetGossipText(gMenu.text_id))
8091 sLog.outErrorDb("Table gossip_menu entry %u are using non-existing text_id %u", gMenu.entry, gMenu.text_id);
8092 continue;
8095 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8097 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 1 for id %u", gMenu.entry, gMenu.text_id);
8098 continue;
8101 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8103 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 2 for id %u", gMenu.entry, gMenu.text_id);
8104 continue;
8107 gMenu.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8108 gMenu.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8110 m_mGossipMenusMap.insert(GossipMenusMap::value_type(gMenu.entry, gMenu));
8112 ++count;
8114 while(result->NextRow());
8116 delete result;
8118 sLog.outString();
8119 sLog.outString( ">> Loaded %u gossip_menu entries", count);
8122 void ObjectMgr::LoadGossipMenuItems()
8124 m_mGossipMenuItemsMap.clear();
8126 QueryResult *result = WorldDatabase.Query(
8127 "SELECT menu_id, id, option_icon, option_text, option_id, npc_option_npcflag, "
8128 "action_menu_id, action_poi_id, action_script_id, box_coded, box_money, box_text, "
8129 "cond_1, cond_1_val_1, cond_1_val_2, "
8130 "cond_2, cond_2_val_1, cond_2_val_2, "
8131 "cond_3, cond_3_val_1, cond_3_val_2 "
8132 "FROM gossip_menu_option");
8134 if (!result)
8136 barGoLink bar(1);
8138 bar.step();
8140 sLog.outString();
8141 sLog.outErrorDb(">> Loaded gossip_menu_option, table is empty!");
8142 return;
8145 barGoLink bar((int)result->GetRowCount());
8147 uint32 count = 0;
8149 std::set<uint32> gossipScriptSet;
8151 for(ScriptMapMap::const_iterator itr = sGossipScripts.begin(); itr != sGossipScripts.end(); ++itr)
8152 gossipScriptSet.insert(itr->first);
8156 bar.step();
8158 Field* fields = result->Fetch();
8160 GossipMenuItems gMenuItem;
8162 gMenuItem.menu_id = fields[0].GetUInt32();
8163 gMenuItem.id = fields[1].GetUInt32();
8164 gMenuItem.option_icon = fields[2].GetUInt8();
8165 gMenuItem.option_text = fields[3].GetCppString();
8166 gMenuItem.option_id = fields[4].GetUInt32();
8167 gMenuItem.npc_option_npcflag = fields[5].GetUInt32();
8168 gMenuItem.action_menu_id = fields[6].GetUInt32();
8169 gMenuItem.action_poi_id = fields[7].GetUInt32();
8170 gMenuItem.action_script_id = fields[8].GetUInt32();
8171 gMenuItem.box_coded = fields[9].GetUInt8() != 0;
8172 gMenuItem.box_money = fields[10].GetUInt32();
8173 gMenuItem.box_text = fields[11].GetCppString();
8175 ConditionType cond_1 = (ConditionType)fields[12].GetUInt32();
8176 uint32 cond_1_val_1 = fields[13].GetUInt32();
8177 uint32 cond_1_val_2 = fields[14].GetUInt32();
8178 ConditionType cond_2 = (ConditionType)fields[15].GetUInt32();
8179 uint32 cond_2_val_1 = fields[16].GetUInt32();
8180 uint32 cond_2_val_2 = fields[17].GetUInt32();
8181 ConditionType cond_3 = (ConditionType)fields[18].GetUInt32();
8182 uint32 cond_3_val_1 = fields[19].GetUInt32();
8183 uint32 cond_3_val_2 = fields[20].GetUInt32();
8185 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8187 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 1 for id %u", gMenuItem.menu_id, gMenuItem.id);
8188 continue;
8190 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8192 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 2 for id %u", gMenuItem.menu_id, gMenuItem.id);
8193 continue;
8195 if (!PlayerCondition::IsValid(cond_3, cond_3_val_1, cond_3_val_2))
8197 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 3 for id %u", gMenuItem.menu_id, gMenuItem.id);
8198 continue;
8201 if (gMenuItem.option_icon >= GOSSIP_ICON_MAX)
8203 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);
8204 gMenuItem.option_icon = GOSSIP_ICON_CHAT;
8207 if (gMenuItem.option_id == GOSSIP_OPTION_NONE)
8208 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);
8210 if (gMenuItem.option_id >= GOSSIP_OPTION_MAX)
8211 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);
8213 if (gMenuItem.action_poi_id && !GetPointOfInterest(gMenuItem.action_poi_id))
8215 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);
8216 gMenuItem.action_poi_id = 0;
8219 if (gMenuItem.action_script_id)
8221 if (gMenuItem.option_id != GOSSIP_OPTION_GOSSIP)
8223 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);
8224 continue;
8227 if (sGossipScripts.find(gMenuItem.action_script_id) == sGossipScripts.end())
8229 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);
8230 continue;
8233 gossipScriptSet.erase(gMenuItem.action_script_id);
8236 gMenuItem.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8237 gMenuItem.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8238 gMenuItem.cond_3 = GetConditionId(cond_3, cond_3_val_1, cond_3_val_2);
8240 m_mGossipMenuItemsMap.insert(GossipMenuItemsMap::value_type(gMenuItem.menu_id, gMenuItem));
8242 ++count;
8245 while(result->NextRow());
8247 delete result;
8249 if (!gossipScriptSet.empty())
8251 for(std::set<uint32>::const_iterator itr = gossipScriptSet.begin(); itr != gossipScriptSet.end(); ++itr)
8252 sLog.outErrorDb("Table `gossip_scripts` contain unused script, id %u.", *itr);
8255 sLog.outString();
8256 sLog.outString(">> Loaded %u gossip_menu_option entries", count);
8259 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
8261 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8262 vList.AddItem(item,maxcount,incrtime,extendedcost);
8264 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
8267 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
8269 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
8270 if(iter == m_mCacheVendorItemMap.end())
8271 return false;
8273 if(!iter->second.FindItem(item))
8274 return false;
8276 iter->second.RemoveItem(item);
8277 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
8278 return true;
8281 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
8283 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
8284 if(!cInfo)
8286 if(pl)
8287 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8288 else
8289 sLog.outErrorDb("Table `npc_vendor` has data for nonexistent creature (Entry: %u), ignoring", vendor_entry);
8290 return false;
8293 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
8295 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
8297 if(pl)
8298 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8299 else
8300 sLog.outErrorDb("Table `npc_vendor` has data for creature (Entry: %u) without vendor flag, ignoring", vendor_entry);
8302 if(skip_vendors)
8303 skip_vendors->insert(vendor_entry);
8305 return false;
8308 if(!GetItemPrototype(item_id))
8310 if(pl)
8311 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
8312 else
8313 sLog.outErrorDb("Table `npc_vendor` for vendor (Entry: %u) contain nonexistent item (%u), ignoring",vendor_entry,item_id);
8314 return false;
8317 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
8319 if(pl)
8320 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
8321 else
8322 sLog.outErrorDb("Table `npc_vendor` contain item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignoring",item_id,ExtendedCost,vendor_entry);
8323 return false;
8326 if(maxcount > 0 && incrtime == 0)
8328 if(pl)
8329 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
8330 else
8331 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignoring", maxcount, item_id, vendor_entry);
8332 return false;
8334 else if(maxcount==0 && incrtime > 0)
8336 if(pl)
8337 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
8338 else
8339 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignoring", item_id, vendor_entry);
8340 return false;
8343 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
8344 if(!vItems)
8345 return true; // later checks for non-empty lists
8347 if(vItems->FindItem(item_id))
8349 if(pl)
8350 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
8351 else
8352 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignoring", item_id, vendor_entry);
8353 return false;
8356 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
8358 if(pl)
8359 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
8360 else
8361 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignoring", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
8362 return false;
8365 return true;
8368 void ObjectMgr::LoadScriptNames()
8370 m_scriptNames.push_back("");
8371 QueryResult *result = WorldDatabase.Query(
8372 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
8373 "UNION "
8374 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
8375 "UNION "
8376 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
8377 "UNION "
8378 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
8379 "UNION "
8380 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
8382 if( !result )
8384 barGoLink bar( 1 );
8385 bar.step();
8386 sLog.outString();
8387 sLog.outErrorDb(">> Loaded empty set of Script Names!");
8388 return;
8391 barGoLink bar( (int)result->GetRowCount() );
8392 uint32 count = 0;
8396 bar.step();
8397 m_scriptNames.push_back((*result)[0].GetString());
8398 ++count;
8399 } while (result->NextRow());
8400 delete result;
8402 std::sort(m_scriptNames.begin(), m_scriptNames.end());
8403 sLog.outString();
8404 sLog.outString( ">> Loaded %d Script Names", count );
8407 uint32 ObjectMgr::GetScriptId(const char *name)
8409 // use binary search to find the script name in the sorted vector
8410 // assume "" is the first element
8411 if(!name) return 0;
8412 ScriptNameMap::const_iterator itr =
8413 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8414 if(itr == m_scriptNames.end() || *itr != name) return 0;
8415 return uint32(itr - m_scriptNames.begin());
8418 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
8420 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8422 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8424 switch(itrM->second.command)
8426 case SCRIPT_COMMAND_TALK:
8428 if(!GetMangosStringLocale (itrM->second.dataint))
8429 sLog.outErrorDb( "Table `db_script_string` is missing string id %u, used in database script id %u.", itrM->second.dataint, itrMM->first);
8431 if (ids.find(itrM->second.dataint) != ids.end())
8432 ids.erase(itrM->second.dataint);
8439 void ObjectMgr::LoadDbScriptStrings()
8441 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8443 std::set<int32> ids;
8445 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8446 if(GetMangosStringLocale(i))
8447 ids.insert(i);
8449 CheckScripts(sQuestEndScripts,ids);
8450 CheckScripts(sQuestStartScripts,ids);
8451 CheckScripts(sSpellScripts,ids);
8452 CheckScripts(sGameObjectScripts,ids);
8453 CheckScripts(sEventScripts,ids);
8454 CheckScripts(sGossipScripts,ids);
8456 sWaypointMgr.CheckTextsExistance(ids);
8458 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8459 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8462 void ObjectMgr::AddGuild( Guild* guild )
8464 mGuildMap[guild->GetId()] = guild ;
8467 void ObjectMgr::RemoveGuild( uint32 Id )
8469 mGuildMap.erase(Id);
8472 void ObjectMgr::AddGroup( Group* group )
8474 mGroupMap[group->GetId()] = group ;
8477 void ObjectMgr::RemoveGroup( Group* group )
8479 mGroupMap.erase(group->GetId());
8482 void ObjectMgr::AddArenaTeam( ArenaTeam* arenaTeam )
8484 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
8487 void ObjectMgr::RemoveArenaTeam( uint32 Id )
8489 mArenaTeamMap.erase(Id);
8492 // Functions for scripting access
8493 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8495 return sObjectMgr.GetAreaTriggerScriptId(trigger_id);
8498 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8500 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8501 // start/end reversed for negative values
8502 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8504 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8505 return false;
8508 return sObjectMgr.LoadMangosStrings(db,table,start_value,end_value);
8511 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8513 return sObjectMgr.GetScriptId(name);
8516 ObjectMgr::ScriptNameMap & GetScriptNames()
8518 return sObjectMgr.GetScriptNames();
8521 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8523 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8526 Quest const* GetQuestTemplateStore(uint32 entry)
8528 return sObjectMgr.GetQuestTemplate(entry);