[8769] Implement mails sending at player levelup.
[getmangos.git] / src / game / ObjectMgr.cpp
blobf8f087ab1d997ba04c0b0e7c685e89858d205acc
1 /*
2 * Copyright (C) 2005-2009 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 "SpellMgr.h"
29 #include "UpdateMask.h"
30 #include "World.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Language.h"
37 #include "GameEventMgr.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
44 #include "WaypointManager.h"
46 INSTANTIATE_SINGLETON_1(ObjectMgr);
48 ScriptMapMap sQuestEndScripts;
49 ScriptMapMap sQuestStartScripts;
50 ScriptMapMap sSpellScripts;
51 ScriptMapMap sGameObjectScripts;
52 ScriptMapMap sEventScripts;
54 bool normalizePlayerName(std::string& name)
56 if(name.empty())
57 return false;
59 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
60 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
62 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
63 return false;
65 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
66 for(size_t i = 1; i < wstr_len; ++i)
67 wstr_buf[i] = wcharToLower(wstr_buf[i]);
69 if(!WStrToUtf8(wstr_buf,wstr_len,name))
70 return false;
72 return true;
75 LanguageDesc lang_description[LANGUAGES_COUNT] =
77 { LANG_ADDON, 0, 0 },
78 { LANG_UNIVERSAL, 0, 0 },
79 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
80 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
81 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
82 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
83 { LANG_COMMON, 668, SKILL_LANG_COMMON },
84 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
85 { LANG_TITAN, 816, SKILL_LANG_TITAN },
86 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
87 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
88 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
89 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
90 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
91 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
92 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
93 { LANG_ZOMBIE, 0, 0 },
94 { LANG_GNOMISH_BINARY, 0, 0 },
95 { LANG_GOBLIN_BINARY, 0, 0 }
98 LanguageDesc const* GetLanguageDescByID(uint32 lang)
100 for(int i = 0; i < LANGUAGES_COUNT; ++i)
102 if(uint32(lang_description[i].lang_id) == lang)
103 return &lang_description[i];
106 return NULL;
109 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
111 if(questStart)
113 // not in expected required quest state
114 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
115 return false;
118 if(questEnd)
120 // not in expected forbidden quest state
121 if(!player || player->GetQuestRewardStatus(questEnd))
122 return false;
125 return true;
128 ObjectMgr::ObjectMgr()
130 m_hiCharGuid = 1;
131 m_hiCreatureGuid = 1;
132 m_hiItemGuid = 1;
133 m_hiGoGuid = 1;
134 m_hiCorpseGuid = 1;
135 m_hiPetNumber = 1;
136 m_ItemTextId = 1;
137 m_mailid = 1;
138 m_equipmentSetGuid = 1;
139 m_guildId = 1;
140 m_arenaTeamId = 1;
141 m_auctionid = 1;
143 // Only zero condition left, others will be added while loading DB tables
144 mConditions.resize(1);
147 ObjectMgr::~ObjectMgr()
149 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
150 delete i->second;
152 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
153 delete[] i->second;
155 // free only if loaded
156 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
157 delete[] playerClassInfo[class_].levelInfo;
159 for (int race = 0; race < MAX_RACES; ++race)
160 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
161 delete[] playerInfo[race][class_].levelInfo;
163 // free group and guild objects
164 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
165 delete (*itr);
167 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
168 delete itr->second;
170 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
171 delete itr->second;
173 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
174 itr->second.Clear();
176 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
177 itr->second.Clear();
180 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
182 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
183 if ((*itr)->GetLeaderGUID() == guid)
184 return *itr;
186 return NULL;
189 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
191 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
192 if (itr != mGuildMap.end())
193 return itr->second;
195 return NULL;
198 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
200 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
201 if (itr->second->GetName() == guildname)
202 return itr->second;
204 return NULL;
207 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
209 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
210 if (itr != mGuildMap.end())
211 return itr->second->GetName();
213 return "";
216 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
218 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
219 if (itr->second->GetLeader() == guid)
220 return itr->second;
222 return NULL;
225 void ObjectMgr::AddGuild(Guild* guild)
227 mGuildMap[guild->GetId()] = guild;
230 void ObjectMgr::RemoveGuild(uint32 Id)
232 mGuildMap.erase(Id);
235 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
237 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
238 if (itr != mArenaTeamMap.end())
239 return itr->second;
241 return NULL;
244 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
246 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
247 if (itr->second->GetName() == arenateamname)
248 return itr->second;
250 return NULL;
253 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
255 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
256 if (itr->second->GetCaptain() == guid)
257 return itr->second;
259 return NULL;
262 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
264 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
267 void ObjectMgr::RemoveArenaTeam(uint32 Id)
269 mArenaTeamMap.erase(Id);
272 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
274 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
277 void ObjectMgr::LoadCreatureLocales()
279 mCreatureLocaleMap.clear(); // need for reload case
281 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");
283 if(!result)
285 barGoLink bar(1);
287 bar.step();
289 sLog.outString();
290 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
291 return;
294 barGoLink bar(result->GetRowCount());
298 Field *fields = result->Fetch();
299 bar.step();
301 uint32 entry = fields[0].GetUInt32();
303 CreatureLocale& data = mCreatureLocaleMap[entry];
305 for(int i = 1; i < MAX_LOCALE; ++i)
307 std::string str = fields[1+2*(i-1)].GetCppString();
308 if(!str.empty())
310 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
311 if(idx >= 0)
313 if(data.Name.size() <= idx)
314 data.Name.resize(idx+1);
316 data.Name[idx] = str;
319 str = fields[1+2*(i-1)+1].GetCppString();
320 if(!str.empty())
322 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
323 if(idx >= 0)
325 if(data.SubName.size() <= idx)
326 data.SubName.resize(idx+1);
328 data.SubName[idx] = str;
332 } while (result->NextRow());
334 delete result;
336 sLog.outString();
337 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
340 void ObjectMgr::LoadNpcOptionLocales()
342 mNpcOptionLocaleMap.clear(); // need for reload case
344 QueryResult *result = WorldDatabase.Query("SELECT entry,"
345 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
346 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
347 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
348 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
349 "FROM locales_npc_option");
351 if(!result)
353 barGoLink bar(1);
355 bar.step();
357 sLog.outString();
358 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
359 return;
362 barGoLink bar(result->GetRowCount());
366 Field *fields = result->Fetch();
367 bar.step();
369 uint32 entry = fields[0].GetUInt32();
371 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
373 for(int i = 1; i < MAX_LOCALE; ++i)
375 std::string str = fields[1+2*(i-1)].GetCppString();
376 if(!str.empty())
378 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
379 if(idx >= 0)
381 if(data.OptionText.size() <= idx)
382 data.OptionText.resize(idx+1);
384 data.OptionText[idx] = str;
387 str = fields[1+2*(i-1)+1].GetCppString();
388 if(!str.empty())
390 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
391 if(idx >= 0)
393 if(data.BoxText.size() <= idx)
394 data.BoxText.resize(idx+1);
396 data.BoxText[idx] = str;
400 } while (result->NextRow());
402 delete result;
404 sLog.outString();
405 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
408 void ObjectMgr::LoadPointOfInterestLocales()
410 mPointOfInterestLocaleMap.clear(); // need for reload case
412 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");
414 if(!result)
416 barGoLink bar(1);
418 bar.step();
420 sLog.outString();
421 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
422 return;
425 barGoLink bar(result->GetRowCount());
429 Field *fields = result->Fetch();
430 bar.step();
432 uint32 entry = fields[0].GetUInt32();
434 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
436 for(int i = 1; i < MAX_LOCALE; ++i)
438 std::string str = fields[i].GetCppString();
439 if(str.empty())
440 continue;
442 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
443 if(idx >= 0)
445 if(data.IconName.size() <= idx)
446 data.IconName.resize(idx+1);
448 data.IconName[idx] = str;
451 } while (result->NextRow());
453 delete result;
455 sLog.outString();
456 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
459 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
461 template<class D>
462 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
464 dst = D(objmgr.GetScriptId(src));
468 void ObjectMgr::LoadCreatureTemplates()
470 SQLCreatureLoader loader;
471 loader.Load(sCreatureStorage);
473 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
474 sLog.outString();
476 std::set<uint32> difficultyEntries1; // already loaded difficulty 1 value in creatures
477 std::set<uint32> hasDifficultyEntries1; // already loaded creatures with difficulty 1 values
479 // check data correctness
480 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
482 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
483 if (!cInfo)
484 continue;
486 if (cInfo->DifficultyEntry1)
488 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry1);
489 if (!difficultyInfo)
491 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_1`=%u but creature entry %u not exist.", i, cInfo->DifficultyEntry1, cInfo->DifficultyEntry1);
492 continue;
495 if (difficultyEntries1.find(i)!=difficultyEntries1.end())
497 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty 1 but have value in `difficulty_entry_1`.",i);
498 continue;
501 if (difficultyEntries1.find(cInfo->DifficultyEntry1)!=difficultyEntries1.end())
503 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty 1 for another entry.",cInfo->DifficultyEntry1);
504 continue;
507 if (hasDifficultyEntries1.find(cInfo->DifficultyEntry1)!=hasDifficultyEntries1.end())
509 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_1`=%u but creature entry %u have difficulty 1 entry also.",i,cInfo->DifficultyEntry1,cInfo->DifficultyEntry1);
510 continue;
513 if (cInfo->unit_class != difficultyInfo->unit_class)
515 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty 1 mode (Entry: %u, class %u).",i, cInfo->unit_class, cInfo->DifficultyEntry1, difficultyInfo->unit_class);
516 continue;
519 if (cInfo->npcflag != difficultyInfo->npcflag)
521 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty 1 mode (Entry: %u).",i,cInfo->DifficultyEntry1);
522 continue;
525 if (cInfo->trainer_class != difficultyInfo->trainer_class)
527 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty 1 mode (Entry: %u).",i,cInfo->DifficultyEntry1);
528 continue;
531 if (cInfo->trainer_race != difficultyInfo->trainer_race)
533 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty 1 mode (Entry: %u).",i,cInfo->DifficultyEntry1);
534 continue;
537 if (cInfo->trainer_type != difficultyInfo->trainer_type)
539 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty 1 mode (Entry: %u).",i,cInfo->DifficultyEntry1);
540 continue;
543 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
545 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty 1 mode (Entry: %u).",i,cInfo->DifficultyEntry1);
546 continue;
549 if (difficultyInfo->AIName && *difficultyInfo->AIName)
551 sLog.outErrorDb("Difficulty 1 mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",cInfo->DifficultyEntry1,i);
552 continue;
555 if (difficultyInfo->ScriptID)
557 sLog.outErrorDb("Difficulty 1 mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",cInfo->DifficultyEntry1,i);
558 continue;
561 hasDifficultyEntries1.insert(i);
562 difficultyEntries1.insert(cInfo->DifficultyEntry1);
565 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
566 if (!factionTemplate)
567 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
569 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
570 if (!factionTemplate)
571 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
573 // used later for scale
574 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
576 if (cInfo->DisplayID_A[0])
578 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
579 if(!displayEntry)
581 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
582 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
584 else if(!displayScaleEntry)
585 displayScaleEntry = displayEntry;
587 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
588 if (!minfo)
589 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A (%u)", cInfo->Entry, cInfo->DisplayID_A[0]);
592 if (cInfo->DisplayID_A[1])
594 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
595 if(!displayEntry)
597 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
598 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
600 else if(!displayScaleEntry)
601 displayScaleEntry = displayEntry;
603 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
604 if (!minfo)
605 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A2 (%u)", cInfo->Entry, cInfo->DisplayID_A[1]);
608 if (cInfo->DisplayID_H[0])
610 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
611 if(!displayEntry)
613 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
614 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
616 else if(!displayScaleEntry)
617 displayScaleEntry = displayEntry;
619 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
620 if (!minfo)
621 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H (%u)", cInfo->Entry, cInfo->DisplayID_H[0]);
624 if (cInfo->DisplayID_H[1])
626 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
627 if(!displayEntry)
629 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
630 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
632 else if(!displayScaleEntry)
633 displayScaleEntry = displayEntry;
635 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
636 if (!minfo)
637 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H2 (%u)", cInfo->Entry, cInfo->DisplayID_H[1]);
640 if (!displayScaleEntry)
641 sLog.outErrorDb("Creature (Entry: %u) not has any existed display id in DisplayID_A/DisplayID_A2/DisplayID_H/DisplayID_H2", cInfo->Entry);
643 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
645 if(cInfo->KillCredit[k])
647 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
649 sLog.outErrorDb("Creature (Entry: %u) has not existed creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
650 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
655 if (cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
656 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
658 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
660 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
661 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
664 if(cInfo->baseattacktime == 0)
665 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
667 if(cInfo->rangeattacktime == 0)
668 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
670 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
672 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);
673 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
676 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
677 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
679 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
681 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
682 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
685 // must exist or used hidden but used in data horse case
686 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
688 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
689 const_cast<CreatureInfo*>(cInfo)->family = 0;
692 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
694 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
695 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
698 if(cInfo->PetSpellDataId)
700 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
701 if(!spellDataId)
702 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
705 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
707 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
709 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
710 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
714 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
716 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
717 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
720 if(cInfo->equipmentId > 0) // 0 no equipment
722 if(!GetEquipmentInfo(cInfo->equipmentId))
724 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);
725 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
729 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
730 if(cInfo->scale <= 0.0f)
732 if(displayScaleEntry)
733 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
734 else
735 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
740 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
742 // Now add the auras, format "spellid effectindex spellid effectindex..."
743 char *p,*s;
744 std::vector<int> val;
745 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
746 if(p)
748 while (p[0]!=0)
750 ++p;
751 if (p[0]==' ')
753 val.push_back(atoi(s));
754 s=++p;
757 if (p!=s)
758 val.push_back(atoi(s));
760 // free char* loaded memory
761 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
763 // wrong list
764 if (val.size()%2)
766 addon->auras = NULL;
767 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
768 return;
772 // empty list
773 if(val.empty())
775 addon->auras = NULL;
776 return;
779 // replace by new structures array
780 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
782 uint32 i=0;
783 for(uint32 j = 0; j < val.size()/2; ++j)
785 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
786 cAura.spell_id = (uint32)val[2*j+0];
787 cAura.effect_idx = (uint32)val[2*j+1];
788 if ( cAura.effect_idx > 2 )
790 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);
791 continue;
793 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
794 if (!AdditionalSpellInfo)
796 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
797 continue;
800 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
802 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);
803 continue;
806 ++i;
809 // fill terminator element (after last added)
810 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
811 endAura.spell_id = 0;
812 endAura.effect_idx = 0;
815 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
817 creatureaddons.Load();
819 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
820 sLog.outString();
822 // check data correctness and convert 'auras'
823 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
825 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
826 if(!addon)
827 continue;
829 if (addon->mount)
831 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
833 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
834 const_cast<CreatureDataAddon*>(addon)->mount = 0;
838 if (!sEmotesStore.LookupEntry(addon->emote))
839 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
841 if (addon->move_flags & (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4))
843 sLog.outErrorDb("Creature (%s %u) movement flags mask defined in `%s` include forbidden flags (" I32FMT ") that can crash client, cleanup at load.", entryName, addon->guidOrEntry, creatureaddons.GetTableName(), (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4));
844 const_cast<CreatureDataAddon*>(addon)->move_flags &= ~(MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4);
847 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
851 void ObjectMgr::LoadCreatureAddons()
853 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
855 // check entry ids
856 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
857 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
858 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
859 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
861 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
863 // check entry ids
864 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
865 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
866 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
867 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
870 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
872 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
875 void ObjectMgr::LoadEquipmentTemplates()
877 sEquipmentStorage.Load();
879 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
881 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
883 if(!eqInfo)
884 continue;
886 for(uint8 j=0; j<3; j++)
888 if(!eqInfo->equipentry[j])
889 continue;
891 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
893 if(!dbcitem)
895 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
896 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
897 continue;
900 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
901 dbcitem->InventoryType != INVTYPE_SHIELD &&
902 dbcitem->InventoryType != INVTYPE_RANGED &&
903 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
904 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
905 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
906 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
907 dbcitem->InventoryType != INVTYPE_THROWN &&
908 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
910 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);
911 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
915 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
916 sLog.outString();
919 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
921 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
924 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
926 // Load creature model (display id)
927 if (data && data->displayid)
928 return data->displayid;
930 // use defaults from the template
931 uint32 display_id;
933 // DisplayID_A is used if no team is given
934 if (team == HORDE)
936 if(cinfo->DisplayID_H[0])
937 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
938 else
939 display_id = cinfo->DisplayID_H[1];
941 if(!display_id)
942 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
944 else
946 if(cinfo->DisplayID_A[0])
947 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
948 else
949 display_id = cinfo->DisplayID_A[1];
951 if(!display_id)
952 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
955 return display_id;
958 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
960 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
961 if(!minfo)
962 return NULL;
964 // If a model for another gender exists, 50% chance to use it
965 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
967 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
968 if(!minfo_tmp)
970 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
971 return minfo; // not fatal, just use the previous one
973 else
974 return minfo_tmp;
976 else
977 return minfo;
980 void ObjectMgr::LoadCreatureModelInfo()
982 sCreatureModelStorage.Load();
984 // post processing
985 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
987 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
988 if (!minfo)
989 continue;
991 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
992 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
994 if (minfo->gender > GENDER_NONE)
996 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
997 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1000 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1002 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1003 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1007 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1008 sLog.outString();
1011 void ObjectMgr::LoadCreatures()
1013 uint32 count = 0;
1014 // 0 1 2 3
1015 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1016 // 4 5 6 7 8 9 10 11
1017 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1018 // 12 13 14 15 16 17 18 19
1019 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1020 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1021 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1023 if(!result)
1025 barGoLink bar(1);
1027 bar.step();
1029 sLog.outString();
1030 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1031 return;
1034 // build single time for check creature data
1035 std::set<uint32> difficultyCreatures1;
1036 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1037 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1038 if(cInfo->DifficultyEntry1)
1039 difficultyCreatures1.insert(cInfo->DifficultyEntry1);
1041 // build single time for check spawnmask
1042 std::map<uint32,uint32> spawnMasks;
1043 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1044 if(sMapStore.LookupEntry(i))
1045 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1046 if (GetMapDifficultyData(i,Difficulty(k)))
1047 spawnMasks[i] |= (1 << k);
1049 barGoLink bar(result->GetRowCount());
1053 Field *fields = result->Fetch();
1054 bar.step();
1056 uint32 guid = fields[ 0].GetUInt32();
1057 uint32 entry = fields[ 1].GetUInt32();
1059 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1060 if(!cInfo)
1062 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1063 continue;
1066 CreatureData& data = mCreatureDataMap[guid];
1068 data.id = entry;
1069 data.mapid = fields[ 2].GetUInt32();
1070 data.displayid = fields[ 3].GetUInt32();
1071 data.equipmentId = fields[ 4].GetUInt32();
1072 data.posX = fields[ 5].GetFloat();
1073 data.posY = fields[ 6].GetFloat();
1074 data.posZ = fields[ 7].GetFloat();
1075 data.orientation = fields[ 8].GetFloat();
1076 data.spawntimesecs = fields[ 9].GetUInt32();
1077 data.spawndist = fields[10].GetFloat();
1078 data.currentwaypoint= fields[11].GetUInt32();
1079 data.curhealth = fields[12].GetUInt32();
1080 data.curmana = fields[13].GetUInt32();
1081 data.is_dead = fields[14].GetBool();
1082 data.movementType = fields[15].GetUInt8();
1083 data.spawnMask = fields[16].GetUInt8();
1084 data.phaseMask = fields[17].GetUInt16();
1085 int16 gameEvent = fields[18].GetInt16();
1086 int16 PoolId = fields[19].GetInt16();
1088 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1089 if(!mapEntry)
1091 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1092 continue;
1095 if (data.spawnMask & ~spawnMasks[data.mapid])
1096 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 );
1098 if(difficultyCreatures1.find(data.id)!=difficultyCreatures1.end())
1100 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty 1 template (entry: %u) in `creature_template`, skipped.",guid, data.id );
1101 continue;
1104 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1106 if(!GetEquipmentInfo(data.equipmentId))
1108 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);
1109 data.equipmentId = -1;
1113 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1115 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 );
1116 data.curhealth = cInfo->minhealth;
1119 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1121 if(!mapEntry || !mapEntry->IsDungeon())
1122 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);
1125 if(data.curmana < cInfo->minmana)
1127 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 );
1128 data.curmana = cInfo->minmana;
1131 if(data.spawndist < 0.0f)
1133 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1134 data.spawndist = 0.0f;
1136 else if(data.movementType == RANDOM_MOTION_TYPE)
1138 if(data.spawndist == 0.0f)
1140 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 );
1141 data.movementType = IDLE_MOTION_TYPE;
1144 else if(data.movementType == IDLE_MOTION_TYPE)
1146 if(data.spawndist != 0.0f)
1148 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1149 data.spawndist = 0.0f;
1153 if(data.phaseMask==0)
1155 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1156 data.phaseMask = 1;
1159 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1160 AddCreatureToGrid(guid, &data);
1162 ++count;
1164 } while (result->NextRow());
1166 delete result;
1168 sLog.outString();
1169 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1172 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1174 uint8 mask = data->spawnMask;
1175 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1177 if(mask & 1)
1179 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1180 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1182 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1183 cell_guids.creatures.insert(guid);
1188 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1190 uint8 mask = data->spawnMask;
1191 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1193 if(mask & 1)
1195 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1196 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1198 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1199 cell_guids.creatures.erase(guid);
1204 void ObjectMgr::LoadGameobjects()
1206 uint32 count = 0;
1208 // 0 1 2 3 4 5 6
1209 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1210 // 7 8 9 10 11 12 13 14 15 16 17
1211 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1212 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1213 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1215 if(!result)
1217 barGoLink bar(1);
1219 bar.step();
1221 sLog.outString();
1222 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1223 return;
1226 // build single time for check spawnmask
1227 std::map<uint32,uint32> spawnMasks;
1228 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1229 if(sMapStore.LookupEntry(i))
1230 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1231 if (GetMapDifficultyData(i,Difficulty(k)))
1232 spawnMasks[i] |= (1 << k);
1234 barGoLink bar(result->GetRowCount());
1238 Field *fields = result->Fetch();
1239 bar.step();
1241 uint32 guid = fields[ 0].GetUInt32();
1242 uint32 entry = fields[ 1].GetUInt32();
1244 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1245 if (!gInfo)
1247 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1248 continue;
1251 if(!gInfo->displayId)
1253 switch(gInfo->type)
1255 // can be invisible always and then not req. display id in like case
1256 case GAMEOBJECT_TYPE_TRAP:
1257 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1258 break;
1259 default:
1260 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1261 break;
1264 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1266 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1267 continue;
1270 GameObjectData& data = mGameObjectDataMap[guid];
1272 data.id = entry;
1273 data.mapid = fields[ 2].GetUInt32();
1274 data.posX = fields[ 3].GetFloat();
1275 data.posY = fields[ 4].GetFloat();
1276 data.posZ = fields[ 5].GetFloat();
1277 data.orientation = fields[ 6].GetFloat();
1278 data.rotation0 = fields[ 7].GetFloat();
1279 data.rotation1 = fields[ 8].GetFloat();
1280 data.rotation2 = fields[ 9].GetFloat();
1281 data.rotation3 = fields[10].GetFloat();
1282 data.spawntimesecs = fields[11].GetInt32();
1284 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1285 if(!mapEntry)
1287 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1288 continue;
1291 if (data.spawnMask & ~spawnMasks[data.mapid])
1292 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);
1294 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1296 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1299 data.animprogress = fields[12].GetUInt32();
1301 uint32 go_state = fields[13].GetUInt32();
1302 if (go_state >= MAX_GO_STATE)
1304 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1305 continue;
1307 data.go_state = GOState(go_state);
1309 data.spawnMask = fields[14].GetUInt8();
1310 data.phaseMask = fields[15].GetUInt16();
1311 int16 gameEvent = fields[16].GetInt16();
1312 int16 PoolId = fields[17].GetInt16();
1314 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1316 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1317 continue;
1320 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1322 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1323 continue;
1326 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1328 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1329 continue;
1332 if(data.phaseMask == 0)
1334 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1335 data.phaseMask = 1;
1338 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1339 AddGameobjectToGrid(guid, &data);
1340 ++count;
1342 } while (result->NextRow());
1344 delete result;
1346 sLog.outString();
1347 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1350 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1352 uint8 mask = data->spawnMask;
1353 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1355 if(mask & 1)
1357 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1358 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1360 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1361 cell_guids.gameobjects.insert(guid);
1366 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1368 uint8 mask = data->spawnMask;
1369 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1371 if(mask & 1)
1373 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1374 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1376 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1377 cell_guids.gameobjects.erase(guid);
1382 void ObjectMgr::LoadCreatureRespawnTimes()
1384 // remove outdated data
1385 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1387 uint32 count = 0;
1389 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1391 if(!result)
1393 barGoLink bar(1);
1395 bar.step();
1397 sLog.outString();
1398 sLog.outString(">> Loaded 0 creature respawn time.");
1399 return;
1402 barGoLink bar(result->GetRowCount());
1406 Field *fields = result->Fetch();
1407 bar.step();
1409 uint32 loguid = fields[0].GetUInt32();
1410 uint64 respawn_time = fields[1].GetUInt64();
1411 uint32 instance = fields[2].GetUInt32();
1413 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1415 ++count;
1416 } while (result->NextRow());
1418 delete result;
1420 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1421 sLog.outString();
1424 void ObjectMgr::LoadGameobjectRespawnTimes()
1426 // remove outdated data
1427 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1429 uint32 count = 0;
1431 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1433 if(!result)
1435 barGoLink bar(1);
1437 bar.step();
1439 sLog.outString();
1440 sLog.outString(">> Loaded 0 gameobject respawn time.");
1441 return;
1444 barGoLink bar(result->GetRowCount());
1448 Field *fields = result->Fetch();
1449 bar.step();
1451 uint32 loguid = fields[0].GetUInt32();
1452 uint64 respawn_time = fields[1].GetUInt64();
1453 uint32 instance = fields[2].GetUInt32();
1455 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1457 ++count;
1458 } while (result->NextRow());
1460 delete result;
1462 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1463 sLog.outString();
1466 // name must be checked to correctness (if received) before call this function
1467 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1469 uint64 guid = 0;
1471 CharacterDatabase.escape_string(name);
1473 // Player name safe to sending to DB (checked at login) and this function using
1474 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1475 if(result)
1477 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1479 delete result;
1482 return guid;
1485 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1487 // prevent DB access for online player
1488 if(Player* player = GetPlayer(guid))
1490 name = player->GetName();
1491 return true;
1494 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1496 if(result)
1498 name = (*result)[0].GetCppString();
1499 delete result;
1500 return true;
1503 return false;
1506 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1508 // prevent DB access for online player
1509 if(Player* player = GetPlayer(guid))
1511 return Player::TeamForRace(player->getRace());
1514 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1516 if(result)
1518 uint8 race = (*result)[0].GetUInt8();
1519 delete result;
1520 return Player::TeamForRace(race);
1523 return 0;
1526 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1528 // prevent DB access for online player
1529 if(Player* player = GetPlayer(guid))
1531 return player->GetSession()->GetAccountId();
1534 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1535 if(result)
1537 uint32 acc = (*result)[0].GetUInt32();
1538 delete result;
1539 return acc;
1542 return 0;
1545 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1547 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1548 if(result)
1550 uint32 acc = (*result)[0].GetUInt32();
1551 delete result;
1552 return acc;
1555 return 0;
1558 void ObjectMgr::LoadItemLocales()
1560 mItemLocaleMap.clear(); // need for reload case
1562 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");
1564 if(!result)
1566 barGoLink bar(1);
1568 bar.step();
1570 sLog.outString();
1571 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1572 return;
1575 barGoLink bar(result->GetRowCount());
1579 Field *fields = result->Fetch();
1580 bar.step();
1582 uint32 entry = fields[0].GetUInt32();
1584 ItemLocale& data = mItemLocaleMap[entry];
1586 for(int i = 1; i < MAX_LOCALE; ++i)
1588 std::string str = fields[1+2*(i-1)].GetCppString();
1589 if(!str.empty())
1591 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1592 if(idx >= 0)
1594 if(data.Name.size() <= idx)
1595 data.Name.resize(idx+1);
1597 data.Name[idx] = str;
1601 str = fields[1+2*(i-1)+1].GetCppString();
1602 if(!str.empty())
1604 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1605 if(idx >= 0)
1607 if(data.Description.size() <= idx)
1608 data.Description.resize(idx+1);
1610 data.Description[idx] = str;
1614 } while (result->NextRow());
1616 delete result;
1618 sLog.outString();
1619 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1622 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1624 template<class D>
1625 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1627 dst = D(objmgr.GetScriptId(src));
1631 void ObjectMgr::LoadItemPrototypes()
1633 SQLItemLoader loader;
1634 loader.Load(sItemStorage);
1635 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1636 sLog.outString();
1638 // check data correctness
1639 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1641 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1642 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1643 if(!proto)
1645 /* to many errors, and possible not all items really used in game
1646 if (dbcitem)
1647 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1649 continue;
1652 if(dbcitem)
1654 if(proto->Class != dbcitem->Class)
1656 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1657 // It safe let use Class from DB
1659 /* disabled: have some strange wrong cases for Subclass values.
1660 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1661 if(proto->SubClass != dbcitem->SubClass)
1663 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);
1664 // It safe let use Subclass from DB
1668 if(proto->Unk0 != dbcitem->Unk0)
1670 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1671 // It safe let use Unk0 from DB
1674 if(proto->Material != dbcitem->Material)
1676 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1677 // It safe let use Material from DB
1680 if(proto->InventoryType != dbcitem->InventoryType)
1682 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1683 // It safe let use InventoryType from DB
1686 if(proto->DisplayInfoID != dbcitem->DisplayId)
1688 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1689 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1691 if(proto->Sheath != dbcitem->Sheath)
1693 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1694 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1697 else
1699 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1702 if(proto->Class >= MAX_ITEM_CLASS)
1704 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1705 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1708 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1710 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1711 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1714 if(proto->Quality >= MAX_ITEM_QUALITY)
1716 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1717 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1720 if(proto->BuyCount <= 0)
1722 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1723 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1726 if(proto->InventoryType >= MAX_INVTYPE)
1728 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1729 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1732 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1734 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1735 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1739 // can be used in equip slot, as page read use in inventory, or spell casting at use
1740 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1741 if(!req)
1743 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1745 if(proto->Spells[j].SpellId)
1747 req = true;
1748 break;
1753 if(req)
1755 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1756 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1758 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1759 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1763 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1765 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1766 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1769 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1770 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1772 if(proto->RequiredReputationFaction)
1774 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1776 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1777 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1780 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1781 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1783 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1784 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1786 if(proto->MaxCount < -1)
1788 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1789 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1792 if(proto->Stackable == 0)
1794 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1795 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1797 else if(proto->Stackable < -1)
1799 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1800 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1802 else if(proto->Stackable > 1000)
1804 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1805 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1808 if(proto->ContainerSlots > MAX_BAG_SIZE)
1810 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1811 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1814 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1816 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1817 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1820 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1822 // for ItemStatValue != 0
1823 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1825 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1826 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1829 switch(proto->ItemStat[j].ItemStatType)
1831 case ITEM_MOD_SPELL_HEALING_DONE:
1832 case ITEM_MOD_SPELL_DAMAGE_DONE:
1833 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1834 break;
1835 default:
1836 break;
1840 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1842 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1844 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1845 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1849 // special format
1850 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1852 // spell_1
1853 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1855 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);
1856 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1857 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1858 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1859 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1862 // spell_2 have learning spell
1863 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1865 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);
1866 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1867 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1868 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1870 else if(!proto->Spells[1].SpellId)
1872 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1873 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1874 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1876 else
1878 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1879 if(!spellInfo)
1881 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1882 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1883 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1884 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1886 // allowed only in special format
1887 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1889 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1890 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1891 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1892 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1896 // spell_3*,spell_4*,spell_5* is empty
1897 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1899 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1901 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1902 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1903 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1905 else if(proto->Spells[j].SpellId != 0)
1907 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1908 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1912 // normal spell list
1913 else
1915 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1917 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1919 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1920 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1921 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1923 // on hit can be sued only at weapon
1924 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1926 if(proto->Class != ITEM_CLASS_WEAPON)
1927 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);
1930 if(proto->Spells[j].SpellId)
1932 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1933 if(!spellInfo)
1935 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1936 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1938 // allowed only in special format
1939 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1941 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1942 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1948 if(proto->Bonding >= MAX_BIND_TYPE)
1949 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1951 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1952 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1954 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1955 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1957 if(proto->Sheath >= MAX_SHEATHETYPE)
1959 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1960 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1963 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1965 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1966 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1969 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1971 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1972 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1975 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1977 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1978 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1981 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1982 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1984 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1985 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1987 if(proto->BagFamily)
1989 // check bits
1990 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1992 uint32 mask = 1 << j;
1993 if((proto->BagFamily & mask)==0)
1994 continue;
1996 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1997 if(!bf)
1999 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2000 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2001 continue;
2004 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2006 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2007 if(!ctEntry)
2009 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2010 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2016 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2017 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2019 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2021 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2023 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2024 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2028 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2029 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2031 if(proto->FoodType >= MAX_PET_DIET)
2033 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2034 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2037 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2039 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2040 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2043 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2045 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2046 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2051 void ObjectMgr::LoadItemRequiredTarget()
2053 m_ItemRequiredTarget.clear(); // needed for reload case
2055 uint32 count = 0;
2057 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2059 if (!result)
2061 barGoLink bar(1);
2063 bar.step();
2065 sLog.outString();
2066 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2067 return;
2070 barGoLink bar(result->GetRowCount());
2074 Field *fields = result->Fetch();
2075 bar.step();
2077 uint32 uiItemId = fields[0].GetUInt32();
2078 uint32 uiType = fields[1].GetUInt32();
2079 uint32 uiTargetEntry = fields[2].GetUInt32();
2081 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2083 if (!pItemProto)
2085 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2086 continue;
2089 bool bIsItemSpellValid = false;
2091 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2093 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2095 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2096 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2098 SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2099 if (bounds.first != bounds.second)
2100 break;
2102 for (int j = 0; j < 3; ++j)
2104 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2105 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2106 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2107 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2109 bIsItemSpellValid = true;
2110 break;
2113 if (bIsItemSpellValid)
2114 break;
2119 if (!bIsItemSpellValid)
2121 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);
2122 continue;
2125 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2127 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2128 continue;
2131 if (!uiTargetEntry)
2133 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2134 continue;
2137 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2139 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2140 continue;
2143 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2145 ++count;
2146 } while (result->NextRow());
2148 delete result;
2150 sLog.outString();
2151 sLog.outString(">> Loaded %u Item required targets", count);
2154 void ObjectMgr::LoadPetLevelInfo()
2156 // Loading levels data
2158 // 0 1 2 3 4 5 6 7 8 9
2159 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2161 uint32 count = 0;
2163 if (!result)
2165 barGoLink bar( 1 );
2166 bar.step();
2168 sLog.outString();
2169 sLog.outString(">> Loaded %u level pet stats definitions", count);
2170 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2171 return;
2174 barGoLink bar( result->GetRowCount() );
2178 Field* fields = result->Fetch();
2180 uint32 creature_id = fields[0].GetUInt32();
2181 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2183 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2184 continue;
2187 uint32 current_level = fields[1].GetUInt32();
2188 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2190 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2191 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2192 else
2194 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2195 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2197 continue;
2199 else if(current_level < 1)
2201 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2202 continue;
2205 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2207 if(pInfoMapEntry==NULL)
2208 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2210 // data for level 1 stored in [0] array element, ...
2211 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2213 pLevelInfo->health = fields[2].GetUInt16();
2214 pLevelInfo->mana = fields[3].GetUInt16();
2215 pLevelInfo->armor = fields[9].GetUInt16();
2217 for (int i = 0; i < MAX_STATS; i++)
2219 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2222 bar.step();
2223 ++count;
2225 while (result->NextRow());
2227 delete result;
2229 sLog.outString();
2230 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2233 // Fill gaps and check integrity
2234 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2236 PetLevelInfo* pInfo = itr->second;
2238 // fatal error if no level 1 data
2239 if(!pInfo || pInfo[0].health == 0 )
2241 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2242 exit(1);
2245 // fill level gaps
2246 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2248 if(pInfo[level].health == 0)
2250 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2251 pInfo[level] = pInfo[level-1];
2257 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2259 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2260 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2262 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2263 if(itr == petInfo.end())
2264 return NULL;
2266 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2269 void ObjectMgr::LoadPlayerInfo()
2271 // Load playercreate
2273 // 0 1 2 3 4 5 6
2274 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2276 uint32 count = 0;
2278 if (!result)
2280 barGoLink bar( 1 );
2282 sLog.outString();
2283 sLog.outString( ">> Loaded %u player create definitions", count );
2284 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2285 exit(1);
2288 barGoLink bar( result->GetRowCount() );
2292 Field* fields = result->Fetch();
2294 uint32 current_race = fields[0].GetUInt32();
2295 uint32 current_class = fields[1].GetUInt32();
2296 uint32 mapId = fields[2].GetUInt32();
2297 uint32 zoneId = fields[3].GetUInt32();
2298 float positionX = fields[4].GetFloat();
2299 float positionY = fields[5].GetFloat();
2300 float positionZ = fields[6].GetFloat();
2302 if(current_race >= MAX_RACES)
2304 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2305 continue;
2308 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2309 if(!rEntry)
2311 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2312 continue;
2315 if(current_class >= MAX_CLASSES)
2317 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2318 continue;
2321 if(!sChrClassesStore.LookupEntry(current_class))
2323 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2324 continue;
2327 // accept DB data only for valid position (and non instanceable)
2328 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2330 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2331 continue;
2334 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2336 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2337 continue;
2340 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2342 pInfo->mapId = mapId;
2343 pInfo->zoneId = zoneId;
2344 pInfo->positionX = positionX;
2345 pInfo->positionY = positionY;
2346 pInfo->positionZ = positionZ;
2348 pInfo->displayId_m = rEntry->model_m;
2349 pInfo->displayId_f = rEntry->model_f;
2351 bar.step();
2352 ++count;
2354 while (result->NextRow());
2356 delete result;
2358 sLog.outString();
2359 sLog.outString( ">> Loaded %u player create definitions", count );
2362 // Load playercreate items
2364 // 0 1 2 3
2365 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2367 uint32 count = 0;
2369 if (!result)
2371 barGoLink bar( 1 );
2373 bar.step();
2375 sLog.outString();
2376 sLog.outString( ">> Loaded %u custom player create items", count );
2378 else
2380 barGoLink bar( result->GetRowCount() );
2384 Field* fields = result->Fetch();
2386 uint32 current_race = fields[0].GetUInt32();
2387 if(current_race >= MAX_RACES)
2389 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2390 continue;
2393 uint32 current_class = fields[1].GetUInt32();
2394 if(current_class >= MAX_CLASSES)
2396 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2397 continue;
2400 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2402 uint32 item_id = fields[2].GetUInt32();
2404 if(!GetItemPrototype(item_id))
2406 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);
2407 continue;
2410 uint32 amount = fields[3].GetUInt32();
2412 if(!amount)
2414 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2415 continue;
2418 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2420 bar.step();
2421 ++count;
2423 while(result->NextRow());
2425 delete result;
2427 sLog.outString();
2428 sLog.outString( ">> Loaded %u custom player create items", count );
2432 // Load playercreate spells
2434 // 0 1 2
2435 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2437 uint32 count = 0;
2439 if (!result)
2441 barGoLink bar( 1 );
2443 sLog.outString();
2444 sLog.outString( ">> Loaded %u player create spells", count );
2445 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2447 else
2449 barGoLink bar( result->GetRowCount() );
2453 Field* fields = result->Fetch();
2455 uint32 current_race = fields[0].GetUInt32();
2456 if(current_race >= MAX_RACES)
2458 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2459 continue;
2462 uint32 current_class = fields[1].GetUInt32();
2463 if(current_class >= MAX_CLASSES)
2465 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2466 continue;
2469 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2470 pInfo->spell.push_back(fields[2].GetUInt32());
2472 bar.step();
2473 ++count;
2475 while( result->NextRow() );
2477 delete result;
2479 sLog.outString();
2480 sLog.outString( ">> Loaded %u player create spells", count );
2484 // Load playercreate actions
2486 // 0 1 2 3 4
2487 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2489 uint32 count = 0;
2491 if (!result)
2493 barGoLink bar( 1 );
2495 sLog.outString();
2496 sLog.outString( ">> Loaded %u player create actions", count );
2497 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2499 else
2501 barGoLink bar( result->GetRowCount() );
2505 Field* fields = result->Fetch();
2507 uint32 current_race = fields[0].GetUInt32();
2508 if(current_race >= MAX_RACES)
2510 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2511 continue;
2514 uint32 current_class = fields[1].GetUInt32();
2515 if(current_class >= MAX_CLASSES)
2517 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2518 continue;
2521 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2522 pInfo->action.push_back(PlayerCreateInfoAction(fields[2].GetUInt8(),fields[3].GetUInt32(),fields[4].GetUInt8()));
2524 bar.step();
2525 ++count;
2527 while( result->NextRow() );
2529 delete result;
2531 sLog.outString();
2532 sLog.outString( ">> Loaded %u player create actions", count );
2536 // Loading levels data (class only dependent)
2538 // 0 1 2 3
2539 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2541 uint32 count = 0;
2543 if (!result)
2545 barGoLink bar( 1 );
2547 sLog.outString();
2548 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2549 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2550 exit(1);
2553 barGoLink bar( result->GetRowCount() );
2557 Field* fields = result->Fetch();
2559 uint32 current_class = fields[0].GetUInt32();
2560 if(current_class >= MAX_CLASSES)
2562 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2563 continue;
2566 uint32 current_level = fields[1].GetUInt32();
2567 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2569 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2570 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2571 else
2573 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2574 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2576 continue;
2579 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2581 if(!pClassInfo->levelInfo)
2582 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2584 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2586 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2587 pClassLevelInfo->basemana = fields[3].GetUInt16();
2589 bar.step();
2590 ++count;
2592 while (result->NextRow());
2594 delete result;
2596 sLog.outString();
2597 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2600 // Fill gaps and check integrity
2601 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2603 // skip non existed classes
2604 if(!sChrClassesStore.LookupEntry(class_))
2605 continue;
2607 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2609 // fatal error if no level 1 data
2610 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2612 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2613 exit(1);
2616 // fill level gaps
2617 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2619 if(pClassInfo->levelInfo[level].basehealth == 0)
2621 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2622 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2627 // Loading levels data (class/race dependent)
2629 // 0 1 2 3 4 5 6 7
2630 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2632 uint32 count = 0;
2634 if (!result)
2636 barGoLink bar( 1 );
2638 sLog.outString();
2639 sLog.outString( ">> Loaded %u level stats definitions", count );
2640 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2641 exit(1);
2644 barGoLink bar( result->GetRowCount() );
2648 Field* fields = result->Fetch();
2650 uint32 current_race = fields[0].GetUInt32();
2651 if(current_race >= MAX_RACES)
2653 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2654 continue;
2657 uint32 current_class = fields[1].GetUInt32();
2658 if(current_class >= MAX_CLASSES)
2660 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2661 continue;
2664 uint32 current_level = fields[2].GetUInt32();
2665 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2667 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2668 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2669 else
2671 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2672 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2674 continue;
2677 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2679 if(!pInfo->levelInfo)
2680 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2682 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2684 for (int i = 0; i < MAX_STATS; i++)
2686 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2689 bar.step();
2690 ++count;
2692 while (result->NextRow());
2694 delete result;
2696 sLog.outString();
2697 sLog.outString( ">> Loaded %u level stats definitions", count );
2700 // Fill gaps and check integrity
2701 for (int race = 0; race < MAX_RACES; ++race)
2703 // skip non existed races
2704 if(!sChrRacesStore.LookupEntry(race))
2705 continue;
2707 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2709 // skip non existed classes
2710 if(!sChrClassesStore.LookupEntry(class_))
2711 continue;
2713 PlayerInfo* pInfo = &playerInfo[race][class_];
2715 // skip non loaded combinations
2716 if(!pInfo->displayId_m || !pInfo->displayId_f)
2717 continue;
2719 // skip expansion races if not playing with expansion
2720 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2721 continue;
2723 // skip expansion classes if not playing with expansion
2724 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2725 continue;
2727 // fatal error if no level 1 data
2728 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2730 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2731 exit(1);
2734 // fill level gaps
2735 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2737 if(pInfo->levelInfo[level].stats[0] == 0)
2739 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2740 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2746 // Loading xp per level data
2748 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2749 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2750 mPlayerXPperLevel[level] = 0;
2752 // 0 1
2753 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2755 uint32 count = 0;
2757 if (!result)
2759 barGoLink bar( 1 );
2761 sLog.outString();
2762 sLog.outString( ">> Loaded %u xp for level definitions", count );
2763 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2764 exit(1);
2767 barGoLink bar( result->GetRowCount() );
2771 Field* fields = result->Fetch();
2773 uint32 current_level = fields[0].GetUInt32();
2774 uint32 current_xp = fields[1].GetUInt32();
2776 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2778 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2779 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2780 else
2782 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2783 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2785 continue;
2787 //PlayerXPperLevel
2788 mPlayerXPperLevel[current_level] = current_xp;
2789 bar.step();
2790 ++count;
2792 while (result->NextRow());
2794 delete result;
2796 sLog.outString();
2797 sLog.outString( ">> Loaded %u xp for level definitions", count );
2800 // fill level gaps
2801 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2803 if( mPlayerXPperLevel[level] == 0)
2805 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2806 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2811 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2813 if(level < 1 || class_ >= MAX_CLASSES)
2814 return;
2816 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2818 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2819 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2821 *info = pInfo->levelInfo[level-1];
2824 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2826 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2827 return;
2829 PlayerInfo const* pInfo = &playerInfo[race][class_];
2830 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2831 return;
2833 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2834 *info = pInfo->levelInfo[level-1];
2835 else
2836 BuildPlayerLevelInfo(race,class_,level,info);
2839 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2841 // base data (last known level)
2842 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2844 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2846 switch(_class)
2848 case CLASS_WARRIOR:
2849 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2850 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2851 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2852 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2853 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2854 break;
2855 case CLASS_PALADIN:
2856 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2857 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2858 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2859 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2860 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2861 break;
2862 case CLASS_HUNTER:
2863 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2864 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2865 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2866 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2867 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2868 break;
2869 case CLASS_ROGUE:
2870 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2871 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2872 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2873 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2874 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2875 break;
2876 case CLASS_PRIEST:
2877 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2878 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2879 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2880 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2881 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2882 break;
2883 case CLASS_SHAMAN:
2884 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2885 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2886 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2887 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2888 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2889 break;
2890 case CLASS_MAGE:
2891 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2892 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2893 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2894 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2895 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2896 break;
2897 case CLASS_WARLOCK:
2898 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2899 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2900 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2901 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2902 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2903 break;
2904 case CLASS_DRUID:
2905 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2906 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2907 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2908 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2909 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2914 void ObjectMgr::LoadGuilds()
2916 Guild *newGuild;
2917 uint32 count = 0;
2919 // 0 1 2 3 4 5 6
2920 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
2921 // 7 8 9 10 11 12
2922 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
2923 "FROM guild ORDER BY guildid ASC");
2925 if( !result )
2928 barGoLink bar( 1 );
2930 bar.step();
2932 sLog.outString();
2933 sLog.outString( ">> Loaded %u guild definitions", count );
2934 return;
2937 // load guild ranks
2938 // 0 1 2 3 4
2939 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
2941 // load guild members
2942 // 0 1 2 3 4 5 6
2943 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
2944 // 7 8 9 10 11 12
2945 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
2946 // 13 14 15 16 17 18
2947 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
2948 // 19 20 21 22 23
2949 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
2950 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
2952 // load guild bank tab rights
2953 // 0 1 2 3 4
2954 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
2956 barGoLink bar( result->GetRowCount() );
2960 //Field *fields = result->Fetch();
2962 bar.step();
2963 ++count;
2965 newGuild = new Guild;
2966 if (!newGuild->LoadGuildFromDB(result) ||
2967 !newGuild->LoadRanksFromDB(guildRanksResult) ||
2968 !newGuild->LoadMembersFromDB(guildMembersResult) ||
2969 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
2970 !newGuild->CheckGuildStructure()
2973 newGuild->Disband();
2974 delete newGuild;
2975 continue;
2977 AddGuild(newGuild);
2979 }while( result->NextRow() );
2981 delete result;
2982 delete guildRanksResult;
2983 delete guildMembersResult;
2984 delete guildBankTabRightsResult;
2986 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
2987 //you can comment these lines if you don't plan to change CONFIG_GUILD_EVENT_LOG_COUNT and CONFIG_GUILD_BANK_EVENT_LOG_COUNT
2988 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_EVENT_LOG_COUNT));
2989 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));
2991 sLog.outString();
2992 sLog.outString( ">> Loaded %u guild definitions", count );
2995 void ObjectMgr::LoadArenaTeams()
2997 uint32 count = 0;
2999 // 0 1 2 3 4 5
3000 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3001 // 6 7 8 9 10 11 12 13 14
3002 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3003 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3005 if( !result )
3008 barGoLink bar( 1 );
3010 bar.step();
3012 sLog.outString();
3013 sLog.outString( ">> Loaded %u arenateam definitions", count );
3014 return;
3017 // load arena_team members
3018 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3019 // 0 1 2 3 4 5 6 7 8
3020 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3021 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3023 barGoLink bar( result->GetRowCount() );
3027 Field *fields = result->Fetch();
3029 bar.step();
3030 ++count;
3032 ArenaTeam *newArenaTeam = new ArenaTeam;
3033 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3034 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3036 newArenaTeam->Disband(NULL);
3037 delete newArenaTeam;
3038 continue;
3040 AddArenaTeam(newArenaTeam);
3041 }while( result->NextRow() );
3043 delete result;
3044 delete arenaTeamMembersResult;
3046 sLog.outString();
3047 sLog.outString( ">> Loaded %u arenateam definitions", count );
3050 void ObjectMgr::LoadGroups()
3052 // -- loading groups --
3053 Group *group = NULL;
3054 uint64 leaderGuid = 0;
3055 uint32 count = 0;
3056 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3057 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid FROM groups");
3059 if( !result )
3061 barGoLink bar( 1 );
3063 bar.step();
3065 sLog.outString();
3066 sLog.outString( ">> Loaded %u group definitions", count );
3067 return;
3070 barGoLink bar( result->GetRowCount() );
3074 bar.step();
3075 Field *fields = result->Fetch();
3076 ++count;
3077 leaderGuid = MAKE_NEW_GUID(fields[16].GetUInt32(),0,HIGHGUID_PLAYER);
3079 group = new Group;
3080 if(!group->LoadGroupFromDB(leaderGuid, result, false))
3082 group->Disband();
3083 delete group;
3084 continue;
3086 AddGroup(group);
3087 }while( result->NextRow() );
3089 delete result;
3091 sLog.outString();
3092 sLog.outString( ">> Loaded %u group definitions", count );
3094 // -- loading members --
3095 count = 0;
3096 group = NULL;
3097 leaderGuid = 0;
3098 // 0 1 2 3
3099 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
3100 if(!result)
3102 barGoLink bar2( 1 );
3103 bar2.step();
3105 else
3107 barGoLink bar2( result->GetRowCount() );
3110 bar2.step();
3111 Field *fields = result->Fetch();
3112 count++;
3113 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
3114 if(!group || group->GetLeaderGUID() != leaderGuid)
3116 group = GetGroupByLeader(leaderGuid);
3117 if(!group)
3119 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
3120 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3121 continue;
3125 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
3127 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
3128 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3130 }while( result->NextRow() );
3131 delete result;
3134 // clean groups
3135 // TODO: maybe delete from the DB before loading in this case
3136 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
3138 if((*itr)->GetMembersCount() < 2)
3140 (*itr)->Disband();
3141 delete *itr;
3142 mGroupSet.erase(itr++);
3144 else
3145 ++itr;
3148 // -- loading instances --
3149 count = 0;
3150 group = NULL;
3151 leaderGuid = 0;
3152 result = CharacterDatabase.Query(
3153 // 0 1 2 3 4 5
3154 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
3155 // 6
3156 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
3157 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
3160 if(!result)
3162 barGoLink bar2( 1 );
3163 bar2.step();
3165 else
3167 barGoLink bar2( result->GetRowCount() );
3170 bar2.step();
3171 Field *fields = result->Fetch();
3172 count++;
3173 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3174 if(!group || group->GetLeaderGUID() != leaderGuid)
3176 group = GetGroupByLeader(leaderGuid);
3177 if(!group)
3179 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
3180 continue;
3184 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
3185 if(!mapEntry || !mapEntry->IsDungeon())
3187 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
3188 continue;
3191 uint32 diff = fields[4].GetUInt8();
3192 if(diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3194 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff);
3195 diff = 0; // default for both difficaly types
3198 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3199 group->BindToInstance(save, fields[3].GetBool(), true);
3200 }while( result->NextRow() );
3201 delete result;
3204 sLog.outString();
3205 sLog.outString( ">> Loaded %u group-instance binds total", count );
3207 sLog.outString();
3208 sLog.outString( ">> Loaded %u group members total", count );
3211 void ObjectMgr::LoadQuests()
3213 // For reload case
3214 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3215 delete itr->second;
3216 mQuestTemplates.clear();
3218 mExclusiveQuestGroups.clear();
3220 // 0 1 2 3 4 5 6 7 8
3221 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3222 // 9 10 11 12 13 14 15 16
3223 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3224 // 17 18 19 20 21 22 23 24 25 26 27 28
3225 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
3226 // 29 30 31 32 33 34 35 36 37 38
3227 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3228 // 39 40 41 42 43 44 45 46 47 48 49 50
3229 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3230 // 51 52 53 54 55 56 57 58
3231 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3232 // 59 60 61 62 63 64 65 66
3233 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3234 // 67 68 69 70
3235 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3236 // 71 72 73 74 75 76
3237 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3238 // 77 78 79 80 81 82
3239 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3240 // 83 84 85 86 87 88 89 90
3241 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3242 // 91 92 93 94 95 96 97 98 99 100
3243 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3244 // 101 102 103 104 105 106 107 108 109 110 111
3245 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3246 // 112 113 114 115 116 117 118 119
3247 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3248 // 120 121 122 123 124 125
3249 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3250 // 126 127 128 129
3251 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3252 // 130 131
3253 "StartScript, CompleteScript"
3254 " FROM quest_template");
3255 if(result == NULL)
3257 barGoLink bar( 1 );
3258 bar.step();
3260 sLog.outString();
3261 sLog.outString( ">> Loaded 0 quests definitions" );
3262 sLog.outErrorDb("`quest_template` table is empty!");
3263 return;
3266 // create multimap previous quest for each existed quest
3267 // some quests can have many previous maps set by NextQuestId in previous quest
3268 // for example set of race quests can lead to single not race specific quest
3269 barGoLink bar( result->GetRowCount() );
3272 bar.step();
3273 Field *fields = result->Fetch();
3275 Quest * newQuest = new Quest(fields);
3276 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3277 } while( result->NextRow() );
3279 delete result;
3281 // Post processing
3283 std::map<uint32,uint32> usedMailTemplates;
3285 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3287 Quest * qinfo = iter->second;
3289 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3291 if( qinfo->GetQuestMethod() >= 3 )
3293 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3296 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3298 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3299 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
3300 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3303 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3305 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3307 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3308 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3312 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3314 // at auto-reward can be rewarded only RewChoiceItemId[0]
3315 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3317 if(uint32 id = qinfo->RewChoiceItemId[j])
3319 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3320 qinfo->GetQuestId(),j+1,id,j+1);
3321 // no changes, quest ignore this data
3326 // client quest log visual (area case)
3327 if( qinfo->ZoneOrSort > 0 )
3329 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3331 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3332 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3333 // no changes, quest not dependent from this value but can have problems at client
3336 // client quest log visual (sort case)
3337 if( qinfo->ZoneOrSort < 0 )
3339 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3340 if( !qSort )
3342 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3343 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3344 // 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)
3346 //check SkillOrClass value (class case).
3347 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3349 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3350 if(qinfo->SkillOrClass < 0)
3352 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3353 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3356 //check for proper SkillOrClass value (skill case)
3357 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3359 // skill is positive value in SkillOrClass
3360 if(qinfo->SkillOrClass != skill_id )
3362 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3363 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3364 //override, and force proper value here?
3369 // SkillOrClass (class case)
3370 if( qinfo->SkillOrClass < 0 )
3372 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3374 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3375 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3378 // SkillOrClass (skill case)
3379 if( qinfo->SkillOrClass > 0 )
3381 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3383 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3384 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3388 if( qinfo->RequiredSkillValue )
3390 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3392 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3393 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3394 // no changes, quest can't be done for this requirement
3397 if( qinfo->SkillOrClass <= 0 )
3399 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3400 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3401 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3404 // else Skill quests can have 0 skill level, this is ok
3406 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3408 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3409 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3410 // no changes, quest can't be done for this requirement
3413 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3415 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3416 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3417 // no changes, quest can't be done for this requirement
3420 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3422 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3423 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3424 // no changes, quest can't be done for this requirement
3427 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3429 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3430 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3431 // no changes, quest can't be done for this requirement
3434 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3436 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3437 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3438 // no changes, quest can't be done for this requirement
3441 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3443 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3444 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3445 // warning
3448 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3450 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3451 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3452 // warning
3455 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3457 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3458 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3459 // warning
3462 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3464 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3465 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3466 qinfo->CharTitleId = 0;
3467 // quest can't reward this title
3470 if(qinfo->SrcItemId)
3472 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3474 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3475 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3476 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3478 else if(qinfo->SrcItemCount==0)
3480 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3481 qinfo->GetQuestId(),qinfo->SrcItemId);
3482 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3485 else if(qinfo->SrcItemCount>0)
3487 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3488 qinfo->GetQuestId(),qinfo->SrcItemCount);
3489 qinfo->SrcItemCount=0; // no quest work changes in fact
3492 if(qinfo->SrcSpell)
3494 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3495 if(!spellInfo)
3497 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3498 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3499 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3501 else if(!SpellMgr::IsSpellValid(spellInfo))
3503 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3504 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3505 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3509 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3511 uint32 id = qinfo->ReqItemId[j];
3512 if(id)
3514 if(qinfo->ReqItemCount[j] == 0)
3516 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3517 qinfo->GetQuestId(), j+1, id, j+1);
3518 // no changes, quest can't be done for this requirement
3521 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3523 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3525 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3526 qinfo->GetQuestId(), j+1, id, id);
3527 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3530 else if(qinfo->ReqItemCount[j] > 0)
3532 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3533 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3534 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3538 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3540 uint32 id = qinfo->ReqSourceId[j];
3541 if(id)
3543 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3545 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3546 qinfo->GetQuestId(),j+1,id,id);
3547 // no changes, quest can't be done for this requirement
3550 else
3552 if(qinfo->ReqSourceCount[j]>0)
3554 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3555 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3556 // no changes, quest ignore this data
3561 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3563 uint32 id = qinfo->ReqSpell[j];
3564 if(id)
3566 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3567 if(!spellInfo)
3569 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3570 qinfo->GetQuestId(),j+1,id,id);
3571 continue;
3574 if(!qinfo->ReqCreatureOrGOId[j])
3576 bool found = false;
3577 for(int k = 0; k < 3; ++k)
3579 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3580 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3582 found = true;
3583 break;
3587 if(found)
3589 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3591 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);
3593 // this will prevent quest completing without objective
3594 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3597 else
3599 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.",
3600 qinfo->GetQuestId(),j+1,id,j+1,id);
3601 // no changes, quest can't be done for this requirement
3607 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3609 int32 id = qinfo->ReqCreatureOrGOId[j];
3610 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3612 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3613 qinfo->GetQuestId(),j+1,id,uint32(-id));
3614 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3617 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3619 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3620 qinfo->GetQuestId(),j+1,id,uint32(id));
3621 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3624 if(id)
3626 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3628 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3630 if(!qinfo->ReqCreatureOrGOCount[j])
3632 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3633 qinfo->GetQuestId(),j+1,id,j+1);
3634 // no changes, quest can be incorrectly done, but we already report this
3637 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3639 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3640 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3641 // no changes, quest ignore this data
3645 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3647 uint32 id = qinfo->RewChoiceItemId[j];
3648 if(id)
3650 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3652 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3653 qinfo->GetQuestId(),j+1,id,id);
3654 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3657 if(!qinfo->RewChoiceItemCount[j])
3659 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3660 qinfo->GetQuestId(),j+1,id,j+1);
3661 // no changes, quest can't be done
3664 else if(qinfo->RewChoiceItemCount[j]>0)
3666 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3667 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3668 // no changes, quest ignore this data
3672 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3674 uint32 id = qinfo->RewItemId[j];
3675 if(id)
3677 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3679 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3680 qinfo->GetQuestId(),j+1,id,id);
3681 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3684 if(!qinfo->RewItemCount[j])
3686 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3687 qinfo->GetQuestId(),j+1,id,j+1);
3688 // no changes
3691 else if(qinfo->RewItemCount[j]>0)
3693 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3694 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3695 // no changes, quest ignore this data
3699 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3701 if(qinfo->RewRepFaction[j])
3703 if(!qinfo->RewRepValue[j])
3705 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3706 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3707 // no changes
3710 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3712 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.",
3713 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3714 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3717 else if(qinfo->RewRepValue[j]!=0)
3719 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3720 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3721 // no changes, quest ignore this data
3725 if(qinfo->RewSpell)
3727 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3729 if(!spellInfo)
3731 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3732 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3733 qinfo->RewSpell = 0; // no spell reward will display for this quest
3735 else if(!SpellMgr::IsSpellValid(spellInfo))
3737 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3738 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3739 qinfo->RewSpell = 0; // no spell reward will display for this quest
3741 else if(GetTalentSpellCost(qinfo->RewSpell))
3743 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3744 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3745 qinfo->RewSpell = 0; // no spell reward will display for this quest
3749 if(qinfo->RewSpellCast)
3751 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3753 if(!spellInfo)
3755 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3756 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3757 qinfo->RewSpellCast = 0; // no spell will be casted on player
3759 else if(!SpellMgr::IsSpellValid(spellInfo))
3761 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3762 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3763 qinfo->RewSpellCast = 0; // no spell will be casted on player
3765 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3767 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3768 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3769 qinfo->RewSpellCast = 0; // no spell will be casted on player
3773 if (qinfo->RewMailTemplateId)
3775 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3777 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3778 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3779 qinfo->RewMailTemplateId = 0; // no mail will send to player
3780 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3782 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3784 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3785 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3786 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3787 qinfo->RewMailTemplateId = 0; // no mail will send to player
3788 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3790 else
3791 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3794 if (qinfo->NextQuestInChain)
3796 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3797 if (qNextItr == mQuestTemplates.end())
3799 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3800 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3801 qinfo->NextQuestInChain = 0;
3803 else
3804 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3807 // fill additional data stores
3808 if (qinfo->PrevQuestId)
3810 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3812 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3814 else
3816 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3820 if(qinfo->NextQuestId)
3822 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3823 if (qNextItr == mQuestTemplates.end())
3825 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3827 else
3829 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3830 qNextItr->second->prevQuests.push_back(signedQuestId);
3834 if(qinfo->ExclusiveGroup)
3835 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3836 if(qinfo->LimitTime)
3837 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3840 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3841 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3843 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3844 if(!spellInfo)
3845 continue;
3847 for(int j = 0; j < 3; ++j)
3849 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3850 continue;
3852 uint32 quest_id = spellInfo->EffectMiscValue[j];
3854 Quest const* quest = GetQuestTemplate(quest_id);
3856 // some quest referenced in spells not exist (outdated spells)
3857 if(!quest)
3858 continue;
3860 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3862 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);
3864 // this will prevent quest completing without objective
3865 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3870 sLog.outString();
3871 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3874 void ObjectMgr::LoadQuestLocales()
3876 mQuestLocaleMap.clear(); // need for reload case
3878 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3879 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3880 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3881 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3882 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3883 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3884 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3885 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3886 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3887 " FROM locales_quest"
3890 if(!result)
3892 barGoLink bar(1);
3894 bar.step();
3896 sLog.outString();
3897 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3898 return;
3901 barGoLink bar(result->GetRowCount());
3905 Field *fields = result->Fetch();
3906 bar.step();
3908 uint32 entry = fields[0].GetUInt32();
3910 QuestLocale& data = mQuestLocaleMap[entry];
3912 for(int i = 1; i < MAX_LOCALE; ++i)
3914 std::string str = fields[1+10*(i-1)].GetCppString();
3915 if(!str.empty())
3917 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3918 if(idx >= 0)
3920 if(data.Title.size() <= idx)
3921 data.Title.resize(idx+1);
3923 data.Title[idx] = str;
3926 str = fields[1+10*(i-1)+1].GetCppString();
3927 if(!str.empty())
3929 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3930 if(idx >= 0)
3932 if(data.Details.size() <= idx)
3933 data.Details.resize(idx+1);
3935 data.Details[idx] = str;
3938 str = fields[1+10*(i-1)+2].GetCppString();
3939 if(!str.empty())
3941 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3942 if(idx >= 0)
3944 if(data.Objectives.size() <= idx)
3945 data.Objectives.resize(idx+1);
3947 data.Objectives[idx] = str;
3950 str = fields[1+10*(i-1)+3].GetCppString();
3951 if(!str.empty())
3953 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3954 if(idx >= 0)
3956 if(data.OfferRewardText.size() <= idx)
3957 data.OfferRewardText.resize(idx+1);
3959 data.OfferRewardText[idx] = str;
3962 str = fields[1+10*(i-1)+4].GetCppString();
3963 if(!str.empty())
3965 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3966 if(idx >= 0)
3968 if(data.RequestItemsText.size() <= idx)
3969 data.RequestItemsText.resize(idx+1);
3971 data.RequestItemsText[idx] = str;
3974 str = fields[1+10*(i-1)+5].GetCppString();
3975 if(!str.empty())
3977 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3978 if(idx >= 0)
3980 if(data.EndText.size() <= idx)
3981 data.EndText.resize(idx+1);
3983 data.EndText[idx] = str;
3986 for(int k = 0; k < 4; ++k)
3988 str = fields[1+10*(i-1)+6+k].GetCppString();
3989 if(!str.empty())
3991 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3992 if(idx >= 0)
3994 if(data.ObjectiveText[k].size() <= idx)
3995 data.ObjectiveText[k].resize(idx+1);
3997 data.ObjectiveText[k][idx] = str;
4002 } while (result->NextRow());
4004 delete result;
4006 sLog.outString();
4007 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4010 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4012 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4013 return;
4015 sLog.outString( "%s :", tablename);
4017 scripts.clear(); // need for reload support
4019 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
4021 uint32 count = 0;
4023 if( !result )
4025 barGoLink bar( 1 );
4026 bar.step();
4028 sLog.outString();
4029 sLog.outString( ">> Loaded %u script definitions", count );
4030 return;
4033 barGoLink bar( result->GetRowCount() );
4037 bar.step();
4039 Field *fields = result->Fetch();
4040 ScriptInfo tmp;
4041 tmp.id = fields[0].GetUInt32();
4042 tmp.delay = fields[1].GetUInt32();
4043 tmp.command = fields[2].GetUInt32();
4044 tmp.datalong = fields[3].GetUInt32();
4045 tmp.datalong2 = fields[4].GetUInt32();
4046 tmp.dataint = fields[5].GetInt32();
4047 tmp.x = fields[6].GetFloat();
4048 tmp.y = fields[7].GetFloat();
4049 tmp.z = fields[8].GetFloat();
4050 tmp.o = fields[9].GetFloat();
4052 // generic command args check
4053 switch(tmp.command)
4055 case SCRIPT_COMMAND_TALK:
4057 if(tmp.datalong > 3)
4059 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4060 continue;
4062 if(tmp.dataint==0)
4064 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4065 continue;
4067 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4069 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);
4070 continue;
4073 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4074 break;
4077 case SCRIPT_COMMAND_EMOTE:
4079 if(!sEmotesStore.LookupEntry(tmp.datalong))
4081 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4082 continue;
4084 break;
4087 case SCRIPT_COMMAND_TELEPORT_TO:
4089 if(!sMapStore.LookupEntry(tmp.datalong))
4091 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4092 continue;
4095 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4097 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);
4098 continue;
4100 break;
4103 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4105 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4107 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);
4108 continue;
4111 if(!GetCreatureTemplate(tmp.datalong))
4113 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4114 continue;
4116 break;
4119 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4121 GameObjectData const* data = GetGOData(tmp.datalong);
4122 if(!data)
4124 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4125 continue;
4128 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4129 if(!info)
4131 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);
4132 continue;
4135 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4136 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4137 info->type==GAMEOBJECT_TYPE_DOOR ||
4138 info->type==GAMEOBJECT_TYPE_BUTTON ||
4139 info->type==GAMEOBJECT_TYPE_TRAP )
4141 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4142 continue;
4144 break;
4146 case SCRIPT_COMMAND_OPEN_DOOR:
4147 case SCRIPT_COMMAND_CLOSE_DOOR:
4149 GameObjectData const* data = GetGOData(tmp.datalong);
4150 if(!data)
4152 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);
4153 continue;
4156 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4157 if(!info)
4159 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);
4160 continue;
4163 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4165 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);
4166 continue;
4169 break;
4171 case SCRIPT_COMMAND_QUEST_EXPLORED:
4173 Quest const* quest = GetQuestTemplate(tmp.datalong);
4174 if(!quest)
4176 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);
4177 continue;
4180 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4182 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);
4184 // this will prevent quest completing without objective
4185 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4187 // continue; - quest objective requirement set and command can be allowed
4190 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4192 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",
4193 tablename,tmp.datalong2,tmp.id);
4194 continue;
4197 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4199 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",
4200 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4201 continue;
4204 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4206 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",
4207 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4208 continue;
4211 break;
4214 case SCRIPT_COMMAND_REMOVE_AURA:
4216 if(!sSpellStore.LookupEntry(tmp.datalong))
4218 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4219 tablename,tmp.datalong,tmp.id);
4220 continue;
4222 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4224 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4225 tablename,tmp.datalong2,tmp.id);
4226 continue;
4228 break;
4230 case SCRIPT_COMMAND_CAST_SPELL:
4232 if(!sSpellStore.LookupEntry(tmp.datalong))
4234 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4235 tablename,tmp.datalong,tmp.id);
4236 continue;
4238 if(tmp.datalong2 & ~0x3) // 2 bits
4240 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4241 tablename,tmp.datalong2,tmp.id);
4242 continue;
4244 break;
4248 if (scripts.find(tmp.id) == scripts.end())
4250 ScriptMap emptyMap;
4251 scripts[tmp.id] = emptyMap;
4253 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4255 ++count;
4256 } while( result->NextRow() );
4258 delete result;
4260 sLog.outString();
4261 sLog.outString( ">> Loaded %u script definitions", count );
4264 void ObjectMgr::LoadGameObjectScripts()
4266 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4268 // check ids
4269 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4271 if(!GetGOData(itr->first))
4272 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4276 void ObjectMgr::LoadQuestEndScripts()
4278 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4280 // check ids
4281 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4283 if(!GetQuestTemplate(itr->first))
4284 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4288 void ObjectMgr::LoadQuestStartScripts()
4290 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4292 // check ids
4293 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4295 if(!GetQuestTemplate(itr->first))
4296 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4300 void ObjectMgr::LoadSpellScripts()
4302 LoadScripts(sSpellScripts, "spell_scripts");
4304 // check ids
4305 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4307 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4309 if(!spellInfo)
4311 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4312 continue;
4315 //check for correct spellEffect
4316 bool found = false;
4317 for(int i=0; i<3; ++i)
4319 // skip empty effects
4320 if( !spellInfo->Effect[i] )
4321 continue;
4323 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4325 found = true;
4326 break;
4330 if(!found)
4331 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4335 void ObjectMgr::LoadEventScripts()
4337 LoadScripts(sEventScripts, "event_scripts");
4339 std::set<uint32> evt_scripts;
4340 // Load all possible script entries from gameobjects
4341 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4343 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4344 if (goInfo)
4346 switch(goInfo->type)
4348 case GAMEOBJECT_TYPE_GOOBER:
4349 if (goInfo->goober.eventId)
4350 evt_scripts.insert(goInfo->goober.eventId);
4351 break;
4352 case GAMEOBJECT_TYPE_CHEST:
4353 if (goInfo->chest.eventId)
4354 evt_scripts.insert(goInfo->chest.eventId);
4355 break;
4356 case GAMEOBJECT_TYPE_CAMERA:
4357 if (goInfo->camera.eventID)
4358 evt_scripts.insert(goInfo->camera.eventID);
4359 default:
4360 break;
4364 // Load all possible script entries from spells
4365 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4367 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4368 if (spell)
4370 for(int j=0; j<3; ++j)
4372 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4374 if (spell->EffectMiscValue[j])
4375 evt_scripts.insert(spell->EffectMiscValue[j]);
4380 // Then check if all scripts are in above list of possible script entries
4381 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4383 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4384 if (itr2 == evt_scripts.end())
4385 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",
4386 itr->first, SPELL_EFFECT_SEND_EVENT);
4390 void ObjectMgr::LoadItemTexts()
4392 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4394 uint32 count = 0;
4396 if( !result )
4398 barGoLink bar( 1 );
4399 bar.step();
4401 sLog.outString();
4402 sLog.outString( ">> Loaded %u item pages", count );
4403 return;
4406 barGoLink bar( result->GetRowCount() );
4408 Field* fields;
4411 bar.step();
4413 fields = result->Fetch();
4415 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4417 ++count;
4419 } while ( result->NextRow() );
4421 delete result;
4423 sLog.outString();
4424 sLog.outString( ">> Loaded %u item texts", count );
4427 void ObjectMgr::LoadPageTexts()
4429 sPageTextStore.Free(); // for reload case
4431 sPageTextStore.Load();
4432 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4433 sLog.outString();
4435 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4437 // check data correctness
4438 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4439 if(!page)
4440 continue;
4442 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4444 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4445 continue;
4448 // detect circular reference
4449 std::set<uint32> checkedPages;
4450 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4452 if(!pageItr->Next_Page)
4453 break;
4454 checkedPages.insert(pageItr->Page_ID);
4455 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4457 std::ostringstream ss;
4458 ss<< "The text page(s) ";
4459 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4460 ss << *itr << " ";
4461 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4462 << pageItr->Page_ID <<" to 0";
4463 sLog.outErrorDb(ss.str().c_str());
4464 const_cast<PageText*>(pageItr)->Next_Page = 0;
4465 break;
4471 void ObjectMgr::LoadPageTextLocales()
4473 mPageTextLocaleMap.clear(); // need for reload case
4475 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");
4477 if(!result)
4479 barGoLink bar(1);
4481 bar.step();
4483 sLog.outString();
4484 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4485 return;
4488 barGoLink bar(result->GetRowCount());
4492 Field *fields = result->Fetch();
4493 bar.step();
4495 uint32 entry = fields[0].GetUInt32();
4497 PageTextLocale& data = mPageTextLocaleMap[entry];
4499 for(int i = 1; i < MAX_LOCALE; ++i)
4501 std::string str = fields[i].GetCppString();
4502 if(str.empty())
4503 continue;
4505 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4506 if(idx >= 0)
4508 if(data.Text.size() <= idx)
4509 data.Text.resize(idx+1);
4511 data.Text[idx] = str;
4515 } while (result->NextRow());
4517 delete result;
4519 sLog.outString();
4520 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4523 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4525 template<class D>
4526 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4528 dst = D(objmgr.GetScriptId(src));
4532 void ObjectMgr::LoadInstanceTemplate()
4534 SQLInstanceLoader loader;
4535 loader.Load(sInstanceTemplate);
4537 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4539 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4540 if(!temp)
4541 continue;
4543 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4544 if(!entry)
4546 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4547 continue;
4550 //FIXME: now exist heroic instance, normal/heroic raid instances
4551 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4552 // entry->resetTimeRaid store reset time for normal raid only
4553 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4554 // but at some point wee need implement reset time dependent from raid instance mode
4555 if(temp->reset_delay == 0)
4557 MapDifficulty const* mapDiffNorm = GetMapDifficultyData(temp->map,DUNGEON_DIFFICULTY_NORMAL);
4558 MapDifficulty const* mapDiffHeroic = GetMapDifficultyData(temp->map,DUNGEON_DIFFICULTY_HEROIC);
4560 // no reset time
4561 if ((!mapDiffNorm || mapDiffNorm->resetTime == 0) &&
4562 (!mapDiffHeroic || mapDiffHeroic->resetTime == 0))
4563 continue;
4565 // use defaults from the DBC
4566 if(mapDiffHeroic && mapDiffHeroic->resetTime) // for both raid and non raids, read above
4568 temp->reset_delay = mapDiffHeroic->resetTime / DAY;
4570 else if (mapDiffNorm && mapDiffNorm->resetTime && entry->map_type == MAP_RAID)
4571 // for normal raid only
4573 temp->reset_delay = mapDiffNorm->resetTime / DAY;
4577 // the reset_delay must be at least one day
4578 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4581 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4582 sLog.outString();
4585 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4587 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4588 if(itr != mGossipText.end())
4589 return &itr->second;
4590 return NULL;
4593 void ObjectMgr::LoadGossipText()
4595 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4597 int count = 0;
4598 if( !result )
4600 barGoLink bar( 1 );
4601 bar.step();
4603 sLog.outString();
4604 sLog.outString( ">> Loaded %u npc texts", count );
4605 return;
4608 int cic;
4610 barGoLink bar( result->GetRowCount() );
4614 ++count;
4615 cic = 0;
4617 Field *fields = result->Fetch();
4619 bar.step();
4621 uint32 Text_ID = fields[cic++].GetUInt32();
4622 if(!Text_ID)
4624 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4625 continue;
4628 GossipText& gText = mGossipText[Text_ID];
4630 for (int i=0; i< 8; i++)
4632 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4633 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4635 gText.Options[i].Language = fields[cic++].GetUInt32();
4636 gText.Options[i].Probability = fields[cic++].GetFloat();
4638 for(int j=0; j < 3; ++j)
4640 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4641 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4644 } while( result->NextRow() );
4646 sLog.outString();
4647 sLog.outString( ">> Loaded %u npc texts", count );
4648 delete result;
4651 void ObjectMgr::LoadNpcTextLocales()
4653 mNpcTextLocaleMap.clear(); // need for reload case
4655 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4656 "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,"
4657 "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,"
4658 "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,"
4659 "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,"
4660 "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,"
4661 "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,"
4662 "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, "
4663 "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 "
4664 " FROM locales_npc_text");
4666 if(!result)
4668 barGoLink bar(1);
4670 bar.step();
4672 sLog.outString();
4673 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4674 return;
4677 barGoLink bar(result->GetRowCount());
4681 Field *fields = result->Fetch();
4682 bar.step();
4684 uint32 entry = fields[0].GetUInt32();
4686 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4688 for(int i=1; i<MAX_LOCALE; ++i)
4690 for(int j=0; j<8; ++j)
4692 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4693 if(!str0.empty())
4695 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4696 if(idx >= 0)
4698 if(data.Text_0[j].size() <= idx)
4699 data.Text_0[j].resize(idx+1);
4701 data.Text_0[j][idx] = str0;
4704 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4705 if(!str1.empty())
4707 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4708 if(idx >= 0)
4710 if(data.Text_1[j].size() <= idx)
4711 data.Text_1[j].resize(idx+1);
4713 data.Text_1[j][idx] = str1;
4718 } while (result->NextRow());
4720 delete result;
4722 sLog.outString();
4723 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4726 //not very fast function but it is called only once a day, or on starting-up
4727 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4729 time_t basetime = time(NULL);
4730 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4731 //delete all old mails without item and without body immediately, if starting server
4732 if (!serverUp)
4733 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4734 // 0 1 2 3 4 5 6 7 8 9
4735 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);
4736 if ( !result )
4738 barGoLink bar(1);
4739 bar.step();
4740 sLog.outString();
4741 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4742 return; // any mails need to be returned or deleted
4745 //std::ostringstream delitems, delmails; //will be here for optimization
4746 //bool deletemail = false, deleteitem = false;
4747 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4748 //delmails << "DELETE FROM mail WHERE id IN ( "
4750 barGoLink bar( result->GetRowCount() );
4751 uint32 count = 0;
4752 Field *fields;
4756 bar.step();
4758 fields = result->Fetch();
4759 Mail *m = new Mail;
4760 m->messageID = fields[0].GetUInt32();
4761 m->messageType = fields[1].GetUInt8();
4762 m->sender = fields[2].GetUInt32();
4763 m->receiver = fields[3].GetUInt32();
4764 m->itemTextId = fields[4].GetUInt32();
4765 bool has_items = fields[5].GetBool();
4766 m->expire_time = (time_t)fields[6].GetUInt64();
4767 m->deliver_time = 0;
4768 m->COD = fields[7].GetUInt32();
4769 m->checked = fields[8].GetUInt32();
4770 m->mailTemplateId = fields[9].GetInt16();
4772 Player *pl = 0;
4773 if (serverUp)
4774 pl = GetPlayer((uint64)m->receiver);
4775 if (pl && pl->m_mailsLoaded)
4776 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4777 //his in mailbox and he has already listed his mails )
4778 delete m;
4779 continue;
4781 //delete or return mail:
4782 if (has_items)
4784 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4785 if(resultItems)
4789 Field *fields2 = resultItems->Fetch();
4791 uint32 item_guid_low = fields2[0].GetUInt32();
4792 uint32 item_template = fields2[1].GetUInt32();
4794 m->AddItem(item_guid_low, item_template);
4796 while (resultItems->NextRow());
4798 delete resultItems;
4800 //if it is mail from AH, it shouldn't be returned, but deleted
4801 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4803 // mail open and then not returned
4804 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4805 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4807 else
4809 //mail will be returned:
4810 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);
4811 delete m;
4812 continue;
4816 if (m->itemTextId)
4817 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4819 //deletemail = true;
4820 //delmails << m->messageID << ", ";
4821 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4822 delete m;
4823 ++count;
4824 } while (result->NextRow());
4825 delete result;
4827 sLog.outString();
4828 sLog.outString( ">> Loaded %u mails", count );
4831 void ObjectMgr::LoadQuestAreaTriggers()
4833 mQuestAreaTriggerMap.clear(); // need for reload case
4835 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4837 uint32 count = 0;
4839 if( !result )
4841 barGoLink bar( 1 );
4842 bar.step();
4844 sLog.outString();
4845 sLog.outString( ">> Loaded %u quest trigger points", count );
4846 return;
4849 barGoLink bar( result->GetRowCount() );
4853 ++count;
4854 bar.step();
4856 Field *fields = result->Fetch();
4858 uint32 trigger_ID = fields[0].GetUInt32();
4859 uint32 quest_ID = fields[1].GetUInt32();
4861 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4862 if(!atEntry)
4864 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4865 continue;
4868 Quest const* quest = GetQuestTemplate(quest_ID);
4870 if(!quest)
4872 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4873 continue;
4876 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4878 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);
4880 // this will prevent quest completing without objective
4881 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4883 // continue; - quest modified to required objective and trigger can be allowed.
4886 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4888 } while( result->NextRow() );
4890 delete result;
4892 sLog.outString();
4893 sLog.outString( ">> Loaded %u quest trigger points", count );
4896 void ObjectMgr::LoadTavernAreaTriggers()
4898 mTavernAreaTriggerSet.clear(); // need for reload case
4900 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4902 uint32 count = 0;
4904 if( !result )
4906 barGoLink bar( 1 );
4907 bar.step();
4909 sLog.outString();
4910 sLog.outString( ">> Loaded %u tavern triggers", count );
4911 return;
4914 barGoLink bar( result->GetRowCount() );
4918 ++count;
4919 bar.step();
4921 Field *fields = result->Fetch();
4923 uint32 Trigger_ID = fields[0].GetUInt32();
4925 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4926 if(!atEntry)
4928 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4929 continue;
4932 mTavernAreaTriggerSet.insert(Trigger_ID);
4933 } while( result->NextRow() );
4935 delete result;
4937 sLog.outString();
4938 sLog.outString( ">> Loaded %u tavern triggers", count );
4941 void ObjectMgr::LoadAreaTriggerScripts()
4943 mAreaTriggerScripts.clear(); // need for reload case
4944 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4946 uint32 count = 0;
4948 if( !result )
4950 barGoLink bar( 1 );
4951 bar.step();
4953 sLog.outString();
4954 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4955 return;
4958 barGoLink bar( result->GetRowCount() );
4962 ++count;
4963 bar.step();
4965 Field *fields = result->Fetch();
4967 uint32 Trigger_ID = fields[0].GetUInt32();
4968 const char *scriptName = fields[1].GetString();
4970 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4971 if(!atEntry)
4973 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4974 continue;
4976 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4977 } while( result->NextRow() );
4979 delete result;
4981 sLog.outString();
4982 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4985 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4987 bool found = false;
4988 float dist;
4989 uint32 id = 0;
4991 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4993 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4994 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4995 continue;
4997 uint8 field = (uint8)((i - 1) / 32);
4998 uint32 submask = 1<<((i-1)%32);
5000 // skip not taxi network nodes
5001 if((sTaxiNodesMask[field] & submask)==0)
5002 continue;
5004 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5005 if(found)
5007 if(dist2 < dist)
5009 dist = dist2;
5010 id = i;
5013 else
5015 found = true;
5016 dist = dist2;
5017 id = i;
5021 return id;
5024 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5026 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5027 if(src_i==sTaxiPathSetBySource.end())
5029 path = 0;
5030 cost = 0;
5031 return;
5034 TaxiPathSetForSource& pathSet = src_i->second;
5036 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5037 if(dest_i==pathSet.end())
5039 path = 0;
5040 cost = 0;
5041 return;
5044 cost = dest_i->second.price;
5045 path = dest_i->second.ID;
5048 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5050 uint16 mount_entry = 0;
5052 // select mount creature id
5053 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5054 if(node)
5056 if (team == ALLIANCE)
5058 mount_entry = node->MountCreatureID[1];
5059 if(!mount_entry && allowed_alt_team)
5060 mount_entry = node->MountCreatureID[0];
5062 else if (team == HORDE)
5064 mount_entry = node->MountCreatureID[0];
5066 if(!mount_entry && allowed_alt_team)
5067 mount_entry = node->MountCreatureID[1];
5071 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5072 if (!mount_info)
5073 return 0;
5075 uint16 mount_id = objmgr.ChooseDisplayId(team,mount_info);
5076 if (!mount_id)
5077 return 0;
5079 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(mount_id);
5080 if (minfo)
5081 mount_id = minfo->modelid;
5083 return mount_id;
5086 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5088 if(path >= sTaxiPathNodesByPath.size())
5089 return;
5091 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5093 pathnodes.Resize(nodeList.size());
5094 mapIds.resize(nodeList.size());
5096 for(size_t i = 0; i < nodeList.size(); ++i)
5098 pathnodes[ i ].x = nodeList[i].x;
5099 pathnodes[ i ].y = nodeList[i].y;
5100 pathnodes[ i ].z = nodeList[i].z;
5102 mapIds[i] = nodeList[i].mapid;
5106 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5108 if(path >= sTaxiPathNodesByPath.size())
5109 return;
5111 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5113 pathnodes.Resize(nodeList.size());
5115 for(size_t i = 0; i < nodeList.size(); ++i)
5117 pathnodes[ i ].mapid = nodeList[i].mapid;
5118 pathnodes[ i ].x = nodeList[i].x;
5119 pathnodes[ i ].y = nodeList[i].y;
5120 pathnodes[ i ].z = nodeList[i].z;
5121 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5122 pathnodes[ i ].delay = nodeList[i].delay;
5126 void ObjectMgr::LoadGraveyardZones()
5128 mGraveYardMap.clear(); // need for reload case
5130 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5132 uint32 count = 0;
5134 if( !result )
5136 barGoLink bar( 1 );
5137 bar.step();
5139 sLog.outString();
5140 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5141 return;
5144 barGoLink bar( result->GetRowCount() );
5148 ++count;
5149 bar.step();
5151 Field *fields = result->Fetch();
5153 uint32 safeLocId = fields[0].GetUInt32();
5154 uint32 zoneId = fields[1].GetUInt32();
5155 uint32 team = fields[2].GetUInt32();
5157 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5158 if(!entry)
5160 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5161 continue;
5164 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5165 if(!areaEntry)
5167 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5168 continue;
5171 if(areaEntry->zone != 0)
5173 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5174 continue;
5177 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5179 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5180 continue;
5183 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5184 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5185 } while( result->NextRow() );
5187 delete result;
5189 sLog.outString();
5190 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5193 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5195 // search for zone associated closest graveyard
5196 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
5198 // Simulate std. algorithm:
5199 // found some graveyard associated to (ghost_zone,ghost_map)
5201 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5202 // then check faction
5203 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5204 // then check faction
5205 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5206 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5207 if(graveLow==graveUp)
5209 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5210 return NULL;
5213 // at corpse map
5214 bool foundNear = false;
5215 float distNear;
5216 WorldSafeLocsEntry const* entryNear = NULL;
5218 // at entrance map for corpse map
5219 bool foundEntr = false;
5220 float distEntr;
5221 WorldSafeLocsEntry const* entryEntr = NULL;
5223 // some where other
5224 WorldSafeLocsEntry const* entryFar = NULL;
5226 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5228 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5230 GraveYardData const& data = itr->second;
5232 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5233 if(!entry)
5235 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5236 continue;
5239 // skip enemy faction graveyard
5240 // team == 0 case can be at call from .neargrave
5241 if(data.team != 0 && team != 0 && data.team != team)
5242 continue;
5244 // find now nearest graveyard at other map
5245 if(MapId != entry->map_id)
5247 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5248 if (!mapEntry ||
5249 mapEntry->entrance_map < 0 ||
5250 mapEntry->entrance_map != entry->map_id ||
5251 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5253 // not have any corrdinates for check distance anyway
5254 entryFar = entry;
5255 continue;
5258 // at entrance map calculate distance (2D);
5259 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5260 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5261 if(foundEntr)
5263 if(dist2 < distEntr)
5265 distEntr = dist2;
5266 entryEntr = entry;
5269 else
5271 foundEntr = true;
5272 distEntr = dist2;
5273 entryEntr = entry;
5276 // find now nearest graveyard at same map
5277 else
5279 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5280 if(foundNear)
5282 if(dist2 < distNear)
5284 distNear = dist2;
5285 entryNear = entry;
5288 else
5290 foundNear = true;
5291 distNear = dist2;
5292 entryNear = entry;
5297 if(entryNear)
5298 return entryNear;
5300 if(entryEntr)
5301 return entryEntr;
5303 return entryFar;
5306 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5308 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5309 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5311 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5313 if(itr->second.safeLocId==id)
5314 return &itr->second;
5317 return NULL;
5320 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5322 if(FindGraveYardData(id,zoneId))
5323 return false;
5325 // add link to loaded data
5326 GraveYardData data;
5327 data.safeLocId = id;
5328 data.team = team;
5330 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5332 // add link to DB
5333 if(inDB)
5335 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5336 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5339 return true;
5342 void ObjectMgr::LoadAreaTriggerTeleports()
5344 mAreaTriggers.clear(); // need for reload case
5346 uint32 count = 0;
5348 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5349 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");
5350 if( !result )
5353 barGoLink bar( 1 );
5355 bar.step();
5357 sLog.outString();
5358 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5359 return;
5362 barGoLink bar( result->GetRowCount() );
5366 Field *fields = result->Fetch();
5368 bar.step();
5370 ++count;
5372 uint32 Trigger_ID = fields[0].GetUInt32();
5374 AreaTrigger at;
5376 at.requiredLevel = fields[1].GetUInt8();
5377 at.requiredItem = fields[2].GetUInt32();
5378 at.requiredItem2 = fields[3].GetUInt32();
5379 at.heroicKey = fields[4].GetUInt32();
5380 at.heroicKey2 = fields[5].GetUInt32();
5381 at.requiredQuest = fields[6].GetUInt32();
5382 at.requiredQuestHeroic = fields[7].GetUInt32();
5383 at.requiredFailedText = fields[8].GetCppString();
5384 at.target_mapId = fields[9].GetUInt32();
5385 at.target_X = fields[10].GetFloat();
5386 at.target_Y = fields[11].GetFloat();
5387 at.target_Z = fields[12].GetFloat();
5388 at.target_Orientation = fields[13].GetFloat();
5390 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5391 if(!atEntry)
5393 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5394 continue;
5397 if(at.requiredItem)
5399 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5400 if(!pProto)
5402 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5403 at.requiredItem = 0;
5406 if(at.requiredItem2)
5408 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5409 if(!pProto)
5411 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5412 at.requiredItem2 = 0;
5416 if(at.heroicKey)
5418 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5419 if(!pProto)
5421 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5422 at.heroicKey = 0;
5426 if(at.heroicKey2)
5428 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5429 if(!pProto)
5431 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5432 at.heroicKey2 = 0;
5436 if(at.requiredQuest)
5438 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5439 if(qReqItr == mQuestTemplates.end())
5441 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5442 at.requiredQuest = 0;
5446 if(at.requiredQuestHeroic)
5448 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5449 if(qReqItr == mQuestTemplates.end())
5451 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5452 at.requiredQuestHeroic = 0;
5456 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5457 if(!mapEntry)
5459 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5460 continue;
5463 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5465 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5466 continue;
5469 mAreaTriggers[Trigger_ID] = at;
5471 } while( result->NextRow() );
5473 delete result;
5475 sLog.outString();
5476 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5480 * Searches for the areatrigger which teleports players out of the given map
5482 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5484 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5485 if(!mapEntry) return NULL;
5486 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5488 if(itr->second.target_mapId == mapEntry->entrance_map)
5490 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5491 if(atEntry && atEntry->mapid == Map)
5492 return &itr->second;
5495 return NULL;
5499 * Searches for the areatrigger which teleports players to the given map
5501 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5503 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5505 if(itr->second.target_mapId == Map)
5507 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5508 if(atEntry)
5509 return &itr->second;
5512 return NULL;
5515 void ObjectMgr::SetHighestGuids()
5517 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5518 if( result )
5520 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5521 delete result;
5524 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5525 if( result )
5527 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5528 delete result;
5531 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5532 if( result )
5534 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5535 delete result;
5538 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5539 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5540 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5541 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5542 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5544 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5545 if( result )
5547 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5548 delete result;
5551 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5552 if( result )
5554 m_auctionid = (*result)[0].GetUInt32()+1;
5555 delete result;
5558 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5559 if( result )
5561 m_mailid = (*result)[0].GetUInt32()+1;
5562 delete result;
5565 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5566 if( result )
5568 m_ItemTextId = (*result)[0].GetUInt32()+1;
5569 delete result;
5572 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5573 if( result )
5575 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5576 delete result;
5579 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5580 if (result)
5582 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5583 delete result;
5586 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5587 if (result)
5589 m_equipmentSetGuid = (*result)[0].GetUInt64()+1;
5590 delete result;
5593 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5594 if (result)
5596 m_guildId = (*result)[0].GetUInt32()+1;
5597 delete result;
5601 uint32 ObjectMgr::GenerateArenaTeamId()
5603 if(m_arenaTeamId>=0xFFFFFFFE)
5605 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5606 World::StopNow(ERROR_EXIT_CODE);
5608 return m_arenaTeamId++;
5611 uint32 ObjectMgr::GenerateAuctionID()
5613 if(m_auctionid>=0xFFFFFFFE)
5615 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5616 World::StopNow(ERROR_EXIT_CODE);
5618 return m_auctionid++;
5621 uint64 ObjectMgr::GenerateEquipmentSetGuid()
5623 if(m_equipmentSetGuid>=0xFFFFFFFFFFFFFFFEll)
5625 sLog.outError("EquipmentSet guid overflow!! Can't continue, shutting down server. ");
5626 World::StopNow(ERROR_EXIT_CODE);
5628 return m_equipmentSetGuid++;
5631 uint32 ObjectMgr::GenerateGuildId()
5633 if(m_guildId>=0xFFFFFFFE)
5635 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5636 World::StopNow(ERROR_EXIT_CODE);
5638 return m_guildId++;
5641 uint32 ObjectMgr::GenerateMailID()
5643 if(m_mailid>=0xFFFFFFFE)
5645 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5646 World::StopNow(ERROR_EXIT_CODE);
5648 return m_mailid++;
5651 uint32 ObjectMgr::GenerateItemTextID()
5653 if(m_ItemTextId>=0xFFFFFFFE)
5655 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5656 World::StopNow(ERROR_EXIT_CODE);
5658 return m_ItemTextId++;
5661 uint32 ObjectMgr::CreateItemText(std::string text)
5663 uint32 newItemTextId = GenerateItemTextID();
5664 //insert new itempage to container
5665 mItemTexts[ newItemTextId ] = text;
5666 //save new itempage
5667 CharacterDatabase.escape_string(text);
5668 //any Delete query needed, itemTextId is maximum of all ids
5669 std::ostringstream query;
5670 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5671 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5672 return newItemTextId;
5675 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5677 switch(guidhigh)
5679 case HIGHGUID_ITEM:
5680 if(m_hiItemGuid>=0xFFFFFFFE)
5682 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5683 World::StopNow(ERROR_EXIT_CODE);
5685 return m_hiItemGuid++;
5686 case HIGHGUID_UNIT:
5687 if(m_hiCreatureGuid>=0x00FFFFFE)
5689 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5690 World::StopNow(ERROR_EXIT_CODE);
5692 return m_hiCreatureGuid++;
5693 case HIGHGUID_PLAYER:
5694 if(m_hiCharGuid>=0xFFFFFFFE)
5696 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5697 World::StopNow(ERROR_EXIT_CODE);
5699 return m_hiCharGuid++;
5700 case HIGHGUID_GAMEOBJECT:
5701 if(m_hiGoGuid>=0x00FFFFFE)
5703 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5704 World::StopNow(ERROR_EXIT_CODE);
5706 return m_hiGoGuid++;
5707 case HIGHGUID_CORPSE:
5708 if(m_hiCorpseGuid>=0xFFFFFFFE)
5710 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5711 World::StopNow(ERROR_EXIT_CODE);
5713 return m_hiCorpseGuid++;
5714 default:
5715 ASSERT(0);
5718 ASSERT(0);
5719 return 0;
5722 void ObjectMgr::LoadGameObjectLocales()
5724 mGameObjectLocaleMap.clear(); // need for reload case
5726 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5727 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5728 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5729 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5731 if(!result)
5733 barGoLink bar(1);
5735 bar.step();
5737 sLog.outString();
5738 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5739 return;
5742 barGoLink bar(result->GetRowCount());
5746 Field *fields = result->Fetch();
5747 bar.step();
5749 uint32 entry = fields[0].GetUInt32();
5751 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5753 for(int i = 1; i < MAX_LOCALE; ++i)
5755 std::string str = fields[i].GetCppString();
5756 if(!str.empty())
5758 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5759 if(idx >= 0)
5761 if(data.Name.size() <= idx)
5762 data.Name.resize(idx+1);
5764 data.Name[idx] = str;
5769 for(int i = 1; i < MAX_LOCALE; ++i)
5771 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5772 if(!str.empty())
5774 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5775 if(idx >= 0)
5777 if(data.CastBarCaption.size() <= idx)
5778 data.CastBarCaption.resize(idx+1);
5780 data.CastBarCaption[idx] = str;
5785 } while (result->NextRow());
5787 delete result;
5789 sLog.outString();
5790 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5793 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5795 template<class D>
5796 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5798 dst = D(objmgr.GetScriptId(src));
5802 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5804 if (sLockStore.LookupEntry(dataN))
5805 return;
5807 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5808 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5811 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5813 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5815 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5816 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5817 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5819 /* disable check for while (too many error reports baout not existed in trap templates
5820 else
5821 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5822 goInfo->id,goInfo->type,N,dataN,dataN);
5826 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5828 if (sSpellStore.LookupEntry(dataN))
5829 return;
5831 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5832 goInfo->id,goInfo->type,N,dataN,dataN);
5835 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5837 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5838 return;
5840 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5841 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5843 // prevent client and server unexpected work
5844 const_cast<uint32&>(dataN) = 0;
5847 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5849 // 0/1 correct values
5850 if (dataN <= 1)
5851 return;
5853 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5854 goInfo->id,goInfo->type,N,dataN);
5857 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5859 // 0/1 correct values
5860 if (dataN <= 1)
5861 return;
5863 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5864 goInfo->id,goInfo->type,N,dataN);
5867 void ObjectMgr::LoadGameobjectInfo()
5869 SQLGameObjectLoader loader;
5870 loader.Load(sGOStorage);
5872 // some checks
5873 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5875 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5876 if (!goInfo)
5877 continue;
5879 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5881 switch(goInfo->type)
5883 case GAMEOBJECT_TYPE_DOOR: //0
5885 if (goInfo->door.lockId)
5886 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5887 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5888 break;
5890 case GAMEOBJECT_TYPE_BUTTON: //1
5892 if (goInfo->button.lockId)
5893 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5894 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5895 break;
5897 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5899 if (goInfo->questgiver.lockId)
5900 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5901 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5902 break;
5904 case GAMEOBJECT_TYPE_CHEST: //3
5906 if (goInfo->chest.lockId)
5907 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5909 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
5911 if (goInfo->chest.linkedTrapId) // linked trap
5912 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5913 break;
5915 case GAMEOBJECT_TYPE_TRAP: //6
5917 if (goInfo->trap.lockId)
5918 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5919 /* disable check for while, too many not existed spells
5920 if (goInfo->trap.spellId) // spell
5921 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5923 break;
5925 case GAMEOBJECT_TYPE_CHAIR: //7
5926 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5927 break;
5928 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5930 if (goInfo->spellFocus.focusId)
5932 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5933 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5934 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5937 if (goInfo->spellFocus.linkedTrapId) // linked trap
5938 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5939 break;
5941 case GAMEOBJECT_TYPE_GOOBER: //10
5943 if (goInfo->goober.lockId)
5944 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5946 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
5948 if (goInfo->goober.pageId) // pageId
5950 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5951 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5952 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5954 /* disable check for while, too many not existed spells
5955 if (goInfo->goober.spellId) // spell
5956 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5958 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5959 if (goInfo->goober.linkedTrapId) // linked trap
5960 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5961 break;
5963 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5965 if (goInfo->areadamage.lockId)
5966 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5967 break;
5969 case GAMEOBJECT_TYPE_CAMERA: //13
5971 if (goInfo->camera.lockId)
5972 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5973 break;
5975 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5977 if (goInfo->moTransport.taxiPathId)
5979 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5980 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5981 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5983 break;
5985 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5987 /* disable check for while, too many not existed spells
5988 // always must have spell
5989 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5991 break;
5993 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5995 // always must have spell
5996 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5997 break;
5999 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6001 if (goInfo->flagstand.lockId)
6002 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6003 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6004 break;
6006 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6008 if (goInfo->fishinghole.lockId)
6009 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6010 break;
6012 case GAMEOBJECT_TYPE_FLAGDROP: //26
6014 if (goInfo->flagdrop.lockId)
6015 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6016 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6017 break;
6019 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6020 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6021 break;
6025 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6026 sLog.outString();
6029 void ObjectMgr::LoadExplorationBaseXP()
6031 uint32 count = 0;
6032 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6034 if( !result )
6036 barGoLink bar( 1 );
6038 bar.step();
6040 sLog.outString();
6041 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6042 return;
6045 barGoLink bar( result->GetRowCount() );
6049 bar.step();
6051 Field *fields = result->Fetch();
6052 uint32 level = fields[0].GetUInt32();
6053 uint32 basexp = fields[1].GetUInt32();
6054 mBaseXPTable[level] = basexp;
6055 ++count;
6057 while (result->NextRow());
6059 delete result;
6061 sLog.outString();
6062 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6065 uint32 ObjectMgr::GetBaseXP(uint32 level)
6067 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
6070 uint32 ObjectMgr::GetXPForLevel(uint32 level)
6072 if (level < mPlayerXPperLevel.size())
6073 return mPlayerXPperLevel[level];
6074 return 0;
6077 void ObjectMgr::LoadPetNames()
6079 uint32 count = 0;
6080 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6082 if( !result )
6084 barGoLink bar( 1 );
6086 bar.step();
6088 sLog.outString();
6089 sLog.outString( ">> Loaded %u pet name parts", count );
6090 return;
6093 barGoLink bar( result->GetRowCount() );
6097 bar.step();
6099 Field *fields = result->Fetch();
6100 std::string word = fields[0].GetString();
6101 uint32 entry = fields[1].GetUInt32();
6102 bool half = fields[2].GetBool();
6103 if(half)
6104 PetHalfName1[entry].push_back(word);
6105 else
6106 PetHalfName0[entry].push_back(word);
6107 ++count;
6109 while (result->NextRow());
6110 delete result;
6112 sLog.outString();
6113 sLog.outString( ">> Loaded %u pet name parts", count );
6116 void ObjectMgr::LoadPetNumber()
6118 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6119 if(result)
6121 Field *fields = result->Fetch();
6122 m_hiPetNumber = fields[0].GetUInt32()+1;
6123 delete result;
6126 barGoLink bar( 1 );
6127 bar.step();
6129 sLog.outString();
6130 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
6133 std::string ObjectMgr::GeneratePetName(uint32 entry)
6135 std::vector<std::string> & list0 = PetHalfName0[entry];
6136 std::vector<std::string> & list1 = PetHalfName1[entry];
6138 if(list0.empty() || list1.empty())
6140 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6141 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6142 if(!petname)
6143 petname = cinfo->Name;
6144 return std::string(petname);
6147 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6150 uint32 ObjectMgr::GeneratePetNumber()
6152 return ++m_hiPetNumber;
6155 void ObjectMgr::LoadCorpses()
6157 uint32 count = 0;
6158 // 0 1 2 3 4 5 6 7 8 10
6159 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");
6161 if( !result )
6163 barGoLink bar( 1 );
6165 bar.step();
6167 sLog.outString();
6168 sLog.outString( ">> Loaded %u corpses", count );
6169 return;
6172 barGoLink bar( result->GetRowCount() );
6176 bar.step();
6178 Field *fields = result->Fetch();
6180 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6182 Corpse *corpse = new Corpse;
6183 if(!corpse->LoadFromDB(guid,fields))
6185 delete corpse;
6186 continue;
6189 ObjectAccessor::Instance().AddCorpse(corpse);
6191 ++count;
6193 while (result->NextRow());
6194 delete result;
6196 sLog.outString();
6197 sLog.outString( ">> Loaded %u corpses", count );
6200 void ObjectMgr::LoadReputationOnKill()
6202 uint32 count = 0;
6204 // 0 1 2
6205 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6206 // 3 4 5 6 7 8 9
6207 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6208 "FROM creature_onkill_reputation");
6210 if(!result)
6212 barGoLink bar(1);
6214 bar.step();
6216 sLog.outString();
6217 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6218 return;
6221 barGoLink bar(result->GetRowCount());
6225 Field *fields = result->Fetch();
6226 bar.step();
6228 uint32 creature_id = fields[0].GetUInt32();
6230 ReputationOnKillEntry repOnKill;
6231 repOnKill.repfaction1 = fields[1].GetUInt32();
6232 repOnKill.repfaction2 = fields[2].GetUInt32();
6233 repOnKill.is_teamaward1 = fields[3].GetBool();
6234 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6235 repOnKill.repvalue1 = fields[5].GetInt32();
6236 repOnKill.is_teamaward2 = fields[6].GetBool();
6237 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6238 repOnKill.repvalue2 = fields[8].GetInt32();
6239 repOnKill.team_dependent = fields[9].GetUInt8();
6241 if(!GetCreatureTemplate(creature_id))
6243 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6244 continue;
6247 if(repOnKill.repfaction1)
6249 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6250 if(!factionEntry1)
6252 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6253 continue;
6257 if(repOnKill.repfaction2)
6259 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6260 if(!factionEntry2)
6262 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6263 continue;
6267 mRepOnKill[creature_id] = repOnKill;
6269 ++count;
6270 } while (result->NextRow());
6272 delete result;
6274 sLog.outString();
6275 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6278 void ObjectMgr::LoadPointsOfInterest()
6280 uint32 count = 0;
6282 // 0 1 2 3 4 5
6283 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6285 if(!result)
6287 barGoLink bar(1);
6289 bar.step();
6291 sLog.outString();
6292 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6293 return;
6296 barGoLink bar(result->GetRowCount());
6300 Field *fields = result->Fetch();
6301 bar.step();
6303 uint32 point_id = fields[0].GetUInt32();
6305 PointOfInterest POI;
6306 POI.x = fields[1].GetFloat();
6307 POI.y = fields[2].GetFloat();
6308 POI.icon = fields[3].GetUInt32();
6309 POI.flags = fields[4].GetUInt32();
6310 POI.data = fields[5].GetUInt32();
6311 POI.icon_name = fields[6].GetCppString();
6313 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6315 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6316 continue;
6319 mPointsOfInterest[point_id] = POI;
6321 ++count;
6322 } while (result->NextRow());
6324 delete result;
6326 sLog.outString();
6327 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6330 void ObjectMgr::LoadNPCSpellClickSpells()
6332 uint32 count = 0;
6334 mSpellClickInfoMap.clear();
6335 // 0 1 2 3 4 5
6336 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6338 if(!result)
6340 barGoLink bar(1);
6342 bar.step();
6344 sLog.outString();
6345 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6346 return;
6349 barGoLink bar(result->GetRowCount());
6353 Field *fields = result->Fetch();
6354 bar.step();
6356 uint32 npc_entry = fields[0].GetUInt32();
6357 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6358 if (!cInfo)
6360 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6361 continue;
6364 uint32 spellid = fields[1].GetUInt32();
6365 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6366 if (!spellinfo)
6368 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6369 continue;
6372 uint32 quest_start = fields[2].GetUInt32();
6374 // quest might be 0 to enable spellclick independent of any quest
6375 if (quest_start)
6377 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6379 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6380 continue;
6385 bool quest_start_active = fields[3].GetBool();
6387 uint32 quest_end = fields[4].GetUInt32();
6388 // quest might be 0 to enable spellclick active infinity after start quest
6389 if (quest_end)
6391 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6393 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6394 continue;
6399 uint8 castFlags = fields[5].GetUInt8();
6400 SpellClickInfo info;
6401 info.spellId = spellid;
6402 info.questStart = quest_start;
6403 info.questStartCanActive = quest_start_active;
6404 info.questEnd = quest_end;
6405 info.castFlags = castFlags;
6406 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6408 // mark creature template as spell clickable
6409 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6411 ++count;
6412 } while (result->NextRow());
6414 delete result;
6416 sLog.outString();
6417 sLog.outString(">> Loaded %u spellclick definitions", count);
6420 void ObjectMgr::LoadWeatherZoneChances()
6422 uint32 count = 0;
6424 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6425 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");
6427 if(!result)
6429 barGoLink bar(1);
6431 bar.step();
6433 sLog.outString();
6434 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6435 return;
6438 barGoLink bar(result->GetRowCount());
6442 Field *fields = result->Fetch();
6443 bar.step();
6445 uint32 zone_id = fields[0].GetUInt32();
6447 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6449 for(int season = 0; season < WEATHER_SEASONS; ++season)
6451 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6452 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6453 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6455 if(wzc.data[season].rainChance > 100)
6457 wzc.data[season].rainChance = 25;
6458 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6461 if(wzc.data[season].snowChance > 100)
6463 wzc.data[season].snowChance = 25;
6464 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6467 if(wzc.data[season].stormChance > 100)
6469 wzc.data[season].stormChance = 25;
6470 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6474 ++count;
6475 } while (result->NextRow());
6477 delete result;
6479 sLog.outString();
6480 sLog.outString(">> Loaded %u weather definitions", count);
6483 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6485 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6486 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6487 if(t)
6488 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6491 void ObjectMgr::DeleteCreatureData(uint32 guid)
6493 // remove mapid*cellid -> guid_set map
6494 CreatureData const* data = GetCreatureData(guid);
6495 if(data)
6496 RemoveCreatureFromGrid(guid, data);
6498 mCreatureDataMap.erase(guid);
6501 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6503 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6504 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6505 if(t)
6506 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6509 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6511 RespawnTimes::iterator next;
6513 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6515 next = itr;
6516 ++next;
6518 if(GUID_HIPART(itr->first)==instance)
6519 mGORespawnTimes.erase(itr);
6522 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6524 next = itr;
6525 ++next;
6527 if(GUID_HIPART(itr->first)==instance)
6528 mCreatureRespawnTimes.erase(itr);
6531 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6532 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6535 void ObjectMgr::DeleteGOData(uint32 guid)
6537 // remove mapid*cellid -> guid_set map
6538 GameObjectData const* data = GetGOData(guid);
6539 if(data)
6540 RemoveGameobjectFromGrid(guid, data);
6542 mGameObjectDataMap.erase(guid);
6545 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6547 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6548 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6549 cell_guids.corpses[player_guid] = instance;
6552 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6554 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6555 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6556 cell_guids.corpses.erase(player_guid);
6559 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6561 map.clear(); // need for reload case
6563 uint32 count = 0;
6565 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6567 if(!result)
6569 barGoLink bar(1);
6571 bar.step();
6573 sLog.outString();
6574 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6575 return;
6578 barGoLink bar(result->GetRowCount());
6582 Field *fields = result->Fetch();
6583 bar.step();
6585 uint32 id = fields[0].GetUInt32();
6586 uint32 quest = fields[1].GetUInt32();
6588 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6590 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6591 continue;
6594 map.insert(QuestRelations::value_type(id,quest));
6596 ++count;
6597 } while (result->NextRow());
6599 delete result;
6601 sLog.outString();
6602 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6605 void ObjectMgr::LoadGameobjectQuestRelations()
6607 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6609 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6611 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6612 if(!goInfo)
6613 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6614 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6615 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6619 void ObjectMgr::LoadGameobjectInvolvedRelations()
6621 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6623 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6625 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6626 if(!goInfo)
6627 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6628 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6629 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6633 void ObjectMgr::LoadCreatureQuestRelations()
6635 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6637 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6639 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6640 if(!cInfo)
6641 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6642 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6643 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);
6647 void ObjectMgr::LoadCreatureInvolvedRelations()
6649 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6651 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6653 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6654 if(!cInfo)
6655 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6656 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6657 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);
6661 void ObjectMgr::LoadReservedPlayersNames()
6663 m_ReservedNames.clear(); // need for reload case
6665 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6667 uint32 count = 0;
6669 if( !result )
6671 barGoLink bar( 1 );
6672 bar.step();
6674 sLog.outString();
6675 sLog.outString( ">> Loaded %u reserved player names", count );
6676 return;
6679 barGoLink bar( result->GetRowCount() );
6681 Field* fields;
6684 bar.step();
6685 fields = result->Fetch();
6686 std::string name= fields[0].GetCppString();
6688 std::wstring wstr;
6689 if(!Utf8toWStr (name,wstr))
6691 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6692 continue;
6695 wstrToLower(wstr);
6697 m_ReservedNames.insert(wstr);
6698 ++count;
6699 } while ( result->NextRow() );
6701 delete result;
6703 sLog.outString();
6704 sLog.outString( ">> Loaded %u reserved player names", count );
6707 bool ObjectMgr::IsReservedName( const std::string& name ) const
6709 std::wstring wstr;
6710 if(!Utf8toWStr (name,wstr))
6711 return false;
6713 wstrToLower(wstr);
6715 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6718 enum LanguageType
6720 LT_BASIC_LATIN = 0x0000,
6721 LT_EXTENDEN_LATIN = 0x0001,
6722 LT_CYRILLIC = 0x0002,
6723 LT_EAST_ASIA = 0x0004,
6724 LT_ANY = 0xFFFF
6727 static LanguageType GetRealmLanguageType(bool create)
6729 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6731 case REALM_ZONE_UNKNOWN: // any language
6732 case REALM_ZONE_DEVELOPMENT:
6733 case REALM_ZONE_TEST_SERVER:
6734 case REALM_ZONE_QA_SERVER:
6735 return LT_ANY;
6736 case REALM_ZONE_UNITED_STATES: // extended-Latin
6737 case REALM_ZONE_OCEANIC:
6738 case REALM_ZONE_LATIN_AMERICA:
6739 case REALM_ZONE_ENGLISH:
6740 case REALM_ZONE_GERMAN:
6741 case REALM_ZONE_FRENCH:
6742 case REALM_ZONE_SPANISH:
6743 return LT_EXTENDEN_LATIN;
6744 case REALM_ZONE_KOREA: // East-Asian
6745 case REALM_ZONE_TAIWAN:
6746 case REALM_ZONE_CHINA:
6747 return LT_EAST_ASIA;
6748 case REALM_ZONE_RUSSIAN: // Cyrillic
6749 return LT_CYRILLIC;
6750 default:
6751 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6755 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6757 if(strictMask==0) // any language, ignore realm
6759 if(isExtendedLatinString(wstr,numericOrSpace))
6760 return true;
6761 if(isCyrillicString(wstr,numericOrSpace))
6762 return true;
6763 if(isEastAsianString(wstr,numericOrSpace))
6764 return true;
6765 return false;
6768 if(strictMask & 0x2) // realm zone specific
6770 LanguageType lt = GetRealmLanguageType(create);
6771 if(lt & LT_EXTENDEN_LATIN)
6772 if(isExtendedLatinString(wstr,numericOrSpace))
6773 return true;
6774 if(lt & LT_CYRILLIC)
6775 if(isCyrillicString(wstr,numericOrSpace))
6776 return true;
6777 if(lt & LT_EAST_ASIA)
6778 if(isEastAsianString(wstr,numericOrSpace))
6779 return true;
6782 if(strictMask & 0x1) // basic Latin
6784 if(isBasicLatinString(wstr,numericOrSpace))
6785 return true;
6788 return false;
6791 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6793 std::wstring wname;
6794 if(!Utf8toWStr(name,wname))
6795 return CHAR_NAME_INVALID_CHARACTER;
6797 if(wname.size() > MAX_PLAYER_NAME)
6798 return CHAR_NAME_TOO_LONG;
6800 uint32 minName = sWorld.getConfig(CONFIG_MIN_PLAYER_NAME);
6801 if(wname.size() < minName)
6802 return CHAR_NAME_TOO_SHORT;
6804 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6805 if(!isValidString(wname,strictMask,false,create))
6806 return CHAR_NAME_MIXED_LANGUAGES;
6808 return CHAR_NAME_SUCCESS;
6811 bool ObjectMgr::IsValidCharterName( const std::string& name )
6813 std::wstring wname;
6814 if(!Utf8toWStr(name,wname))
6815 return false;
6817 if(wname.size() > MAX_CHARTER_NAME)
6818 return false;
6820 uint32 minName = sWorld.getConfig(CONFIG_MIN_CHARTER_NAME);
6821 if(wname.size() < minName)
6822 return false;
6824 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6826 return isValidString(wname,strictMask,true);
6829 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
6831 std::wstring wname;
6832 if(!Utf8toWStr(name,wname))
6833 return PET_NAME_INVALID;
6835 if(wname.size() > MAX_PET_NAME)
6836 return PET_NAME_TOO_LONG;
6838 uint32 minName = sWorld.getConfig(CONFIG_MIN_PET_NAME);
6839 if(wname.size() < minName)
6840 return PET_NAME_TOO_SHORT;
6842 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6843 if(!isValidString(wname,strictMask,false))
6844 return PET_NAME_MIXED_LANGUAGES;
6846 return PET_NAME_SUCCESS;
6849 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6851 if(loc==LOCALE_enUS)
6852 return -1;
6854 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6855 if(m_LocalForIndex[i]==loc)
6856 return i;
6858 return -1;
6861 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6863 if (i<0 || i>=m_LocalForIndex.size())
6864 return LOCALE_enUS;
6866 return m_LocalForIndex[i];
6869 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6871 if(loc==LOCALE_enUS)
6872 return -1;
6874 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6875 if(m_LocalForIndex[i]==loc)
6876 return i;
6878 m_LocalForIndex.push_back(loc);
6879 return m_LocalForIndex.size()-1;
6882 void ObjectMgr::LoadGameObjectForQuests()
6884 mGameObjectForQuestSet.clear(); // need for reload case
6886 if( !sGOStorage.MaxEntry )
6888 barGoLink bar( 1 );
6889 bar.step();
6890 sLog.outString();
6891 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6892 return;
6895 barGoLink bar( sGOStorage.MaxEntry - 1 );
6896 uint32 count = 0;
6898 // collect GO entries for GO that must activated
6899 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6901 bar.step();
6902 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6903 if(!goInfo)
6904 continue;
6906 switch(goInfo->type)
6908 // scan GO chest with loot including quest items
6909 case GAMEOBJECT_TYPE_CHEST:
6911 uint32 loot_id = goInfo->GetLootId();
6913 // find quest loot for GO
6914 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6916 mGameObjectForQuestSet.insert(go_entry);
6917 ++count;
6919 break;
6921 case GAMEOBJECT_TYPE_GOOBER:
6923 if(goInfo->goober.questId) //quests objects
6925 mGameObjectForQuestSet.insert(go_entry);
6926 count++;
6928 break;
6930 default:
6931 break;
6935 sLog.outString();
6936 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6939 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6941 int32 start_value = min_value;
6942 int32 end_value = max_value;
6943 // some string can have negative indexes range
6944 if (start_value < 0)
6946 if (end_value >= start_value)
6948 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6949 return false;
6952 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
6953 std::swap(start_value,end_value);
6954 ++start_value;
6955 ++end_value;
6957 else
6959 if (start_value >= end_value)
6961 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6962 return false;
6966 // cleanup affected map part for reloading case
6967 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6969 if (itr->first >= start_value && itr->first < end_value)
6970 mMangosStringLocaleMap.erase(itr++);
6971 else
6972 ++itr;
6975 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);
6977 if (!result)
6979 barGoLink bar(1);
6981 bar.step();
6983 sLog.outString();
6984 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6985 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6986 else
6987 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6988 return false;
6991 uint32 count = 0;
6993 barGoLink bar(result->GetRowCount());
6997 Field *fields = result->Fetch();
6998 bar.step();
7000 int32 entry = fields[0].GetInt32();
7002 if (entry==0)
7004 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7005 continue;
7007 else if (entry < start_value || entry >= end_value)
7009 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7010 continue;
7013 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7015 if (data.Content.size() > 0)
7017 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7018 continue;
7021 data.Content.resize(1);
7022 ++count;
7024 // 0 -> default, idx in to idx+1
7025 data.Content[0] = fields[1].GetCppString();
7027 for(int i = 1; i < MAX_LOCALE; ++i)
7029 std::string str = fields[i+1].GetCppString();
7030 if (!str.empty())
7032 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7033 if (idx >= 0)
7035 // 0 -> default, idx in to idx+1
7036 if (data.Content.size() <= idx+1)
7037 data.Content.resize(idx+2);
7039 data.Content[idx+1] = str;
7043 } while (result->NextRow());
7045 delete result;
7047 sLog.outString();
7048 if (min_value == MIN_MANGOS_STRING_ID)
7049 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7050 else
7051 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7053 return true;
7056 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7058 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7059 // Content[0] always exist if exist MangosStringLocale
7060 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7062 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7063 return msl->Content[locale_idx+1].c_str();
7064 else
7065 return msl->Content[0].c_str();
7068 if(entry > 0)
7069 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7070 else
7071 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7072 return "<error>";
7075 void ObjectMgr::LoadFishingBaseSkillLevel()
7077 mFishingBaseForArea.clear(); // for reload case
7079 uint32 count = 0;
7080 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7082 if( !result )
7084 barGoLink bar( 1 );
7086 bar.step();
7088 sLog.outString();
7089 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7090 return;
7093 barGoLink bar( result->GetRowCount() );
7097 bar.step();
7099 Field *fields = result->Fetch();
7100 uint32 entry = fields[0].GetUInt32();
7101 int32 skill = fields[1].GetInt32();
7103 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7104 if(!fArea)
7106 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7107 continue;
7110 mFishingBaseForArea[entry] = skill;
7111 ++count;
7113 while (result->NextRow());
7115 delete result;
7117 sLog.outString();
7118 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7121 // Searches for the same condition already in Conditions store
7122 // Returns Id if found, else adds it to Conditions and returns Id
7123 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7125 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7126 for (uint16 i=0; i < mConditions.size(); ++i)
7128 if (lc == mConditions[i])
7129 return i;
7132 mConditions.push_back(lc);
7134 if(mConditions.size() > 0xFFFF)
7136 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7137 return 0;
7140 return mConditions.size() - 1;
7143 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7145 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7147 std::wstring wname;
7148 if(!Utf8toWStr(names.name[i],wname))
7149 return false;
7151 if(mainpart!=GetMainPartOfName(wname,i+1))
7152 return false;
7154 return true;
7157 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7159 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7160 if(i!= mAreaTriggerScripts.end())
7161 return i->second;
7162 return 0;
7165 // Checks if player meets the condition
7166 bool PlayerCondition::Meets(Player const * player) const
7168 if( !player )
7169 return false; // player not present, return false
7171 switch (condition)
7173 case CONDITION_NONE:
7174 return true; // empty condition, always met
7175 case CONDITION_AURA:
7176 return player->HasAura(value1, value2);
7177 case CONDITION_ITEM:
7178 return player->HasItemCount(value1, value2);
7179 case CONDITION_ITEM_EQUIPPED:
7180 return player->HasItemOrGemWithIdEquipped(value1,1);
7181 case CONDITION_ZONEID:
7182 return player->GetZoneId() == value1;
7183 case CONDITION_REPUTATION_RANK:
7185 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7186 return faction && player->GetReputationMgr().GetRank(faction) >= int32(value2);
7188 case CONDITION_TEAM:
7189 return player->GetTeam() == value1;
7190 case CONDITION_SKILL:
7191 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7192 case CONDITION_QUESTREWARDED:
7193 return player->GetQuestRewardStatus(value1);
7194 case CONDITION_QUESTTAKEN:
7196 QuestStatus status = player->GetQuestStatus(value1);
7197 return (status == QUEST_STATUS_INCOMPLETE);
7199 case CONDITION_AD_COMMISSION_AURA:
7201 Unit::AuraMap const& auras = player->GetAuras();
7202 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7203 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7204 return true;
7205 return false;
7207 case CONDITION_NO_AURA:
7208 return !player->HasAura(value1, value2);
7209 case CONDITION_ACTIVE_EVENT:
7210 return gameeventmgr.IsActiveEvent(value1);
7211 default:
7212 return false;
7216 // Verification of condition values validity
7217 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7219 if( condition >= MAX_CONDITION) // Wrong condition type
7221 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7222 return false;
7225 switch (condition)
7227 case CONDITION_AURA:
7229 if(!sSpellStore.LookupEntry(value1))
7231 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7232 return false;
7234 if(value2 > 2)
7236 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7237 return false;
7239 break;
7241 case CONDITION_ITEM:
7243 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
7244 if(!proto)
7246 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7247 return false;
7249 break;
7251 case CONDITION_ITEM_EQUIPPED:
7253 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
7254 if(!proto)
7256 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7257 return false;
7259 break;
7261 case CONDITION_ZONEID:
7263 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7264 if(!areaEntry)
7266 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7267 return false;
7269 if(areaEntry->zone != 0)
7271 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7272 return false;
7274 break;
7276 case CONDITION_REPUTATION_RANK:
7278 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7279 if(!factionEntry)
7281 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7282 return false;
7284 break;
7286 case CONDITION_TEAM:
7288 if (value1 != ALLIANCE && value1 != HORDE)
7290 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7291 return false;
7293 break;
7295 case CONDITION_SKILL:
7297 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7298 if (!pSkill)
7300 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7301 return false;
7303 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7305 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7306 return false;
7308 break;
7310 case CONDITION_QUESTREWARDED:
7311 case CONDITION_QUESTTAKEN:
7313 Quest const *Quest = objmgr.GetQuestTemplate(value1);
7314 if (!Quest)
7316 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7317 return false;
7319 if(value2)
7320 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7321 break;
7323 case CONDITION_AD_COMMISSION_AURA:
7325 if(value1)
7326 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7327 if(value2)
7328 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7329 break;
7331 case CONDITION_NO_AURA:
7333 if(!sSpellStore.LookupEntry(value1))
7335 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7336 return false;
7338 if(value2 > 2)
7340 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7341 return false;
7343 break;
7345 case CONDITION_ACTIVE_EVENT:
7347 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
7348 if(value1 >=events.size() || !events[value1].isValid())
7350 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7351 return false;
7353 break;
7355 case CONDITION_NONE:
7356 break;
7358 return true;
7361 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7363 switch(pSkill->categoryId)
7365 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7366 case SKILL_CATEGORY_WEAPON:
7367 if(pSkill->id!=SKILL_FIST_WEAPONS)
7368 return SKILL_RANGE_LEVEL;
7369 else
7370 return SKILL_RANGE_MONO;
7371 case SKILL_CATEGORY_ARMOR:
7372 case SKILL_CATEGORY_CLASS:
7373 if(pSkill->id != SKILL_LOCKPICKING)
7374 return SKILL_RANGE_MONO;
7375 else
7376 return SKILL_RANGE_LEVEL;
7377 case SKILL_CATEGORY_SECONDARY:
7378 case SKILL_CATEGORY_PROFESSION:
7379 // not set skills for professions and racial abilities
7380 if(IsProfessionSkill(pSkill->id))
7381 return SKILL_RANGE_RANK;
7382 else if(racial)
7383 return SKILL_RANGE_NONE;
7384 else
7385 return SKILL_RANGE_MONO;
7386 default:
7387 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7388 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7389 return SKILL_RANGE_NONE;
7393 void ObjectMgr::LoadGameTele()
7395 m_GameTeleMap.clear(); // for reload case
7397 uint32 count = 0;
7398 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7400 if( !result )
7402 barGoLink bar( 1 );
7404 bar.step();
7406 sLog.outString();
7407 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7408 return;
7411 barGoLink bar( result->GetRowCount() );
7415 bar.step();
7417 Field *fields = result->Fetch();
7419 uint32 id = fields[0].GetUInt32();
7421 GameTele gt;
7423 gt.position_x = fields[1].GetFloat();
7424 gt.position_y = fields[2].GetFloat();
7425 gt.position_z = fields[3].GetFloat();
7426 gt.orientation = fields[4].GetFloat();
7427 gt.mapId = fields[5].GetUInt32();
7428 gt.name = fields[6].GetCppString();
7430 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7432 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7433 continue;
7436 if(!Utf8toWStr(gt.name,gt.wnameLow))
7438 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7439 continue;
7442 wstrToLower( gt.wnameLow );
7444 m_GameTeleMap[id] = gt;
7446 ++count;
7448 while (result->NextRow());
7449 delete result;
7451 sLog.outString();
7452 sLog.outString( ">> Loaded %u GameTeleports", count );
7455 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7457 // explicit name case
7458 std::wstring wname;
7459 if(!Utf8toWStr(name,wname))
7460 return false;
7462 // converting string that we try to find to lower case
7463 wstrToLower( wname );
7465 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7466 const GameTele* alt = NULL;
7467 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7468 if(itr->second.wnameLow == wname)
7469 return &itr->second;
7470 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7471 alt = &itr->second;
7473 return alt;
7476 bool ObjectMgr::AddGameTele(GameTele& tele)
7478 // find max id
7479 uint32 new_id = 0;
7480 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7481 if(itr->first > new_id)
7482 new_id = itr->first;
7484 // use next
7485 ++new_id;
7487 if(!Utf8toWStr(tele.name,tele.wnameLow))
7488 return false;
7490 wstrToLower( tele.wnameLow );
7492 m_GameTeleMap[new_id] = tele;
7494 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')",
7495 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7498 bool ObjectMgr::DeleteGameTele(const std::string& name)
7500 // explicit name case
7501 std::wstring wname;
7502 if(!Utf8toWStr(name,wname))
7503 return false;
7505 // converting string that we try to find to lower case
7506 wstrToLower( wname );
7508 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7510 if(itr->second.wnameLow == wname)
7512 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7513 m_GameTeleMap.erase(itr);
7514 return true;
7518 return false;
7521 void ObjectMgr::LoadMailLevelRewards()
7523 m_mailLevelRewardMap.clear(); // for reload case
7525 uint32 count = 0;
7526 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7528 if( !result )
7530 barGoLink bar( 1 );
7532 bar.step();
7534 sLog.outString();
7535 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7536 return;
7539 barGoLink bar( result->GetRowCount() );
7543 bar.step();
7545 Field *fields = result->Fetch();
7547 uint8 level = fields[0].GetUInt8();
7548 uint32 raceMask = fields[1].GetUInt32();
7549 uint32 mailTemplateId = fields[2].GetUInt32();
7550 uint32 senderEntry = fields[3].GetUInt32();
7552 if(level > MAX_LEVEL)
7554 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7555 continue;
7558 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7560 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7561 continue;
7564 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7566 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7567 continue;
7570 if(!GetCreatureTemplateStore(senderEntry))
7572 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);
7573 continue;
7576 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7578 ++count;
7580 while (result->NextRow());
7581 delete result;
7583 sLog.outString();
7584 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7587 void ObjectMgr::LoadTrainerSpell()
7589 // For reload case
7590 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7591 itr->second.Clear();
7592 m_mCacheTrainerSpellMap.clear();
7594 std::set<uint32> skip_trainers;
7596 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7598 if( !result )
7600 barGoLink bar( 1 );
7602 bar.step();
7604 sLog.outString();
7605 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7606 return;
7609 barGoLink bar( result->GetRowCount() );
7611 std::set<uint32> talentIds;
7613 uint32 count = 0;
7616 bar.step();
7618 Field* fields = result->Fetch();
7620 uint32 entry = fields[0].GetUInt32();
7621 uint32 spell = fields[1].GetUInt32();
7623 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7625 if(!cInfo)
7627 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7628 continue;
7631 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7633 if(skip_trainers.count(entry) == 0)
7635 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7636 skip_trainers.insert(entry);
7638 continue;
7641 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7642 if(!spellinfo)
7644 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7645 continue;
7648 if(!SpellMgr::IsSpellValid(spellinfo))
7650 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7651 continue;
7654 if(GetTalentSpellCost(spell))
7656 if(talentIds.count(spell)==0)
7658 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7659 talentIds.insert(spell);
7661 continue;
7664 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7666 TrainerSpell& trainerSpell = data.spellList[spell];
7667 trainerSpell.spell = spell;
7668 trainerSpell.spellCost = fields[2].GetUInt32();
7669 trainerSpell.reqSkill = fields[3].GetUInt32();
7670 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7671 trainerSpell.reqLevel = fields[5].GetUInt32();
7673 if(!trainerSpell.reqLevel)
7674 trainerSpell.reqLevel = spellinfo->spellLevel;
7676 // calculate learned spell for profession case when stored cast-spell
7677 trainerSpell.learnedSpell = spell;
7678 for(int i = 0; i <3; ++i)
7680 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7681 continue;
7682 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7684 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7685 break;
7689 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7690 data.trainerType = 2;
7692 ++count;
7694 } while (result->NextRow());
7695 delete result;
7697 sLog.outString();
7698 sLog.outString( ">> Loaded %d Trainers", count );
7701 void ObjectMgr::LoadVendors()
7703 // For reload case
7704 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7705 itr->second.Clear();
7706 m_mCacheVendorItemMap.clear();
7708 std::set<uint32> skip_vendors;
7710 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7711 if( !result )
7713 barGoLink bar( 1 );
7715 bar.step();
7717 sLog.outString();
7718 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7719 return;
7722 barGoLink bar( result->GetRowCount() );
7724 uint32 count = 0;
7727 bar.step();
7728 Field* fields = result->Fetch();
7730 uint32 entry = fields[0].GetUInt32();
7731 uint32 item_id = fields[1].GetUInt32();
7732 uint32 maxcount = fields[2].GetUInt32();
7733 uint32 incrtime = fields[3].GetUInt32();
7734 uint32 ExtendedCost = fields[4].GetUInt32();
7736 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7737 continue;
7739 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7741 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7742 ++count;
7744 } while (result->NextRow());
7745 delete result;
7747 sLog.outString();
7748 sLog.outString( ">> Loaded %d Vendors ", count );
7751 void ObjectMgr::LoadNpcTextId()
7754 m_mCacheNpcTextIdMap.clear();
7756 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7757 if( !result )
7759 barGoLink bar( 1 );
7761 bar.step();
7763 sLog.outString();
7764 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7765 return;
7768 barGoLink bar( result->GetRowCount() );
7770 uint32 count = 0;
7771 uint32 guid,textid;
7774 bar.step();
7776 Field* fields = result->Fetch();
7778 guid = fields[0].GetUInt32();
7779 textid = fields[1].GetUInt32();
7781 if (!GetCreatureData(guid))
7783 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7784 continue;
7786 if (!GetGossipText(textid))
7788 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7789 continue;
7792 m_mCacheNpcTextIdMap[guid] = textid ;
7793 ++count;
7795 } while (result->NextRow());
7796 delete result;
7798 sLog.outString();
7799 sLog.outString( ">> Loaded %d NpcTextId ", count );
7802 void ObjectMgr::LoadNpcOptions()
7804 m_mCacheNpcOptionList.clear(); // For reload case
7806 QueryResult *result = WorldDatabase.Query(
7807 // 0 1 2 3 4 5 6 7 8
7808 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7809 "FROM npc_option");
7811 if( !result )
7813 barGoLink bar( 1 );
7815 bar.step();
7817 sLog.outString();
7818 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7819 return;
7822 barGoLink bar( result->GetRowCount() );
7824 uint32 count = 0;
7828 bar.step();
7830 Field* fields = result->Fetch();
7832 GossipOption go;
7833 go.Id = fields[0].GetUInt32();
7834 go.GossipId = fields[1].GetUInt32();
7835 go.NpcFlag = fields[2].GetUInt32();
7836 go.Icon = fields[3].GetUInt32();
7837 go.Action = fields[4].GetUInt32();
7838 go.BoxMoney = fields[5].GetUInt32();
7839 go.Coded = fields[6].GetUInt8()!=0;
7840 go.OptionText = fields[7].GetCppString();
7841 go.BoxText = fields[8].GetCppString();
7843 m_mCacheNpcOptionList.push_back(go);
7845 ++count;
7847 } while (result->NextRow());
7848 delete result;
7850 sLog.outString();
7851 sLog.outString( ">> Loaded %d npc_option entries", count );
7854 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7856 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7857 vList.AddItem(item,maxcount,incrtime,extendedcost);
7859 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7862 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7864 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7865 if(iter == m_mCacheVendorItemMap.end())
7866 return false;
7868 if(!iter->second.FindItem(item))
7869 return false;
7871 iter->second.RemoveItem(item);
7872 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7873 return true;
7876 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7878 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7879 if(!cInfo)
7881 if(pl)
7882 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7883 else
7884 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7885 return false;
7888 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7890 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7892 if(pl)
7893 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7894 else
7895 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7897 if(skip_vendors)
7898 skip_vendors->insert(vendor_entry);
7900 return false;
7903 if(!GetItemPrototype(item_id))
7905 if(pl)
7906 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7907 else
7908 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7909 return false;
7912 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7914 if(pl)
7915 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7916 else
7917 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7918 return false;
7921 if(maxcount > 0 && incrtime == 0)
7923 if(pl)
7924 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7925 else
7926 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7927 return false;
7929 else if(maxcount==0 && incrtime > 0)
7931 if(pl)
7932 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7933 else
7934 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7935 return false;
7938 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7939 if(!vItems)
7940 return true; // later checks for non-empty lists
7942 if(vItems->FindItem(item_id))
7944 if(pl)
7945 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7946 else
7947 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7948 return false;
7951 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7953 if(pl)
7954 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7955 else
7956 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7957 return false;
7960 return true;
7963 void ObjectMgr::LoadScriptNames()
7965 m_scriptNames.push_back("");
7966 QueryResult *result = WorldDatabase.Query(
7967 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7968 "UNION "
7969 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7970 "UNION "
7971 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7972 "UNION "
7973 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7974 "UNION "
7975 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7977 if( !result )
7979 barGoLink bar( 1 );
7980 bar.step();
7981 sLog.outString();
7982 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7983 return;
7986 barGoLink bar( result->GetRowCount() );
7987 uint32 count = 0;
7991 bar.step();
7992 m_scriptNames.push_back((*result)[0].GetString());
7993 ++count;
7994 } while (result->NextRow());
7995 delete result;
7997 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7998 sLog.outString();
7999 sLog.outString( ">> Loaded %d Script Names", count );
8002 uint32 ObjectMgr::GetScriptId(const char *name)
8004 // use binary search to find the script name in the sorted vector
8005 // assume "" is the first element
8006 if(!name) return 0;
8007 ScriptNameMap::const_iterator itr =
8008 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8009 if(itr == m_scriptNames.end() || *itr != name) return 0;
8010 return itr - m_scriptNames.begin();
8013 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
8015 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8017 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8019 switch(itrM->second.command)
8021 case SCRIPT_COMMAND_TALK:
8023 if(!GetMangosStringLocale (itrM->second.dataint))
8024 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
8026 if(ids.count(itrM->second.dataint))
8027 ids.erase(itrM->second.dataint);
8034 void ObjectMgr::LoadDbScriptStrings()
8036 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8038 std::set<int32> ids;
8040 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8041 if(GetMangosStringLocale(i))
8042 ids.insert(i);
8044 CheckScripts(sQuestEndScripts,ids);
8045 CheckScripts(sQuestStartScripts,ids);
8046 CheckScripts(sSpellScripts,ids);
8047 CheckScripts(sGameObjectScripts,ids);
8048 CheckScripts(sEventScripts,ids);
8050 WaypointMgr.CheckTextsExistance(ids);
8052 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8053 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8056 // Functions for scripting access
8057 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8059 return objmgr.GetAreaTriggerScriptId(trigger_id);
8062 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8064 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8065 // start/end reversed for negative values
8066 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8068 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8069 return false;
8072 return objmgr.LoadMangosStrings(db,table,start_value,end_value);
8075 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8077 return objmgr.GetScriptId(name);
8080 ObjectMgr::ScriptNameMap & GetScriptNames()
8082 return objmgr.GetScriptNames();
8085 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8087 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8090 Quest const* GetQuestTemplateStore(uint32 entry)
8092 return objmgr.GetQuestTemplate(entry);