[7745] Fixed gcc warnings.
[getmangos.git] / src / game / ObjectMgr.cpp
blob0cc7d3210b5140e5f50e074625e7a2f63a2155f1
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 ObjectMgr::ObjectMgr()
111 m_hiCharGuid = 1;
112 m_hiCreatureGuid = 1;
113 m_hiPetGuid = 1;
114 m_hiVehicleGuid = 1;
115 m_hiItemGuid = 1;
116 m_hiGoGuid = 1;
117 m_hiDoGuid = 1;
118 m_hiCorpseGuid = 1;
119 m_hiPetNumber = 1;
120 m_ItemTextId = 1;
121 m_mailid = 1;
122 m_guildId = 1;
123 m_arenaTeamId = 1;
124 m_auctionid = 1;
126 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
127 mGuildBankTabPrice[0] = 100;
128 mGuildBankTabPrice[1] = 250;
129 mGuildBankTabPrice[2] = 500;
130 mGuildBankTabPrice[3] = 1000;
131 mGuildBankTabPrice[4] = 2500;
132 mGuildBankTabPrice[5] = 5000;
134 // Only zero condition left, others will be added while loading DB tables
135 mConditions.resize(1);
138 ObjectMgr::~ObjectMgr()
140 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
141 delete i->second;
143 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
144 delete[] i->second;
146 // free only if loaded
147 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
148 delete[] playerClassInfo[class_].levelInfo;
150 for (int race = 0; race < MAX_RACES; ++race)
151 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
152 delete[] playerInfo[race][class_].levelInfo;
154 // free group and guild objects
155 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
156 delete (*itr);
158 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
159 delete itr->second;
161 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
162 itr->second.Clear();
164 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
165 itr->second.Clear();
168 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
170 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
171 if ((*itr)->GetLeaderGUID() == guid)
172 return *itr;
174 return NULL;
177 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
179 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
180 if (itr != mGuildMap.end())
181 return itr->second;
183 return NULL;
186 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
188 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
189 if (itr->second->GetName() == guildname)
190 return itr->second;
192 return NULL;
195 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
197 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
198 if (itr != mGuildMap.end())
199 return itr->second->GetName();
201 return "";
204 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
206 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
207 if (itr->second->GetLeader() == guid)
208 return itr->second;
210 return NULL;
213 void ObjectMgr::AddGuild(Guild* guild)
215 mGuildMap[guild->GetId()] = guild;
218 void ObjectMgr::RemoveGuild(uint32 Id)
220 mGuildMap.erase(Id);
223 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
225 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
226 if (itr != mArenaTeamMap.end())
227 return itr->second;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
234 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
235 if (itr->second->GetName() == arenateamname)
236 return itr->second;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
243 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
244 if (itr->second->GetCaptain() == guid)
245 return itr->second;
247 return NULL;
250 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
252 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
255 void ObjectMgr::RemoveArenaTeam(uint32 Id)
257 mArenaTeamMap.erase(Id);
260 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
262 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
265 void ObjectMgr::LoadCreatureLocales()
267 mCreatureLocaleMap.clear(); // need for reload case
269 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");
271 if(!result)
273 barGoLink bar(1);
275 bar.step();
277 sLog.outString();
278 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
279 return;
282 barGoLink bar(result->GetRowCount());
286 Field *fields = result->Fetch();
287 bar.step();
289 uint32 entry = fields[0].GetUInt32();
291 CreatureLocale& data = mCreatureLocaleMap[entry];
293 for(int i = 1; i < MAX_LOCALE; ++i)
295 std::string str = fields[1+2*(i-1)].GetCppString();
296 if(!str.empty())
298 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
299 if(idx >= 0)
301 if(data.Name.size() <= idx)
302 data.Name.resize(idx+1);
304 data.Name[idx] = str;
307 str = fields[1+2*(i-1)+1].GetCppString();
308 if(!str.empty())
310 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
311 if(idx >= 0)
313 if(data.SubName.size() <= idx)
314 data.SubName.resize(idx+1);
316 data.SubName[idx] = str;
320 } while (result->NextRow());
322 delete result;
324 sLog.outString();
325 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
328 void ObjectMgr::LoadNpcOptionLocales()
330 mNpcOptionLocaleMap.clear(); // need for reload case
332 QueryResult *result = WorldDatabase.Query("SELECT entry,"
333 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
334 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
335 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
336 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
337 "FROM locales_npc_option");
339 if(!result)
341 barGoLink bar(1);
343 bar.step();
345 sLog.outString();
346 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
347 return;
350 barGoLink bar(result->GetRowCount());
354 Field *fields = result->Fetch();
355 bar.step();
357 uint32 entry = fields[0].GetUInt32();
359 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
361 for(int i = 1; i < MAX_LOCALE; ++i)
363 std::string str = fields[1+2*(i-1)].GetCppString();
364 if(!str.empty())
366 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
367 if(idx >= 0)
369 if(data.OptionText.size() <= idx)
370 data.OptionText.resize(idx+1);
372 data.OptionText[idx] = str;
375 str = fields[1+2*(i-1)+1].GetCppString();
376 if(!str.empty())
378 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
379 if(idx >= 0)
381 if(data.BoxText.size() <= idx)
382 data.BoxText.resize(idx+1);
384 data.BoxText[idx] = str;
388 } while (result->NextRow());
390 delete result;
392 sLog.outString();
393 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
396 void ObjectMgr::LoadPointOfInterestLocales()
398 mPointOfInterestLocaleMap.clear(); // need for reload case
400 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");
402 if(!result)
404 barGoLink bar(1);
406 bar.step();
408 sLog.outString();
409 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
410 return;
413 barGoLink bar(result->GetRowCount());
417 Field *fields = result->Fetch();
418 bar.step();
420 uint32 entry = fields[0].GetUInt32();
422 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
424 for(int i = 1; i < MAX_LOCALE; ++i)
426 std::string str = fields[i].GetCppString();
427 if(str.empty())
428 continue;
430 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
431 if(idx >= 0)
433 if(data.IconName.size() <= idx)
434 data.IconName.resize(idx+1);
436 data.IconName[idx] = str;
439 } while (result->NextRow());
441 delete result;
443 sLog.outString();
444 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
447 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
449 template<class D>
450 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
452 dst = D(objmgr.GetScriptId(src));
456 void ObjectMgr::LoadCreatureTemplates()
458 SQLCreatureLoader loader;
459 loader.Load(sCreatureStorage);
461 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
462 sLog.outString();
464 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
465 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
467 // check data correctness
468 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
470 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
471 if(!cInfo)
472 continue;
474 if(cInfo->HeroicEntry)
476 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
477 if(!heroicInfo)
479 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
480 continue;
483 if(heroicEntries.find(i)!=heroicEntries.end())
485 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
486 continue;
489 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
491 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
492 continue;
495 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
497 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
498 continue;
501 if(cInfo->npcflag != heroicInfo->npcflag)
503 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
504 continue;
507 if(cInfo->classNum != heroicInfo->classNum)
509 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
510 continue;
513 if(cInfo->race != heroicInfo->race)
515 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
516 continue;
519 if(cInfo->trainer_type != heroicInfo->trainer_type)
521 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
522 continue;
525 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
527 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
528 continue;
531 if(heroicInfo->AIName && *heroicInfo->AIName)
533 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `AIName`, but in any case will used normal mode creature (Entry: %u) AIName.",cInfo->HeroicEntry,i);
534 continue;
537 if(heroicInfo->ScriptID)
539 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `ScriptName`, but in any case will used normal mode creature (Entry: %u) ScriptName.",cInfo->HeroicEntry,i);
540 continue;
543 hasHeroicEntries.insert(i);
544 heroicEntries.insert(cInfo->HeroicEntry);
547 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
548 if(!factionTemplate)
549 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
551 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
552 if(!factionTemplate)
553 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
555 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
556 if (!minfo)
557 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
558 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
559 if (!minfo)
560 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
562 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
564 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
565 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
568 if(cInfo->baseattacktime == 0)
569 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
571 if(cInfo->rangeattacktime == 0)
572 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
574 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
575 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
577 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
579 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
580 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
583 // must exist or used hidden but used in data horse case
584 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
586 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
587 const_cast<CreatureInfo*>(cInfo)->family = 0;
590 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
592 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
593 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
596 if(cInfo->PetSpellDataId)
598 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
599 if(!spellDataId)
600 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
603 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
605 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
607 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
608 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
612 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
614 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
615 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
618 if(cInfo->equipmentId > 0) // 0 no equipment
620 if(!GetEquipmentInfo(cInfo->equipmentId))
622 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);
623 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
627 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
628 if(cInfo->scale <= 0.0f)
630 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
631 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
636 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
638 // Now add the auras, format "spellid effectindex spellid effectindex..."
639 char *p,*s;
640 std::vector<int> val;
641 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
642 if(p)
644 while (p[0]!=0)
646 ++p;
647 if (p[0]==' ')
649 val.push_back(atoi(s));
650 s=++p;
653 if (p!=s)
654 val.push_back(atoi(s));
656 // free char* loaded memory
657 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
659 // wrong list
660 if (val.size()%2)
662 addon->auras = NULL;
663 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
664 return;
668 // empty list
669 if(val.empty())
671 addon->auras = NULL;
672 return;
675 // replace by new structures array
676 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
678 int i=0;
679 for(int j=0;j<val.size()/2;++j)
681 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
682 cAura.spell_id = (uint32)val[2*j+0];
683 cAura.effect_idx = (uint32)val[2*j+1];
684 if ( cAura.effect_idx > 2 )
686 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);
687 continue;
689 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
690 if (!AdditionalSpellInfo)
692 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
693 continue;
696 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
698 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);
699 continue;
702 ++i;
705 // fill terminator element (after last added)
706 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
707 endAura.spell_id = 0;
708 endAura.effect_idx = 0;
711 void ObjectMgr::LoadCreatureAddons()
713 sCreatureInfoAddonStorage.Load();
715 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
716 sLog.outString();
718 // check data correctness and convert 'auras'
719 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
721 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
722 if(!addon)
723 continue;
725 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
727 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
728 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
731 sCreatureDataAddonStorage.Load();
733 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
734 sLog.outString();
736 // check data correctness and convert 'auras'
737 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
739 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
740 if(!addon)
741 continue;
743 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
745 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
746 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
750 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
752 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
755 void ObjectMgr::LoadEquipmentTemplates()
757 sEquipmentStorage.Load();
759 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
761 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
763 if(!eqInfo)
764 continue;
766 for(uint8 j=0; j<3; j++)
768 if(!eqInfo->equipentry[j])
769 continue;
771 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
773 if(!dbcitem)
775 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
776 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
777 continue;
780 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
781 dbcitem->InventoryType != INVTYPE_SHIELD &&
782 dbcitem->InventoryType != INVTYPE_RANGED &&
783 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
784 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
785 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
786 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
787 dbcitem->InventoryType != INVTYPE_THROWN &&
788 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
790 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);
791 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
795 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
796 sLog.outString();
798 // This DBC is currently only used for item templates and creature equipments checks.
799 sItemStore.Clear();
802 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
804 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
807 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
809 // Load creature model (display id)
810 uint32 display_id;
811 if (!data || data->displayid == 0) // use defaults from the template
813 // DisplayID_A is used if no team is given
814 if (team == HORDE)
815 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
816 else
817 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
819 else // overridden in creature data
820 display_id = data->displayid;
822 return display_id;
825 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
827 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
828 if(!minfo)
829 return NULL;
831 // If a model for another gender exists, 50% chance to use it
832 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
834 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
835 if(!minfo_tmp)
837 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
838 return minfo; // not fatal, just use the previous one
840 else
841 return minfo_tmp;
843 else
844 return minfo;
847 void ObjectMgr::LoadCreatureModelInfo()
849 sCreatureModelStorage.Load();
851 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
852 sLog.outString();
855 void ObjectMgr::LoadCreatures()
857 uint32 count = 0;
858 // 0 1 2 3
859 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
860 // 4 5 6 7 8 9 10 11
861 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
862 // 12 13 14 15 16 17 18 19
863 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
864 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
865 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
867 if(!result)
869 barGoLink bar(1);
871 bar.step();
873 sLog.outString();
874 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
875 return;
878 // build single time for check creature data
879 std::set<uint32> heroicCreatures;
880 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
881 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
882 if(cInfo->HeroicEntry)
883 heroicCreatures.insert(cInfo->HeroicEntry);
885 barGoLink bar(result->GetRowCount());
889 Field *fields = result->Fetch();
890 bar.step();
892 uint32 guid = fields[ 0].GetUInt32();
893 uint32 entry = fields[ 1].GetUInt32();
895 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
896 if(!cInfo)
898 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
899 continue;
902 CreatureData& data = mCreatureDataMap[guid];
904 data.id = entry;
905 data.mapid = fields[ 2].GetUInt32();
906 data.displayid = fields[ 3].GetUInt32();
907 data.equipmentId = fields[ 4].GetUInt32();
908 data.posX = fields[ 5].GetFloat();
909 data.posY = fields[ 6].GetFloat();
910 data.posZ = fields[ 7].GetFloat();
911 data.orientation = fields[ 8].GetFloat();
912 data.spawntimesecs = fields[ 9].GetUInt32();
913 data.spawndist = fields[10].GetFloat();
914 data.currentwaypoint= fields[11].GetUInt32();
915 data.curhealth = fields[12].GetUInt32();
916 data.curmana = fields[13].GetUInt32();
917 data.is_dead = fields[14].GetBool();
918 data.movementType = fields[15].GetUInt8();
919 data.spawnMask = fields[16].GetUInt8();
920 data.phaseMask = fields[17].GetUInt16();
921 int16 gameEvent = fields[18].GetInt16();
922 int16 PoolId = fields[19].GetInt16();
924 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
926 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
927 continue;
930 if(data.equipmentId > 0) // -1 no equipment, 0 use default
932 if(!GetEquipmentInfo(data.equipmentId))
934 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);
935 data.equipmentId = -1;
939 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
941 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 );
942 data.curhealth = cInfo->minhealth;
945 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
947 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
948 if(!map || !map->IsDungeon())
949 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);
952 if(data.curmana < cInfo->minmana)
954 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 );
955 data.curmana = cInfo->minmana;
958 if(data.spawndist < 0.0f)
960 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
961 data.spawndist = 0.0f;
963 else if(data.movementType == RANDOM_MOTION_TYPE)
965 if(data.spawndist == 0.0f)
967 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 );
968 data.movementType = IDLE_MOTION_TYPE;
971 else if(data.movementType == IDLE_MOTION_TYPE)
973 if(data.spawndist != 0.0f)
975 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
976 data.spawndist = 0.0f;
980 if(data.phaseMask==0)
982 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
983 data.phaseMask = 1;
986 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
987 AddCreatureToGrid(guid, &data);
989 ++count;
991 } while (result->NextRow());
993 delete result;
995 sLog.outString();
996 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
999 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1001 uint8 mask = data->spawnMask;
1002 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1004 if(mask & 1)
1006 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1007 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1009 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1010 cell_guids.creatures.insert(guid);
1015 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1017 uint8 mask = data->spawnMask;
1018 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1020 if(mask & 1)
1022 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1023 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1025 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1026 cell_guids.creatures.erase(guid);
1031 void ObjectMgr::LoadGameobjects()
1033 uint32 count = 0;
1035 // 0 1 2 3 4 5 6
1036 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1037 // 7 8 9 10 11 12 13 14 15 16 17
1038 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1039 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1040 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1042 if(!result)
1044 barGoLink bar(1);
1046 bar.step();
1048 sLog.outString();
1049 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1050 return;
1053 barGoLink bar(result->GetRowCount());
1057 Field *fields = result->Fetch();
1058 bar.step();
1060 uint32 guid = fields[ 0].GetUInt32();
1061 uint32 entry = fields[ 1].GetUInt32();
1063 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1064 if(!gInfo)
1066 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1067 continue;
1070 GameObjectData& data = mGameObjectDataMap[guid];
1072 data.id = entry;
1073 data.mapid = fields[ 2].GetUInt32();
1074 data.posX = fields[ 3].GetFloat();
1075 data.posY = fields[ 4].GetFloat();
1076 data.posZ = fields[ 5].GetFloat();
1077 data.orientation = fields[ 6].GetFloat();
1078 data.rotation0 = fields[ 7].GetFloat();
1079 data.rotation1 = fields[ 8].GetFloat();
1080 data.rotation2 = fields[ 9].GetFloat();
1081 data.rotation3 = fields[10].GetFloat();
1082 data.spawntimesecs = fields[11].GetInt32();
1083 data.animprogress = fields[12].GetUInt32();
1085 uint32 go_state = fields[13].GetUInt32();
1086 if (go_state >= MAX_GO_STATE)
1088 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip",guid,data.id,go_state);
1089 continue;
1091 data.go_state = GOState(go_state);
1093 data.spawnMask = fields[14].GetUInt8();
1094 data.phaseMask = fields[15].GetUInt16();
1095 int16 gameEvent = fields[16].GetInt16();
1096 int16 PoolId = fields[17].GetInt16();
1098 if(data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1100 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip",guid,data.id,data.rotation2 );
1101 continue;
1104 if(data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1106 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip",guid,data.id,data.rotation3 );
1107 continue;
1110 if(!MapManager::IsValidMapCoord(data.mapid,data.posX,data.posY,data.posZ,data.orientation))
1112 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip",guid,data.id );
1113 continue;
1116 if(data.phaseMask==0)
1118 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1119 data.phaseMask = 1;
1122 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1123 AddGameobjectToGrid(guid, &data);
1124 ++count;
1126 } while (result->NextRow());
1128 delete result;
1130 sLog.outString();
1131 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1134 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1136 uint8 mask = data->spawnMask;
1137 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1139 if(mask & 1)
1141 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1142 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1144 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1145 cell_guids.gameobjects.insert(guid);
1150 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1152 uint8 mask = data->spawnMask;
1153 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1155 if(mask & 1)
1157 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1158 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1160 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1161 cell_guids.gameobjects.erase(guid);
1166 void ObjectMgr::LoadCreatureRespawnTimes()
1168 // remove outdated data
1169 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1171 uint32 count = 0;
1173 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1175 if(!result)
1177 barGoLink bar(1);
1179 bar.step();
1181 sLog.outString();
1182 sLog.outString(">> Loaded 0 creature respawn time.");
1183 return;
1186 barGoLink bar(result->GetRowCount());
1190 Field *fields = result->Fetch();
1191 bar.step();
1193 uint32 loguid = fields[0].GetUInt32();
1194 uint64 respawn_time = fields[1].GetUInt64();
1195 uint32 instance = fields[2].GetUInt32();
1197 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1199 ++count;
1200 } while (result->NextRow());
1202 delete result;
1204 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1205 sLog.outString();
1208 void ObjectMgr::LoadGameobjectRespawnTimes()
1210 // remove outdated data
1211 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1213 uint32 count = 0;
1215 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1217 if(!result)
1219 barGoLink bar(1);
1221 bar.step();
1223 sLog.outString();
1224 sLog.outString(">> Loaded 0 gameobject respawn time.");
1225 return;
1228 barGoLink bar(result->GetRowCount());
1232 Field *fields = result->Fetch();
1233 bar.step();
1235 uint32 loguid = fields[0].GetUInt32();
1236 uint64 respawn_time = fields[1].GetUInt64();
1237 uint32 instance = fields[2].GetUInt32();
1239 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1241 ++count;
1242 } while (result->NextRow());
1244 delete result;
1246 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1247 sLog.outString();
1250 // name must be checked to correctness (if received) before call this function
1251 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1253 uint64 guid = 0;
1255 CharacterDatabase.escape_string(name);
1257 // Player name safe to sending to DB (checked at login) and this function using
1258 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1259 if(result)
1261 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1263 delete result;
1266 return guid;
1269 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1271 // prevent DB access for online player
1272 if(Player* player = GetPlayer(guid))
1274 name = player->GetName();
1275 return true;
1278 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1280 if(result)
1282 name = (*result)[0].GetCppString();
1283 delete result;
1284 return true;
1287 return false;
1290 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1292 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1294 if(result)
1296 uint8 race = (*result)[0].GetUInt8();
1297 delete result;
1298 return Player::TeamForRace(race);
1301 return 0;
1304 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1306 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1307 if(result)
1309 uint32 acc = (*result)[0].GetUInt32();
1310 delete result;
1311 return acc;
1314 return 0;
1317 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1319 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1320 if(result)
1322 uint32 acc = (*result)[0].GetUInt32();
1323 delete result;
1324 return acc;
1327 return 0;
1330 void ObjectMgr::LoadItemLocales()
1332 mItemLocaleMap.clear(); // need for reload case
1334 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");
1336 if(!result)
1338 barGoLink bar(1);
1340 bar.step();
1342 sLog.outString();
1343 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1344 return;
1347 barGoLink bar(result->GetRowCount());
1351 Field *fields = result->Fetch();
1352 bar.step();
1354 uint32 entry = fields[0].GetUInt32();
1356 ItemLocale& data = mItemLocaleMap[entry];
1358 for(int i = 1; i < MAX_LOCALE; ++i)
1360 std::string str = fields[1+2*(i-1)].GetCppString();
1361 if(!str.empty())
1363 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1364 if(idx >= 0)
1366 if(data.Name.size() <= idx)
1367 data.Name.resize(idx+1);
1369 data.Name[idx] = str;
1373 str = fields[1+2*(i-1)+1].GetCppString();
1374 if(!str.empty())
1376 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1377 if(idx >= 0)
1379 if(data.Description.size() <= idx)
1380 data.Description.resize(idx+1);
1382 data.Description[idx] = str;
1386 } while (result->NextRow());
1388 delete result;
1390 sLog.outString();
1391 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1394 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1396 template<class D>
1397 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1399 dst = D(objmgr.GetScriptId(src));
1403 void ObjectMgr::LoadItemPrototypes()
1405 SQLItemLoader loader;
1406 loader.Load(sItemStorage);
1407 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1408 sLog.outString();
1410 // check data correctness
1411 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1413 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1414 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1415 if(!proto)
1417 /* to many errors, and possible not all items really used in game
1418 if (dbcitem)
1419 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1421 continue;
1424 if(dbcitem)
1426 if(proto->Class != dbcitem->Class)
1428 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1429 // It safe let use Class from DB
1431 /* disabled: have some strange wrong cases for Subclass values.
1432 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1433 if(proto->SubClass != dbcitem->SubClass)
1435 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);
1436 // It safe let use Subclass from DB
1440 if(proto->Unk0 != dbcitem->Unk0)
1442 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1443 // It safe let use Unk0 from DB
1446 if(proto->Material != dbcitem->Material)
1448 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1449 // It safe let use Material from DB
1452 if(proto->InventoryType != dbcitem->InventoryType)
1454 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1455 // It safe let use InventoryType from DB
1458 if(proto->DisplayInfoID != dbcitem->DisplayId)
1460 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1461 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1463 if(proto->Sheath != dbcitem->Sheath)
1465 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1466 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1469 else
1471 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1474 if(proto->Class >= MAX_ITEM_CLASS)
1476 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1477 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1480 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1482 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1483 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1486 if(proto->Quality >= MAX_ITEM_QUALITY)
1488 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1489 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1492 if(proto->BuyCount <= 0)
1494 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1495 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1498 if(proto->InventoryType >= MAX_INVTYPE)
1500 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1501 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1504 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1506 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1507 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1512 // can be used in equip slot, as page read use in inventory, or spell casting at use
1513 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1514 if(!req)
1516 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1518 if(proto->Spells[j].SpellId)
1520 req = true;
1521 break;
1526 if(req)
1528 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1529 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1531 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1532 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1536 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1538 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1539 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1542 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1543 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1545 if(proto->RequiredReputationFaction)
1547 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1549 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1550 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1553 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1554 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1556 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1557 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1559 if(proto->MaxCount < -1)
1561 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1562 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1565 if(proto->Stackable==0)
1567 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1568 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1570 else if(proto->Stackable < -1)
1572 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1573 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1575 else if(proto->Stackable > 255)
1577 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1578 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1581 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1583 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1584 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1587 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1589 // for ItemStatValue != 0
1590 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1592 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1593 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1597 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1599 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1601 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1602 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1606 // special format
1607 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1609 // spell_1
1610 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1612 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);
1613 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1614 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1615 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1616 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1619 // spell_2 have learning spell
1620 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1622 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);
1623 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1624 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1625 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1627 else if(!proto->Spells[1].SpellId)
1629 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1630 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1631 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1633 else
1635 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1636 if(!spellInfo)
1638 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1639 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1640 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1641 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1643 // allowed only in special format
1644 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1646 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1647 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1648 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1649 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1653 // spell_3*,spell_4*,spell_5* is empty
1654 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1656 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1658 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1659 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1660 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1662 else if(proto->Spells[j].SpellId != 0)
1664 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1665 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1669 // normal spell list
1670 else
1672 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1674 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1676 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1677 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1678 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1681 if(proto->Spells[j].SpellId)
1683 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1684 if(!spellInfo)
1686 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1687 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1689 // allowed only in special format
1690 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1692 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1693 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1699 if(proto->Bonding >= MAX_BIND_TYPE)
1700 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1702 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1703 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1705 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1706 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1708 if(proto->Sheath >= MAX_SHEATHETYPE)
1710 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1711 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1714 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1716 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1717 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1720 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1722 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1723 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1726 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1728 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1729 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1732 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1733 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1735 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1736 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1738 if(proto->BagFamily)
1740 // check bits
1741 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1743 uint32 mask = 1 << j;
1744 if((proto->BagFamily & mask)==0)
1745 continue;
1747 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1748 if(!bf)
1750 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
1751 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1752 continue;
1755 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
1757 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
1758 if(!ctEntry)
1760 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
1761 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1767 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1768 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1770 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; j++)
1772 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1774 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1775 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1779 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1780 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1782 if(proto->FoodType >= MAX_PET_DIET)
1784 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1785 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1788 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1790 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1791 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1796 void ObjectMgr::LoadPetLevelInfo()
1798 // Loading levels data
1800 // 0 1 2 3 4 5 6 7 8 9
1801 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1803 uint32 count = 0;
1805 if (!result)
1807 barGoLink bar( 1 );
1809 sLog.outString();
1810 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1811 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1812 return;
1815 barGoLink bar( result->GetRowCount() );
1819 Field* fields = result->Fetch();
1821 uint32 creature_id = fields[0].GetUInt32();
1822 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1824 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1825 continue;
1828 uint32 current_level = fields[1].GetUInt32();
1829 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1831 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1832 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1833 else
1835 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1836 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
1838 continue;
1840 else if(current_level < 1)
1842 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1843 continue;
1846 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1848 if(pInfoMapEntry==NULL)
1849 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1851 // data for level 1 stored in [0] array element, ...
1852 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1854 pLevelInfo->health = fields[2].GetUInt16();
1855 pLevelInfo->mana = fields[3].GetUInt16();
1856 pLevelInfo->armor = fields[9].GetUInt16();
1858 for (int i = 0; i < MAX_STATS; i++)
1860 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1863 bar.step();
1864 ++count;
1866 while (result->NextRow());
1868 delete result;
1870 sLog.outString();
1871 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1874 // Fill gaps and check integrity
1875 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1877 PetLevelInfo* pInfo = itr->second;
1879 // fatal error if no level 1 data
1880 if(!pInfo || pInfo[0].health == 0 )
1882 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1883 exit(1);
1886 // fill level gaps
1887 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1889 if(pInfo[level].health == 0)
1891 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1892 pInfo[level] = pInfo[level-1];
1898 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1900 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1901 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1903 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1904 if(itr == petInfo.end())
1905 return NULL;
1907 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1910 void ObjectMgr::LoadPlayerInfo()
1912 // Load playercreate
1914 // 0 1 2 3 4 5 6
1915 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1917 uint32 count = 0;
1919 if (!result)
1921 barGoLink bar( 1 );
1923 sLog.outString();
1924 sLog.outString( ">> Loaded %u player create definitions", count );
1925 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1926 exit(1);
1929 barGoLink bar( result->GetRowCount() );
1933 Field* fields = result->Fetch();
1935 uint32 current_race = fields[0].GetUInt32();
1936 uint32 current_class = fields[1].GetUInt32();
1937 uint32 mapId = fields[2].GetUInt32();
1938 uint32 zoneId = fields[3].GetUInt32();
1939 float positionX = fields[4].GetFloat();
1940 float positionY = fields[5].GetFloat();
1941 float positionZ = fields[6].GetFloat();
1943 if(current_race >= MAX_RACES)
1945 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1946 continue;
1949 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1950 if(!rEntry)
1952 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1953 continue;
1956 if(current_class >= MAX_CLASSES)
1958 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1959 continue;
1962 if(!sChrClassesStore.LookupEntry(current_class))
1964 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1965 continue;
1968 // accept DB data only for valid position (and non instanceable)
1969 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1971 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1972 continue;
1975 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1977 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1978 continue;
1981 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1983 pInfo->mapId = mapId;
1984 pInfo->zoneId = zoneId;
1985 pInfo->positionX = positionX;
1986 pInfo->positionY = positionY;
1987 pInfo->positionZ = positionZ;
1989 pInfo->displayId_m = rEntry->model_m;
1990 pInfo->displayId_f = rEntry->model_f;
1992 bar.step();
1993 ++count;
1995 while (result->NextRow());
1997 delete result;
1999 sLog.outString();
2000 sLog.outString( ">> Loaded %u player create definitions", count );
2003 // Load playercreate items
2005 // 0 1 2 3
2006 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2008 uint32 count = 0;
2010 if (!result)
2012 barGoLink bar( 1 );
2014 bar.step();
2016 sLog.outString();
2017 sLog.outString( ">> Loaded %u custom player create items", count );
2019 else
2021 barGoLink bar( result->GetRowCount() );
2025 Field* fields = result->Fetch();
2027 uint32 current_race = fields[0].GetUInt32();
2028 if(current_race >= MAX_RACES)
2030 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2031 continue;
2034 uint32 current_class = fields[1].GetUInt32();
2035 if(current_class >= MAX_CLASSES)
2037 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2038 continue;
2041 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2043 uint32 item_id = fields[2].GetUInt32();
2045 if(!GetItemPrototype(item_id))
2047 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);
2048 continue;
2051 uint32 amount = fields[3].GetUInt32();
2053 if(!amount)
2055 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2056 continue;
2059 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2061 bar.step();
2062 ++count;
2064 while(result->NextRow());
2066 delete result;
2068 sLog.outString();
2069 sLog.outString( ">> Loaded %u custom player create items", count );
2073 // Load playercreate spells
2075 // 0 1 2
2076 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2078 uint32 count = 0;
2080 if (!result)
2082 barGoLink bar( 1 );
2084 sLog.outString();
2085 sLog.outString( ">> Loaded %u player create spells", count );
2086 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2088 else
2090 barGoLink bar( result->GetRowCount() );
2094 Field* fields = result->Fetch();
2096 uint32 current_race = fields[0].GetUInt32();
2097 if(current_race >= MAX_RACES)
2099 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2100 continue;
2103 uint32 current_class = fields[1].GetUInt32();
2104 if(current_class >= MAX_CLASSES)
2106 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2107 continue;
2110 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2111 pInfo->spell.push_back(fields[2].GetUInt32());
2113 bar.step();
2114 ++count;
2116 while( result->NextRow() );
2118 delete result;
2120 sLog.outString();
2121 sLog.outString( ">> Loaded %u player create spells", count );
2125 // Load playercreate actions
2127 // 0 1 2 3 4 5
2128 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2130 uint32 count = 0;
2132 if (!result)
2134 barGoLink bar( 1 );
2136 sLog.outString();
2137 sLog.outString( ">> Loaded %u player create actions", count );
2138 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2140 else
2142 barGoLink bar( result->GetRowCount() );
2146 Field* fields = result->Fetch();
2148 uint32 current_race = fields[0].GetUInt32();
2149 if(current_race >= MAX_RACES)
2151 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2152 continue;
2155 uint32 current_class = fields[1].GetUInt32();
2156 if(current_class >= MAX_CLASSES)
2158 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2159 continue;
2162 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2163 pInfo->action[0].push_back(fields[2].GetUInt16());
2164 pInfo->action[1].push_back(fields[3].GetUInt16());
2165 pInfo->action[2].push_back(fields[4].GetUInt16());
2166 pInfo->action[3].push_back(fields[5].GetUInt16());
2168 bar.step();
2169 ++count;
2171 while( result->NextRow() );
2173 delete result;
2175 sLog.outString();
2176 sLog.outString( ">> Loaded %u player create actions", count );
2180 // Loading levels data (class only dependent)
2182 // 0 1 2 3
2183 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2185 uint32 count = 0;
2187 if (!result)
2189 barGoLink bar( 1 );
2191 sLog.outString();
2192 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2193 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2194 exit(1);
2197 barGoLink bar( result->GetRowCount() );
2201 Field* fields = result->Fetch();
2203 uint32 current_class = fields[0].GetUInt32();
2204 if(current_class >= MAX_CLASSES)
2206 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2207 continue;
2210 uint32 current_level = fields[1].GetUInt32();
2211 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2213 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2214 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2215 else
2217 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2218 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2220 continue;
2223 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2225 if(!pClassInfo->levelInfo)
2226 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2228 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2230 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2231 pClassLevelInfo->basemana = fields[3].GetUInt16();
2233 bar.step();
2234 ++count;
2236 while (result->NextRow());
2238 delete result;
2240 sLog.outString();
2241 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2244 // Fill gaps and check integrity
2245 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2247 // skip non existed classes
2248 if(!sChrClassesStore.LookupEntry(class_))
2249 continue;
2251 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2253 // fatal error if no level 1 data
2254 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2256 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2257 exit(1);
2260 // fill level gaps
2261 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2263 if(pClassInfo->levelInfo[level].basehealth == 0)
2265 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2266 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2271 // Loading levels data (class/race dependent)
2273 // 0 1 2 3 4 5 6 7
2274 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2276 uint32 count = 0;
2278 if (!result)
2280 barGoLink bar( 1 );
2282 sLog.outString();
2283 sLog.outString( ">> Loaded %u level stats definitions", count );
2284 sLog.outErrorDb( "Error loading `player_levelstats` 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 if(current_race >= MAX_RACES)
2297 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2298 continue;
2301 uint32 current_class = fields[1].GetUInt32();
2302 if(current_class >= MAX_CLASSES)
2304 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2305 continue;
2308 uint32 current_level = fields[2].GetUInt32();
2309 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2311 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2312 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2313 else
2315 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2316 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2318 continue;
2321 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2323 if(!pInfo->levelInfo)
2324 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2326 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2328 for (int i = 0; i < MAX_STATS; i++)
2330 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2333 bar.step();
2334 ++count;
2336 while (result->NextRow());
2338 delete result;
2340 sLog.outString();
2341 sLog.outString( ">> Loaded %u level stats definitions", count );
2344 // Fill gaps and check integrity
2345 for (int race = 0; race < MAX_RACES; ++race)
2347 // skip non existed races
2348 if(!sChrRacesStore.LookupEntry(race))
2349 continue;
2351 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2353 // skip non existed classes
2354 if(!sChrClassesStore.LookupEntry(class_))
2355 continue;
2357 PlayerInfo* pInfo = &playerInfo[race][class_];
2359 // skip non loaded combinations
2360 if(!pInfo->displayId_m || !pInfo->displayId_f)
2361 continue;
2363 // skip expansion races if not playing with expansion
2364 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2365 continue;
2367 // skip expansion classes if not playing with expansion
2368 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2369 continue;
2371 // fatal error if no level 1 data
2372 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2374 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2375 exit(1);
2378 // fill level gaps
2379 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2381 if(pInfo->levelInfo[level].stats[0] == 0)
2383 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2384 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2390 // Loading xp per level data
2392 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2393 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2394 mPlayerXPperLevel[level] = 0;
2396 // 0 1
2397 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2399 uint32 count = 0;
2401 if (!result)
2403 barGoLink bar( 1 );
2405 sLog.outString();
2406 sLog.outString( ">> Loaded %u xp for level definitions", count );
2407 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2408 exit(1);
2411 barGoLink bar( result->GetRowCount() );
2415 Field* fields = result->Fetch();
2417 uint32 current_level = fields[0].GetUInt32();
2418 uint32 current_xp = fields[1].GetUInt32();
2420 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2422 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2423 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2424 else
2426 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2427 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2429 continue;
2431 //PlayerXPperLevel
2432 mPlayerXPperLevel[current_level] = current_xp;
2433 bar.step();
2434 ++count;
2436 while (result->NextRow());
2438 delete result;
2440 sLog.outString();
2441 sLog.outString( ">> Loaded %u xp for level definitions", count );
2444 // fill level gaps
2445 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2447 if( mPlayerXPperLevel[level] == 0)
2449 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2450 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2455 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2457 if(level < 1 || class_ >= MAX_CLASSES)
2458 return;
2460 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2462 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2463 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2465 *info = pInfo->levelInfo[level-1];
2468 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2470 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2471 return;
2473 PlayerInfo const* pInfo = &playerInfo[race][class_];
2474 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2475 return;
2477 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2478 *info = pInfo->levelInfo[level-1];
2479 else
2480 BuildPlayerLevelInfo(race,class_,level,info);
2483 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2485 // base data (last known level)
2486 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2488 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2490 switch(_class)
2492 case CLASS_WARRIOR:
2493 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2494 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2495 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2496 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2497 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2498 break;
2499 case CLASS_PALADIN:
2500 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2501 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2502 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2503 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2504 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2505 break;
2506 case CLASS_HUNTER:
2507 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2508 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2509 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2510 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2511 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2512 break;
2513 case CLASS_ROGUE:
2514 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2515 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2516 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2517 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2518 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2519 break;
2520 case CLASS_PRIEST:
2521 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2522 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2523 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2524 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2525 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2526 break;
2527 case CLASS_SHAMAN:
2528 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2529 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2530 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2531 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2532 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2533 break;
2534 case CLASS_MAGE:
2535 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2536 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2537 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2538 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2539 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2540 break;
2541 case CLASS_WARLOCK:
2542 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2543 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2544 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2545 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2546 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2547 break;
2548 case CLASS_DRUID:
2549 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2550 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2551 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2552 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2553 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2558 void ObjectMgr::LoadGuilds()
2560 Guild *newguild;
2561 uint32 count = 0;
2563 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2565 if( !result )
2568 barGoLink bar( 1 );
2570 bar.step();
2572 sLog.outString();
2573 sLog.outString( ">> Loaded %u guild definitions", count );
2574 return;
2577 barGoLink bar( result->GetRowCount() );
2581 Field *fields = result->Fetch();
2583 bar.step();
2584 ++count;
2586 newguild = new Guild;
2587 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2589 newguild->Disband();
2590 delete newguild;
2591 continue;
2593 AddGuild(newguild);
2595 }while( result->NextRow() );
2597 delete result;
2599 sLog.outString();
2600 sLog.outString( ">> Loaded %u guild definitions", count );
2603 void ObjectMgr::LoadArenaTeams()
2605 uint32 count = 0;
2607 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2609 if( !result )
2612 barGoLink bar( 1 );
2614 bar.step();
2616 sLog.outString();
2617 sLog.outString( ">> Loaded %u arenateam definitions", count );
2618 return;
2621 barGoLink bar( result->GetRowCount() );
2625 Field *fields = result->Fetch();
2627 bar.step();
2628 ++count;
2630 ArenaTeam *newarenateam = new ArenaTeam;
2631 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2633 delete newarenateam;
2634 continue;
2636 AddArenaTeam(newarenateam);
2637 }while( result->NextRow() );
2639 delete result;
2641 sLog.outString();
2642 sLog.outString( ">> Loaded %u arenateam definitions", count );
2645 void ObjectMgr::LoadGroups()
2647 // -- loading groups --
2648 Group *group = NULL;
2649 uint64 leaderGuid = 0;
2650 uint32 count = 0;
2651 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2652 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2654 if( !result )
2656 barGoLink bar( 1 );
2658 bar.step();
2660 sLog.outString();
2661 sLog.outString( ">> Loaded %u group definitions", count );
2662 return;
2665 barGoLink bar( result->GetRowCount() );
2669 bar.step();
2670 Field *fields = result->Fetch();
2671 ++count;
2672 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2674 group = new Group;
2675 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2677 group->Disband();
2678 delete group;
2679 continue;
2681 AddGroup(group);
2682 }while( result->NextRow() );
2684 delete result;
2686 sLog.outString();
2687 sLog.outString( ">> Loaded %u group definitions", count );
2689 // -- loading members --
2690 count = 0;
2691 group = NULL;
2692 leaderGuid = 0;
2693 // 0 1 2 3
2694 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2695 if(!result)
2697 barGoLink bar2( 1 );
2698 bar2.step();
2700 else
2702 barGoLink bar2( result->GetRowCount() );
2705 bar2.step();
2706 Field *fields = result->Fetch();
2707 count++;
2708 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2709 if(!group || group->GetLeaderGUID() != leaderGuid)
2711 group = GetGroupByLeader(leaderGuid);
2712 if(!group)
2714 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2715 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2716 continue;
2720 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2722 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2723 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2725 }while( result->NextRow() );
2726 delete result;
2729 // clean groups
2730 // TODO: maybe delete from the DB before loading in this case
2731 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2733 if((*itr)->GetMembersCount() < 2)
2735 (*itr)->Disband();
2736 delete *itr;
2737 mGroupSet.erase(itr++);
2739 else
2740 ++itr;
2743 // -- loading instances --
2744 count = 0;
2745 group = NULL;
2746 leaderGuid = 0;
2747 result = CharacterDatabase.Query(
2748 // 0 1 2 3 4 5
2749 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2750 // 6
2751 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2752 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2755 if(!result)
2757 barGoLink bar2( 1 );
2758 bar2.step();
2760 else
2762 barGoLink bar2( result->GetRowCount() );
2765 bar2.step();
2766 Field *fields = result->Fetch();
2767 count++;
2768 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2769 if(!group || group->GetLeaderGUID() != leaderGuid)
2771 group = GetGroupByLeader(leaderGuid);
2772 if(!group)
2774 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2775 continue;
2779 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
2780 if(!mapEntry || !mapEntry->IsDungeon())
2782 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
2783 continue;
2786 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2787 group->BindToInstance(save, fields[3].GetBool(), true);
2788 }while( result->NextRow() );
2789 delete result;
2792 sLog.outString();
2793 sLog.outString( ">> Loaded %u group-instance binds total", count );
2795 sLog.outString();
2796 sLog.outString( ">> Loaded %u group members total", count );
2799 void ObjectMgr::LoadQuests()
2801 // For reload case
2802 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2803 delete itr->second;
2804 mQuestTemplates.clear();
2806 mExclusiveQuestGroups.clear();
2808 // 0 1 2 3 4 5 6 7 8
2809 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2810 // 9 10 11 12 13 14 15 16
2811 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2812 // 17 18 19 20 21 22 23 24 25 26 27 28
2813 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2814 // 29 30 31 32 33 34 35 36 37 38
2815 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2816 // 39 40 41 42 43 44 45 46
2817 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2818 // 47 48 49 50 51 52 53 54
2819 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
2820 // 55 56 57 58 59 60 61 62
2821 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2822 // 63 64 65 66
2823 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2824 // 67 68 69 70 71 72
2825 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2826 // 73 74 75 76 77 78
2827 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2828 // 79 80 81 82 83 84 85 86
2829 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2830 // 87 88 89 90 91 92 93 94 95 96
2831 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2832 // 97 98 99 100 101 102 103 104 105 106 107
2833 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2834 // 108 109 110 111 112 113 114 115 116 117
2835 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2836 // 118 119
2837 "StartScript, CompleteScript"
2838 " FROM quest_template");
2839 if(result == NULL)
2841 barGoLink bar( 1 );
2842 bar.step();
2844 sLog.outString();
2845 sLog.outString( ">> Loaded 0 quests definitions" );
2846 sLog.outErrorDb("`quest_template` table is empty!");
2847 return;
2850 // create multimap previous quest for each existed quest
2851 // some quests can have many previous maps set by NextQuestId in previous quest
2852 // for example set of race quests can lead to single not race specific quest
2853 barGoLink bar( result->GetRowCount() );
2856 bar.step();
2857 Field *fields = result->Fetch();
2859 Quest * newQuest = new Quest(fields);
2860 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2861 } while( result->NextRow() );
2863 delete result;
2865 // Post processing
2866 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2868 Quest * qinfo = iter->second;
2870 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2872 if( qinfo->GetQuestMethod() >= 3 )
2874 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2877 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2879 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2880 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2881 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2884 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2886 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2888 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2889 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2893 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2895 // at auto-reward can be rewarded only RewChoiceItemId[0]
2896 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2898 if(uint32 id = qinfo->RewChoiceItemId[j])
2900 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2901 qinfo->GetQuestId(),j+1,id,j+1);
2902 // no changes, quest ignore this data
2907 // client quest log visual (area case)
2908 if( qinfo->ZoneOrSort > 0 )
2910 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2912 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2913 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2914 // no changes, quest not dependent from this value but can have problems at client
2917 // client quest log visual (sort case)
2918 if( qinfo->ZoneOrSort < 0 )
2920 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2921 if( !qSort )
2923 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2924 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2925 // 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)
2927 //check SkillOrClass value (class case).
2928 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2930 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2931 if(qinfo->SkillOrClass < 0)
2933 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2934 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2937 //check for proper SkillOrClass value (skill case)
2938 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2940 // skill is positive value in SkillOrClass
2941 if(qinfo->SkillOrClass != skill_id )
2943 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2944 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2945 //override, and force proper value here?
2950 // SkillOrClass (class case)
2951 if( qinfo->SkillOrClass < 0 )
2953 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2955 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2956 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2959 // SkillOrClass (skill case)
2960 if( qinfo->SkillOrClass > 0 )
2962 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2964 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2965 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2969 if( qinfo->RequiredSkillValue )
2971 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2973 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2974 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2975 // no changes, quest can't be done for this requirement
2978 if( qinfo->SkillOrClass <= 0 )
2980 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2981 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2982 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2985 // else Skill quests can have 0 skill level, this is ok
2987 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2989 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2990 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2991 // no changes, quest can't be done for this requirement
2994 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2996 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2997 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2998 // no changes, quest can't be done for this requirement
3001 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3003 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3004 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3005 // no changes, quest can't be done for this requirement
3008 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3010 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3011 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3012 // no changes, quest can't be done for this requirement
3015 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3017 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3018 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3019 // no changes, quest can't be done for this requirement
3022 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3024 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3025 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3026 // warning
3029 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3031 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3032 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3033 // warning
3036 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3038 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3039 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3040 // warning
3043 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3045 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3046 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3047 qinfo->CharTitleId = 0;
3048 // quest can't reward this title
3051 if(qinfo->SrcItemId)
3053 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3055 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3056 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3057 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3059 else if(qinfo->SrcItemCount==0)
3061 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3062 qinfo->GetQuestId(),qinfo->SrcItemId);
3063 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3066 else if(qinfo->SrcItemCount>0)
3068 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3069 qinfo->GetQuestId(),qinfo->SrcItemCount);
3070 qinfo->SrcItemCount=0; // no quest work changes in fact
3073 if(qinfo->SrcSpell)
3075 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3076 if(!spellInfo)
3078 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3079 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3080 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3082 else if(!SpellMgr::IsSpellValid(spellInfo))
3084 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3085 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3086 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3090 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3092 uint32 id = qinfo->ReqItemId[j];
3093 if(id)
3095 if(qinfo->ReqItemCount[j]==0)
3097 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3098 qinfo->GetQuestId(),j+1,id,j+1);
3099 // no changes, quest can't be done for this requirement
3102 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3104 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3106 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3107 qinfo->GetQuestId(),j+1,id,id);
3108 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3111 else if(qinfo->ReqItemCount[j]>0)
3113 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3114 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3115 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3119 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3121 uint32 id = qinfo->ReqSourceId[j];
3122 if(id)
3124 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3126 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3127 qinfo->GetQuestId(),j+1,id,id);
3128 // no changes, quest can't be done for this requirement
3131 else
3133 if(qinfo->ReqSourceCount[j]>0)
3135 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3136 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3137 // no changes, quest ignore this data
3142 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3144 uint32 id = qinfo->ReqSpell[j];
3145 if(id)
3147 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3148 if(!spellInfo)
3150 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3151 qinfo->GetQuestId(),j+1,id,id);
3152 continue;
3155 if(!qinfo->ReqCreatureOrGOId[j])
3157 bool found = false;
3158 for(int k = 0; k < 3; ++k)
3160 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3161 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3163 found = true;
3164 break;
3168 if(found)
3170 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3172 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);
3174 // this will prevent quest completing without objective
3175 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3178 else
3180 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.",
3181 qinfo->GetQuestId(),j+1,id,j+1,id);
3182 // no changes, quest can't be done for this requirement
3188 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3190 int32 id = qinfo->ReqCreatureOrGOId[j];
3191 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3193 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3194 qinfo->GetQuestId(),j+1,id,uint32(-id));
3195 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3198 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3200 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3201 qinfo->GetQuestId(),j+1,id,uint32(id));
3202 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3205 if(id)
3207 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3209 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3211 if(!qinfo->ReqCreatureOrGOCount[j])
3213 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3214 qinfo->GetQuestId(),j+1,id,j+1);
3215 // no changes, quest can be incorrectly done, but we already report this
3218 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3220 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3221 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3222 // no changes, quest ignore this data
3226 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3228 uint32 id = qinfo->RewChoiceItemId[j];
3229 if(id)
3231 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3233 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3234 qinfo->GetQuestId(),j+1,id,id);
3235 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3238 if(!qinfo->RewChoiceItemCount[j])
3240 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3241 qinfo->GetQuestId(),j+1,id,j+1);
3242 // no changes, quest can't be done
3245 else if(qinfo->RewChoiceItemCount[j]>0)
3247 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3248 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3249 // no changes, quest ignore this data
3253 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3255 uint32 id = qinfo->RewItemId[j];
3256 if(id)
3258 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3260 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3261 qinfo->GetQuestId(),j+1,id,id);
3262 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3265 if(!qinfo->RewItemCount[j])
3267 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3268 qinfo->GetQuestId(),j+1,id,j+1);
3269 // no changes
3272 else if(qinfo->RewItemCount[j]>0)
3274 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3275 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3276 // no changes, quest ignore this data
3280 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3282 if(qinfo->RewRepFaction[j])
3284 if(!qinfo->RewRepValue[j])
3286 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3287 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3288 // no changes
3291 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3293 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.",
3294 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3295 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3298 else if(qinfo->RewRepValue[j]!=0)
3300 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3301 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3302 // no changes, quest ignore this data
3306 if(qinfo->RewSpell)
3308 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3310 if(!spellInfo)
3312 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3313 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3314 qinfo->RewSpell = 0; // no spell reward will display for this quest
3317 else if(!SpellMgr::IsSpellValid(spellInfo))
3319 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3320 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3321 qinfo->RewSpell = 0; // no spell reward will display for this quest
3326 if(qinfo->RewSpellCast)
3328 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3330 if(!spellInfo)
3332 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3333 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3334 qinfo->RewSpellCast = 0; // no spell will be casted on player
3337 else if(!SpellMgr::IsSpellValid(spellInfo))
3339 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3340 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3341 qinfo->RewSpellCast = 0; // no spell will be casted on player
3346 if(qinfo->RewMailTemplateId)
3348 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3350 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3351 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3352 qinfo->RewMailTemplateId = 0; // no mail will send to player
3353 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3357 if(qinfo->NextQuestInChain)
3359 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3360 if(qNextItr == mQuestTemplates.end())
3362 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3363 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3364 qinfo->NextQuestInChain = 0;
3366 else
3367 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3370 // fill additional data stores
3371 if(qinfo->PrevQuestId)
3373 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3375 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3377 else
3379 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3383 if(qinfo->NextQuestId)
3385 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3386 if (qNextItr == mQuestTemplates.end())
3388 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3390 else
3392 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3393 qNextItr->second->prevQuests.push_back(signedQuestId);
3397 if(qinfo->ExclusiveGroup)
3398 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3399 if(qinfo->LimitTime)
3400 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3403 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3404 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3406 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3407 if(!spellInfo)
3408 continue;
3410 for(int j = 0; j < 3; ++j)
3412 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3413 continue;
3415 uint32 quest_id = spellInfo->EffectMiscValue[j];
3417 Quest const* quest = GetQuestTemplate(quest_id);
3419 // some quest referenced in spells not exist (outdated spells)
3420 if(!quest)
3421 continue;
3423 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3425 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);
3427 // this will prevent quest completing without objective
3428 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3433 sLog.outString();
3434 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3437 void ObjectMgr::LoadQuestLocales()
3439 mQuestLocaleMap.clear(); // need for reload case
3441 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3442 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3443 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3444 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3445 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3446 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3447 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3448 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3449 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3450 " FROM locales_quest"
3453 if(!result)
3455 barGoLink bar(1);
3457 bar.step();
3459 sLog.outString();
3460 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3461 return;
3464 barGoLink bar(result->GetRowCount());
3468 Field *fields = result->Fetch();
3469 bar.step();
3471 uint32 entry = fields[0].GetUInt32();
3473 QuestLocale& data = mQuestLocaleMap[entry];
3475 for(int i = 1; i < MAX_LOCALE; ++i)
3477 std::string str = fields[1+10*(i-1)].GetCppString();
3478 if(!str.empty())
3480 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3481 if(idx >= 0)
3483 if(data.Title.size() <= idx)
3484 data.Title.resize(idx+1);
3486 data.Title[idx] = str;
3489 str = fields[1+10*(i-1)+1].GetCppString();
3490 if(!str.empty())
3492 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3493 if(idx >= 0)
3495 if(data.Details.size() <= idx)
3496 data.Details.resize(idx+1);
3498 data.Details[idx] = str;
3501 str = fields[1+10*(i-1)+2].GetCppString();
3502 if(!str.empty())
3504 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3505 if(idx >= 0)
3507 if(data.Objectives.size() <= idx)
3508 data.Objectives.resize(idx+1);
3510 data.Objectives[idx] = str;
3513 str = fields[1+10*(i-1)+3].GetCppString();
3514 if(!str.empty())
3516 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3517 if(idx >= 0)
3519 if(data.OfferRewardText.size() <= idx)
3520 data.OfferRewardText.resize(idx+1);
3522 data.OfferRewardText[idx] = str;
3525 str = fields[1+10*(i-1)+4].GetCppString();
3526 if(!str.empty())
3528 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3529 if(idx >= 0)
3531 if(data.RequestItemsText.size() <= idx)
3532 data.RequestItemsText.resize(idx+1);
3534 data.RequestItemsText[idx] = str;
3537 str = fields[1+10*(i-1)+5].GetCppString();
3538 if(!str.empty())
3540 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3541 if(idx >= 0)
3543 if(data.EndText.size() <= idx)
3544 data.EndText.resize(idx+1);
3546 data.EndText[idx] = str;
3549 for(int k = 0; k < 4; ++k)
3551 str = fields[1+10*(i-1)+6+k].GetCppString();
3552 if(!str.empty())
3554 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3555 if(idx >= 0)
3557 if(data.ObjectiveText[k].size() <= idx)
3558 data.ObjectiveText[k].resize(idx+1);
3560 data.ObjectiveText[k][idx] = str;
3565 } while (result->NextRow());
3567 delete result;
3569 sLog.outString();
3570 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3573 void ObjectMgr::LoadPetCreateSpells()
3575 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3576 if(!result)
3578 barGoLink bar( 1 );
3579 bar.step();
3581 sLog.outString();
3582 sLog.outString( ">> Loaded 0 pet create spells" );
3583 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3584 return;
3587 uint32 count = 0;
3589 barGoLink bar( result->GetRowCount() );
3591 mPetCreateSpell.clear();
3595 Field *fields = result->Fetch();
3596 bar.step();
3598 uint32 creature_id = fields[0].GetUInt32();
3600 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3601 continue;
3603 PetCreateSpellEntry PetCreateSpell;
3604 for(int i = 0; i < 4; i++)
3606 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3608 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3609 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3612 mPetCreateSpell[creature_id] = PetCreateSpell;
3614 ++count;
3616 while (result->NextRow());
3618 delete result;
3620 sLog.outString();
3621 sLog.outString( ">> Loaded %u pet create spells", count );
3624 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3626 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3627 return;
3629 sLog.outString( "%s :", tablename);
3631 scripts.clear(); // need for reload support
3633 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3635 uint32 count = 0;
3637 if( !result )
3639 barGoLink bar( 1 );
3640 bar.step();
3642 sLog.outString();
3643 sLog.outString( ">> Loaded %u script definitions", count );
3644 return;
3647 barGoLink bar( result->GetRowCount() );
3651 bar.step();
3653 Field *fields = result->Fetch();
3654 ScriptInfo tmp;
3655 tmp.id = fields[0].GetUInt32();
3656 tmp.delay = fields[1].GetUInt32();
3657 tmp.command = fields[2].GetUInt32();
3658 tmp.datalong = fields[3].GetUInt32();
3659 tmp.datalong2 = fields[4].GetUInt32();
3660 tmp.dataint = fields[5].GetInt32();
3661 tmp.x = fields[6].GetFloat();
3662 tmp.y = fields[7].GetFloat();
3663 tmp.z = fields[8].GetFloat();
3664 tmp.o = fields[9].GetFloat();
3666 // generic command args check
3667 switch(tmp.command)
3669 case SCRIPT_COMMAND_TALK:
3671 if(tmp.datalong > 3)
3673 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3674 continue;
3676 if(tmp.dataint==0)
3678 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3679 continue;
3681 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3683 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);
3684 continue;
3687 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3688 break;
3691 case SCRIPT_COMMAND_EMOTE:
3693 if(!sEmotesStore.LookupEntry(tmp.datalong))
3695 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
3696 continue;
3698 break;
3701 case SCRIPT_COMMAND_TELEPORT_TO:
3703 if(!sMapStore.LookupEntry(tmp.datalong))
3705 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3706 continue;
3709 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3711 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);
3712 continue;
3714 break;
3717 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3719 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3721 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);
3722 continue;
3725 if(!GetCreatureTemplate(tmp.datalong))
3727 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3728 continue;
3730 break;
3733 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3735 GameObjectData const* data = GetGOData(tmp.datalong);
3736 if(!data)
3738 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3739 continue;
3742 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3743 if(!info)
3745 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);
3746 continue;
3749 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3750 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3751 info->type==GAMEOBJECT_TYPE_DOOR ||
3752 info->type==GAMEOBJECT_TYPE_BUTTON ||
3753 info->type==GAMEOBJECT_TYPE_TRAP )
3755 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3756 continue;
3758 break;
3760 case SCRIPT_COMMAND_OPEN_DOOR:
3761 case SCRIPT_COMMAND_CLOSE_DOOR:
3763 GameObjectData const* data = GetGOData(tmp.datalong);
3764 if(!data)
3766 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);
3767 continue;
3770 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3771 if(!info)
3773 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);
3774 continue;
3777 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3779 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);
3780 continue;
3783 break;
3785 case SCRIPT_COMMAND_QUEST_EXPLORED:
3787 Quest const* quest = GetQuestTemplate(tmp.datalong);
3788 if(!quest)
3790 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);
3791 continue;
3794 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3796 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);
3798 // this will prevent quest completing without objective
3799 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3801 // continue; - quest objective requirement set and command can be allowed
3804 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3806 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",
3807 tablename,tmp.datalong2,tmp.id);
3808 continue;
3811 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3813 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",
3814 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3815 continue;
3818 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3820 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",
3821 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3822 continue;
3825 break;
3828 case SCRIPT_COMMAND_REMOVE_AURA:
3830 if(!sSpellStore.LookupEntry(tmp.datalong))
3832 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3833 tablename,tmp.datalong,tmp.id);
3834 continue;
3836 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3838 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3839 tablename,tmp.datalong2,tmp.id);
3840 continue;
3842 break;
3844 case SCRIPT_COMMAND_CAST_SPELL:
3846 if(!sSpellStore.LookupEntry(tmp.datalong))
3848 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3849 tablename,tmp.datalong,tmp.id);
3850 continue;
3852 if(tmp.datalong2 & ~0x3) // 2 bits
3854 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3855 tablename,tmp.datalong2,tmp.id);
3856 continue;
3858 break;
3862 if (scripts.find(tmp.id) == scripts.end())
3864 ScriptMap emptyMap;
3865 scripts[tmp.id] = emptyMap;
3867 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3869 ++count;
3870 } while( result->NextRow() );
3872 delete result;
3874 sLog.outString();
3875 sLog.outString( ">> Loaded %u script definitions", count );
3878 void ObjectMgr::LoadGameObjectScripts()
3880 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3882 // check ids
3883 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3885 if(!GetGOData(itr->first))
3886 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3890 void ObjectMgr::LoadQuestEndScripts()
3892 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3894 // check ids
3895 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3897 if(!GetQuestTemplate(itr->first))
3898 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3902 void ObjectMgr::LoadQuestStartScripts()
3904 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3906 // check ids
3907 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3909 if(!GetQuestTemplate(itr->first))
3910 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3914 void ObjectMgr::LoadSpellScripts()
3916 LoadScripts(sSpellScripts, "spell_scripts");
3918 // check ids
3919 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3921 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3923 if(!spellInfo)
3925 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3926 continue;
3929 //check for correct spellEffect
3930 bool found = false;
3931 for(int i=0; i<3; ++i)
3933 // skip empty effects
3934 if( !spellInfo->Effect[i] )
3935 continue;
3937 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3939 found = true;
3940 break;
3944 if(!found)
3945 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3949 void ObjectMgr::LoadEventScripts()
3951 LoadScripts(sEventScripts, "event_scripts");
3953 std::set<uint32> evt_scripts;
3954 // Load all possible script entries from gameobjects
3955 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3957 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3958 if (goInfo)
3960 switch(goInfo->type)
3962 case GAMEOBJECT_TYPE_GOOBER:
3963 if(goInfo->goober.eventId)
3964 evt_scripts.insert(goInfo->goober.eventId);
3965 break;
3966 case GAMEOBJECT_TYPE_CHEST:
3967 if(goInfo->chest.eventId)
3968 evt_scripts.insert(goInfo->chest.eventId);
3969 break;
3970 default:
3971 break;
3975 // Load all possible script entries from spells
3976 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3978 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3979 if (spell)
3981 for(int j=0; j<3; ++j)
3983 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3985 if (spell->EffectMiscValue[j])
3986 evt_scripts.insert(spell->EffectMiscValue[j]);
3991 // Then check if all scripts are in above list of possible script entries
3992 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3994 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3995 if (itr2 == evt_scripts.end())
3996 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
4000 void ObjectMgr::LoadItemTexts()
4002 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4004 uint32 count = 0;
4006 if( !result )
4008 barGoLink bar( 1 );
4009 bar.step();
4011 sLog.outString();
4012 sLog.outString( ">> Loaded %u item pages", count );
4013 return;
4016 barGoLink bar( result->GetRowCount() );
4018 Field* fields;
4021 bar.step();
4023 fields = result->Fetch();
4025 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4027 ++count;
4029 } while ( result->NextRow() );
4031 delete result;
4033 sLog.outString();
4034 sLog.outString( ">> Loaded %u item texts", count );
4037 void ObjectMgr::LoadPageTexts()
4039 sPageTextStore.Free(); // for reload case
4041 sPageTextStore.Load();
4042 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4043 sLog.outString();
4045 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4047 // check data correctness
4048 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4049 if(!page)
4050 continue;
4052 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4054 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4055 continue;
4058 // detect circular reference
4059 std::set<uint32> checkedPages;
4060 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4062 if(!pageItr->Next_Page)
4063 break;
4064 checkedPages.insert(pageItr->Page_ID);
4065 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4067 std::ostringstream ss;
4068 ss<< "The text page(s) ";
4069 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4070 ss << *itr << " ";
4071 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4072 << pageItr->Page_ID <<" to 0";
4073 sLog.outErrorDb(ss.str().c_str());
4074 const_cast<PageText*>(pageItr)->Next_Page = 0;
4075 break;
4081 void ObjectMgr::LoadPageTextLocales()
4083 mPageTextLocaleMap.clear(); // need for reload case
4085 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");
4087 if(!result)
4089 barGoLink bar(1);
4091 bar.step();
4093 sLog.outString();
4094 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4095 return;
4098 barGoLink bar(result->GetRowCount());
4102 Field *fields = result->Fetch();
4103 bar.step();
4105 uint32 entry = fields[0].GetUInt32();
4107 PageTextLocale& data = mPageTextLocaleMap[entry];
4109 for(int i = 1; i < MAX_LOCALE; ++i)
4111 std::string str = fields[i].GetCppString();
4112 if(str.empty())
4113 continue;
4115 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4116 if(idx >= 0)
4118 if(data.Text.size() <= idx)
4119 data.Text.resize(idx+1);
4121 data.Text[idx] = str;
4125 } while (result->NextRow());
4127 delete result;
4129 sLog.outString();
4130 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4133 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4135 template<class D>
4136 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4138 dst = D(objmgr.GetScriptId(src));
4142 void ObjectMgr::LoadInstanceTemplate()
4144 SQLInstanceLoader loader;
4145 loader.Load(sInstanceTemplate);
4147 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4149 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4150 if(!temp) continue;
4151 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4152 if(!entry)
4154 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4155 continue;
4157 else if(!entry->HasResetTime())
4158 continue;
4160 //FIXME: now exist heroic instance, normal/heroic raid instances
4161 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4162 // entry->resetTimeRaid store reset time for normal raid only
4163 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4164 // but at some point wee need implement reset time dependent from raid instance mode
4165 if(temp->reset_delay == 0)
4167 // use defaults from the DBC
4168 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4170 temp->reset_delay = entry->resetTimeHeroic / DAY;
4172 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4173 // for normal raid only
4175 temp->reset_delay = entry->resetTimeRaid / DAY;
4179 // the reset_delay must be at least one day
4180 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4183 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4184 sLog.outString();
4187 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4189 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4190 if(itr != mGossipText.end())
4191 return &itr->second;
4192 return NULL;
4195 void ObjectMgr::LoadGossipText()
4197 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4199 int count = 0;
4200 if( !result )
4202 barGoLink bar( 1 );
4203 bar.step();
4205 sLog.outString();
4206 sLog.outString( ">> Loaded %u npc texts", count );
4207 return;
4210 int cic;
4212 barGoLink bar( result->GetRowCount() );
4216 ++count;
4217 cic = 0;
4219 Field *fields = result->Fetch();
4221 bar.step();
4223 uint32 Text_ID = fields[cic++].GetUInt32();
4224 if(!Text_ID)
4226 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4227 continue;
4230 GossipText& gText = mGossipText[Text_ID];
4232 for (int i=0; i< 8; i++)
4234 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4235 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4237 gText.Options[i].Language = fields[cic++].GetUInt32();
4238 gText.Options[i].Probability = fields[cic++].GetFloat();
4240 for(int j=0; j < 3; ++j)
4242 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4243 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4246 } while( result->NextRow() );
4248 sLog.outString();
4249 sLog.outString( ">> Loaded %u npc texts", count );
4250 delete result;
4253 void ObjectMgr::LoadNpcTextLocales()
4255 mNpcTextLocaleMap.clear(); // need for reload case
4257 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4258 "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,"
4259 "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,"
4260 "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,"
4261 "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,"
4262 "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,"
4263 "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,"
4264 "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, "
4265 "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 "
4266 " FROM locales_npc_text");
4268 if(!result)
4270 barGoLink bar(1);
4272 bar.step();
4274 sLog.outString();
4275 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4276 return;
4279 barGoLink bar(result->GetRowCount());
4283 Field *fields = result->Fetch();
4284 bar.step();
4286 uint32 entry = fields[0].GetUInt32();
4288 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4290 for(int i=1; i<MAX_LOCALE; ++i)
4292 for(int j=0; j<8; ++j)
4294 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4295 if(!str0.empty())
4297 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4298 if(idx >= 0)
4300 if(data.Text_0[j].size() <= idx)
4301 data.Text_0[j].resize(idx+1);
4303 data.Text_0[j][idx] = str0;
4306 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4307 if(!str1.empty())
4309 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4310 if(idx >= 0)
4312 if(data.Text_1[j].size() <= idx)
4313 data.Text_1[j].resize(idx+1);
4315 data.Text_1[j][idx] = str1;
4320 } while (result->NextRow());
4322 delete result;
4324 sLog.outString();
4325 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4328 //not very fast function but it is called only once a day, or on starting-up
4329 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4331 time_t basetime = time(NULL);
4332 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4333 //delete all old mails without item and without body immediately, if starting server
4334 if (!serverUp)
4335 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4336 // 0 1 2 3 4 5 6 7 8 9
4337 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" I64FMTD "'", (uint64)basetime);
4338 if ( !result )
4340 barGoLink bar(1);
4341 bar.step();
4342 sLog.outString();
4343 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4344 return; // any mails need to be returned or deleted
4347 //std::ostringstream delitems, delmails; //will be here for optimization
4348 //bool deletemail = false, deleteitem = false;
4349 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4350 //delmails << "DELETE FROM mail WHERE id IN ( "
4352 barGoLink bar( result->GetRowCount() );
4353 uint32 count = 0;
4354 Field *fields;
4358 bar.step();
4360 fields = result->Fetch();
4361 Mail *m = new Mail;
4362 m->messageID = fields[0].GetUInt32();
4363 m->messageType = fields[1].GetUInt8();
4364 m->sender = fields[2].GetUInt32();
4365 m->receiver = fields[3].GetUInt32();
4366 m->itemTextId = fields[4].GetUInt32();
4367 bool has_items = fields[5].GetBool();
4368 m->expire_time = (time_t)fields[6].GetUInt64();
4369 m->deliver_time = 0;
4370 m->COD = fields[7].GetUInt32();
4371 m->checked = fields[8].GetUInt32();
4372 m->mailTemplateId = fields[9].GetInt16();
4374 Player *pl = 0;
4375 if (serverUp)
4376 pl = GetPlayer((uint64)m->receiver);
4377 if (pl && pl->m_mailsLoaded)
4378 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4379 //his in mailbox and he has already listed his mails )
4380 delete m;
4381 continue;
4383 //delete or return mail:
4384 if (has_items)
4386 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4387 if(resultItems)
4391 Field *fields2 = resultItems->Fetch();
4393 uint32 item_guid_low = fields2[0].GetUInt32();
4394 uint32 item_template = fields2[1].GetUInt32();
4396 m->AddItem(item_guid_low, item_template);
4398 while (resultItems->NextRow());
4400 delete resultItems;
4402 //if it is mail from AH, it shouldn't be returned, but deleted
4403 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4405 // mail open and then not returned
4406 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4407 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4409 else
4411 //mail will be returned:
4412 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4413 delete m;
4414 continue;
4418 if (m->itemTextId)
4419 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4421 //deletemail = true;
4422 //delmails << m->messageID << ", ";
4423 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4424 delete m;
4425 ++count;
4426 } while (result->NextRow());
4427 delete result;
4429 sLog.outString();
4430 sLog.outString( ">> Loaded %u mails", count );
4433 void ObjectMgr::LoadQuestAreaTriggers()
4435 mQuestAreaTriggerMap.clear(); // need for reload case
4437 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4439 uint32 count = 0;
4441 if( !result )
4443 barGoLink bar( 1 );
4444 bar.step();
4446 sLog.outString();
4447 sLog.outString( ">> Loaded %u quest trigger points", count );
4448 return;
4451 barGoLink bar( result->GetRowCount() );
4455 ++count;
4456 bar.step();
4458 Field *fields = result->Fetch();
4460 uint32 trigger_ID = fields[0].GetUInt32();
4461 uint32 quest_ID = fields[1].GetUInt32();
4463 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4464 if(!atEntry)
4466 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4467 continue;
4470 Quest const* quest = GetQuestTemplate(quest_ID);
4472 if(!quest)
4474 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4475 continue;
4478 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4480 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);
4482 // this will prevent quest completing without objective
4483 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4485 // continue; - quest modified to required objective and trigger can be allowed.
4488 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4490 } while( result->NextRow() );
4492 delete result;
4494 sLog.outString();
4495 sLog.outString( ">> Loaded %u quest trigger points", count );
4498 void ObjectMgr::LoadTavernAreaTriggers()
4500 mTavernAreaTriggerSet.clear(); // need for reload case
4502 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4504 uint32 count = 0;
4506 if( !result )
4508 barGoLink bar( 1 );
4509 bar.step();
4511 sLog.outString();
4512 sLog.outString( ">> Loaded %u tavern triggers", count );
4513 return;
4516 barGoLink bar( result->GetRowCount() );
4520 ++count;
4521 bar.step();
4523 Field *fields = result->Fetch();
4525 uint32 Trigger_ID = fields[0].GetUInt32();
4527 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4528 if(!atEntry)
4530 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4531 continue;
4534 mTavernAreaTriggerSet.insert(Trigger_ID);
4535 } while( result->NextRow() );
4537 delete result;
4539 sLog.outString();
4540 sLog.outString( ">> Loaded %u tavern triggers", count );
4543 void ObjectMgr::LoadAreaTriggerScripts()
4545 mAreaTriggerScripts.clear(); // need for reload case
4546 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4548 uint32 count = 0;
4550 if( !result )
4552 barGoLink bar( 1 );
4553 bar.step();
4555 sLog.outString();
4556 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4557 return;
4560 barGoLink bar( result->GetRowCount() );
4564 ++count;
4565 bar.step();
4567 Field *fields = result->Fetch();
4569 uint32 Trigger_ID = fields[0].GetUInt32();
4570 const char *scriptName = fields[1].GetString();
4572 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4573 if(!atEntry)
4575 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4576 continue;
4578 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4579 } while( result->NextRow() );
4581 delete result;
4583 sLog.outString();
4584 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4587 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4589 bool found = false;
4590 float dist;
4591 uint32 id = 0;
4593 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4595 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4596 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4597 continue;
4599 uint8 field = (uint8)((i - 1) / 32);
4600 uint32 submask = 1<<((i-1)%32);
4602 // skip not taxi network nodes
4603 if((sTaxiNodesMask[field] & submask)==0)
4604 continue;
4606 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4607 if(found)
4609 if(dist2 < dist)
4611 dist = dist2;
4612 id = i;
4615 else
4617 found = true;
4618 dist = dist2;
4619 id = i;
4623 return id;
4626 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4628 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4629 if(src_i==sTaxiPathSetBySource.end())
4631 path = 0;
4632 cost = 0;
4633 return;
4636 TaxiPathSetForSource& pathSet = src_i->second;
4638 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4639 if(dest_i==pathSet.end())
4641 path = 0;
4642 cost = 0;
4643 return;
4646 cost = dest_i->second.price;
4647 path = dest_i->second.ID;
4650 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4652 uint16 mount_entry = 0;
4653 uint16 mount_id = 0;
4655 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4656 if(node)
4658 if (team == ALLIANCE)
4660 mount_entry = node->MountCreatureID[1];
4661 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4662 if(ci)
4663 mount_id = ci->DisplayID_A;
4665 if (team == HORDE)
4667 mount_entry = node->MountCreatureID[0];
4668 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4669 if(ci)
4670 mount_id = ci->DisplayID_H;
4674 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4675 if(!minfo)
4677 sLog.outErrorDb("Taxi mount (Entry: %u) for taxi node (Id: %u) for team %u has model %u not found in table `creature_model_info`, can't load. ",
4678 mount_entry,id,team,mount_id);
4680 return false;
4682 if(minfo->modelid_other_gender!=0)
4683 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4685 return mount_id;
4688 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4690 if(path >= sTaxiPathNodesByPath.size())
4691 return;
4693 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4695 pathnodes.Resize(nodeList.size());
4696 mapIds.resize(nodeList.size());
4698 for(size_t i = 0; i < nodeList.size(); ++i)
4700 pathnodes[ i ].x = nodeList[i].x;
4701 pathnodes[ i ].y = nodeList[i].y;
4702 pathnodes[ i ].z = nodeList[i].z;
4704 mapIds[i] = nodeList[i].mapid;
4708 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4710 if(path >= sTaxiPathNodesByPath.size())
4711 return;
4713 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4715 pathnodes.Resize(nodeList.size());
4717 for(size_t i = 0; i < nodeList.size(); ++i)
4719 pathnodes[ i ].mapid = nodeList[i].mapid;
4720 pathnodes[ i ].x = nodeList[i].x;
4721 pathnodes[ i ].y = nodeList[i].y;
4722 pathnodes[ i ].z = nodeList[i].z;
4723 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4724 pathnodes[ i ].delay = nodeList[i].delay;
4728 void ObjectMgr::LoadGraveyardZones()
4730 mGraveYardMap.clear(); // need for reload case
4732 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4734 uint32 count = 0;
4736 if( !result )
4738 barGoLink bar( 1 );
4739 bar.step();
4741 sLog.outString();
4742 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4743 return;
4746 barGoLink bar( result->GetRowCount() );
4750 ++count;
4751 bar.step();
4753 Field *fields = result->Fetch();
4755 uint32 safeLocId = fields[0].GetUInt32();
4756 uint32 zoneId = fields[1].GetUInt32();
4757 uint32 team = fields[2].GetUInt32();
4759 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4760 if(!entry)
4762 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4763 continue;
4766 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4767 if(!areaEntry)
4769 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4770 continue;
4773 if(areaEntry->zone != 0)
4775 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4776 continue;
4779 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4781 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4782 continue;
4785 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4786 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4787 } while( result->NextRow() );
4789 delete result;
4791 sLog.outString();
4792 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4795 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4797 // search for zone associated closest graveyard
4798 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4800 // Simulate std. algorithm:
4801 // found some graveyard associated to (ghost_zone,ghost_map)
4803 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4804 // then check faction
4805 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4806 // then check faction
4807 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4808 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4809 if(graveLow==graveUp)
4811 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4812 return NULL;
4815 // at corpse map
4816 bool foundNear = false;
4817 float distNear;
4818 WorldSafeLocsEntry const* entryNear = NULL;
4820 // at entrance map for corpse map
4821 bool foundEntr = false;
4822 float distEntr;
4823 WorldSafeLocsEntry const* entryEntr = NULL;
4825 // some where other
4826 WorldSafeLocsEntry const* entryFar = NULL;
4828 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4830 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4832 GraveYardData const& data = itr->second;
4834 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4835 if(!entry)
4837 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4838 continue;
4841 // skip enemy faction graveyard
4842 // team == 0 case can be at call from .neargrave
4843 if(data.team != 0 && team != 0 && data.team != team)
4844 continue;
4846 // find now nearest graveyard at other map
4847 if(MapId != entry->map_id)
4849 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4850 if (!mapEntry ||
4851 mapEntry->entrance_map < 0 ||
4852 mapEntry->entrance_map != entry->map_id ||
4853 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
4855 // not have any corrdinates for check distance anyway
4856 entryFar = entry;
4857 continue;
4860 // at entrance map calculate distance (2D);
4861 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4862 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4863 if(foundEntr)
4865 if(dist2 < distEntr)
4867 distEntr = dist2;
4868 entryEntr = entry;
4871 else
4873 foundEntr = true;
4874 distEntr = dist2;
4875 entryEntr = entry;
4878 // find now nearest graveyard at same map
4879 else
4881 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4882 if(foundNear)
4884 if(dist2 < distNear)
4886 distNear = dist2;
4887 entryNear = entry;
4890 else
4892 foundNear = true;
4893 distNear = dist2;
4894 entryNear = entry;
4899 if(entryNear)
4900 return entryNear;
4902 if(entryEntr)
4903 return entryEntr;
4905 return entryFar;
4908 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4910 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4911 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4913 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4915 if(itr->second.safeLocId==id)
4916 return &itr->second;
4919 return NULL;
4922 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4924 if(FindGraveYardData(id,zoneId))
4925 return false;
4927 // add link to loaded data
4928 GraveYardData data;
4929 data.safeLocId = id;
4930 data.team = team;
4932 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4934 // add link to DB
4935 if(inDB)
4937 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4938 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4941 return true;
4944 void ObjectMgr::LoadAreaTriggerTeleports()
4946 mAreaTriggers.clear(); // need for reload case
4948 uint32 count = 0;
4950 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4951 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");
4952 if( !result )
4955 barGoLink bar( 1 );
4957 bar.step();
4959 sLog.outString();
4960 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4961 return;
4964 barGoLink bar( result->GetRowCount() );
4968 Field *fields = result->Fetch();
4970 bar.step();
4972 ++count;
4974 uint32 Trigger_ID = fields[0].GetUInt32();
4976 AreaTrigger at;
4978 at.requiredLevel = fields[1].GetUInt8();
4979 at.requiredItem = fields[2].GetUInt32();
4980 at.requiredItem2 = fields[3].GetUInt32();
4981 at.heroicKey = fields[4].GetUInt32();
4982 at.heroicKey2 = fields[5].GetUInt32();
4983 at.requiredQuest = fields[6].GetUInt32();
4984 at.requiredQuestHeroic = fields[7].GetUInt32();
4985 at.requiredFailedText = fields[8].GetCppString();
4986 at.target_mapId = fields[9].GetUInt32();
4987 at.target_X = fields[10].GetFloat();
4988 at.target_Y = fields[11].GetFloat();
4989 at.target_Z = fields[12].GetFloat();
4990 at.target_Orientation = fields[13].GetFloat();
4992 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4993 if(!atEntry)
4995 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4996 continue;
4999 if(at.requiredItem)
5001 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5002 if(!pProto)
5004 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5005 at.requiredItem = 0;
5008 if(at.requiredItem2)
5010 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5011 if(!pProto)
5013 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5014 at.requiredItem2 = 0;
5018 if(at.heroicKey)
5020 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5021 if(!pProto)
5023 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5024 at.heroicKey = 0;
5028 if(at.heroicKey2)
5030 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5031 if(!pProto)
5033 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5034 at.heroicKey2 = 0;
5038 if(at.requiredQuest)
5040 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5041 if(qReqItr == mQuestTemplates.end())
5043 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5044 at.requiredQuest = 0;
5048 if(at.requiredQuestHeroic)
5050 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5051 if(qReqItr == mQuestTemplates.end())
5053 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5054 at.requiredQuestHeroic = 0;
5058 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5059 if(!mapEntry)
5061 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5062 continue;
5065 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5067 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5068 continue;
5071 mAreaTriggers[Trigger_ID] = at;
5073 } while( result->NextRow() );
5075 delete result;
5077 sLog.outString();
5078 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5082 * Searches for the areatrigger which teleports players out of the given map
5084 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5086 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5087 if(!mapEntry) return NULL;
5088 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5090 if(itr->second.target_mapId == mapEntry->entrance_map)
5092 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5093 if(atEntry && atEntry->mapid == Map)
5094 return &itr->second;
5097 return NULL;
5101 * Searches for the areatrigger which teleports players to the given map
5103 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5105 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5107 if(itr->second.target_mapId == Map)
5109 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5110 if(atEntry)
5111 return &itr->second;
5114 return NULL;
5117 void ObjectMgr::SetHighestGuids()
5119 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5120 if( result )
5122 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5123 delete result;
5126 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5127 if( result )
5129 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5130 delete result;
5133 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5134 if( result )
5136 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5137 delete result;
5140 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5141 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5142 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5143 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5144 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5146 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5147 if( result )
5149 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5150 delete result;
5153 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5154 if( result )
5156 m_auctionid = (*result)[0].GetUInt32()+1;
5157 delete result;
5160 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5161 if( result )
5163 m_mailid = (*result)[0].GetUInt32()+1;
5164 delete result;
5167 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5168 if( result )
5170 m_ItemTextId = (*result)[0].GetUInt32()+1;
5171 delete result;
5174 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5175 if( result )
5177 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5178 delete result;
5181 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5182 if (result)
5184 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5185 delete result;
5188 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5189 if (result)
5191 m_guildId = (*result)[0].GetUInt32()+1;
5192 delete result;
5196 uint32 ObjectMgr::GenerateArenaTeamId()
5198 if(m_arenaTeamId>=0xFFFFFFFE)
5200 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5201 World::StopNow(ERROR_EXIT_CODE);
5203 return m_arenaTeamId++;
5206 uint32 ObjectMgr::GenerateAuctionID()
5208 if(m_auctionid>=0xFFFFFFFE)
5210 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5211 World::StopNow(ERROR_EXIT_CODE);
5213 return m_auctionid++;
5216 uint32 ObjectMgr::GenerateGuildId()
5218 if(m_guildId>=0xFFFFFFFE)
5220 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5221 World::StopNow(ERROR_EXIT_CODE);
5223 return m_guildId++;
5226 uint32 ObjectMgr::GenerateMailID()
5228 if(m_mailid>=0xFFFFFFFE)
5230 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5231 World::StopNow(ERROR_EXIT_CODE);
5233 return m_mailid++;
5236 uint32 ObjectMgr::GenerateItemTextID()
5238 if(m_ItemTextId>=0xFFFFFFFE)
5240 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5241 World::StopNow(ERROR_EXIT_CODE);
5243 return m_ItemTextId++;
5246 uint32 ObjectMgr::CreateItemText(std::string text)
5248 uint32 newItemTextId = GenerateItemTextID();
5249 //insert new itempage to container
5250 mItemTexts[ newItemTextId ] = text;
5251 //save new itempage
5252 CharacterDatabase.escape_string(text);
5253 //any Delete query needed, itemTextId is maximum of all ids
5254 std::ostringstream query;
5255 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5256 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5257 return newItemTextId;
5260 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5262 switch(guidhigh)
5264 case HIGHGUID_ITEM:
5265 if(m_hiItemGuid>=0xFFFFFFFE)
5267 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5268 World::StopNow(ERROR_EXIT_CODE);
5270 return m_hiItemGuid++;
5271 case HIGHGUID_UNIT:
5272 if(m_hiCreatureGuid>=0x00FFFFFE)
5274 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5275 World::StopNow(ERROR_EXIT_CODE);
5277 return m_hiCreatureGuid++;
5278 case HIGHGUID_PET:
5279 if(m_hiPetGuid>=0x00FFFFFE)
5281 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5282 World::StopNow(ERROR_EXIT_CODE);
5284 return m_hiPetGuid++;
5285 case HIGHGUID_VEHICLE:
5286 if(m_hiVehicleGuid>=0x00FFFFFF)
5288 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5289 World::StopNow(ERROR_EXIT_CODE);
5291 return m_hiVehicleGuid++;
5292 case HIGHGUID_PLAYER:
5293 if(m_hiCharGuid>=0xFFFFFFFE)
5295 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5296 World::StopNow(ERROR_EXIT_CODE);
5298 return m_hiCharGuid++;
5299 case HIGHGUID_GAMEOBJECT:
5300 if(m_hiGoGuid>=0x00FFFFFE)
5302 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5303 World::StopNow(ERROR_EXIT_CODE);
5305 return m_hiGoGuid++;
5306 case HIGHGUID_CORPSE:
5307 if(m_hiCorpseGuid>=0xFFFFFFFE)
5309 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5310 World::StopNow(ERROR_EXIT_CODE);
5312 return m_hiCorpseGuid++;
5313 case HIGHGUID_DYNAMICOBJECT:
5314 if(m_hiDoGuid>=0xFFFFFFFE)
5316 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5317 World::StopNow(ERROR_EXIT_CODE);
5319 return m_hiDoGuid++;
5320 default:
5321 ASSERT(0);
5324 ASSERT(0);
5325 return 0;
5328 void ObjectMgr::LoadGameObjectLocales()
5330 mGameObjectLocaleMap.clear(); // need for reload case
5332 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5333 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5334 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5335 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5337 if(!result)
5339 barGoLink bar(1);
5341 bar.step();
5343 sLog.outString();
5344 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5345 return;
5348 barGoLink bar(result->GetRowCount());
5352 Field *fields = result->Fetch();
5353 bar.step();
5355 uint32 entry = fields[0].GetUInt32();
5357 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5359 for(int i = 1; i < MAX_LOCALE; ++i)
5361 std::string str = fields[i].GetCppString();
5362 if(!str.empty())
5364 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5365 if(idx >= 0)
5367 if(data.Name.size() <= idx)
5368 data.Name.resize(idx+1);
5370 data.Name[idx] = str;
5375 for(int i = 1; i < MAX_LOCALE; ++i)
5377 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5378 if(!str.empty())
5380 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5381 if(idx >= 0)
5383 if(data.CastBarCaption.size() <= idx)
5384 data.CastBarCaption.resize(idx+1);
5386 data.CastBarCaption[idx] = str;
5391 } while (result->NextRow());
5393 delete result;
5395 sLog.outString();
5396 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5399 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5401 template<class D>
5402 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5404 dst = D(objmgr.GetScriptId(src));
5408 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5410 if (sLockStore.LookupEntry(dataN))
5411 return;
5413 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5414 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5417 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5419 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5421 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5422 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5423 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5425 /* disable check for while (too many error reports baout not existed in trap templates
5426 else
5427 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5428 goInfo->id,goInfo->type,N,dataN,dataN);
5432 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5434 if (sSpellStore.LookupEntry(dataN))
5435 return;
5437 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5438 goInfo->id,goInfo->type,N,dataN,dataN);
5441 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5443 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5444 return;
5446 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5447 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5449 // prevent client and server unexpected work
5450 const_cast<uint32&>(dataN) = 0;
5453 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5455 // 0/1 correct values
5456 if (dataN <= 1)
5457 return;
5459 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5460 goInfo->id,goInfo->type,N,dataN);
5463 void ObjectMgr::LoadGameobjectInfo()
5465 SQLGameObjectLoader loader;
5466 loader.Load(sGOStorage);
5468 // some checks
5469 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5471 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5472 if (!goInfo)
5473 continue;
5475 switch(goInfo->type)
5477 case GAMEOBJECT_TYPE_DOOR: //0
5479 if (goInfo->door.lockId)
5480 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5481 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5482 break;
5484 case GAMEOBJECT_TYPE_BUTTON: //1
5486 if (goInfo->button.lockId)
5487 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5488 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5489 break;
5491 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5493 if (goInfo->questgiver.lockId)
5494 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5495 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5496 break;
5498 case GAMEOBJECT_TYPE_CHEST: //3
5500 if (goInfo->chest.lockId)
5501 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5503 if (goInfo->chest.linkedTrapId) // linked trap
5504 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5505 break;
5507 case GAMEOBJECT_TYPE_TRAP: //6
5509 if (goInfo->trap.lockId)
5510 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5511 /* disable check for while, too many not existed spells
5512 if (goInfo->trap.spellId) // spell
5513 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5515 break;
5517 case GAMEOBJECT_TYPE_CHAIR: //7
5518 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5519 break;
5520 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5522 if (goInfo->spellFocus.focusId)
5524 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5525 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5526 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5529 if (goInfo->spellFocus.linkedTrapId) // linked trap
5530 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5531 break;
5533 case GAMEOBJECT_TYPE_GOOBER: //10
5535 if (goInfo->goober.lockId)
5536 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5538 if (goInfo->goober.pageId) // pageId
5540 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5541 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5542 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5544 /* disable check for while, too many not existed spells
5545 if (goInfo->goober.spellId) // spell
5546 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5548 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5549 if (goInfo->goober.linkedTrapId) // linked trap
5550 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5551 break;
5553 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5555 if (goInfo->areadamage.lockId)
5556 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5557 break;
5559 case GAMEOBJECT_TYPE_CAMERA: //13
5561 if (goInfo->camera.lockId)
5562 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5563 break;
5565 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5567 if (goInfo->moTransport.taxiPathId)
5569 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5570 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5571 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5573 break;
5575 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5577 /* disable check for while, too many not existed spells
5578 // always must have spell
5579 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5581 break;
5583 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5585 // always must have spell
5586 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5587 break;
5589 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5591 if (goInfo->flagstand.lockId)
5592 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5593 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5594 break;
5596 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5598 if (goInfo->fishinghole.lockId)
5599 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5600 break;
5602 case GAMEOBJECT_TYPE_FLAGDROP: //26
5604 if (goInfo->flagdrop.lockId)
5605 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5606 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5607 break;
5609 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5610 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5611 break;
5615 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5616 sLog.outString();
5619 void ObjectMgr::LoadExplorationBaseXP()
5621 uint32 count = 0;
5622 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5624 if( !result )
5626 barGoLink bar( 1 );
5628 bar.step();
5630 sLog.outString();
5631 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5632 return;
5635 barGoLink bar( result->GetRowCount() );
5639 bar.step();
5641 Field *fields = result->Fetch();
5642 uint32 level = fields[0].GetUInt32();
5643 uint32 basexp = fields[1].GetUInt32();
5644 mBaseXPTable[level] = basexp;
5645 ++count;
5647 while (result->NextRow());
5649 delete result;
5651 sLog.outString();
5652 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5655 uint32 ObjectMgr::GetBaseXP(uint32 level)
5657 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5660 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5662 if (level < mPlayerXPperLevel.size())
5663 return mPlayerXPperLevel[level];
5664 return 0;
5667 void ObjectMgr::LoadPetNames()
5669 uint32 count = 0;
5670 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5672 if( !result )
5674 barGoLink bar( 1 );
5676 bar.step();
5678 sLog.outString();
5679 sLog.outString( ">> Loaded %u pet name parts", count );
5680 return;
5683 barGoLink bar( result->GetRowCount() );
5687 bar.step();
5689 Field *fields = result->Fetch();
5690 std::string word = fields[0].GetString();
5691 uint32 entry = fields[1].GetUInt32();
5692 bool half = fields[2].GetBool();
5693 if(half)
5694 PetHalfName1[entry].push_back(word);
5695 else
5696 PetHalfName0[entry].push_back(word);
5697 ++count;
5699 while (result->NextRow());
5700 delete result;
5702 sLog.outString();
5703 sLog.outString( ">> Loaded %u pet name parts", count );
5706 void ObjectMgr::LoadPetNumber()
5708 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5709 if(result)
5711 Field *fields = result->Fetch();
5712 m_hiPetNumber = fields[0].GetUInt32()+1;
5713 delete result;
5716 barGoLink bar( 1 );
5717 bar.step();
5719 sLog.outString();
5720 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5723 std::string ObjectMgr::GeneratePetName(uint32 entry)
5725 std::vector<std::string> & list0 = PetHalfName0[entry];
5726 std::vector<std::string> & list1 = PetHalfName1[entry];
5728 if(list0.empty() || list1.empty())
5730 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5731 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5732 if(!petname)
5733 petname = cinfo->Name;
5734 return std::string(petname);
5737 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5740 uint32 ObjectMgr::GeneratePetNumber()
5742 return ++m_hiPetNumber;
5745 void ObjectMgr::LoadCorpses()
5747 uint32 count = 0;
5748 // 0 1 2 3 4 5 6 7 8 10
5749 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");
5751 if( !result )
5753 barGoLink bar( 1 );
5755 bar.step();
5757 sLog.outString();
5758 sLog.outString( ">> Loaded %u corpses", count );
5759 return;
5762 barGoLink bar( result->GetRowCount() );
5766 bar.step();
5768 Field *fields = result->Fetch();
5770 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5772 Corpse *corpse = new Corpse;
5773 if(!corpse->LoadFromDB(guid,fields))
5775 delete corpse;
5776 continue;
5779 ObjectAccessor::Instance().AddCorpse(corpse);
5781 ++count;
5783 while (result->NextRow());
5784 delete result;
5786 sLog.outString();
5787 sLog.outString( ">> Loaded %u corpses", count );
5790 void ObjectMgr::LoadReputationOnKill()
5792 uint32 count = 0;
5794 // 0 1 2
5795 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5796 // 3 4 5 6 7 8 9
5797 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5798 "FROM creature_onkill_reputation");
5800 if(!result)
5802 barGoLink bar(1);
5804 bar.step();
5806 sLog.outString();
5807 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5808 return;
5811 barGoLink bar(result->GetRowCount());
5815 Field *fields = result->Fetch();
5816 bar.step();
5818 uint32 creature_id = fields[0].GetUInt32();
5820 ReputationOnKillEntry repOnKill;
5821 repOnKill.repfaction1 = fields[1].GetUInt32();
5822 repOnKill.repfaction2 = fields[2].GetUInt32();
5823 repOnKill.is_teamaward1 = fields[3].GetBool();
5824 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5825 repOnKill.repvalue1 = fields[5].GetInt32();
5826 repOnKill.is_teamaward2 = fields[6].GetBool();
5827 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5828 repOnKill.repvalue2 = fields[8].GetInt32();
5829 repOnKill.team_dependent = fields[9].GetUInt8();
5831 if(!GetCreatureTemplate(creature_id))
5833 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5834 continue;
5837 if(repOnKill.repfaction1)
5839 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5840 if(!factionEntry1)
5842 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5843 continue;
5847 if(repOnKill.repfaction2)
5849 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5850 if(!factionEntry2)
5852 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5853 continue;
5857 mRepOnKill[creature_id] = repOnKill;
5859 ++count;
5860 } while (result->NextRow());
5862 delete result;
5864 sLog.outString();
5865 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5868 void ObjectMgr::LoadPointsOfInterest()
5870 uint32 count = 0;
5872 // 0 1 2 3 4 5
5873 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5875 if(!result)
5877 barGoLink bar(1);
5879 bar.step();
5881 sLog.outString();
5882 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5883 return;
5886 barGoLink bar(result->GetRowCount());
5890 Field *fields = result->Fetch();
5891 bar.step();
5893 uint32 point_id = fields[0].GetUInt32();
5895 PointOfInterest POI;
5896 POI.x = fields[1].GetFloat();
5897 POI.y = fields[2].GetFloat();
5898 POI.icon = fields[3].GetUInt32();
5899 POI.flags = fields[4].GetUInt32();
5900 POI.data = fields[5].GetUInt32();
5901 POI.icon_name = fields[6].GetCppString();
5903 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5905 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5906 continue;
5909 mPointsOfInterest[point_id] = POI;
5911 ++count;
5912 } while (result->NextRow());
5914 delete result;
5916 sLog.outString();
5917 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5920 void ObjectMgr::LoadWeatherZoneChances()
5922 uint32 count = 0;
5924 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5925 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");
5927 if(!result)
5929 barGoLink bar(1);
5931 bar.step();
5933 sLog.outString();
5934 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5935 return;
5938 barGoLink bar(result->GetRowCount());
5942 Field *fields = result->Fetch();
5943 bar.step();
5945 uint32 zone_id = fields[0].GetUInt32();
5947 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5949 for(int season = 0; season < WEATHER_SEASONS; ++season)
5951 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5952 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5953 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5955 if(wzc.data[season].rainChance > 100)
5957 wzc.data[season].rainChance = 25;
5958 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
5961 if(wzc.data[season].snowChance > 100)
5963 wzc.data[season].snowChance = 25;
5964 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
5967 if(wzc.data[season].stormChance > 100)
5969 wzc.data[season].stormChance = 25;
5970 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
5974 ++count;
5975 } while (result->NextRow());
5977 delete result;
5979 sLog.outString();
5980 sLog.outString(">> Loaded %u weather definitions", count);
5983 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5985 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5986 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5987 if(t)
5988 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5991 void ObjectMgr::DeleteCreatureData(uint32 guid)
5993 // remove mapid*cellid -> guid_set map
5994 CreatureData const* data = GetCreatureData(guid);
5995 if(data)
5996 RemoveCreatureFromGrid(guid, data);
5998 mCreatureDataMap.erase(guid);
6001 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6003 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6004 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6005 if(t)
6006 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
6009 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6011 RespawnTimes::iterator next;
6013 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6015 next = itr;
6016 ++next;
6018 if(GUID_HIPART(itr->first)==instance)
6019 mGORespawnTimes.erase(itr);
6022 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6024 next = itr;
6025 ++next;
6027 if(GUID_HIPART(itr->first)==instance)
6028 mCreatureRespawnTimes.erase(itr);
6031 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6032 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6035 void ObjectMgr::DeleteGOData(uint32 guid)
6037 // remove mapid*cellid -> guid_set map
6038 GameObjectData const* data = GetGOData(guid);
6039 if(data)
6040 RemoveGameobjectFromGrid(guid, data);
6042 mGameObjectDataMap.erase(guid);
6045 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6047 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6048 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6049 cell_guids.corpses[player_guid] = instance;
6052 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6054 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6055 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6056 cell_guids.corpses.erase(player_guid);
6059 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6061 map.clear(); // need for reload case
6063 uint32 count = 0;
6065 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6067 if(!result)
6069 barGoLink bar(1);
6071 bar.step();
6073 sLog.outString();
6074 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6075 return;
6078 barGoLink bar(result->GetRowCount());
6082 Field *fields = result->Fetch();
6083 bar.step();
6085 uint32 id = fields[0].GetUInt32();
6086 uint32 quest = fields[1].GetUInt32();
6088 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6090 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6091 continue;
6094 map.insert(QuestRelations::value_type(id,quest));
6096 ++count;
6097 } while (result->NextRow());
6099 delete result;
6101 sLog.outString();
6102 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6105 void ObjectMgr::LoadGameobjectQuestRelations()
6107 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6109 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6111 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6112 if(!goInfo)
6113 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6114 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6115 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6119 void ObjectMgr::LoadGameobjectInvolvedRelations()
6121 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6123 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6125 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6126 if(!goInfo)
6127 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6128 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6129 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6133 void ObjectMgr::LoadCreatureQuestRelations()
6135 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6137 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6139 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6140 if(!cInfo)
6141 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6142 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6143 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);
6147 void ObjectMgr::LoadCreatureInvolvedRelations()
6149 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6151 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6153 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6154 if(!cInfo)
6155 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6156 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6157 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);
6161 void ObjectMgr::LoadReservedPlayersNames()
6163 m_ReservedNames.clear(); // need for reload case
6165 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6167 uint32 count = 0;
6169 if( !result )
6171 barGoLink bar( 1 );
6172 bar.step();
6174 sLog.outString();
6175 sLog.outString( ">> Loaded %u reserved player names", count );
6176 return;
6179 barGoLink bar( result->GetRowCount() );
6181 Field* fields;
6184 bar.step();
6185 fields = result->Fetch();
6186 std::string name= fields[0].GetCppString();
6188 std::wstring wstr;
6189 if(!Utf8toWStr (name,wstr))
6191 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6192 continue;
6195 wstrToLower(wstr);
6197 m_ReservedNames.insert(wstr);
6198 ++count;
6199 } while ( result->NextRow() );
6201 delete result;
6203 sLog.outString();
6204 sLog.outString( ">> Loaded %u reserved player names", count );
6207 bool ObjectMgr::IsReservedName( const std::string& name ) const
6209 std::wstring wstr;
6210 if(!Utf8toWStr (name,wstr))
6211 return false;
6213 wstrToLower(wstr);
6215 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6218 enum LanguageType
6220 LT_BASIC_LATIN = 0x0000,
6221 LT_EXTENDEN_LATIN = 0x0001,
6222 LT_CYRILLIC = 0x0002,
6223 LT_EAST_ASIA = 0x0004,
6224 LT_ANY = 0xFFFF
6227 static LanguageType GetRealmLanguageType(bool create)
6229 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6231 case REALM_ZONE_UNKNOWN: // any language
6232 case REALM_ZONE_DEVELOPMENT:
6233 case REALM_ZONE_TEST_SERVER:
6234 case REALM_ZONE_QA_SERVER:
6235 return LT_ANY;
6236 case REALM_ZONE_UNITED_STATES: // extended-Latin
6237 case REALM_ZONE_OCEANIC:
6238 case REALM_ZONE_LATIN_AMERICA:
6239 case REALM_ZONE_ENGLISH:
6240 case REALM_ZONE_GERMAN:
6241 case REALM_ZONE_FRENCH:
6242 case REALM_ZONE_SPANISH:
6243 return LT_EXTENDEN_LATIN;
6244 case REALM_ZONE_KOREA: // East-Asian
6245 case REALM_ZONE_TAIWAN:
6246 case REALM_ZONE_CHINA:
6247 return LT_EAST_ASIA;
6248 case REALM_ZONE_RUSSIAN: // Cyrillic
6249 return LT_CYRILLIC;
6250 default:
6251 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6255 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6257 if(strictMask==0) // any language, ignore realm
6259 if(isExtendedLatinString(wstr,numericOrSpace))
6260 return true;
6261 if(isCyrillicString(wstr,numericOrSpace))
6262 return true;
6263 if(isEastAsianString(wstr,numericOrSpace))
6264 return true;
6265 return false;
6268 if(strictMask & 0x2) // realm zone specific
6270 LanguageType lt = GetRealmLanguageType(create);
6271 if(lt & LT_EXTENDEN_LATIN)
6272 if(isExtendedLatinString(wstr,numericOrSpace))
6273 return true;
6274 if(lt & LT_CYRILLIC)
6275 if(isCyrillicString(wstr,numericOrSpace))
6276 return true;
6277 if(lt & LT_EAST_ASIA)
6278 if(isEastAsianString(wstr,numericOrSpace))
6279 return true;
6282 if(strictMask & 0x1) // basic Latin
6284 if(isBasicLatinString(wstr,numericOrSpace))
6285 return true;
6288 return false;
6291 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6293 std::wstring wname;
6294 if(!Utf8toWStr(name,wname))
6295 return false;
6297 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6298 return false;
6300 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6302 return isValidString(wname,strictMask,false,create);
6305 bool ObjectMgr::IsValidCharterName( const std::string& name )
6307 std::wstring wname;
6308 if(!Utf8toWStr(name,wname))
6309 return false;
6311 if(wname.size() < 1)
6312 return false;
6314 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6316 return isValidString(wname,strictMask,true);
6319 bool ObjectMgr::IsValidPetName( const std::string& name )
6321 std::wstring wname;
6322 if(!Utf8toWStr(name,wname))
6323 return false;
6325 if(wname.size() < 1)
6326 return false;
6328 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6330 return isValidString(wname,strictMask,false);
6333 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6335 if(loc==LOCALE_enUS)
6336 return -1;
6338 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6339 if(m_LocalForIndex[i]==loc)
6340 return i;
6342 return -1;
6345 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6347 if (i<0 || i>=m_LocalForIndex.size())
6348 return LOCALE_enUS;
6350 return m_LocalForIndex[i];
6353 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6355 if(loc==LOCALE_enUS)
6356 return -1;
6358 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6359 if(m_LocalForIndex[i]==loc)
6360 return i;
6362 m_LocalForIndex.push_back(loc);
6363 return m_LocalForIndex.size()-1;
6366 void ObjectMgr::LoadGameObjectForQuests()
6368 mGameObjectForQuestSet.clear(); // need for reload case
6370 if( !sGOStorage.MaxEntry )
6372 barGoLink bar( 1 );
6373 bar.step();
6374 sLog.outString();
6375 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6376 return;
6379 barGoLink bar( sGOStorage.MaxEntry - 1 );
6380 uint32 count = 0;
6382 // collect GO entries for GO that must activated
6383 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6385 bar.step();
6386 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6387 if(!goInfo)
6388 continue;
6390 switch(goInfo->type)
6392 // scan GO chest with loot including quest items
6393 case GAMEOBJECT_TYPE_CHEST:
6395 uint32 loot_id = GameObject::GetLootId(goInfo);
6397 // find quest loot for GO
6398 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6400 mGameObjectForQuestSet.insert(go_entry);
6401 ++count;
6403 break;
6405 case GAMEOBJECT_TYPE_GOOBER:
6407 if(goInfo->goober.questId) //quests objects
6409 mGameObjectForQuestSet.insert(go_entry);
6410 count++;
6412 break;
6414 default:
6415 break;
6419 sLog.outString();
6420 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6423 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6425 // cleanup affected map part for reloading case
6426 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6428 if(itr->first >= min_value && itr->first <= max_value)
6430 MangosStringLocaleMap::iterator itr2 = itr;
6431 ++itr;
6432 mMangosStringLocaleMap.erase(itr2);
6434 else
6435 ++itr;
6438 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);
6440 if(!result)
6442 barGoLink bar(1);
6444 bar.step();
6446 sLog.outString();
6447 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6448 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6449 else
6450 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6451 return false;
6454 uint32 count = 0;
6456 barGoLink bar(result->GetRowCount());
6460 Field *fields = result->Fetch();
6461 bar.step();
6463 int32 entry = fields[0].GetInt32();
6465 if(entry==0)
6467 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6468 continue;
6470 else if(entry < min_value || entry > max_value)
6472 int32 start = min_value > 0 ? min_value : max_value;
6473 int32 end = min_value > 0 ? max_value : min_value;
6474 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6475 continue;
6478 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6480 if(data.Content.size() > 0)
6482 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6483 continue;
6486 data.Content.resize(1);
6487 ++count;
6489 // 0 -> default, idx in to idx+1
6490 data.Content[0] = fields[1].GetCppString();
6492 for(int i = 1; i < MAX_LOCALE; ++i)
6494 std::string str = fields[i+1].GetCppString();
6495 if(!str.empty())
6497 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6498 if(idx >= 0)
6500 // 0 -> default, idx in to idx+1
6501 if(data.Content.size() <= idx+1)
6502 data.Content.resize(idx+2);
6504 data.Content[idx+1] = str;
6508 } while (result->NextRow());
6510 delete result;
6512 sLog.outString();
6513 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6514 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6515 else
6516 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6518 return true;
6521 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6523 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6524 // Content[0] always exist if exist MangosStringLocale
6525 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6527 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6528 return msl->Content[locale_idx+1].c_str();
6529 else
6530 return msl->Content[0].c_str();
6533 if(entry > 0)
6534 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6535 else
6536 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6537 return "<error>";
6540 void ObjectMgr::LoadFishingBaseSkillLevel()
6542 mFishingBaseForArea.clear(); // for reload case
6544 uint32 count = 0;
6545 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6547 if( !result )
6549 barGoLink bar( 1 );
6551 bar.step();
6553 sLog.outString();
6554 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6555 return;
6558 barGoLink bar( result->GetRowCount() );
6562 bar.step();
6564 Field *fields = result->Fetch();
6565 uint32 entry = fields[0].GetUInt32();
6566 int32 skill = fields[1].GetInt32();
6568 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6569 if(!fArea)
6571 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6572 continue;
6575 mFishingBaseForArea[entry] = skill;
6576 ++count;
6578 while (result->NextRow());
6580 delete result;
6582 sLog.outString();
6583 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6586 // Searches for the same condition already in Conditions store
6587 // Returns Id if found, else adds it to Conditions and returns Id
6588 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6590 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6591 for (uint16 i=0; i < mConditions.size(); ++i)
6593 if (lc == mConditions[i])
6594 return i;
6597 mConditions.push_back(lc);
6599 if(mConditions.size() > 0xFFFF)
6601 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6602 return 0;
6605 return mConditions.size() - 1;
6608 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6610 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6612 std::wstring wname;
6613 if(!Utf8toWStr(names.name[i],wname))
6614 return false;
6616 if(mainpart!=GetMainPartOfName(wname,i+1))
6617 return false;
6619 return true;
6622 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6624 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6625 if(i!= mAreaTriggerScripts.end())
6626 return i->second;
6627 return 0;
6630 // Checks if player meets the condition
6631 bool PlayerCondition::Meets(Player const * player) const
6633 if( !player )
6634 return false; // player not present, return false
6636 switch (condition)
6638 case CONDITION_NONE:
6639 return true; // empty condition, always met
6640 case CONDITION_AURA:
6641 return player->HasAura(value1, value2);
6642 case CONDITION_ITEM:
6643 return player->HasItemCount(value1, value2);
6644 case CONDITION_ITEM_EQUIPPED:
6645 return player->HasItemOrGemWithIdEquipped(value1,1);
6646 case CONDITION_ZONEID:
6647 return player->GetZoneId() == value1;
6648 case CONDITION_REPUTATION_RANK:
6650 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6651 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6653 case CONDITION_TEAM:
6654 return player->GetTeam() == value1;
6655 case CONDITION_SKILL:
6656 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6657 case CONDITION_QUESTREWARDED:
6658 return player->GetQuestRewardStatus(value1);
6659 case CONDITION_QUESTTAKEN:
6661 QuestStatus status = player->GetQuestStatus(value1);
6662 return (status == QUEST_STATUS_INCOMPLETE);
6664 case CONDITION_AD_COMMISSION_AURA:
6666 Unit::AuraMap const& auras = player->GetAuras();
6667 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6668 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6669 return true;
6670 return false;
6672 case CONDITION_NO_AURA:
6673 return !player->HasAura(value1, value2);
6674 case CONDITION_ACTIVE_EVENT:
6675 return gameeventmgr.IsActiveEvent(value1);
6676 default:
6677 return false;
6681 // Verification of condition values validity
6682 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6684 if( condition >= MAX_CONDITION) // Wrong condition type
6686 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6687 return false;
6690 switch (condition)
6692 case CONDITION_AURA:
6694 if(!sSpellStore.LookupEntry(value1))
6696 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6697 return false;
6699 if(value2 > 2)
6701 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6702 return false;
6704 break;
6706 case CONDITION_ITEM:
6708 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6709 if(!proto)
6711 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6712 return false;
6714 break;
6716 case CONDITION_ITEM_EQUIPPED:
6718 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6719 if(!proto)
6721 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6722 return false;
6724 break;
6726 case CONDITION_ZONEID:
6728 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6729 if(!areaEntry)
6731 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6732 return false;
6734 if(areaEntry->zone != 0)
6736 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6737 return false;
6739 break;
6741 case CONDITION_REPUTATION_RANK:
6743 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6744 if(!factionEntry)
6746 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6747 return false;
6749 break;
6751 case CONDITION_TEAM:
6753 if (value1 != ALLIANCE && value1 != HORDE)
6755 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6756 return false;
6758 break;
6760 case CONDITION_SKILL:
6762 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6763 if (!pSkill)
6765 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6766 return false;
6768 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6770 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6771 return false;
6773 break;
6775 case CONDITION_QUESTREWARDED:
6776 case CONDITION_QUESTTAKEN:
6778 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6779 if (!Quest)
6781 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6782 return false;
6784 if(value2)
6785 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6786 break;
6788 case CONDITION_AD_COMMISSION_AURA:
6790 if(value1)
6791 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6792 if(value2)
6793 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6794 break;
6796 case CONDITION_NO_AURA:
6798 if(!sSpellStore.LookupEntry(value1))
6800 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6801 return false;
6803 if(value2 > 2)
6805 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6806 return false;
6808 break;
6810 case CONDITION_ACTIVE_EVENT:
6812 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6813 if(value1 >=events.size() || !events[value1].isValid())
6815 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6816 return false;
6818 break;
6820 case CONDITION_NONE:
6821 break;
6823 return true;
6826 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6828 switch(pSkill->categoryId)
6830 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6831 case SKILL_CATEGORY_WEAPON:
6832 if(pSkill->id!=SKILL_FIST_WEAPONS)
6833 return SKILL_RANGE_LEVEL;
6834 else
6835 return SKILL_RANGE_MONO;
6836 case SKILL_CATEGORY_ARMOR:
6837 case SKILL_CATEGORY_CLASS:
6838 if(pSkill->id != SKILL_LOCKPICKING)
6839 return SKILL_RANGE_MONO;
6840 else
6841 return SKILL_RANGE_LEVEL;
6842 case SKILL_CATEGORY_SECONDARY:
6843 case SKILL_CATEGORY_PROFESSION:
6844 // not set skills for professions and racial abilities
6845 if(IsProfessionSkill(pSkill->id))
6846 return SKILL_RANGE_RANK;
6847 else if(racial)
6848 return SKILL_RANGE_NONE;
6849 else
6850 return SKILL_RANGE_MONO;
6851 default:
6852 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6853 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6854 return SKILL_RANGE_NONE;
6858 void ObjectMgr::LoadGameTele()
6860 m_GameTeleMap.clear(); // for reload case
6862 uint32 count = 0;
6863 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6865 if( !result )
6867 barGoLink bar( 1 );
6869 bar.step();
6871 sLog.outString();
6872 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6873 return;
6876 barGoLink bar( result->GetRowCount() );
6880 bar.step();
6882 Field *fields = result->Fetch();
6884 uint32 id = fields[0].GetUInt32();
6886 GameTele gt;
6888 gt.position_x = fields[1].GetFloat();
6889 gt.position_y = fields[2].GetFloat();
6890 gt.position_z = fields[3].GetFloat();
6891 gt.orientation = fields[4].GetFloat();
6892 gt.mapId = fields[5].GetUInt32();
6893 gt.name = fields[6].GetCppString();
6895 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6897 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6898 continue;
6901 if(!Utf8toWStr(gt.name,gt.wnameLow))
6903 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6904 continue;
6907 wstrToLower( gt.wnameLow );
6909 m_GameTeleMap[id] = gt;
6911 ++count;
6913 while (result->NextRow());
6914 delete result;
6916 sLog.outString();
6917 sLog.outString( ">> Loaded %u GameTeleports", count );
6920 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6922 // explicit name case
6923 std::wstring wname;
6924 if(!Utf8toWStr(name,wname))
6925 return false;
6927 // converting string that we try to find to lower case
6928 wstrToLower( wname );
6930 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6931 const GameTele* alt = NULL;
6932 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6933 if(itr->second.wnameLow == wname)
6934 return &itr->second;
6935 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6936 alt = &itr->second;
6938 return alt;
6941 bool ObjectMgr::AddGameTele(GameTele& tele)
6943 // find max id
6944 uint32 new_id = 0;
6945 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6946 if(itr->first > new_id)
6947 new_id = itr->first;
6949 // use next
6950 ++new_id;
6952 if(!Utf8toWStr(tele.name,tele.wnameLow))
6953 return false;
6955 wstrToLower( tele.wnameLow );
6957 m_GameTeleMap[new_id] = tele;
6959 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')",
6960 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6963 bool ObjectMgr::DeleteGameTele(const std::string& name)
6965 // explicit name case
6966 std::wstring wname;
6967 if(!Utf8toWStr(name,wname))
6968 return false;
6970 // converting string that we try to find to lower case
6971 wstrToLower( wname );
6973 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6975 if(itr->second.wnameLow == wname)
6977 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6978 m_GameTeleMap.erase(itr);
6979 return true;
6983 return false;
6986 void ObjectMgr::LoadTrainerSpell()
6988 // For reload case
6989 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6990 itr->second.Clear();
6991 m_mCacheTrainerSpellMap.clear();
6993 std::set<uint32> skip_trainers;
6995 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6997 if( !result )
6999 barGoLink bar( 1 );
7001 bar.step();
7003 sLog.outString();
7004 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7005 return;
7008 barGoLink bar( result->GetRowCount() );
7010 uint32 count = 0;
7013 bar.step();
7015 Field* fields = result->Fetch();
7017 uint32 entry = fields[0].GetUInt32();
7018 uint32 spell = fields[1].GetUInt32();
7020 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7022 if(!cInfo)
7024 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7025 continue;
7028 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7030 if(skip_trainers.count(entry) == 0)
7032 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7033 skip_trainers.insert(entry);
7035 continue;
7038 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7039 if(!spellinfo)
7041 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7042 continue;
7045 if(!SpellMgr::IsSpellValid(spellinfo))
7047 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7048 continue;
7051 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7053 TrainerSpell& trainerSpell = data.spellList[spell];
7054 trainerSpell.spell = spell;
7055 trainerSpell.spellCost = fields[2].GetUInt32();
7056 trainerSpell.reqSkill = fields[3].GetUInt32();
7057 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7058 trainerSpell.reqLevel = fields[5].GetUInt32();
7060 if(!trainerSpell.reqLevel)
7061 trainerSpell.reqLevel = spellinfo->spellLevel;
7063 // calculate learned spell for profession case when stored cast-spell
7064 trainerSpell.learnedSpell = spell;
7065 for(int i = 0; i <3; ++i)
7067 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7068 continue;
7069 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7071 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7072 break;
7076 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7077 data.trainerType = 2;
7079 ++count;
7081 } while (result->NextRow());
7082 delete result;
7084 sLog.outString();
7085 sLog.outString( ">> Loaded %d Trainers", count );
7088 void ObjectMgr::LoadVendors()
7090 // For reload case
7091 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7092 itr->second.Clear();
7093 m_mCacheVendorItemMap.clear();
7095 std::set<uint32> skip_vendors;
7097 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7098 if( !result )
7100 barGoLink bar( 1 );
7102 bar.step();
7104 sLog.outString();
7105 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7106 return;
7109 barGoLink bar( result->GetRowCount() );
7111 uint32 count = 0;
7114 bar.step();
7115 Field* fields = result->Fetch();
7117 uint32 entry = fields[0].GetUInt32();
7118 uint32 item_id = fields[1].GetUInt32();
7119 uint32 maxcount = fields[2].GetUInt32();
7120 uint32 incrtime = fields[3].GetUInt32();
7121 uint32 ExtendedCost = fields[4].GetUInt32();
7123 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7124 continue;
7126 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7128 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7129 ++count;
7131 } while (result->NextRow());
7132 delete result;
7134 sLog.outString();
7135 sLog.outString( ">> Loaded %d Vendors ", count );
7138 void ObjectMgr::LoadNpcTextId()
7141 m_mCacheNpcTextIdMap.clear();
7143 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7144 if( !result )
7146 barGoLink bar( 1 );
7148 bar.step();
7150 sLog.outString();
7151 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7152 return;
7155 barGoLink bar( result->GetRowCount() );
7157 uint32 count = 0;
7158 uint32 guid,textid;
7161 bar.step();
7163 Field* fields = result->Fetch();
7165 guid = fields[0].GetUInt32();
7166 textid = fields[1].GetUInt32();
7168 if (!GetCreatureData(guid))
7170 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7171 continue;
7173 if (!GetGossipText(textid))
7175 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7176 continue;
7179 m_mCacheNpcTextIdMap[guid] = textid ;
7180 ++count;
7182 } while (result->NextRow());
7183 delete result;
7185 sLog.outString();
7186 sLog.outString( ">> Loaded %d NpcTextId ", count );
7189 void ObjectMgr::LoadNpcOptions()
7191 m_mCacheNpcOptionList.clear(); // For reload case
7193 QueryResult *result = WorldDatabase.Query(
7194 // 0 1 2 3 4 5 6 7 8
7195 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7196 "FROM npc_option");
7198 if( !result )
7200 barGoLink bar( 1 );
7202 bar.step();
7204 sLog.outString();
7205 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7206 return;
7209 barGoLink bar( result->GetRowCount() );
7211 uint32 count = 0;
7215 bar.step();
7217 Field* fields = result->Fetch();
7219 GossipOption go;
7220 go.Id = fields[0].GetUInt32();
7221 go.GossipId = fields[1].GetUInt32();
7222 go.NpcFlag = fields[2].GetUInt32();
7223 go.Icon = fields[3].GetUInt32();
7224 go.Action = fields[4].GetUInt32();
7225 go.BoxMoney = fields[5].GetUInt32();
7226 go.Coded = fields[6].GetUInt8()!=0;
7227 go.OptionText = fields[7].GetCppString();
7228 go.BoxText = fields[8].GetCppString();
7230 m_mCacheNpcOptionList.push_back(go);
7232 ++count;
7234 } while (result->NextRow());
7235 delete result;
7237 sLog.outString();
7238 sLog.outString( ">> Loaded %d npc_option entries", count );
7241 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7243 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7244 vList.AddItem(item,maxcount,incrtime,extendedcost);
7246 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7249 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7251 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7252 if(iter == m_mCacheVendorItemMap.end())
7253 return false;
7255 if(!iter->second.FindItem(item))
7256 return false;
7258 iter->second.RemoveItem(item);
7259 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7260 return true;
7263 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7265 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7266 if(!cInfo)
7268 if(pl)
7269 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7270 else
7271 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7272 return false;
7275 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7277 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7279 if(pl)
7280 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7281 else
7282 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7284 if(skip_vendors)
7285 skip_vendors->insert(vendor_entry);
7287 return false;
7290 if(!GetItemPrototype(item_id))
7292 if(pl)
7293 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7294 else
7295 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7296 return false;
7299 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7301 if(pl)
7302 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7303 else
7304 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7305 return false;
7308 if(maxcount > 0 && incrtime == 0)
7310 if(pl)
7311 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7312 else
7313 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7314 return false;
7316 else if(maxcount==0 && incrtime > 0)
7318 if(pl)
7319 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7320 else
7321 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7322 return false;
7325 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7326 if(!vItems)
7327 return true; // later checks for non-empty lists
7329 if(vItems->FindItem(item_id))
7331 if(pl)
7332 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7333 else
7334 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7335 return false;
7338 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7340 if(pl)
7341 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7342 else
7343 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7344 return false;
7347 return true;
7350 void ObjectMgr::LoadScriptNames()
7352 m_scriptNames.push_back("");
7353 QueryResult *result = WorldDatabase.Query(
7354 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7355 "UNION "
7356 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7357 "UNION "
7358 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7359 "UNION "
7360 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7361 "UNION "
7362 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7364 if( !result )
7366 barGoLink bar( 1 );
7367 bar.step();
7368 sLog.outString();
7369 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7370 return;
7373 barGoLink bar( result->GetRowCount() );
7374 uint32 count = 0;
7378 bar.step();
7379 m_scriptNames.push_back((*result)[0].GetString());
7380 ++count;
7381 } while (result->NextRow());
7382 delete result;
7384 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7385 sLog.outString();
7386 sLog.outString( ">> Loaded %d Script Names", count );
7389 uint32 ObjectMgr::GetScriptId(const char *name)
7391 // use binary search to find the script name in the sorted vector
7392 // assume "" is the first element
7393 if(!name) return 0;
7394 ScriptNameMap::const_iterator itr =
7395 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7396 if(itr == m_scriptNames.end() || *itr != name) return 0;
7397 return itr - m_scriptNames.begin();
7400 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7402 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7404 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7406 switch(itrM->second.command)
7408 case SCRIPT_COMMAND_TALK:
7410 if(!GetMangosStringLocale (itrM->second.dataint))
7411 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7413 if(ids.count(itrM->second.dataint))
7414 ids.erase(itrM->second.dataint);
7421 void ObjectMgr::LoadDbScriptStrings()
7423 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7425 std::set<int32> ids;
7427 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7428 if(GetMangosStringLocale(i))
7429 ids.insert(i);
7431 CheckScripts(sQuestEndScripts,ids);
7432 CheckScripts(sQuestStartScripts,ids);
7433 CheckScripts(sSpellScripts,ids);
7434 CheckScripts(sGameObjectScripts,ids);
7435 CheckScripts(sEventScripts,ids);
7437 WaypointMgr.CheckTextsExistance(ids);
7439 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7440 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7443 // Functions for scripting access
7444 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7446 return objmgr.GetAreaTriggerScriptId(trigger_id);
7449 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7451 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7453 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), use (%d - %d) instead.",table,start_value,end_value,-1,std::numeric_limits<int32>::min());
7454 start_value = -1;
7455 end_value = std::numeric_limits<int32>::min();
7458 // for scripting localized strings allowed use _only_ negative entries
7459 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7462 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7464 return objmgr.GetScriptId(name);
7467 ObjectMgr::ScriptNameMap & GetScriptNames()
7469 return objmgr.GetScriptNames();
7472 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7474 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7477 Quest const* GetQuestTemplateStore(uint32 entry)
7479 return objmgr.GetQuestTemplate(entry);