[7592] Correct delay loading for creature waypoints.
[getmangos.git] / src / game / ObjectMgr.cpp
blob77f446f93374f705f430fa35b6e061651abf3870
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 hasHeroicEntries.insert(i);
532 heroicEntries.insert(cInfo->HeroicEntry);
535 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
536 if(!factionTemplate)
537 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
539 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
540 if(!factionTemplate)
541 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
543 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
544 if (!minfo)
545 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
546 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
547 if (!minfo)
548 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
550 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
552 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
553 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
556 if(cInfo->baseattacktime == 0)
557 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
559 if(cInfo->rangeattacktime == 0)
560 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
562 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
563 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
565 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
567 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
568 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
571 // must exist or used hidden but used in data horse case
572 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
574 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
575 const_cast<CreatureInfo*>(cInfo)->family = 0;
578 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
580 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
581 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
584 if(cInfo->PetSpellDataId)
586 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
587 if(!spellDataId)
588 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
591 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
593 if(cInfo->spells[i] && !sSpellStore.LookupEntry(cInfo->spells[i]))
595 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, i+1,cInfo->spells[i]);
596 const_cast<CreatureInfo*>(cInfo)->spells[i] = 0;
600 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
602 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
603 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
606 if(cInfo->equipmentId > 0) // 0 no equipment
608 if(!GetEquipmentInfo(cInfo->equipmentId))
610 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);
611 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
615 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
616 if(cInfo->scale <= 0.0f)
618 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
619 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
624 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
626 // Now add the auras, format "spellid effectindex spellid effectindex..."
627 char *p,*s;
628 std::vector<int> val;
629 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
630 if(p)
632 while (p[0]!=0)
634 ++p;
635 if (p[0]==' ')
637 val.push_back(atoi(s));
638 s=++p;
641 if (p!=s)
642 val.push_back(atoi(s));
644 // free char* loaded memory
645 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
647 // wrong list
648 if (val.size()%2)
650 addon->auras = NULL;
651 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
652 return;
656 // empty list
657 if(val.empty())
659 addon->auras = NULL;
660 return;
663 // replace by new structures array
664 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
666 int i=0;
667 for(int j=0;j<val.size()/2;++j)
669 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
670 cAura.spell_id = (uint32)val[2*j+0];
671 cAura.effect_idx = (uint32)val[2*j+1];
672 if ( cAura.effect_idx > 2 )
674 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);
675 continue;
677 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
678 if (!AdditionalSpellInfo)
680 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
681 continue;
684 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
686 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);
687 continue;
690 ++i;
693 // fill terminator element (after last added)
694 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
695 endAura.spell_id = 0;
696 endAura.effect_idx = 0;
699 void ObjectMgr::LoadCreatureAddons()
701 sCreatureInfoAddonStorage.Load();
703 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
704 sLog.outString();
706 // check data correctness and convert 'auras'
707 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
709 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
710 if(!addon)
711 continue;
713 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
715 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
716 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
719 sCreatureDataAddonStorage.Load();
721 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
722 sLog.outString();
724 // check data correctness and convert 'auras'
725 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
727 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
728 if(!addon)
729 continue;
731 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
733 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
734 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
738 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
740 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
743 void ObjectMgr::LoadEquipmentTemplates()
745 sEquipmentStorage.Load();
747 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
749 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
751 if(!eqInfo)
752 continue;
754 for(uint8 j=0; j<3; j++)
756 if(!eqInfo->equipentry[j])
757 continue;
759 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
761 if(!dbcitem)
763 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
764 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
765 continue;
768 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
769 dbcitem->InventoryType != INVTYPE_SHIELD &&
770 dbcitem->InventoryType != INVTYPE_RANGED &&
771 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
772 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
773 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
774 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
775 dbcitem->InventoryType != INVTYPE_THROWN &&
776 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
778 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);
779 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
783 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
784 sLog.outString();
786 // This DBC is currently only used for item templates and creature equipments checks.
787 sItemStore.Clear();
790 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
792 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
795 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
797 // Load creature model (display id)
798 uint32 display_id;
799 if (!data || data->displayid == 0) // use defaults from the template
801 // DisplayID_A is used if no team is given
802 if (team == HORDE)
803 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
804 else
805 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
807 else // overridden in creature data
808 display_id = data->displayid;
810 return display_id;
813 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
815 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
816 if(!minfo)
817 return NULL;
819 // If a model for another gender exists, 50% chance to use it
820 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
822 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
823 if(!minfo_tmp)
825 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
826 return minfo; // not fatal, just use the previous one
828 else
829 return minfo_tmp;
831 else
832 return minfo;
835 void ObjectMgr::LoadCreatureModelInfo()
837 sCreatureModelStorage.Load();
839 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
840 sLog.outString();
843 void ObjectMgr::LoadCreatures()
845 uint32 count = 0;
846 // 0 1 2 3
847 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
848 // 4 5 6 7 8 9 10 11
849 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
850 // 12 13 14 15 16 17 18 19
851 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
852 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
853 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
855 if(!result)
857 barGoLink bar(1);
859 bar.step();
861 sLog.outString();
862 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
863 return;
866 // build single time for check creature data
867 std::set<uint32> heroicCreatures;
868 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
869 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
870 if(cInfo->HeroicEntry)
871 heroicCreatures.insert(cInfo->HeroicEntry);
873 barGoLink bar(result->GetRowCount());
877 Field *fields = result->Fetch();
878 bar.step();
880 uint32 guid = fields[ 0].GetUInt32();
881 uint32 entry = fields[ 1].GetUInt32();
883 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
884 if(!cInfo)
886 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
887 continue;
890 CreatureData& data = mCreatureDataMap[guid];
892 data.id = entry;
893 data.mapid = fields[ 2].GetUInt32();
894 data.displayid = fields[ 3].GetUInt32();
895 data.equipmentId = fields[ 4].GetUInt32();
896 data.posX = fields[ 5].GetFloat();
897 data.posY = fields[ 6].GetFloat();
898 data.posZ = fields[ 7].GetFloat();
899 data.orientation = fields[ 8].GetFloat();
900 data.spawntimesecs = fields[ 9].GetUInt32();
901 data.spawndist = fields[10].GetFloat();
902 data.currentwaypoint= fields[11].GetUInt32();
903 data.curhealth = fields[12].GetUInt32();
904 data.curmana = fields[13].GetUInt32();
905 data.is_dead = fields[14].GetBool();
906 data.movementType = fields[15].GetUInt8();
907 data.spawnMask = fields[16].GetUInt8();
908 data.phaseMask = fields[17].GetUInt16();
909 int16 gameEvent = fields[18].GetInt16();
910 int16 PoolId = fields[19].GetInt16();
912 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
914 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
915 continue;
918 if(data.equipmentId > 0) // -1 no equipment, 0 use default
920 if(!GetEquipmentInfo(data.equipmentId))
922 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);
923 data.equipmentId = -1;
927 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
929 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 );
930 data.curhealth = cInfo->minhealth;
933 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
935 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
936 if(!map || !map->IsDungeon())
937 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);
940 if(data.curmana < cInfo->minmana)
942 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 );
943 data.curmana = cInfo->minmana;
946 if(data.spawndist < 0.0f)
948 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
949 data.spawndist = 0.0f;
951 else if(data.movementType == RANDOM_MOTION_TYPE)
953 if(data.spawndist == 0.0f)
955 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 );
956 data.movementType = IDLE_MOTION_TYPE;
959 else if(data.movementType == IDLE_MOTION_TYPE)
961 if(data.spawndist != 0.0f)
963 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
964 data.spawndist = 0.0f;
968 if(data.phaseMask==0)
970 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
971 data.phaseMask = 1;
974 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
975 AddCreatureToGrid(guid, &data);
977 ++count;
979 } while (result->NextRow());
981 delete result;
983 sLog.outString();
984 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
987 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
989 uint8 mask = data->spawnMask;
990 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
992 if(mask & 1)
994 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
995 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
997 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
998 cell_guids.creatures.insert(guid);
1003 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1005 uint8 mask = data->spawnMask;
1006 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1008 if(mask & 1)
1010 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1011 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1013 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1014 cell_guids.creatures.erase(guid);
1019 void ObjectMgr::LoadGameobjects()
1021 uint32 count = 0;
1023 // 0 1 2 3 4 5 6
1024 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1025 // 7 8 9 10 11 12 13 14 15 16 17
1026 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1027 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1028 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1030 if(!result)
1032 barGoLink bar(1);
1034 bar.step();
1036 sLog.outString();
1037 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1038 return;
1041 barGoLink bar(result->GetRowCount());
1045 Field *fields = result->Fetch();
1046 bar.step();
1048 uint32 guid = fields[ 0].GetUInt32();
1049 uint32 entry = fields[ 1].GetUInt32();
1051 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1052 if(!gInfo)
1054 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1055 continue;
1058 GameObjectData& data = mGameObjectDataMap[guid];
1060 data.id = entry;
1061 data.mapid = fields[ 2].GetUInt32();
1062 data.posX = fields[ 3].GetFloat();
1063 data.posY = fields[ 4].GetFloat();
1064 data.posZ = fields[ 5].GetFloat();
1065 data.orientation = fields[ 6].GetFloat();
1066 data.rotation0 = fields[ 7].GetFloat();
1067 data.rotation1 = fields[ 8].GetFloat();
1068 data.rotation2 = fields[ 9].GetFloat();
1069 data.rotation3 = fields[10].GetFloat();
1070 data.spawntimesecs = fields[11].GetInt32();
1071 data.animprogress = fields[12].GetUInt32();
1072 data.go_state = fields[13].GetUInt32();
1073 data.spawnMask = fields[14].GetUInt8();
1074 data.phaseMask = fields[15].GetUInt16();
1075 int16 gameEvent = fields[16].GetInt16();
1076 int16 PoolId = fields[17].GetInt16();
1078 if(data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1080 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip",guid,data.id,data.rotation2 );
1081 continue;
1084 if(data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1086 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip",guid,data.id,data.rotation3 );
1087 continue;
1090 if(!MapManager::IsValidMapCoord(data.mapid,data.posX,data.posY,data.posZ,data.orientation))
1092 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip",guid,data.id );
1093 continue;
1096 if(data.phaseMask==0)
1098 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1099 data.phaseMask = 1;
1102 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1103 AddGameobjectToGrid(guid, &data);
1104 ++count;
1106 } while (result->NextRow());
1108 delete result;
1110 sLog.outString();
1111 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1114 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1116 uint8 mask = data->spawnMask;
1117 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1119 if(mask & 1)
1121 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1122 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1124 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1125 cell_guids.gameobjects.insert(guid);
1130 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1132 uint8 mask = data->spawnMask;
1133 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1135 if(mask & 1)
1137 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1138 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1140 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1141 cell_guids.gameobjects.erase(guid);
1146 void ObjectMgr::LoadCreatureRespawnTimes()
1148 // remove outdated data
1149 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1151 uint32 count = 0;
1153 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1155 if(!result)
1157 barGoLink bar(1);
1159 bar.step();
1161 sLog.outString();
1162 sLog.outString(">> Loaded 0 creature respawn time.");
1163 return;
1166 barGoLink bar(result->GetRowCount());
1170 Field *fields = result->Fetch();
1171 bar.step();
1173 uint32 loguid = fields[0].GetUInt32();
1174 uint64 respawn_time = fields[1].GetUInt64();
1175 uint32 instance = fields[2].GetUInt32();
1177 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1179 ++count;
1180 } while (result->NextRow());
1182 delete result;
1184 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1185 sLog.outString();
1188 void ObjectMgr::LoadGameobjectRespawnTimes()
1190 // remove outdated data
1191 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1193 uint32 count = 0;
1195 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1197 if(!result)
1199 barGoLink bar(1);
1201 bar.step();
1203 sLog.outString();
1204 sLog.outString(">> Loaded 0 gameobject respawn time.");
1205 return;
1208 barGoLink bar(result->GetRowCount());
1212 Field *fields = result->Fetch();
1213 bar.step();
1215 uint32 loguid = fields[0].GetUInt32();
1216 uint64 respawn_time = fields[1].GetUInt64();
1217 uint32 instance = fields[2].GetUInt32();
1219 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1221 ++count;
1222 } while (result->NextRow());
1224 delete result;
1226 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1227 sLog.outString();
1230 // name must be checked to correctness (if received) before call this function
1231 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1233 uint64 guid = 0;
1235 CharacterDatabase.escape_string(name);
1237 // Player name safe to sending to DB (checked at login) and this function using
1238 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1239 if(result)
1241 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1243 delete result;
1246 return guid;
1249 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1251 // prevent DB access for online player
1252 if(Player* player = GetPlayer(guid))
1254 name = player->GetName();
1255 return true;
1258 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1260 if(result)
1262 name = (*result)[0].GetCppString();
1263 delete result;
1264 return true;
1267 return false;
1270 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1272 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1274 if(result)
1276 uint8 race = (*result)[0].GetUInt8();
1277 delete result;
1278 return Player::TeamForRace(race);
1281 return 0;
1284 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1286 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1287 if(result)
1289 uint32 acc = (*result)[0].GetUInt32();
1290 delete result;
1291 return acc;
1294 return 0;
1297 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1299 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1300 if(result)
1302 uint32 acc = (*result)[0].GetUInt32();
1303 delete result;
1304 return acc;
1307 return 0;
1310 void ObjectMgr::LoadItemLocales()
1312 mItemLocaleMap.clear(); // need for reload case
1314 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");
1316 if(!result)
1318 barGoLink bar(1);
1320 bar.step();
1322 sLog.outString();
1323 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1324 return;
1327 barGoLink bar(result->GetRowCount());
1331 Field *fields = result->Fetch();
1332 bar.step();
1334 uint32 entry = fields[0].GetUInt32();
1336 ItemLocale& data = mItemLocaleMap[entry];
1338 for(int i = 1; i < MAX_LOCALE; ++i)
1340 std::string str = fields[1+2*(i-1)].GetCppString();
1341 if(!str.empty())
1343 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1344 if(idx >= 0)
1346 if(data.Name.size() <= idx)
1347 data.Name.resize(idx+1);
1349 data.Name[idx] = str;
1353 str = fields[1+2*(i-1)+1].GetCppString();
1354 if(!str.empty())
1356 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1357 if(idx >= 0)
1359 if(data.Description.size() <= idx)
1360 data.Description.resize(idx+1);
1362 data.Description[idx] = str;
1366 } while (result->NextRow());
1368 delete result;
1370 sLog.outString();
1371 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1374 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1376 template<class D>
1377 void convert_from_str(uint32 field_pos, char *src, D &dst)
1379 dst = D(objmgr.GetScriptId(src));
1383 void ObjectMgr::LoadItemPrototypes()
1385 SQLItemLoader loader;
1386 loader.Load(sItemStorage);
1387 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1388 sLog.outString();
1390 // check data correctness
1391 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1393 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1394 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1395 if(!proto)
1397 /* to many errors, and possible not all items really used in game
1398 if (dbcitem)
1399 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1401 continue;
1404 if(dbcitem)
1406 if(proto->Class != dbcitem->Class)
1408 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1409 // It safe let use Class from DB
1411 /* disabled: have some strange wrong cases for Subclass values.
1412 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1413 if(proto->SubClass != dbcitem->SubClass)
1415 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);
1416 // It safe let use Subclass from DB
1420 if(proto->Unk0 != dbcitem->Unk0)
1422 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1423 // It safe let use Unk0 from DB
1426 if(proto->Material != dbcitem->Material)
1428 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1429 // It safe let use Material from DB
1432 if(proto->InventoryType != dbcitem->InventoryType)
1434 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1435 // It safe let use InventoryType from DB
1438 if(proto->DisplayInfoID != dbcitem->DisplayId)
1440 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1441 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1443 if(proto->Sheath != dbcitem->Sheath)
1445 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1446 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1449 else
1451 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1454 if(proto->Class >= MAX_ITEM_CLASS)
1456 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1457 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1460 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1462 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1463 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1466 if(proto->Quality >= MAX_ITEM_QUALITY)
1468 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1469 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1472 if(proto->BuyCount <= 0)
1474 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1475 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1478 if(proto->InventoryType >= MAX_INVTYPE)
1480 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1481 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1484 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1486 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1487 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1492 // can be used in equip slot, as page read use in inventory, or spell casting at use
1493 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1494 if(!req)
1496 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1498 if(proto->Spells[j].SpellId)
1500 req = true;
1501 break;
1506 if(req)
1508 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1509 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1511 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1512 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1516 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1518 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1519 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1522 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1523 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1525 if(proto->RequiredReputationFaction)
1527 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1529 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1530 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1533 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1534 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1536 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1537 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1539 if(proto->MaxCount < -1)
1541 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1542 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1545 if(proto->Stackable==0)
1547 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1548 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1550 else if(proto->Stackable < -1)
1552 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1553 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1555 else if(proto->Stackable > 255)
1557 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1558 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1561 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1563 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1564 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1567 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1569 // for ItemStatValue != 0
1570 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1572 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1573 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1577 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1579 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1581 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1582 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1586 // special format
1587 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1589 // spell_1
1590 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1592 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);
1593 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1594 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1595 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1596 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1599 // spell_2 have learning spell
1600 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1602 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);
1603 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1604 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1605 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1607 else if(!proto->Spells[1].SpellId)
1609 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1610 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1611 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1613 else
1615 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1616 if(!spellInfo)
1618 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1619 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1620 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1621 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1623 // allowed only in special format
1624 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1626 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1627 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1628 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1629 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1633 // spell_3*,spell_4*,spell_5* is empty
1634 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1636 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1638 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1639 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1640 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1642 else if(proto->Spells[j].SpellId != 0)
1644 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1645 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1649 // normal spell list
1650 else
1652 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1654 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1656 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1657 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1658 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1661 if(proto->Spells[j].SpellId)
1663 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1664 if(!spellInfo)
1666 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1667 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1669 // allowed only in special format
1670 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1672 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1673 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1679 if(proto->Bonding >= MAX_BIND_TYPE)
1680 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1682 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1683 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1685 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1686 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1688 if(proto->Sheath >= MAX_SHEATHETYPE)
1690 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1691 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1694 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1696 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1697 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1700 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1702 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1703 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1706 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1708 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1709 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1712 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1713 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1715 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1716 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1718 if(proto->BagFamily)
1720 // check bits
1721 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1723 uint32 mask = 1 << j;
1724 if((proto->BagFamily & mask)==0)
1725 continue;
1727 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1728 if(!bf)
1730 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
1731 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1732 continue;
1735 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
1737 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
1738 if(!ctEntry)
1740 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
1741 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1747 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1748 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1750 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; j++)
1752 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1754 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1755 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1759 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1760 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1762 if(proto->FoodType >= MAX_PET_DIET)
1764 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1765 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1768 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1770 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1771 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1776 void ObjectMgr::LoadPetLevelInfo()
1778 // Loading levels data
1780 // 0 1 2 3 4 5 6 7 8 9
1781 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1783 uint32 count = 0;
1785 if (!result)
1787 barGoLink bar( 1 );
1789 sLog.outString();
1790 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1791 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1792 return;
1795 barGoLink bar( result->GetRowCount() );
1799 Field* fields = result->Fetch();
1801 uint32 creature_id = fields[0].GetUInt32();
1802 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1804 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1805 continue;
1808 uint32 current_level = fields[1].GetUInt32();
1809 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1811 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1812 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1813 else
1815 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1816 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
1818 continue;
1820 else if(current_level < 1)
1822 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1823 continue;
1826 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1828 if(pInfoMapEntry==NULL)
1829 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1831 // data for level 1 stored in [0] array element, ...
1832 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1834 pLevelInfo->health = fields[2].GetUInt16();
1835 pLevelInfo->mana = fields[3].GetUInt16();
1836 pLevelInfo->armor = fields[9].GetUInt16();
1838 for (int i = 0; i < MAX_STATS; i++)
1840 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1843 bar.step();
1844 ++count;
1846 while (result->NextRow());
1848 delete result;
1850 sLog.outString();
1851 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1854 // Fill gaps and check integrity
1855 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1857 PetLevelInfo* pInfo = itr->second;
1859 // fatal error if no level 1 data
1860 if(!pInfo || pInfo[0].health == 0 )
1862 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1863 exit(1);
1866 // fill level gaps
1867 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1869 if(pInfo[level].health == 0)
1871 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1872 pInfo[level] = pInfo[level-1];
1878 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1880 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1881 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1883 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1884 if(itr == petInfo.end())
1885 return NULL;
1887 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1890 void ObjectMgr::LoadPlayerInfo()
1892 // Load playercreate
1894 // 0 1 2 3 4 5 6
1895 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1897 uint32 count = 0;
1899 if (!result)
1901 barGoLink bar( 1 );
1903 sLog.outString();
1904 sLog.outString( ">> Loaded %u player create definitions", count );
1905 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1906 exit(1);
1909 barGoLink bar( result->GetRowCount() );
1913 Field* fields = result->Fetch();
1915 uint32 current_race = fields[0].GetUInt32();
1916 uint32 current_class = fields[1].GetUInt32();
1917 uint32 mapId = fields[2].GetUInt32();
1918 uint32 zoneId = fields[3].GetUInt32();
1919 float positionX = fields[4].GetFloat();
1920 float positionY = fields[5].GetFloat();
1921 float positionZ = fields[6].GetFloat();
1923 if(current_race >= MAX_RACES)
1925 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1926 continue;
1929 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1930 if(!rEntry)
1932 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1933 continue;
1936 if(current_class >= MAX_CLASSES)
1938 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1939 continue;
1942 if(!sChrClassesStore.LookupEntry(current_class))
1944 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1945 continue;
1948 // accept DB data only for valid position (and non instanceable)
1949 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1951 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1952 continue;
1955 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1957 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1958 continue;
1961 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1963 pInfo->mapId = mapId;
1964 pInfo->zoneId = zoneId;
1965 pInfo->positionX = positionX;
1966 pInfo->positionY = positionY;
1967 pInfo->positionZ = positionZ;
1969 pInfo->displayId_m = rEntry->model_m;
1970 pInfo->displayId_f = rEntry->model_f;
1972 bar.step();
1973 ++count;
1975 while (result->NextRow());
1977 delete result;
1979 sLog.outString();
1980 sLog.outString( ">> Loaded %u player create definitions", count );
1983 // Load playercreate items
1985 // 0 1 2 3
1986 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
1988 uint32 count = 0;
1990 if (!result)
1992 barGoLink bar( 1 );
1994 bar.step();
1996 sLog.outString();
1997 sLog.outString( ">> Loaded %u custom player create items", count );
1999 else
2001 barGoLink bar( result->GetRowCount() );
2005 Field* fields = result->Fetch();
2007 uint32 current_race = fields[0].GetUInt32();
2008 if(current_race >= MAX_RACES)
2010 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2011 continue;
2014 uint32 current_class = fields[1].GetUInt32();
2015 if(current_class >= MAX_CLASSES)
2017 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2018 continue;
2021 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2023 uint32 item_id = fields[2].GetUInt32();
2025 if(!GetItemPrototype(item_id))
2027 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);
2028 continue;
2031 uint32 amount = fields[3].GetUInt32();
2033 if(!amount)
2035 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2036 continue;
2039 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2041 bar.step();
2042 ++count;
2044 while(result->NextRow());
2046 delete result;
2048 sLog.outString();
2049 sLog.outString( ">> Loaded %u custom player create items", count );
2053 // Load playercreate spells
2055 // 0 1 2
2056 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2058 uint32 count = 0;
2060 if (!result)
2062 barGoLink bar( 1 );
2064 sLog.outString();
2065 sLog.outString( ">> Loaded %u player create spells", count );
2066 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2068 else
2070 barGoLink bar( result->GetRowCount() );
2074 Field* fields = result->Fetch();
2076 uint32 current_race = fields[0].GetUInt32();
2077 if(current_race >= MAX_RACES)
2079 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2080 continue;
2083 uint32 current_class = fields[1].GetUInt32();
2084 if(current_class >= MAX_CLASSES)
2086 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2087 continue;
2090 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2091 pInfo->spell.push_back(fields[2].GetUInt32());
2093 bar.step();
2094 ++count;
2096 while( result->NextRow() );
2098 delete result;
2100 sLog.outString();
2101 sLog.outString( ">> Loaded %u player create spells", count );
2105 // Load playercreate actions
2107 // 0 1 2 3 4 5
2108 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2110 uint32 count = 0;
2112 if (!result)
2114 barGoLink bar( 1 );
2116 sLog.outString();
2117 sLog.outString( ">> Loaded %u player create actions", count );
2118 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2120 else
2122 barGoLink bar( result->GetRowCount() );
2126 Field* fields = result->Fetch();
2128 uint32 current_race = fields[0].GetUInt32();
2129 if(current_race >= MAX_RACES)
2131 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2132 continue;
2135 uint32 current_class = fields[1].GetUInt32();
2136 if(current_class >= MAX_CLASSES)
2138 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2139 continue;
2142 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2143 pInfo->action[0].push_back(fields[2].GetUInt16());
2144 pInfo->action[1].push_back(fields[3].GetUInt16());
2145 pInfo->action[2].push_back(fields[4].GetUInt16());
2146 pInfo->action[3].push_back(fields[5].GetUInt16());
2148 bar.step();
2149 ++count;
2151 while( result->NextRow() );
2153 delete result;
2155 sLog.outString();
2156 sLog.outString( ">> Loaded %u player create actions", count );
2160 // Loading levels data (class only dependent)
2162 // 0 1 2 3
2163 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2165 uint32 count = 0;
2167 if (!result)
2169 barGoLink bar( 1 );
2171 sLog.outString();
2172 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2173 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2174 exit(1);
2177 barGoLink bar( result->GetRowCount() );
2181 Field* fields = result->Fetch();
2183 uint32 current_class = fields[0].GetUInt32();
2184 if(current_class >= MAX_CLASSES)
2186 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2187 continue;
2190 uint32 current_level = fields[1].GetUInt32();
2191 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2193 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2194 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2195 else
2197 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2198 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2200 continue;
2203 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2205 if(!pClassInfo->levelInfo)
2206 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2208 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2210 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2211 pClassLevelInfo->basemana = fields[3].GetUInt16();
2213 bar.step();
2214 ++count;
2216 while (result->NextRow());
2218 delete result;
2220 sLog.outString();
2221 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2224 // Fill gaps and check integrity
2225 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2227 // skip non existed classes
2228 if(!sChrClassesStore.LookupEntry(class_))
2229 continue;
2231 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2233 // fatal error if no level 1 data
2234 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2236 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2237 exit(1);
2240 // fill level gaps
2241 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2243 if(pClassInfo->levelInfo[level].basehealth == 0)
2245 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2246 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2251 // Loading levels data (class/race dependent)
2253 // 0 1 2 3 4 5 6 7
2254 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2256 uint32 count = 0;
2258 if (!result)
2260 barGoLink bar( 1 );
2262 sLog.outString();
2263 sLog.outString( ">> Loaded %u level stats definitions", count );
2264 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2265 exit(1);
2268 barGoLink bar( result->GetRowCount() );
2272 Field* fields = result->Fetch();
2274 uint32 current_race = fields[0].GetUInt32();
2275 if(current_race >= MAX_RACES)
2277 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2278 continue;
2281 uint32 current_class = fields[1].GetUInt32();
2282 if(current_class >= MAX_CLASSES)
2284 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2285 continue;
2288 uint32 current_level = fields[2].GetUInt32();
2289 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2291 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2292 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2293 else
2295 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2296 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2298 continue;
2301 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2303 if(!pInfo->levelInfo)
2304 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2306 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2308 for (int i = 0; i < MAX_STATS; i++)
2310 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2313 bar.step();
2314 ++count;
2316 while (result->NextRow());
2318 delete result;
2320 sLog.outString();
2321 sLog.outString( ">> Loaded %u level stats definitions", count );
2324 // Fill gaps and check integrity
2325 for (int race = 0; race < MAX_RACES; ++race)
2327 // skip non existed races
2328 if(!sChrRacesStore.LookupEntry(race))
2329 continue;
2331 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2333 // skip non existed classes
2334 if(!sChrClassesStore.LookupEntry(class_))
2335 continue;
2337 PlayerInfo* pInfo = &playerInfo[race][class_];
2339 // skip non loaded combinations
2340 if(!pInfo->displayId_m || !pInfo->displayId_f)
2341 continue;
2343 // skip expansion races if not playing with expansion
2344 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2345 continue;
2347 // skip expansion classes if not playing with expansion
2348 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2349 continue;
2351 // fatal error if no level 1 data
2352 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2354 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2355 exit(1);
2358 // fill level gaps
2359 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2361 if(pInfo->levelInfo[level].stats[0] == 0)
2363 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2364 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2370 // Loading xp per level data
2372 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2373 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2374 mPlayerXPperLevel[level] = 0;
2376 // 0 1
2377 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2379 uint32 count = 0;
2381 if (!result)
2383 barGoLink bar( 1 );
2385 sLog.outString();
2386 sLog.outString( ">> Loaded %u xp for level definitions", count );
2387 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2388 exit(1);
2391 barGoLink bar( result->GetRowCount() );
2395 Field* fields = result->Fetch();
2397 uint32 current_level = fields[0].GetUInt32();
2398 uint32 current_xp = fields[1].GetUInt32();
2400 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2402 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2403 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2404 else
2406 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2407 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2409 continue;
2411 //PlayerXPperLevel
2412 mPlayerXPperLevel[current_level] = current_xp;
2413 bar.step();
2414 ++count;
2416 while (result->NextRow());
2418 delete result;
2420 sLog.outString();
2421 sLog.outString( ">> Loaded %u xp for level definitions", count );
2424 // fill level gaps
2425 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2427 if( mPlayerXPperLevel[level] == 0)
2429 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2430 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2435 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2437 if(level < 1 || class_ >= MAX_CLASSES)
2438 return;
2440 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2442 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2443 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2445 *info = pInfo->levelInfo[level-1];
2448 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2450 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2451 return;
2453 PlayerInfo const* pInfo = &playerInfo[race][class_];
2454 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2455 return;
2457 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2458 *info = pInfo->levelInfo[level-1];
2459 else
2460 BuildPlayerLevelInfo(race,class_,level,info);
2463 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2465 // base data (last known level)
2466 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2468 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2470 switch(_class)
2472 case CLASS_WARRIOR:
2473 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2474 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2475 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2476 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2477 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2478 break;
2479 case CLASS_PALADIN:
2480 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2481 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2482 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2483 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2484 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2485 break;
2486 case CLASS_HUNTER:
2487 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2488 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2489 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2490 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2491 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2492 break;
2493 case CLASS_ROGUE:
2494 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2495 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2496 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2497 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2498 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2499 break;
2500 case CLASS_PRIEST:
2501 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2502 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2503 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2504 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2505 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2506 break;
2507 case CLASS_SHAMAN:
2508 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2509 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2510 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2511 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2512 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2513 break;
2514 case CLASS_MAGE:
2515 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2516 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2517 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2518 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2519 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2520 break;
2521 case CLASS_WARLOCK:
2522 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2523 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2524 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2525 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2526 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2527 break;
2528 case CLASS_DRUID:
2529 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2530 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2531 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2532 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2533 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2538 void ObjectMgr::LoadGuilds()
2540 Guild *newguild;
2541 uint32 count = 0;
2543 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2545 if( !result )
2548 barGoLink bar( 1 );
2550 bar.step();
2552 sLog.outString();
2553 sLog.outString( ">> Loaded %u guild definitions", count );
2554 return;
2557 barGoLink bar( result->GetRowCount() );
2561 Field *fields = result->Fetch();
2563 bar.step();
2564 ++count;
2566 newguild = new Guild;
2567 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2569 newguild->Disband();
2570 delete newguild;
2571 continue;
2573 AddGuild(newguild);
2575 }while( result->NextRow() );
2577 delete result;
2579 sLog.outString();
2580 sLog.outString( ">> Loaded %u guild definitions", count );
2583 void ObjectMgr::LoadArenaTeams()
2585 uint32 count = 0;
2587 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2589 if( !result )
2592 barGoLink bar( 1 );
2594 bar.step();
2596 sLog.outString();
2597 sLog.outString( ">> Loaded %u arenateam definitions", count );
2598 return;
2601 barGoLink bar( result->GetRowCount() );
2605 Field *fields = result->Fetch();
2607 bar.step();
2608 ++count;
2610 ArenaTeam *newarenateam = new ArenaTeam;
2611 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2613 delete newarenateam;
2614 continue;
2616 AddArenaTeam(newarenateam);
2617 }while( result->NextRow() );
2619 delete result;
2621 sLog.outString();
2622 sLog.outString( ">> Loaded %u arenateam definitions", count );
2625 void ObjectMgr::LoadGroups()
2627 // -- loading groups --
2628 Group *group = NULL;
2629 uint64 leaderGuid = 0;
2630 uint32 count = 0;
2631 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2632 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2634 if( !result )
2636 barGoLink bar( 1 );
2638 bar.step();
2640 sLog.outString();
2641 sLog.outString( ">> Loaded %u group definitions", count );
2642 return;
2645 barGoLink bar( result->GetRowCount() );
2649 bar.step();
2650 Field *fields = result->Fetch();
2651 ++count;
2652 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2654 group = new Group;
2655 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2657 group->Disband();
2658 delete group;
2659 continue;
2661 AddGroup(group);
2662 }while( result->NextRow() );
2664 delete result;
2666 sLog.outString();
2667 sLog.outString( ">> Loaded %u group definitions", count );
2669 // -- loading members --
2670 count = 0;
2671 group = NULL;
2672 leaderGuid = 0;
2673 // 0 1 2 3
2674 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2675 if(!result)
2677 barGoLink bar( 1 );
2678 bar.step();
2680 else
2682 barGoLink bar( result->GetRowCount() );
2685 bar.step();
2686 Field *fields = result->Fetch();
2687 count++;
2688 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2689 if(!group || group->GetLeaderGUID() != leaderGuid)
2691 group = GetGroupByLeader(leaderGuid);
2692 if(!group)
2694 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2695 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2696 continue;
2700 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2702 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2703 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2705 }while( result->NextRow() );
2706 delete result;
2709 // clean groups
2710 // TODO: maybe delete from the DB before loading in this case
2711 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2713 if((*itr)->GetMembersCount() < 2)
2715 (*itr)->Disband();
2716 delete *itr;
2717 mGroupSet.erase(itr++);
2719 else
2720 ++itr;
2723 // -- loading instances --
2724 count = 0;
2725 group = NULL;
2726 leaderGuid = 0;
2727 result = CharacterDatabase.Query(
2728 // 0 1 2 3 4 5
2729 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2730 // 6
2731 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2732 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2735 if(!result)
2737 barGoLink bar( 1 );
2738 bar.step();
2740 else
2742 barGoLink bar( result->GetRowCount() );
2745 bar.step();
2746 Field *fields = result->Fetch();
2747 count++;
2748 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2749 if(!group || group->GetLeaderGUID() != leaderGuid)
2751 group = GetGroupByLeader(leaderGuid);
2752 if(!group)
2754 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2755 continue;
2759 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
2760 if(!mapEntry || !mapEntry->IsDungeon())
2762 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
2763 continue;
2766 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2767 group->BindToInstance(save, fields[3].GetBool(), true);
2768 }while( result->NextRow() );
2769 delete result;
2772 sLog.outString();
2773 sLog.outString( ">> Loaded %u group-instance binds total", count );
2775 sLog.outString();
2776 sLog.outString( ">> Loaded %u group members total", count );
2779 void ObjectMgr::LoadQuests()
2781 // For reload case
2782 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2783 delete itr->second;
2784 mQuestTemplates.clear();
2786 mExclusiveQuestGroups.clear();
2788 // 0 1 2 3 4 5 6 7 8
2789 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2790 // 9 10 11 12 13 14 15 16
2791 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2792 // 17 18 19 20 21 22 23 24 25 26 27 28
2793 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2794 // 29 30 31 32 33 34 35 36 37 38
2795 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2796 // 39 40 41 42 43 44 45 46
2797 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2798 // 47 48 49 50 51 52 53 54
2799 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
2800 // 55 56 57 58 59 60 61 62
2801 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2802 // 63 64 65 66
2803 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2804 // 67 68 69 70 71 72
2805 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2806 // 73 74 75 76 77 78
2807 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2808 // 79 80 81 82 83 84 85 86
2809 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2810 // 87 88 89 90 91 92 93 94 95 96
2811 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2812 // 97 98 99 100 101 102 103 104 105 106 107
2813 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2814 // 108 109 110 111 112 113 114 115 116 117
2815 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2816 // 118 119
2817 "StartScript, CompleteScript"
2818 " FROM quest_template");
2819 if(result == NULL)
2821 barGoLink bar( 1 );
2822 bar.step();
2824 sLog.outString();
2825 sLog.outString( ">> Loaded 0 quests definitions" );
2826 sLog.outErrorDb("`quest_template` table is empty!");
2827 return;
2830 // create multimap previous quest for each existed quest
2831 // some quests can have many previous maps set by NextQuestId in previous quest
2832 // for example set of race quests can lead to single not race specific quest
2833 barGoLink bar( result->GetRowCount() );
2836 bar.step();
2837 Field *fields = result->Fetch();
2839 Quest * newQuest = new Quest(fields);
2840 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2841 } while( result->NextRow() );
2843 delete result;
2845 // Post processing
2846 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2848 Quest * qinfo = iter->second;
2850 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2852 if( qinfo->GetQuestMethod() >= 3 )
2854 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2857 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2859 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2860 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2861 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2864 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2866 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2868 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2869 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2873 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2875 // at auto-reward can be rewarded only RewChoiceItemId[0]
2876 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2878 if(uint32 id = qinfo->RewChoiceItemId[j])
2880 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2881 qinfo->GetQuestId(),j+1,id,j+1);
2882 // no changes, quest ignore this data
2887 // client quest log visual (area case)
2888 if( qinfo->ZoneOrSort > 0 )
2890 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2892 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2893 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2894 // no changes, quest not dependent from this value but can have problems at client
2897 // client quest log visual (sort case)
2898 if( qinfo->ZoneOrSort < 0 )
2900 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2901 if( !qSort )
2903 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2904 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2905 // 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)
2907 //check SkillOrClass value (class case).
2908 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2910 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2911 if(qinfo->SkillOrClass < 0)
2913 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2914 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2917 //check for proper SkillOrClass value (skill case)
2918 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2920 // skill is positive value in SkillOrClass
2921 if(qinfo->SkillOrClass != skill_id )
2923 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2924 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2925 //override, and force proper value here?
2930 // SkillOrClass (class case)
2931 if( qinfo->SkillOrClass < 0 )
2933 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2935 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2936 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2939 // SkillOrClass (skill case)
2940 if( qinfo->SkillOrClass > 0 )
2942 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2944 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2945 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2949 if( qinfo->RequiredSkillValue )
2951 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2953 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2954 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2955 // no changes, quest can't be done for this requirement
2958 if( qinfo->SkillOrClass <= 0 )
2960 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2961 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2962 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2965 // else Skill quests can have 0 skill level, this is ok
2967 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2969 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2970 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2971 // no changes, quest can't be done for this requirement
2974 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2976 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2977 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2978 // no changes, quest can't be done for this requirement
2981 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2983 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2984 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2985 // no changes, quest can't be done for this requirement
2988 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
2990 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2991 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
2992 // no changes, quest can't be done for this requirement
2995 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2997 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2998 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2999 // no changes, quest can't be done for this requirement
3002 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3004 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3005 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3006 // warning
3009 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3011 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3012 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3013 // warning
3016 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3018 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3019 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3020 // warning
3023 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3025 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3026 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3027 qinfo->CharTitleId = 0;
3028 // quest can't reward this title
3031 if(qinfo->SrcItemId)
3033 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3035 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3036 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3037 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3039 else if(qinfo->SrcItemCount==0)
3041 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3042 qinfo->GetQuestId(),qinfo->SrcItemId);
3043 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3046 else if(qinfo->SrcItemCount>0)
3048 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3049 qinfo->GetQuestId(),qinfo->SrcItemCount);
3050 qinfo->SrcItemCount=0; // no quest work changes in fact
3053 if(qinfo->SrcSpell)
3055 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3056 if(!spellInfo)
3058 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3059 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3060 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3062 else if(!SpellMgr::IsSpellValid(spellInfo))
3064 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3065 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3066 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3070 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3072 uint32 id = qinfo->ReqItemId[j];
3073 if(id)
3075 if(qinfo->ReqItemCount[j]==0)
3077 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3078 qinfo->GetQuestId(),j+1,id,j+1);
3079 // no changes, quest can't be done for this requirement
3082 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3084 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3086 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3087 qinfo->GetQuestId(),j+1,id,id);
3088 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3091 else if(qinfo->ReqItemCount[j]>0)
3093 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3094 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3095 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3099 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3101 uint32 id = qinfo->ReqSourceId[j];
3102 if(id)
3104 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3106 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3107 qinfo->GetQuestId(),j+1,id,id);
3108 // no changes, quest can't be done for this requirement
3111 else
3113 if(qinfo->ReqSourceCount[j]>0)
3115 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3116 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3117 // no changes, quest ignore this data
3122 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3124 uint32 id = qinfo->ReqSpell[j];
3125 if(id)
3127 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3128 if(!spellInfo)
3130 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3131 qinfo->GetQuestId(),j+1,id,id);
3132 // no changes, quest can't be done for this requirement
3135 if(!qinfo->ReqCreatureOrGOId[j])
3137 bool found = false;
3138 for(int k = 0; k < 3; ++k)
3140 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3141 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3143 found = true;
3144 break;
3148 if(found)
3150 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3152 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);
3154 // this will prevent quest completing without objective
3155 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3158 else
3160 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.",
3161 qinfo->GetQuestId(),j+1,id,j+1,id);
3162 // no changes, quest can't be done for this requirement
3168 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3170 int32 id = qinfo->ReqCreatureOrGOId[j];
3171 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3173 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3174 qinfo->GetQuestId(),j+1,id,uint32(-id));
3175 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3178 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3180 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3181 qinfo->GetQuestId(),j+1,id,uint32(id));
3182 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3185 if(id)
3187 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3189 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3191 if(!qinfo->ReqCreatureOrGOCount[j])
3193 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3194 qinfo->GetQuestId(),j+1,id,j+1);
3195 // no changes, quest can be incorrectly done, but we already report this
3198 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3200 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3201 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3202 // no changes, quest ignore this data
3206 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3208 uint32 id = qinfo->RewChoiceItemId[j];
3209 if(id)
3211 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3213 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3214 qinfo->GetQuestId(),j+1,id,id);
3215 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3218 if(!qinfo->RewChoiceItemCount[j])
3220 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3221 qinfo->GetQuestId(),j+1,id,j+1);
3222 // no changes, quest can't be done
3225 else if(qinfo->RewChoiceItemCount[j]>0)
3227 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3228 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3229 // no changes, quest ignore this data
3233 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3235 uint32 id = qinfo->RewItemId[j];
3236 if(id)
3238 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3240 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3241 qinfo->GetQuestId(),j+1,id,id);
3242 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3245 if(!qinfo->RewItemCount[j])
3247 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3248 qinfo->GetQuestId(),j+1,id,j+1);
3249 // no changes
3252 else if(qinfo->RewItemCount[j]>0)
3254 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3255 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3256 // no changes, quest ignore this data
3260 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3262 if(qinfo->RewRepFaction[j])
3264 if(!qinfo->RewRepValue[j])
3266 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3267 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3268 // no changes
3271 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3273 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.",
3274 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3275 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3278 else if(qinfo->RewRepValue[j]!=0)
3280 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3281 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3282 // no changes, quest ignore this data
3286 if(qinfo->RewSpell)
3288 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3290 if(!spellInfo)
3292 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3293 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3294 qinfo->RewSpell = 0; // no spell reward will display for this quest
3297 else if(!SpellMgr::IsSpellValid(spellInfo))
3299 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3300 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3301 qinfo->RewSpell = 0; // no spell reward will display for this quest
3306 if(qinfo->RewSpellCast)
3308 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3310 if(!spellInfo)
3312 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3313 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3314 qinfo->RewSpellCast = 0; // no spell will be casted on player
3317 else if(!SpellMgr::IsSpellValid(spellInfo))
3319 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3320 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3321 qinfo->RewSpellCast = 0; // no spell will be casted on player
3326 if(qinfo->RewMailTemplateId)
3328 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3330 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3331 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3332 qinfo->RewMailTemplateId = 0; // no mail will send to player
3333 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3337 if(qinfo->NextQuestInChain)
3339 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3340 if(qNextItr == mQuestTemplates.end())
3342 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3343 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3344 qinfo->NextQuestInChain = 0;
3346 else
3347 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3350 // fill additional data stores
3351 if(qinfo->PrevQuestId)
3353 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3355 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3357 else
3359 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3363 if(qinfo->NextQuestId)
3365 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3366 if (qNextItr == mQuestTemplates.end())
3368 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3370 else
3372 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3373 qNextItr->second->prevQuests.push_back(signedQuestId);
3377 if(qinfo->ExclusiveGroup)
3378 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3379 if(qinfo->LimitTime)
3380 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3383 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3384 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3386 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3387 if(!spellInfo)
3388 continue;
3390 for(int j = 0; j < 3; ++j)
3392 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3393 continue;
3395 uint32 quest_id = spellInfo->EffectMiscValue[j];
3397 Quest const* quest = GetQuestTemplate(quest_id);
3399 // some quest referenced in spells not exist (outdated spells)
3400 if(!quest)
3401 continue;
3403 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3405 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);
3407 // this will prevent quest completing without objective
3408 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3413 sLog.outString();
3414 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3417 void ObjectMgr::LoadQuestLocales()
3419 mQuestLocaleMap.clear(); // need for reload case
3421 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3422 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3423 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3424 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3425 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3426 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3427 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3428 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3429 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3430 " FROM locales_quest"
3433 if(!result)
3435 barGoLink bar(1);
3437 bar.step();
3439 sLog.outString();
3440 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3441 return;
3444 barGoLink bar(result->GetRowCount());
3448 Field *fields = result->Fetch();
3449 bar.step();
3451 uint32 entry = fields[0].GetUInt32();
3453 QuestLocale& data = mQuestLocaleMap[entry];
3455 for(int i = 1; i < MAX_LOCALE; ++i)
3457 std::string str = fields[1+10*(i-1)].GetCppString();
3458 if(!str.empty())
3460 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3461 if(idx >= 0)
3463 if(data.Title.size() <= idx)
3464 data.Title.resize(idx+1);
3466 data.Title[idx] = str;
3469 str = fields[1+10*(i-1)+1].GetCppString();
3470 if(!str.empty())
3472 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3473 if(idx >= 0)
3475 if(data.Details.size() <= idx)
3476 data.Details.resize(idx+1);
3478 data.Details[idx] = str;
3481 str = fields[1+10*(i-1)+2].GetCppString();
3482 if(!str.empty())
3484 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3485 if(idx >= 0)
3487 if(data.Objectives.size() <= idx)
3488 data.Objectives.resize(idx+1);
3490 data.Objectives[idx] = str;
3493 str = fields[1+10*(i-1)+3].GetCppString();
3494 if(!str.empty())
3496 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3497 if(idx >= 0)
3499 if(data.OfferRewardText.size() <= idx)
3500 data.OfferRewardText.resize(idx+1);
3502 data.OfferRewardText[idx] = str;
3505 str = fields[1+10*(i-1)+4].GetCppString();
3506 if(!str.empty())
3508 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3509 if(idx >= 0)
3511 if(data.RequestItemsText.size() <= idx)
3512 data.RequestItemsText.resize(idx+1);
3514 data.RequestItemsText[idx] = str;
3517 str = fields[1+10*(i-1)+5].GetCppString();
3518 if(!str.empty())
3520 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3521 if(idx >= 0)
3523 if(data.EndText.size() <= idx)
3524 data.EndText.resize(idx+1);
3526 data.EndText[idx] = str;
3529 for(int k = 0; k < 4; ++k)
3531 str = fields[1+10*(i-1)+6+k].GetCppString();
3532 if(!str.empty())
3534 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3535 if(idx >= 0)
3537 if(data.ObjectiveText[k].size() <= idx)
3538 data.ObjectiveText[k].resize(idx+1);
3540 data.ObjectiveText[k][idx] = str;
3545 } while (result->NextRow());
3547 delete result;
3549 sLog.outString();
3550 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3553 void ObjectMgr::LoadPetCreateSpells()
3555 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3556 if(!result)
3558 barGoLink bar( 1 );
3559 bar.step();
3561 sLog.outString();
3562 sLog.outString( ">> Loaded 0 pet create spells" );
3563 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3564 return;
3567 uint32 count = 0;
3569 barGoLink bar( result->GetRowCount() );
3571 mPetCreateSpell.clear();
3575 Field *fields = result->Fetch();
3576 bar.step();
3578 uint32 creature_id = fields[0].GetUInt32();
3580 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3581 continue;
3583 PetCreateSpellEntry PetCreateSpell;
3584 for(int i = 0; i < 4; i++)
3586 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3588 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3589 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3592 mPetCreateSpell[creature_id] = PetCreateSpell;
3594 ++count;
3596 while (result->NextRow());
3598 delete result;
3600 sLog.outString();
3601 sLog.outString( ">> Loaded %u pet create spells", count );
3604 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3606 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3607 return;
3609 sLog.outString( "%s :", tablename);
3611 scripts.clear(); // need for reload support
3613 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3615 uint32 count = 0;
3617 if( !result )
3619 barGoLink bar( 1 );
3620 bar.step();
3622 sLog.outString();
3623 sLog.outString( ">> Loaded %u script definitions", count );
3624 return;
3627 barGoLink bar( result->GetRowCount() );
3631 bar.step();
3633 Field *fields = result->Fetch();
3634 ScriptInfo tmp;
3635 tmp.id = fields[0].GetUInt32();
3636 tmp.delay = fields[1].GetUInt32();
3637 tmp.command = fields[2].GetUInt32();
3638 tmp.datalong = fields[3].GetUInt32();
3639 tmp.datalong2 = fields[4].GetUInt32();
3640 tmp.dataint = fields[5].GetInt32();
3641 tmp.x = fields[6].GetFloat();
3642 tmp.y = fields[7].GetFloat();
3643 tmp.z = fields[8].GetFloat();
3644 tmp.o = fields[9].GetFloat();
3646 // generic command args check
3647 switch(tmp.command)
3649 case SCRIPT_COMMAND_TALK:
3651 if(tmp.datalong > 3)
3653 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3654 continue;
3656 if(tmp.dataint==0)
3658 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3659 continue;
3661 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3663 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);
3664 continue;
3667 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3668 break;
3671 case SCRIPT_COMMAND_TELEPORT_TO:
3673 if(!sMapStore.LookupEntry(tmp.datalong))
3675 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3676 continue;
3679 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3681 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);
3682 continue;
3684 break;
3687 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3689 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3691 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);
3692 continue;
3695 if(!GetCreatureTemplate(tmp.datalong))
3697 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3698 continue;
3700 break;
3703 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3705 GameObjectData const* data = GetGOData(tmp.datalong);
3706 if(!data)
3708 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3709 continue;
3712 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3713 if(!info)
3715 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);
3716 continue;
3719 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3720 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3721 info->type==GAMEOBJECT_TYPE_DOOR ||
3722 info->type==GAMEOBJECT_TYPE_BUTTON ||
3723 info->type==GAMEOBJECT_TYPE_TRAP )
3725 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3726 continue;
3728 break;
3730 case SCRIPT_COMMAND_OPEN_DOOR:
3731 case SCRIPT_COMMAND_CLOSE_DOOR:
3733 GameObjectData const* data = GetGOData(tmp.datalong);
3734 if(!data)
3736 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);
3737 continue;
3740 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3741 if(!info)
3743 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);
3744 continue;
3747 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3749 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);
3750 continue;
3753 break;
3755 case SCRIPT_COMMAND_QUEST_EXPLORED:
3757 Quest const* quest = GetQuestTemplate(tmp.datalong);
3758 if(!quest)
3760 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);
3761 continue;
3764 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3766 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);
3768 // this will prevent quest completing without objective
3769 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3771 // continue; - quest objective requirement set and command can be allowed
3774 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3776 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",
3777 tablename,tmp.datalong2,tmp.id);
3778 continue;
3781 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3783 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",
3784 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3785 continue;
3788 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3790 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",
3791 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3792 continue;
3795 break;
3798 case SCRIPT_COMMAND_REMOVE_AURA:
3800 if(!sSpellStore.LookupEntry(tmp.datalong))
3802 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3803 tablename,tmp.datalong,tmp.id);
3804 continue;
3806 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3808 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3809 tablename,tmp.datalong2,tmp.id);
3810 continue;
3812 break;
3814 case SCRIPT_COMMAND_CAST_SPELL:
3816 if(!sSpellStore.LookupEntry(tmp.datalong))
3818 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3819 tablename,tmp.datalong,tmp.id);
3820 continue;
3822 if(tmp.datalong2 & ~0x3) // 2 bits
3824 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3825 tablename,tmp.datalong2,tmp.id);
3826 continue;
3828 break;
3832 if (scripts.find(tmp.id) == scripts.end())
3834 ScriptMap emptyMap;
3835 scripts[tmp.id] = emptyMap;
3837 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3839 ++count;
3840 } while( result->NextRow() );
3842 delete result;
3844 sLog.outString();
3845 sLog.outString( ">> Loaded %u script definitions", count );
3848 void ObjectMgr::LoadGameObjectScripts()
3850 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3852 // check ids
3853 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3855 if(!GetGOData(itr->first))
3856 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3860 void ObjectMgr::LoadQuestEndScripts()
3862 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3864 // check ids
3865 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3867 if(!GetQuestTemplate(itr->first))
3868 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3872 void ObjectMgr::LoadQuestStartScripts()
3874 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3876 // check ids
3877 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3879 if(!GetQuestTemplate(itr->first))
3880 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3884 void ObjectMgr::LoadSpellScripts()
3886 LoadScripts(sSpellScripts, "spell_scripts");
3888 // check ids
3889 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3891 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3893 if(!spellInfo)
3895 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3896 continue;
3899 //check for correct spellEffect
3900 bool found = false;
3901 for(int i=0; i<3; ++i)
3903 // skip empty effects
3904 if( !spellInfo->Effect[i] )
3905 continue;
3907 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3909 found = true;
3910 break;
3914 if(!found)
3915 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3919 void ObjectMgr::LoadEventScripts()
3921 LoadScripts(sEventScripts, "event_scripts");
3923 std::set<uint32> evt_scripts;
3924 // Load all possible script entries from gameobjects
3925 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3927 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3928 if (goInfo)
3930 switch(goInfo->type)
3932 case GAMEOBJECT_TYPE_GOOBER:
3933 if(goInfo->goober.eventId)
3934 evt_scripts.insert(goInfo->goober.eventId);
3935 break;
3936 case GAMEOBJECT_TYPE_CHEST:
3937 if(goInfo->chest.eventId)
3938 evt_scripts.insert(goInfo->chest.eventId);
3939 break;
3940 default:
3941 break;
3945 // Load all possible script entries from spells
3946 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3948 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3949 if (spell)
3951 for(int j=0; j<3; ++j)
3953 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3955 if (spell->EffectMiscValue[j])
3956 evt_scripts.insert(spell->EffectMiscValue[j]);
3961 // Then check if all scripts are in above list of possible script entries
3962 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3964 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3965 if (itr2 == evt_scripts.end())
3966 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);
3970 void ObjectMgr::LoadItemTexts()
3972 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3974 uint32 count = 0;
3976 if( !result )
3978 barGoLink bar( 1 );
3979 bar.step();
3981 sLog.outString();
3982 sLog.outString( ">> Loaded %u item pages", count );
3983 return;
3986 barGoLink bar( result->GetRowCount() );
3988 Field* fields;
3991 bar.step();
3993 fields = result->Fetch();
3995 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3997 ++count;
3999 } while ( result->NextRow() );
4001 delete result;
4003 sLog.outString();
4004 sLog.outString( ">> Loaded %u item texts", count );
4007 void ObjectMgr::LoadPageTexts()
4009 sPageTextStore.Free(); // for reload case
4011 sPageTextStore.Load();
4012 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4013 sLog.outString();
4015 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4017 // check data correctness
4018 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4019 if(!page)
4020 continue;
4022 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4024 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4025 continue;
4028 // detect circular reference
4029 std::set<uint32> checkedPages;
4030 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4032 if(!pageItr->Next_Page)
4033 break;
4034 checkedPages.insert(pageItr->Page_ID);
4035 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4037 std::ostringstream ss;
4038 ss<< "The text page(s) ";
4039 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4040 ss << *itr << " ";
4041 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4042 << pageItr->Page_ID <<" to 0";
4043 sLog.outErrorDb(ss.str().c_str());
4044 const_cast<PageText*>(pageItr)->Next_Page = 0;
4045 break;
4051 void ObjectMgr::LoadPageTextLocales()
4053 mPageTextLocaleMap.clear(); // need for reload case
4055 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");
4057 if(!result)
4059 barGoLink bar(1);
4061 bar.step();
4063 sLog.outString();
4064 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4065 return;
4068 barGoLink bar(result->GetRowCount());
4072 Field *fields = result->Fetch();
4073 bar.step();
4075 uint32 entry = fields[0].GetUInt32();
4077 PageTextLocale& data = mPageTextLocaleMap[entry];
4079 for(int i = 1; i < MAX_LOCALE; ++i)
4081 std::string str = fields[i].GetCppString();
4082 if(str.empty())
4083 continue;
4085 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4086 if(idx >= 0)
4088 if(data.Text.size() <= idx)
4089 data.Text.resize(idx+1);
4091 data.Text[idx] = str;
4095 } while (result->NextRow());
4097 delete result;
4099 sLog.outString();
4100 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4103 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4105 template<class D>
4106 void convert_from_str(uint32 field_pos, char *src, D &dst)
4108 dst = D(objmgr.GetScriptId(src));
4112 void ObjectMgr::LoadInstanceTemplate()
4114 SQLInstanceLoader loader;
4115 loader.Load(sInstanceTemplate);
4117 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4119 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4120 if(!temp) continue;
4121 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4122 if(!entry)
4124 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4125 continue;
4127 else if(!entry->HasResetTime())
4128 continue;
4130 //FIXME: now exist heroic instance, normal/heroic raid instances
4131 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4132 // entry->resetTimeRaid store reset time for normal raid only
4133 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4134 // but at some point wee need implement reset time dependent from raid instance mode
4135 if(temp->reset_delay == 0)
4137 // use defaults from the DBC
4138 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4140 temp->reset_delay = entry->resetTimeHeroic / DAY;
4142 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4143 // for normal raid only
4145 temp->reset_delay = entry->resetTimeRaid / DAY;
4149 // the reset_delay must be at least one day
4150 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4153 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4154 sLog.outString();
4157 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4159 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4160 if(itr != mGossipText.end())
4161 return &itr->second;
4162 return NULL;
4165 void ObjectMgr::LoadGossipText()
4167 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4169 int count = 0;
4170 if( !result )
4172 barGoLink bar( 1 );
4173 bar.step();
4175 sLog.outString();
4176 sLog.outString( ">> Loaded %u npc texts", count );
4177 return;
4180 int cic;
4182 barGoLink bar( result->GetRowCount() );
4186 ++count;
4187 cic = 0;
4189 Field *fields = result->Fetch();
4191 bar.step();
4193 uint32 Text_ID = fields[cic++].GetUInt32();
4194 if(!Text_ID)
4196 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4197 continue;
4200 GossipText& gText = mGossipText[Text_ID];
4202 for (int i=0; i< 8; i++)
4204 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4205 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4207 gText.Options[i].Language = fields[cic++].GetUInt32();
4208 gText.Options[i].Probability = fields[cic++].GetFloat();
4210 for(int j=0; j < 3; ++j)
4212 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4213 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4216 } while( result->NextRow() );
4218 sLog.outString();
4219 sLog.outString( ">> Loaded %u npc texts", count );
4220 delete result;
4223 void ObjectMgr::LoadNpcTextLocales()
4225 mNpcTextLocaleMap.clear(); // need for reload case
4227 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4228 "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,"
4229 "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,"
4230 "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,"
4231 "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,"
4232 "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,"
4233 "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,"
4234 "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, "
4235 "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 "
4236 " FROM locales_npc_text");
4238 if(!result)
4240 barGoLink bar(1);
4242 bar.step();
4244 sLog.outString();
4245 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4246 return;
4249 barGoLink bar(result->GetRowCount());
4253 Field *fields = result->Fetch();
4254 bar.step();
4256 uint32 entry = fields[0].GetUInt32();
4258 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4260 for(int i=1; i<MAX_LOCALE; ++i)
4262 for(int j=0; j<8; ++j)
4264 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4265 if(!str0.empty())
4267 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4268 if(idx >= 0)
4270 if(data.Text_0[j].size() <= idx)
4271 data.Text_0[j].resize(idx+1);
4273 data.Text_0[j][idx] = str0;
4276 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4277 if(!str1.empty())
4279 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4280 if(idx >= 0)
4282 if(data.Text_1[j].size() <= idx)
4283 data.Text_1[j].resize(idx+1);
4285 data.Text_1[j][idx] = str1;
4290 } while (result->NextRow());
4292 delete result;
4294 sLog.outString();
4295 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4298 //not very fast function but it is called only once a day, or on starting-up
4299 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4301 time_t basetime = time(NULL);
4302 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4303 //delete all old mails without item and without body immediately, if starting server
4304 if (!serverUp)
4305 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4306 // 0 1 2 3 4 5 6 7 8 9
4307 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);
4308 if ( !result )
4310 barGoLink bar(1);
4311 bar.step();
4312 sLog.outString();
4313 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4314 return; // any mails need to be returned or deleted
4317 //std::ostringstream delitems, delmails; //will be here for optimization
4318 //bool deletemail = false, deleteitem = false;
4319 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4320 //delmails << "DELETE FROM mail WHERE id IN ( "
4322 barGoLink bar( result->GetRowCount() );
4323 uint32 count = 0;
4324 Field *fields;
4328 bar.step();
4330 fields = result->Fetch();
4331 Mail *m = new Mail;
4332 m->messageID = fields[0].GetUInt32();
4333 m->messageType = fields[1].GetUInt8();
4334 m->sender = fields[2].GetUInt32();
4335 m->receiver = fields[3].GetUInt32();
4336 m->itemTextId = fields[4].GetUInt32();
4337 bool has_items = fields[5].GetBool();
4338 m->expire_time = (time_t)fields[6].GetUInt64();
4339 m->deliver_time = 0;
4340 m->COD = fields[7].GetUInt32();
4341 m->checked = fields[8].GetUInt32();
4342 m->mailTemplateId = fields[9].GetInt16();
4344 Player *pl = 0;
4345 if (serverUp)
4346 pl = GetPlayer((uint64)m->receiver);
4347 if (pl && pl->m_mailsLoaded)
4348 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4349 //his in mailbox and he has already listed his mails )
4350 delete m;
4351 continue;
4353 //delete or return mail:
4354 if (has_items)
4356 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4357 if(resultItems)
4361 Field *fields2 = resultItems->Fetch();
4363 uint32 item_guid_low = fields2[0].GetUInt32();
4364 uint32 item_template = fields2[1].GetUInt32();
4366 m->AddItem(item_guid_low, item_template);
4368 while (resultItems->NextRow());
4370 delete resultItems;
4372 //if it is mail from AH, it shouldn't be returned, but deleted
4373 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4375 // mail open and then not returned
4376 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4377 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4379 else
4381 //mail will be returned:
4382 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);
4383 delete m;
4384 continue;
4388 if (m->itemTextId)
4389 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4391 //deletemail = true;
4392 //delmails << m->messageID << ", ";
4393 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4394 delete m;
4395 ++count;
4396 } while (result->NextRow());
4397 delete result;
4399 sLog.outString();
4400 sLog.outString( ">> Loaded %u mails", count );
4403 void ObjectMgr::LoadQuestAreaTriggers()
4405 mQuestAreaTriggerMap.clear(); // need for reload case
4407 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4409 uint32 count = 0;
4411 if( !result )
4413 barGoLink bar( 1 );
4414 bar.step();
4416 sLog.outString();
4417 sLog.outString( ">> Loaded %u quest trigger points", count );
4418 return;
4421 barGoLink bar( result->GetRowCount() );
4425 ++count;
4426 bar.step();
4428 Field *fields = result->Fetch();
4430 uint32 trigger_ID = fields[0].GetUInt32();
4431 uint32 quest_ID = fields[1].GetUInt32();
4433 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4434 if(!atEntry)
4436 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4437 continue;
4440 Quest const* quest = GetQuestTemplate(quest_ID);
4442 if(!quest)
4444 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4445 continue;
4448 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4450 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);
4452 // this will prevent quest completing without objective
4453 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4455 // continue; - quest modified to required objective and trigger can be allowed.
4458 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4460 } while( result->NextRow() );
4462 delete result;
4464 sLog.outString();
4465 sLog.outString( ">> Loaded %u quest trigger points", count );
4468 void ObjectMgr::LoadTavernAreaTriggers()
4470 mTavernAreaTriggerSet.clear(); // need for reload case
4472 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4474 uint32 count = 0;
4476 if( !result )
4478 barGoLink bar( 1 );
4479 bar.step();
4481 sLog.outString();
4482 sLog.outString( ">> Loaded %u tavern triggers", count );
4483 return;
4486 barGoLink bar( result->GetRowCount() );
4490 ++count;
4491 bar.step();
4493 Field *fields = result->Fetch();
4495 uint32 Trigger_ID = fields[0].GetUInt32();
4497 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4498 if(!atEntry)
4500 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4501 continue;
4504 mTavernAreaTriggerSet.insert(Trigger_ID);
4505 } while( result->NextRow() );
4507 delete result;
4509 sLog.outString();
4510 sLog.outString( ">> Loaded %u tavern triggers", count );
4513 void ObjectMgr::LoadAreaTriggerScripts()
4515 mAreaTriggerScripts.clear(); // need for reload case
4516 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4518 uint32 count = 0;
4520 if( !result )
4522 barGoLink bar( 1 );
4523 bar.step();
4525 sLog.outString();
4526 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4527 return;
4530 barGoLink bar( result->GetRowCount() );
4534 ++count;
4535 bar.step();
4537 Field *fields = result->Fetch();
4539 uint32 Trigger_ID = fields[0].GetUInt32();
4540 const char *scriptName = fields[1].GetString();
4542 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4543 if(!atEntry)
4545 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4546 continue;
4548 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4549 } while( result->NextRow() );
4551 delete result;
4553 sLog.outString();
4554 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4557 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4559 bool found = false;
4560 float dist;
4561 uint32 id = 0;
4563 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4565 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4566 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4567 continue;
4569 uint8 field = (uint8)((i - 1) / 32);
4570 uint32 submask = 1<<((i-1)%32);
4572 // skip not taxi network nodes
4573 if((sTaxiNodesMask[field] & submask)==0)
4574 continue;
4576 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4577 if(found)
4579 if(dist2 < dist)
4581 dist = dist2;
4582 id = i;
4585 else
4587 found = true;
4588 dist = dist2;
4589 id = i;
4593 return id;
4596 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4598 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4599 if(src_i==sTaxiPathSetBySource.end())
4601 path = 0;
4602 cost = 0;
4603 return;
4606 TaxiPathSetForSource& pathSet = src_i->second;
4608 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4609 if(dest_i==pathSet.end())
4611 path = 0;
4612 cost = 0;
4613 return;
4616 cost = dest_i->second.price;
4617 path = dest_i->second.ID;
4620 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4622 uint16 mount_entry = 0;
4623 uint16 mount_id = 0;
4625 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4626 if(node)
4628 if (team == ALLIANCE)
4630 mount_entry = node->MountCreatureID[1];
4631 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4632 if(ci)
4633 mount_id = ci->DisplayID_A;
4635 if (team == HORDE)
4637 mount_entry = node->MountCreatureID[0];
4638 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4639 if(ci)
4640 mount_id = ci->DisplayID_H;
4644 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4645 if(!minfo)
4647 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. ",
4648 mount_entry,id,team,mount_id);
4650 return false;
4652 if(minfo->modelid_other_gender!=0)
4653 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4655 return mount_id;
4658 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4660 if(path >= sTaxiPathNodesByPath.size())
4661 return;
4663 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4665 pathnodes.Resize(nodeList.size());
4666 mapIds.resize(nodeList.size());
4668 for(size_t i = 0; i < nodeList.size(); ++i)
4670 pathnodes[ i ].x = nodeList[i].x;
4671 pathnodes[ i ].y = nodeList[i].y;
4672 pathnodes[ i ].z = nodeList[i].z;
4674 mapIds[i] = nodeList[i].mapid;
4678 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4680 if(path >= sTaxiPathNodesByPath.size())
4681 return;
4683 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4685 pathnodes.Resize(nodeList.size());
4687 for(size_t i = 0; i < nodeList.size(); ++i)
4689 pathnodes[ i ].mapid = nodeList[i].mapid;
4690 pathnodes[ i ].x = nodeList[i].x;
4691 pathnodes[ i ].y = nodeList[i].y;
4692 pathnodes[ i ].z = nodeList[i].z;
4693 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4694 pathnodes[ i ].delay = nodeList[i].delay;
4698 void ObjectMgr::LoadGraveyardZones()
4700 mGraveYardMap.clear(); // need for reload case
4702 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4704 uint32 count = 0;
4706 if( !result )
4708 barGoLink bar( 1 );
4709 bar.step();
4711 sLog.outString();
4712 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4713 return;
4716 barGoLink bar( result->GetRowCount() );
4720 ++count;
4721 bar.step();
4723 Field *fields = result->Fetch();
4725 uint32 safeLocId = fields[0].GetUInt32();
4726 uint32 zoneId = fields[1].GetUInt32();
4727 uint32 team = fields[2].GetUInt32();
4729 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4730 if(!entry)
4732 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4733 continue;
4736 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4737 if(!areaEntry)
4739 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4740 continue;
4743 if(areaEntry->zone != 0)
4745 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4746 continue;
4749 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4751 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4752 continue;
4755 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4756 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4757 } while( result->NextRow() );
4759 delete result;
4761 sLog.outString();
4762 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4765 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4767 // search for zone associated closest graveyard
4768 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4770 // Simulate std. algorithm:
4771 // found some graveyard associated to (ghost_zone,ghost_map)
4773 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4774 // then check faction
4775 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4776 // then check faction
4777 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4778 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4779 if(graveLow==graveUp)
4781 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4782 return NULL;
4785 // at corpse map
4786 bool foundNear = false;
4787 float distNear;
4788 WorldSafeLocsEntry const* entryNear = NULL;
4790 // at entrance map for corpse map
4791 bool foundEntr = false;
4792 float distEntr;
4793 WorldSafeLocsEntry const* entryEntr = NULL;
4795 // some where other
4796 WorldSafeLocsEntry const* entryFar = NULL;
4798 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4800 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4802 GraveYardData const& data = itr->second;
4804 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4805 if(!entry)
4807 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4808 continue;
4811 // skip enemy faction graveyard
4812 // team == 0 case can be at call from .neargrave
4813 if(data.team != 0 && team != 0 && data.team != team)
4814 continue;
4816 // find now nearest graveyard at other map
4817 if(MapId != entry->map_id)
4819 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4820 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4821 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4823 // not have any corrdinates for check distance anyway
4824 entryFar = entry;
4825 continue;
4828 // at entrance map calculate distance (2D);
4829 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4830 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4831 if(foundEntr)
4833 if(dist2 < distEntr)
4835 distEntr = dist2;
4836 entryEntr = entry;
4839 else
4841 foundEntr = true;
4842 distEntr = dist2;
4843 entryEntr = entry;
4846 // find now nearest graveyard at same map
4847 else
4849 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4850 if(foundNear)
4852 if(dist2 < distNear)
4854 distNear = dist2;
4855 entryNear = entry;
4858 else
4860 foundNear = true;
4861 distNear = dist2;
4862 entryNear = entry;
4867 if(entryNear)
4868 return entryNear;
4870 if(entryEntr)
4871 return entryEntr;
4873 return entryFar;
4876 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4878 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4879 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4881 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4883 if(itr->second.safeLocId==id)
4884 return &itr->second;
4887 return NULL;
4890 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4892 if(FindGraveYardData(id,zoneId))
4893 return false;
4895 // add link to loaded data
4896 GraveYardData data;
4897 data.safeLocId = id;
4898 data.team = team;
4900 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4902 // add link to DB
4903 if(inDB)
4905 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4906 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4909 return true;
4912 void ObjectMgr::LoadAreaTriggerTeleports()
4914 mAreaTriggers.clear(); // need for reload case
4916 uint32 count = 0;
4918 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4919 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");
4920 if( !result )
4923 barGoLink bar( 1 );
4925 bar.step();
4927 sLog.outString();
4928 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4929 return;
4932 barGoLink bar( result->GetRowCount() );
4936 Field *fields = result->Fetch();
4938 bar.step();
4940 ++count;
4942 uint32 Trigger_ID = fields[0].GetUInt32();
4944 AreaTrigger at;
4946 at.requiredLevel = fields[1].GetUInt8();
4947 at.requiredItem = fields[2].GetUInt32();
4948 at.requiredItem2 = fields[3].GetUInt32();
4949 at.heroicKey = fields[4].GetUInt32();
4950 at.heroicKey2 = fields[5].GetUInt32();
4951 at.requiredQuest = fields[6].GetUInt32();
4952 at.requiredQuestHeroic = fields[7].GetUInt32();
4953 at.requiredFailedText = fields[8].GetCppString();
4954 at.target_mapId = fields[9].GetUInt32();
4955 at.target_X = fields[10].GetFloat();
4956 at.target_Y = fields[11].GetFloat();
4957 at.target_Z = fields[12].GetFloat();
4958 at.target_Orientation = fields[13].GetFloat();
4960 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4961 if(!atEntry)
4963 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4964 continue;
4967 if(at.requiredItem)
4969 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4970 if(!pProto)
4972 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4973 at.requiredItem = 0;
4976 if(at.requiredItem2)
4978 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4979 if(!pProto)
4981 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4982 at.requiredItem2 = 0;
4986 if(at.heroicKey)
4988 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4989 if(!pProto)
4991 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4992 at.heroicKey = 0;
4996 if(at.heroicKey2)
4998 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4999 if(!pProto)
5001 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5002 at.heroicKey2 = 0;
5006 if(at.requiredQuest)
5008 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5009 if(qReqItr == mQuestTemplates.end())
5011 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5012 at.requiredQuest = 0;
5016 if(at.requiredQuestHeroic)
5018 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5019 if(qReqItr == mQuestTemplates.end())
5021 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5022 at.requiredQuestHeroic = 0;
5026 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5027 if(!mapEntry)
5029 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5030 continue;
5033 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5035 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5036 continue;
5039 mAreaTriggers[Trigger_ID] = at;
5041 } while( result->NextRow() );
5043 delete result;
5045 sLog.outString();
5046 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5050 * Searches for the areatrigger which teleports players out of the given map
5052 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5054 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5055 if(!mapEntry) return NULL;
5056 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5058 if(itr->second.target_mapId == mapEntry->entrance_map)
5060 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5061 if(atEntry && atEntry->mapid == Map)
5062 return &itr->second;
5065 return NULL;
5069 * Searches for the areatrigger which teleports players to the given map
5071 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5073 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5075 if(itr->second.target_mapId == Map)
5077 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5078 if(atEntry)
5079 return &itr->second;
5082 return NULL;
5085 void ObjectMgr::SetHighestGuids()
5087 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5088 if( result )
5090 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5091 delete result;
5094 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5095 if( result )
5097 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5098 delete result;
5101 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5102 if( result )
5104 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5105 delete result;
5108 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5109 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5110 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5111 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5112 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5114 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5115 if( result )
5117 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5118 delete result;
5121 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5122 if( result )
5124 m_auctionid = (*result)[0].GetUInt32()+1;
5125 delete result;
5128 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5129 if( result )
5131 m_mailid = (*result)[0].GetUInt32()+1;
5132 delete result;
5135 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5136 if( result )
5138 m_ItemTextId = (*result)[0].GetUInt32()+1;
5139 delete result;
5142 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5143 if( result )
5145 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5146 delete result;
5149 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5150 if (result)
5152 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5153 delete result;
5156 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5157 if (result)
5159 m_guildId = (*result)[0].GetUInt32()+1;
5160 delete result;
5164 uint32 ObjectMgr::GenerateArenaTeamId()
5166 if(m_arenaTeamId>=0xFFFFFFFE)
5168 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5169 World::StopNow(ERROR_EXIT_CODE);
5171 return m_arenaTeamId++;
5174 uint32 ObjectMgr::GenerateAuctionID()
5176 if(m_auctionid>=0xFFFFFFFE)
5178 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5179 World::StopNow(ERROR_EXIT_CODE);
5181 return m_auctionid++;
5184 uint32 ObjectMgr::GenerateGuildId()
5186 if(m_guildId>=0xFFFFFFFE)
5188 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5189 World::StopNow(ERROR_EXIT_CODE);
5191 return m_guildId++;
5194 uint32 ObjectMgr::GenerateMailID()
5196 if(m_mailid>=0xFFFFFFFE)
5198 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5199 World::StopNow(ERROR_EXIT_CODE);
5201 return m_mailid++;
5204 uint32 ObjectMgr::GenerateItemTextID()
5206 if(m_ItemTextId>=0xFFFFFFFE)
5208 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5209 World::StopNow(ERROR_EXIT_CODE);
5211 return m_ItemTextId++;
5214 uint32 ObjectMgr::CreateItemText(std::string text)
5216 uint32 newItemTextId = GenerateItemTextID();
5217 //insert new itempage to container
5218 mItemTexts[ newItemTextId ] = text;
5219 //save new itempage
5220 CharacterDatabase.escape_string(text);
5221 //any Delete query needed, itemTextId is maximum of all ids
5222 std::ostringstream query;
5223 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5224 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5225 return newItemTextId;
5228 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5230 switch(guidhigh)
5232 case HIGHGUID_ITEM:
5233 if(m_hiItemGuid>=0xFFFFFFFE)
5235 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5236 World::StopNow(ERROR_EXIT_CODE);
5238 return m_hiItemGuid++;
5239 case HIGHGUID_UNIT:
5240 if(m_hiCreatureGuid>=0x00FFFFFE)
5242 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5243 World::StopNow(ERROR_EXIT_CODE);
5245 return m_hiCreatureGuid++;
5246 case HIGHGUID_PET:
5247 if(m_hiPetGuid>=0x00FFFFFE)
5249 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5250 World::StopNow(ERROR_EXIT_CODE);
5252 return m_hiPetGuid++;
5253 case HIGHGUID_VEHICLE:
5254 if(m_hiVehicleGuid>=0x00FFFFFF)
5256 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5257 World::StopNow(ERROR_EXIT_CODE);
5259 return m_hiVehicleGuid++;
5260 case HIGHGUID_PLAYER:
5261 if(m_hiCharGuid>=0xFFFFFFFE)
5263 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5264 World::StopNow(ERROR_EXIT_CODE);
5266 return m_hiCharGuid++;
5267 case HIGHGUID_GAMEOBJECT:
5268 if(m_hiGoGuid>=0x00FFFFFE)
5270 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5271 World::StopNow(ERROR_EXIT_CODE);
5273 return m_hiGoGuid++;
5274 case HIGHGUID_CORPSE:
5275 if(m_hiCorpseGuid>=0xFFFFFFFE)
5277 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5278 World::StopNow(ERROR_EXIT_CODE);
5280 return m_hiCorpseGuid++;
5281 case HIGHGUID_DYNAMICOBJECT:
5282 if(m_hiDoGuid>=0xFFFFFFFE)
5284 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5285 World::StopNow(ERROR_EXIT_CODE);
5287 return m_hiDoGuid++;
5288 default:
5289 ASSERT(0);
5292 ASSERT(0);
5293 return 0;
5296 void ObjectMgr::LoadGameObjectLocales()
5298 mGameObjectLocaleMap.clear(); // need for reload case
5300 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5301 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5302 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5303 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5305 if(!result)
5307 barGoLink bar(1);
5309 bar.step();
5311 sLog.outString();
5312 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5313 return;
5316 barGoLink bar(result->GetRowCount());
5320 Field *fields = result->Fetch();
5321 bar.step();
5323 uint32 entry = fields[0].GetUInt32();
5325 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5327 for(int i = 1; i < MAX_LOCALE; ++i)
5329 std::string str = fields[i].GetCppString();
5330 if(!str.empty())
5332 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5333 if(idx >= 0)
5335 if(data.Name.size() <= idx)
5336 data.Name.resize(idx+1);
5338 data.Name[idx] = str;
5343 for(int i = 1; i < MAX_LOCALE; ++i)
5345 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5346 if(!str.empty())
5348 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5349 if(idx >= 0)
5351 if(data.CastBarCaption.size() <= idx)
5352 data.CastBarCaption.resize(idx+1);
5354 data.CastBarCaption[idx] = str;
5359 } while (result->NextRow());
5361 delete result;
5363 sLog.outString();
5364 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5367 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5369 template<class D>
5370 void convert_from_str(uint32 field_pos, char *src, D &dst)
5372 dst = D(objmgr.GetScriptId(src));
5376 void ObjectMgr::LoadGameobjectInfo()
5378 SQLGameObjectLoader loader;
5379 loader.Load(sGOStorage);
5381 // some checks
5382 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5384 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5385 if(!goInfo)
5386 continue;
5388 switch(goInfo->type)
5390 case GAMEOBJECT_TYPE_DOOR: //0
5392 if(goInfo->door.lockId)
5394 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5395 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5396 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5398 break;
5400 case GAMEOBJECT_TYPE_BUTTON: //1
5402 if(goInfo->button.lockId)
5404 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5405 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5406 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5408 break;
5410 case GAMEOBJECT_TYPE_CHEST: //3
5412 if(goInfo->chest.lockId)
5414 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5415 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5416 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5418 if(goInfo->chest.linkedTrapId) // linked trap
5420 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5422 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5423 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5424 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5426 /* disable check for while
5427 else
5428 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5429 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5432 break;
5434 case GAMEOBJECT_TYPE_TRAP: //6
5436 /* disable check for while
5437 if(goInfo->trap.spellId) // spell
5439 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5440 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5441 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5444 break;
5446 case GAMEOBJECT_TYPE_CHAIR: //7
5447 if(goInfo->chair.height > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5449 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5450 id,goInfo->type,goInfo->chair.height,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5452 // prevent client and server unexpected work
5453 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5455 break;
5456 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5458 if(goInfo->spellFocus.focusId)
5460 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5461 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5462 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5465 if(goInfo->spellFocus.linkedTrapId) // linked trap
5467 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5469 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5470 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5471 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5473 /* disable check for while
5474 else
5475 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5476 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5479 break;
5481 case GAMEOBJECT_TYPE_GOOBER: //10
5483 if(goInfo->goober.pageId) // pageId
5485 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5486 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5487 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5489 /* disable check for while
5490 if(goInfo->goober.spellId) // spell
5492 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5493 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5494 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5497 if(goInfo->goober.linkedTrapId) // linked trap
5499 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5501 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5502 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5503 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5505 /* disable check for while
5506 else
5507 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5508 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5511 break;
5513 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5515 if(goInfo->moTransport.taxiPathId)
5517 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5518 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5519 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5521 break;
5523 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5525 /* disabled
5526 if(goInfo->summoningRitual.spellId)
5528 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5529 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5530 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5533 break;
5535 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5537 if(goInfo->spellcaster.spellId) // spell
5539 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5540 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5541 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5543 break;
5545 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5546 if(goInfo->barberChair.chairheight > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5548 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5549 id,goInfo->type,goInfo->barberChair.chairheight,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5551 // prevent client and server unexpected work
5552 const_cast<GameObjectInfo*>(goInfo)->barberChair.chairheight = 0;
5554 break;
5558 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5559 sLog.outString();
5562 void ObjectMgr::LoadExplorationBaseXP()
5564 uint32 count = 0;
5565 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5567 if( !result )
5569 barGoLink bar( 1 );
5571 bar.step();
5573 sLog.outString();
5574 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5575 return;
5578 barGoLink bar( result->GetRowCount() );
5582 bar.step();
5584 Field *fields = result->Fetch();
5585 uint32 level = fields[0].GetUInt32();
5586 uint32 basexp = fields[1].GetUInt32();
5587 mBaseXPTable[level] = basexp;
5588 ++count;
5590 while (result->NextRow());
5592 delete result;
5594 sLog.outString();
5595 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5598 uint32 ObjectMgr::GetBaseXP(uint32 level)
5600 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5603 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5605 if (level < mPlayerXPperLevel.size())
5606 return mPlayerXPperLevel[level];
5607 return 0;
5610 void ObjectMgr::LoadPetNames()
5612 uint32 count = 0;
5613 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5615 if( !result )
5617 barGoLink bar( 1 );
5619 bar.step();
5621 sLog.outString();
5622 sLog.outString( ">> Loaded %u pet name parts", count );
5623 return;
5626 barGoLink bar( result->GetRowCount() );
5630 bar.step();
5632 Field *fields = result->Fetch();
5633 std::string word = fields[0].GetString();
5634 uint32 entry = fields[1].GetUInt32();
5635 bool half = fields[2].GetBool();
5636 if(half)
5637 PetHalfName1[entry].push_back(word);
5638 else
5639 PetHalfName0[entry].push_back(word);
5640 ++count;
5642 while (result->NextRow());
5643 delete result;
5645 sLog.outString();
5646 sLog.outString( ">> Loaded %u pet name parts", count );
5649 void ObjectMgr::LoadPetNumber()
5651 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5652 if(result)
5654 Field *fields = result->Fetch();
5655 m_hiPetNumber = fields[0].GetUInt32()+1;
5656 delete result;
5659 barGoLink bar( 1 );
5660 bar.step();
5662 sLog.outString();
5663 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5666 std::string ObjectMgr::GeneratePetName(uint32 entry)
5668 std::vector<std::string> & list0 = PetHalfName0[entry];
5669 std::vector<std::string> & list1 = PetHalfName1[entry];
5671 if(list0.empty() || list1.empty())
5673 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5674 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5675 if(!petname)
5676 petname = cinfo->Name;
5677 return std::string(petname);
5680 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5683 uint32 ObjectMgr::GeneratePetNumber()
5685 return ++m_hiPetNumber;
5688 void ObjectMgr::LoadCorpses()
5690 uint32 count = 0;
5691 // 0 1 2 3 4 5 6 7 8 10
5692 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");
5694 if( !result )
5696 barGoLink bar( 1 );
5698 bar.step();
5700 sLog.outString();
5701 sLog.outString( ">> Loaded %u corpses", count );
5702 return;
5705 barGoLink bar( result->GetRowCount() );
5709 bar.step();
5711 Field *fields = result->Fetch();
5713 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5715 Corpse *corpse = new Corpse;
5716 if(!corpse->LoadFromDB(guid,fields))
5718 delete corpse;
5719 continue;
5722 ObjectAccessor::Instance().AddCorpse(corpse);
5724 ++count;
5726 while (result->NextRow());
5727 delete result;
5729 sLog.outString();
5730 sLog.outString( ">> Loaded %u corpses", count );
5733 void ObjectMgr::LoadReputationOnKill()
5735 uint32 count = 0;
5737 // 0 1 2
5738 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5739 // 3 4 5 6 7 8 9
5740 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5741 "FROM creature_onkill_reputation");
5743 if(!result)
5745 barGoLink bar(1);
5747 bar.step();
5749 sLog.outString();
5750 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5751 return;
5754 barGoLink bar(result->GetRowCount());
5758 Field *fields = result->Fetch();
5759 bar.step();
5761 uint32 creature_id = fields[0].GetUInt32();
5763 ReputationOnKillEntry repOnKill;
5764 repOnKill.repfaction1 = fields[1].GetUInt32();
5765 repOnKill.repfaction2 = fields[2].GetUInt32();
5766 repOnKill.is_teamaward1 = fields[3].GetBool();
5767 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5768 repOnKill.repvalue1 = fields[5].GetInt32();
5769 repOnKill.is_teamaward2 = fields[6].GetBool();
5770 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5771 repOnKill.repvalue2 = fields[8].GetInt32();
5772 repOnKill.team_dependent = fields[9].GetUInt8();
5774 if(!GetCreatureTemplate(creature_id))
5776 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5777 continue;
5780 if(repOnKill.repfaction1)
5782 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5783 if(!factionEntry1)
5785 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5786 continue;
5790 if(repOnKill.repfaction2)
5792 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5793 if(!factionEntry2)
5795 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5796 continue;
5800 mRepOnKill[creature_id] = repOnKill;
5802 ++count;
5803 } while (result->NextRow());
5805 delete result;
5807 sLog.outString();
5808 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5811 void ObjectMgr::LoadPointsOfInterest()
5813 uint32 count = 0;
5815 // 0 1 2 3 4 5
5816 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5818 if(!result)
5820 barGoLink bar(1);
5822 bar.step();
5824 sLog.outString();
5825 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5826 return;
5829 barGoLink bar(result->GetRowCount());
5833 Field *fields = result->Fetch();
5834 bar.step();
5836 uint32 point_id = fields[0].GetUInt32();
5838 PointOfInterest POI;
5839 POI.x = fields[1].GetFloat();
5840 POI.y = fields[2].GetFloat();
5841 POI.icon = fields[3].GetUInt32();
5842 POI.flags = fields[4].GetUInt32();
5843 POI.data = fields[5].GetUInt32();
5844 POI.icon_name = fields[6].GetCppString();
5846 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5848 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5849 continue;
5852 mPointsOfInterest[point_id] = POI;
5854 ++count;
5855 } while (result->NextRow());
5857 delete result;
5859 sLog.outString();
5860 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5863 void ObjectMgr::LoadWeatherZoneChances()
5865 uint32 count = 0;
5867 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5868 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");
5870 if(!result)
5872 barGoLink bar(1);
5874 bar.step();
5876 sLog.outString();
5877 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5878 return;
5881 barGoLink bar(result->GetRowCount());
5885 Field *fields = result->Fetch();
5886 bar.step();
5888 uint32 zone_id = fields[0].GetUInt32();
5890 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5892 for(int season = 0; season < WEATHER_SEASONS; ++season)
5894 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5895 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5896 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5898 if(wzc.data[season].rainChance > 100)
5900 wzc.data[season].rainChance = 25;
5901 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
5904 if(wzc.data[season].snowChance > 100)
5906 wzc.data[season].snowChance = 25;
5907 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
5910 if(wzc.data[season].stormChance > 100)
5912 wzc.data[season].stormChance = 25;
5913 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
5917 ++count;
5918 } while (result->NextRow());
5920 delete result;
5922 sLog.outString();
5923 sLog.outString(">> Loaded %u weather definitions", count);
5926 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5928 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5929 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5930 if(t)
5931 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5934 void ObjectMgr::DeleteCreatureData(uint32 guid)
5936 // remove mapid*cellid -> guid_set map
5937 CreatureData const* data = GetCreatureData(guid);
5938 if(data)
5939 RemoveCreatureFromGrid(guid, data);
5941 mCreatureDataMap.erase(guid);
5944 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5946 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5947 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5948 if(t)
5949 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5952 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5954 RespawnTimes::iterator next;
5956 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5958 next = itr;
5959 ++next;
5961 if(GUID_HIPART(itr->first)==instance)
5962 mGORespawnTimes.erase(itr);
5965 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5967 next = itr;
5968 ++next;
5970 if(GUID_HIPART(itr->first)==instance)
5971 mCreatureRespawnTimes.erase(itr);
5974 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5975 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5978 void ObjectMgr::DeleteGOData(uint32 guid)
5980 // remove mapid*cellid -> guid_set map
5981 GameObjectData const* data = GetGOData(guid);
5982 if(data)
5983 RemoveGameobjectFromGrid(guid, data);
5985 mGameObjectDataMap.erase(guid);
5988 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5990 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5991 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5992 cell_guids.corpses[player_guid] = instance;
5995 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5997 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5998 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5999 cell_guids.corpses.erase(player_guid);
6002 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6004 map.clear(); // need for reload case
6006 uint32 count = 0;
6008 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6010 if(!result)
6012 barGoLink bar(1);
6014 bar.step();
6016 sLog.outString();
6017 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6018 return;
6021 barGoLink bar(result->GetRowCount());
6025 Field *fields = result->Fetch();
6026 bar.step();
6028 uint32 id = fields[0].GetUInt32();
6029 uint32 quest = fields[1].GetUInt32();
6031 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6033 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6034 continue;
6037 map.insert(QuestRelations::value_type(id,quest));
6039 ++count;
6040 } while (result->NextRow());
6042 delete result;
6044 sLog.outString();
6045 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6048 void ObjectMgr::LoadGameobjectQuestRelations()
6050 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6052 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6054 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6055 if(!goInfo)
6056 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6057 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6058 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6062 void ObjectMgr::LoadGameobjectInvolvedRelations()
6064 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6066 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6068 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6069 if(!goInfo)
6070 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6071 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6072 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6076 void ObjectMgr::LoadCreatureQuestRelations()
6078 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6080 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6082 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6083 if(!cInfo)
6084 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6085 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6086 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);
6090 void ObjectMgr::LoadCreatureInvolvedRelations()
6092 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6094 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6096 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6097 if(!cInfo)
6098 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6099 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6100 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);
6104 void ObjectMgr::LoadReservedPlayersNames()
6106 m_ReservedNames.clear(); // need for reload case
6108 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6110 uint32 count = 0;
6112 if( !result )
6114 barGoLink bar( 1 );
6115 bar.step();
6117 sLog.outString();
6118 sLog.outString( ">> Loaded %u reserved player names", count );
6119 return;
6122 barGoLink bar( result->GetRowCount() );
6124 Field* fields;
6127 bar.step();
6128 fields = result->Fetch();
6129 std::string name= fields[0].GetCppString();
6131 std::wstring wstr;
6132 if(!Utf8toWStr (name,wstr))
6134 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6135 continue;
6138 wstrToLower(wstr);
6140 m_ReservedNames.insert(wstr);
6141 ++count;
6142 } while ( result->NextRow() );
6144 delete result;
6146 sLog.outString();
6147 sLog.outString( ">> Loaded %u reserved player names", count );
6150 bool ObjectMgr::IsReservedName( const std::string& name ) const
6152 std::wstring wstr;
6153 if(!Utf8toWStr (name,wstr))
6154 return false;
6156 wstrToLower(wstr);
6158 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6161 enum LanguageType
6163 LT_BASIC_LATIN = 0x0000,
6164 LT_EXTENDEN_LATIN = 0x0001,
6165 LT_CYRILLIC = 0x0002,
6166 LT_EAST_ASIA = 0x0004,
6167 LT_ANY = 0xFFFF
6170 static LanguageType GetRealmLanguageType(bool create)
6172 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6174 case REALM_ZONE_UNKNOWN: // any language
6175 case REALM_ZONE_DEVELOPMENT:
6176 case REALM_ZONE_TEST_SERVER:
6177 case REALM_ZONE_QA_SERVER:
6178 return LT_ANY;
6179 case REALM_ZONE_UNITED_STATES: // extended-Latin
6180 case REALM_ZONE_OCEANIC:
6181 case REALM_ZONE_LATIN_AMERICA:
6182 case REALM_ZONE_ENGLISH:
6183 case REALM_ZONE_GERMAN:
6184 case REALM_ZONE_FRENCH:
6185 case REALM_ZONE_SPANISH:
6186 return LT_EXTENDEN_LATIN;
6187 case REALM_ZONE_KOREA: // East-Asian
6188 case REALM_ZONE_TAIWAN:
6189 case REALM_ZONE_CHINA:
6190 return LT_EAST_ASIA;
6191 case REALM_ZONE_RUSSIAN: // Cyrillic
6192 return LT_CYRILLIC;
6193 default:
6194 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6198 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6200 if(strictMask==0) // any language, ignore realm
6202 if(isExtendedLatinString(wstr,numericOrSpace))
6203 return true;
6204 if(isCyrillicString(wstr,numericOrSpace))
6205 return true;
6206 if(isEastAsianString(wstr,numericOrSpace))
6207 return true;
6208 return false;
6211 if(strictMask & 0x2) // realm zone specific
6213 LanguageType lt = GetRealmLanguageType(create);
6214 if(lt & LT_EXTENDEN_LATIN)
6215 if(isExtendedLatinString(wstr,numericOrSpace))
6216 return true;
6217 if(lt & LT_CYRILLIC)
6218 if(isCyrillicString(wstr,numericOrSpace))
6219 return true;
6220 if(lt & LT_EAST_ASIA)
6221 if(isEastAsianString(wstr,numericOrSpace))
6222 return true;
6225 if(strictMask & 0x1) // basic Latin
6227 if(isBasicLatinString(wstr,numericOrSpace))
6228 return true;
6231 return false;
6234 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6236 std::wstring wname;
6237 if(!Utf8toWStr(name,wname))
6238 return false;
6240 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6241 return false;
6243 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6245 return isValidString(wname,strictMask,false,create);
6248 bool ObjectMgr::IsValidCharterName( const std::string& name )
6250 std::wstring wname;
6251 if(!Utf8toWStr(name,wname))
6252 return false;
6254 if(wname.size() < 1)
6255 return false;
6257 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6259 return isValidString(wname,strictMask,true);
6262 bool ObjectMgr::IsValidPetName( const std::string& name )
6264 std::wstring wname;
6265 if(!Utf8toWStr(name,wname))
6266 return false;
6268 if(wname.size() < 1)
6269 return false;
6271 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6273 return isValidString(wname,strictMask,false);
6276 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6278 if(loc==LOCALE_enUS)
6279 return -1;
6281 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6282 if(m_LocalForIndex[i]==loc)
6283 return i;
6285 return -1;
6288 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6290 if (i<0 || i>=m_LocalForIndex.size())
6291 return LOCALE_enUS;
6293 return m_LocalForIndex[i];
6296 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6298 if(loc==LOCALE_enUS)
6299 return -1;
6301 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6302 if(m_LocalForIndex[i]==loc)
6303 return i;
6305 m_LocalForIndex.push_back(loc);
6306 return m_LocalForIndex.size()-1;
6309 void ObjectMgr::LoadGameObjectForQuests()
6311 mGameObjectForQuestSet.clear(); // need for reload case
6313 if( !sGOStorage.MaxEntry )
6315 barGoLink bar( 1 );
6316 bar.step();
6317 sLog.outString();
6318 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6319 return;
6322 barGoLink bar( sGOStorage.MaxEntry - 1 );
6323 uint32 count = 0;
6325 // collect GO entries for GO that must activated
6326 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6328 bar.step();
6329 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6330 if(!goInfo)
6331 continue;
6333 switch(goInfo->type)
6335 // scan GO chest with loot including quest items
6336 case GAMEOBJECT_TYPE_CHEST:
6338 uint32 loot_id = GameObject::GetLootId(goInfo);
6340 // find quest loot for GO
6341 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6343 mGameObjectForQuestSet.insert(go_entry);
6344 ++count;
6346 break;
6348 case GAMEOBJECT_TYPE_GOOBER:
6350 if(goInfo->goober.questId) //quests objects
6352 mGameObjectForQuestSet.insert(go_entry);
6353 count++;
6355 break;
6357 default:
6358 break;
6362 sLog.outString();
6363 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6366 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6368 // cleanup affected map part for reloading case
6369 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6371 if(itr->first >= min_value && itr->first <= max_value)
6373 MangosStringLocaleMap::iterator itr2 = itr;
6374 ++itr;
6375 mMangosStringLocaleMap.erase(itr2);
6377 else
6378 ++itr;
6381 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);
6383 if(!result)
6385 barGoLink bar(1);
6387 bar.step();
6389 sLog.outString();
6390 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6391 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6392 else
6393 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6394 return false;
6397 uint32 count = 0;
6399 barGoLink bar(result->GetRowCount());
6403 Field *fields = result->Fetch();
6404 bar.step();
6406 int32 entry = fields[0].GetInt32();
6408 if(entry==0)
6410 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6411 continue;
6413 else if(entry < min_value || entry > max_value)
6415 int32 start = min_value > 0 ? min_value : max_value;
6416 int32 end = min_value > 0 ? max_value : min_value;
6417 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6418 continue;
6421 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6423 if(data.Content.size() > 0)
6425 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6426 continue;
6429 data.Content.resize(1);
6430 ++count;
6432 // 0 -> default, idx in to idx+1
6433 data.Content[0] = fields[1].GetCppString();
6435 for(int i = 1; i < MAX_LOCALE; ++i)
6437 std::string str = fields[i+1].GetCppString();
6438 if(!str.empty())
6440 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6441 if(idx >= 0)
6443 // 0 -> default, idx in to idx+1
6444 if(data.Content.size() <= idx+1)
6445 data.Content.resize(idx+2);
6447 data.Content[idx+1] = str;
6451 } while (result->NextRow());
6453 delete result;
6455 sLog.outString();
6456 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6457 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6458 else
6459 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6461 return true;
6464 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6466 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6467 // Content[0] always exist if exist MangosStringLocale
6468 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6470 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6471 return msl->Content[locale_idx+1].c_str();
6472 else
6473 return msl->Content[0].c_str();
6476 if(entry > 0)
6477 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6478 else
6479 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6480 return "<error>";
6483 void ObjectMgr::LoadFishingBaseSkillLevel()
6485 mFishingBaseForArea.clear(); // for reload case
6487 uint32 count = 0;
6488 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6490 if( !result )
6492 barGoLink bar( 1 );
6494 bar.step();
6496 sLog.outString();
6497 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6498 return;
6501 barGoLink bar( result->GetRowCount() );
6505 bar.step();
6507 Field *fields = result->Fetch();
6508 uint32 entry = fields[0].GetUInt32();
6509 int32 skill = fields[1].GetInt32();
6511 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6512 if(!fArea)
6514 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6515 continue;
6518 mFishingBaseForArea[entry] = skill;
6519 ++count;
6521 while (result->NextRow());
6523 delete result;
6525 sLog.outString();
6526 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6529 // Searches for the same condition already in Conditions store
6530 // Returns Id if found, else adds it to Conditions and returns Id
6531 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6533 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6534 for (uint16 i=0; i < mConditions.size(); ++i)
6536 if (lc == mConditions[i])
6537 return i;
6540 mConditions.push_back(lc);
6542 if(mConditions.size() > 0xFFFF)
6544 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6545 return 0;
6548 return mConditions.size() - 1;
6551 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6553 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6555 std::wstring wname;
6556 if(!Utf8toWStr(names.name[i],wname))
6557 return false;
6559 if(mainpart!=GetMainPartOfName(wname,i+1))
6560 return false;
6562 return true;
6565 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6567 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6568 if(i!= mAreaTriggerScripts.end())
6569 return i->second;
6570 return 0;
6573 // Checks if player meets the condition
6574 bool PlayerCondition::Meets(Player const * player) const
6576 if( !player )
6577 return false; // player not present, return false
6579 switch (condition)
6581 case CONDITION_NONE:
6582 return true; // empty condition, always met
6583 case CONDITION_AURA:
6584 return player->HasAura(value1, value2);
6585 case CONDITION_ITEM:
6586 return player->HasItemCount(value1, value2);
6587 case CONDITION_ITEM_EQUIPPED:
6588 return player->HasItemOrGemWithIdEquipped(value1,1);
6589 case CONDITION_ZONEID:
6590 return player->GetZoneId() == value1;
6591 case CONDITION_REPUTATION_RANK:
6593 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6594 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6596 case CONDITION_TEAM:
6597 return player->GetTeam() == value1;
6598 case CONDITION_SKILL:
6599 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6600 case CONDITION_QUESTREWARDED:
6601 return player->GetQuestRewardStatus(value1);
6602 case CONDITION_QUESTTAKEN:
6604 QuestStatus status = player->GetQuestStatus(value1);
6605 return (status == QUEST_STATUS_INCOMPLETE);
6607 case CONDITION_AD_COMMISSION_AURA:
6609 Unit::AuraMap const& auras = player->GetAuras();
6610 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6611 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6612 return true;
6613 return false;
6615 case CONDITION_NO_AURA:
6616 return !player->HasAura(value1, value2);
6617 case CONDITION_ACTIVE_EVENT:
6618 return gameeventmgr.IsActiveEvent(value1);
6619 default:
6620 return false;
6624 // Verification of condition values validity
6625 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6627 if( condition >= MAX_CONDITION) // Wrong condition type
6629 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6630 return false;
6633 switch (condition)
6635 case CONDITION_AURA:
6637 if(!sSpellStore.LookupEntry(value1))
6639 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6640 return false;
6642 if(value2 > 2)
6644 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6645 return false;
6647 break;
6649 case CONDITION_ITEM:
6651 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6652 if(!proto)
6654 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6655 return false;
6657 break;
6659 case CONDITION_ITEM_EQUIPPED:
6661 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6662 if(!proto)
6664 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6665 return false;
6667 break;
6669 case CONDITION_ZONEID:
6671 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6672 if(!areaEntry)
6674 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6675 return false;
6677 if(areaEntry->zone != 0)
6679 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6680 return false;
6682 break;
6684 case CONDITION_REPUTATION_RANK:
6686 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6687 if(!factionEntry)
6689 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6690 return false;
6692 break;
6694 case CONDITION_TEAM:
6696 if (value1 != ALLIANCE && value1 != HORDE)
6698 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6699 return false;
6701 break;
6703 case CONDITION_SKILL:
6705 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6706 if (!pSkill)
6708 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6709 return false;
6711 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6713 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6714 return false;
6716 break;
6718 case CONDITION_QUESTREWARDED:
6719 case CONDITION_QUESTTAKEN:
6721 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6722 if (!Quest)
6724 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6725 return false;
6727 if(value2)
6728 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6729 break;
6731 case CONDITION_AD_COMMISSION_AURA:
6733 if(value1)
6734 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6735 if(value2)
6736 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6737 break;
6739 case CONDITION_NO_AURA:
6741 if(!sSpellStore.LookupEntry(value1))
6743 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6744 return false;
6746 if(value2 > 2)
6748 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6749 return false;
6751 break;
6753 case CONDITION_ACTIVE_EVENT:
6755 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6756 if(value1 >=events.size() || !events[value1].isValid())
6758 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6759 return false;
6761 break;
6764 return true;
6767 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6769 switch(pSkill->categoryId)
6771 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6772 case SKILL_CATEGORY_WEAPON:
6773 if(pSkill->id!=SKILL_FIST_WEAPONS)
6774 return SKILL_RANGE_LEVEL;
6775 else
6776 return SKILL_RANGE_MONO;
6777 case SKILL_CATEGORY_ARMOR:
6778 case SKILL_CATEGORY_CLASS:
6779 if(pSkill->id != SKILL_LOCKPICKING)
6780 return SKILL_RANGE_MONO;
6781 else
6782 return SKILL_RANGE_LEVEL;
6783 case SKILL_CATEGORY_SECONDARY:
6784 case SKILL_CATEGORY_PROFESSION:
6785 // not set skills for professions and racial abilities
6786 if(IsProfessionSkill(pSkill->id))
6787 return SKILL_RANGE_RANK;
6788 else if(racial)
6789 return SKILL_RANGE_NONE;
6790 else
6791 return SKILL_RANGE_MONO;
6792 default:
6793 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6794 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6795 return SKILL_RANGE_NONE;
6799 void ObjectMgr::LoadGameTele()
6801 m_GameTeleMap.clear(); // for reload case
6803 uint32 count = 0;
6804 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6806 if( !result )
6808 barGoLink bar( 1 );
6810 bar.step();
6812 sLog.outString();
6813 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6814 return;
6817 barGoLink bar( result->GetRowCount() );
6821 bar.step();
6823 Field *fields = result->Fetch();
6825 uint32 id = fields[0].GetUInt32();
6827 GameTele gt;
6829 gt.position_x = fields[1].GetFloat();
6830 gt.position_y = fields[2].GetFloat();
6831 gt.position_z = fields[3].GetFloat();
6832 gt.orientation = fields[4].GetFloat();
6833 gt.mapId = fields[5].GetUInt32();
6834 gt.name = fields[6].GetCppString();
6836 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6838 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6839 continue;
6842 if(!Utf8toWStr(gt.name,gt.wnameLow))
6844 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6845 continue;
6848 wstrToLower( gt.wnameLow );
6850 m_GameTeleMap[id] = gt;
6852 ++count;
6854 while (result->NextRow());
6855 delete result;
6857 sLog.outString();
6858 sLog.outString( ">> Loaded %u GameTeleports", count );
6861 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6863 // explicit name case
6864 std::wstring wname;
6865 if(!Utf8toWStr(name,wname))
6866 return false;
6868 // converting string that we try to find to lower case
6869 wstrToLower( wname );
6871 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6872 const GameTele* alt = NULL;
6873 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6874 if(itr->second.wnameLow == wname)
6875 return &itr->second;
6876 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6877 alt = &itr->second;
6879 return alt;
6882 bool ObjectMgr::AddGameTele(GameTele& tele)
6884 // find max id
6885 uint32 new_id = 0;
6886 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6887 if(itr->first > new_id)
6888 new_id = itr->first;
6890 // use next
6891 ++new_id;
6893 if(!Utf8toWStr(tele.name,tele.wnameLow))
6894 return false;
6896 wstrToLower( tele.wnameLow );
6898 m_GameTeleMap[new_id] = tele;
6900 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')",
6901 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6904 bool ObjectMgr::DeleteGameTele(const std::string& name)
6906 // explicit name case
6907 std::wstring wname;
6908 if(!Utf8toWStr(name,wname))
6909 return false;
6911 // converting string that we try to find to lower case
6912 wstrToLower( wname );
6914 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6916 if(itr->second.wnameLow == wname)
6918 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6919 m_GameTeleMap.erase(itr);
6920 return true;
6924 return false;
6927 void ObjectMgr::LoadTrainerSpell()
6929 // For reload case
6930 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6931 itr->second.Clear();
6932 m_mCacheTrainerSpellMap.clear();
6934 std::set<uint32> skip_trainers;
6936 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6938 if( !result )
6940 barGoLink bar( 1 );
6942 bar.step();
6944 sLog.outString();
6945 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6946 return;
6949 barGoLink bar( result->GetRowCount() );
6951 uint32 count = 0;
6954 bar.step();
6956 Field* fields = result->Fetch();
6958 uint32 entry = fields[0].GetUInt32();
6959 uint32 spell = fields[1].GetUInt32();
6961 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6963 if(!cInfo)
6965 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6966 continue;
6969 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6971 if(skip_trainers.count(entry) == 0)
6973 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6974 skip_trainers.insert(entry);
6976 continue;
6979 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6980 if(!spellinfo)
6982 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6983 continue;
6986 if(!SpellMgr::IsSpellValid(spellinfo))
6988 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6989 continue;
6992 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6994 TrainerSpell& trainerSpell = data.spellList[spell];
6995 trainerSpell.spell = spell;
6996 trainerSpell.spellCost = fields[2].GetUInt32();
6997 trainerSpell.reqSkill = fields[3].GetUInt32();
6998 trainerSpell.reqSkillValue = fields[4].GetUInt32();
6999 trainerSpell.reqLevel = fields[5].GetUInt32();
7001 if(!trainerSpell.reqLevel)
7002 trainerSpell.reqLevel = spellinfo->spellLevel;
7004 // calculate learned spell for profession case when stored cast-spell
7005 trainerSpell.learnedSpell = spell;
7006 for(int i = 0; i <3; ++i)
7008 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7009 continue;
7010 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7012 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7013 break;
7017 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7018 data.trainerType = 2;
7020 ++count;
7022 } while (result->NextRow());
7023 delete result;
7025 sLog.outString();
7026 sLog.outString( ">> Loaded %d Trainers", count );
7029 void ObjectMgr::LoadVendors()
7031 // For reload case
7032 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7033 itr->second.Clear();
7034 m_mCacheVendorItemMap.clear();
7036 std::set<uint32> skip_vendors;
7038 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7039 if( !result )
7041 barGoLink bar( 1 );
7043 bar.step();
7045 sLog.outString();
7046 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7047 return;
7050 barGoLink bar( result->GetRowCount() );
7052 uint32 count = 0;
7055 bar.step();
7056 Field* fields = result->Fetch();
7058 uint32 entry = fields[0].GetUInt32();
7059 uint32 item_id = fields[1].GetUInt32();
7060 uint32 maxcount = fields[2].GetUInt32();
7061 uint32 incrtime = fields[3].GetUInt32();
7062 uint32 ExtendedCost = fields[4].GetUInt32();
7064 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7065 continue;
7067 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7069 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7070 ++count;
7072 } while (result->NextRow());
7073 delete result;
7075 sLog.outString();
7076 sLog.outString( ">> Loaded %d Vendors ", count );
7079 void ObjectMgr::LoadNpcTextId()
7082 m_mCacheNpcTextIdMap.clear();
7084 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7085 if( !result )
7087 barGoLink bar( 1 );
7089 bar.step();
7091 sLog.outString();
7092 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7093 return;
7096 barGoLink bar( result->GetRowCount() );
7098 uint32 count = 0;
7099 uint32 guid,textid;
7102 bar.step();
7104 Field* fields = result->Fetch();
7106 guid = fields[0].GetUInt32();
7107 textid = fields[1].GetUInt32();
7109 if (!GetCreatureData(guid))
7111 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7112 continue;
7114 if (!GetGossipText(textid))
7116 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7117 continue;
7120 m_mCacheNpcTextIdMap[guid] = textid ;
7121 ++count;
7123 } while (result->NextRow());
7124 delete result;
7126 sLog.outString();
7127 sLog.outString( ">> Loaded %d NpcTextId ", count );
7130 void ObjectMgr::LoadNpcOptions()
7132 m_mCacheNpcOptionList.clear(); // For reload case
7134 QueryResult *result = WorldDatabase.Query(
7135 // 0 1 2 3 4 5 6 7 8
7136 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7137 "FROM npc_option");
7139 if( !result )
7141 barGoLink bar( 1 );
7143 bar.step();
7145 sLog.outString();
7146 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7147 return;
7150 barGoLink bar( result->GetRowCount() );
7152 uint32 count = 0;
7156 bar.step();
7158 Field* fields = result->Fetch();
7160 GossipOption go;
7161 go.Id = fields[0].GetUInt32();
7162 go.GossipId = fields[1].GetUInt32();
7163 go.NpcFlag = fields[2].GetUInt32();
7164 go.Icon = fields[3].GetUInt32();
7165 go.Action = fields[4].GetUInt32();
7166 go.BoxMoney = fields[5].GetUInt32();
7167 go.Coded = fields[6].GetUInt8()!=0;
7168 go.OptionText = fields[7].GetCppString();
7169 go.BoxText = fields[8].GetCppString();
7171 m_mCacheNpcOptionList.push_back(go);
7173 ++count;
7175 } while (result->NextRow());
7176 delete result;
7178 sLog.outString();
7179 sLog.outString( ">> Loaded %d npc_option entries", count );
7182 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7184 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7185 vList.AddItem(item,maxcount,incrtime,extendedcost);
7187 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7190 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7192 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7193 if(iter == m_mCacheVendorItemMap.end())
7194 return false;
7196 if(!iter->second.FindItem(item))
7197 return false;
7199 iter->second.RemoveItem(item);
7200 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7201 return true;
7204 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7206 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7207 if(!cInfo)
7209 if(pl)
7210 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7211 else
7212 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7213 return false;
7216 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7218 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7220 if(pl)
7221 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7222 else
7223 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7225 if(skip_vendors)
7226 skip_vendors->insert(vendor_entry);
7228 return false;
7231 if(!GetItemPrototype(item_id))
7233 if(pl)
7234 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7235 else
7236 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7237 return false;
7240 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7242 if(pl)
7243 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7244 else
7245 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7246 return false;
7249 if(maxcount > 0 && incrtime == 0)
7251 if(pl)
7252 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7253 else
7254 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7255 return false;
7257 else if(maxcount==0 && incrtime > 0)
7259 if(pl)
7260 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7261 else
7262 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7263 return false;
7266 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7267 if(!vItems)
7268 return true; // later checks for non-empty lists
7270 if(vItems->FindItem(item_id))
7272 if(pl)
7273 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7274 else
7275 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7276 return false;
7279 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7281 if(pl)
7282 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7283 else
7284 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7285 return false;
7288 return true;
7291 void ObjectMgr::LoadScriptNames()
7293 m_scriptNames.push_back("");
7294 QueryResult *result = WorldDatabase.Query(
7295 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7296 "UNION "
7297 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7298 "UNION "
7299 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7300 "UNION "
7301 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7302 "UNION "
7303 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7305 if( !result )
7307 barGoLink bar( 1 );
7308 bar.step();
7309 sLog.outString();
7310 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7311 return;
7314 barGoLink bar( result->GetRowCount() );
7315 uint32 count = 0;
7319 bar.step();
7320 m_scriptNames.push_back((*result)[0].GetString());
7321 ++count;
7322 } while (result->NextRow());
7323 delete result;
7325 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7326 sLog.outString();
7327 sLog.outString( ">> Loaded %d Script Names", count );
7330 uint32 ObjectMgr::GetScriptId(const char *name)
7332 // use binary search to find the script name in the sorted vector
7333 // assume "" is the first element
7334 if(!name) return 0;
7335 ScriptNameMap::const_iterator itr =
7336 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7337 if(itr == m_scriptNames.end() || *itr != name) return 0;
7338 return itr - m_scriptNames.begin();
7341 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7343 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7345 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7347 if(itrM->second.dataint)
7349 if(!GetMangosStringLocale (itrM->second.dataint))
7350 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7352 if(ids.count(itrM->second.dataint))
7353 ids.erase(itrM->second.dataint);
7359 void ObjectMgr::LoadDbScriptStrings()
7361 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7363 std::set<int32> ids;
7365 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7366 if(GetMangosStringLocale(i))
7367 ids.insert(i);
7369 CheckScripts(sQuestEndScripts,ids);
7370 CheckScripts(sQuestStartScripts,ids);
7371 CheckScripts(sSpellScripts,ids);
7372 CheckScripts(sGameObjectScripts,ids);
7373 CheckScripts(sEventScripts,ids);
7375 WaypointMgr.CheckTextsExistance(ids);
7377 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7378 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7381 // Functions for scripting access
7382 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7384 return objmgr.GetAreaTriggerScriptId(trigger_id);
7387 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7389 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7391 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());
7392 start_value = -1;
7393 end_value = std::numeric_limits<int32>::min();
7396 // for scripting localized strings allowed use _only_ negative entries
7397 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7400 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7402 return objmgr.GetScriptId(name);
7405 ObjectMgr::ScriptNameMap & GetScriptNames()
7407 return objmgr.GetScriptNames();
7410 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7412 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7415 Quest const* GetQuestTemplateStore(uint32 entry)
7417 return objmgr.GetQuestTemplate(entry);