[7689] Batter EventAI loading checks and fix one from possible crash cases.
[getmangos.git] / src / game / ObjectMgr.cpp
blobd87ef41501c17e084b73030aa00cd997bc9e2100
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
23 #include "Policies/SingletonImp.h"
25 #include "Log.h"
26 #include "MapManager.h"
27 #include "ObjectMgr.h"
28 #include "SpellMgr.h"
29 #include "UpdateMask.h"
30 #include "World.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Language.h"
37 #include "GameEventMgr.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
44 #include "WaypointManager.h"
46 INSTANTIATE_SINGLETON_1(ObjectMgr);
48 ScriptMapMap sQuestEndScripts;
49 ScriptMapMap sQuestStartScripts;
50 ScriptMapMap sSpellScripts;
51 ScriptMapMap sGameObjectScripts;
52 ScriptMapMap sEventScripts;
54 bool normalizePlayerName(std::string& name)
56 if(name.empty())
57 return false;
59 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
60 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
62 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
63 return false;
65 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
66 for(size_t i = 1; i < wstr_len; ++i)
67 wstr_buf[i] = wcharToLower(wstr_buf[i]);
69 if(!WStrToUtf8(wstr_buf,wstr_len,name))
70 return false;
72 return true;
75 LanguageDesc lang_description[LANGUAGES_COUNT] =
77 { LANG_ADDON, 0, 0 },
78 { LANG_UNIVERSAL, 0, 0 },
79 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
80 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
81 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
82 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
83 { LANG_COMMON, 668, SKILL_LANG_COMMON },
84 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
85 { LANG_TITAN, 816, SKILL_LANG_TITAN },
86 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
87 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
88 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
89 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
90 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
91 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
92 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
93 { LANG_ZOMBIE, 0, 0 },
94 { LANG_GNOMISH_BINARY, 0, 0 },
95 { LANG_GOBLIN_BINARY, 0, 0 }
98 LanguageDesc const* GetLanguageDescByID(uint32 lang)
100 for(int i = 0; i < LANGUAGES_COUNT; ++i)
102 if(uint32(lang_description[i].lang_id) == lang)
103 return &lang_description[i];
106 return NULL;
109 ObjectMgr::ObjectMgr()
111 m_hiCharGuid = 1;
112 m_hiCreatureGuid = 1;
113 m_hiPetGuid = 1;
114 m_hiVehicleGuid = 1;
115 m_hiItemGuid = 1;
116 m_hiGoGuid = 1;
117 m_hiDoGuid = 1;
118 m_hiCorpseGuid = 1;
119 m_hiPetNumber = 1;
120 m_ItemTextId = 1;
121 m_mailid = 1;
122 m_guildId = 1;
123 m_arenaTeamId = 1;
124 m_auctionid = 1;
126 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
127 mGuildBankTabPrice[0] = 100;
128 mGuildBankTabPrice[1] = 250;
129 mGuildBankTabPrice[2] = 500;
130 mGuildBankTabPrice[3] = 1000;
131 mGuildBankTabPrice[4] = 2500;
132 mGuildBankTabPrice[5] = 5000;
134 // Only zero condition left, others will be added while loading DB tables
135 mConditions.resize(1);
138 ObjectMgr::~ObjectMgr()
140 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
141 delete i->second;
143 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
144 delete[] i->second;
146 // free only if loaded
147 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
148 delete[] playerClassInfo[class_].levelInfo;
150 for (int race = 0; race < MAX_RACES; ++race)
151 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
152 delete[] playerInfo[race][class_].levelInfo;
154 // free group and guild objects
155 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
156 delete (*itr);
158 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
159 delete itr->second;
161 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
162 itr->second.Clear();
164 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
165 itr->second.Clear();
168 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
170 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
171 if ((*itr)->GetLeaderGUID() == guid)
172 return *itr;
174 return NULL;
177 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
179 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
180 if (itr != mGuildMap.end())
181 return itr->second;
183 return NULL;
186 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
188 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
189 if (itr->second->GetName() == guildname)
190 return itr->second;
192 return NULL;
195 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
197 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
198 if (itr != mGuildMap.end())
199 return itr->second->GetName();
201 return "";
204 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
206 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
207 if (itr->second->GetLeader() == guid)
208 return itr->second;
210 return NULL;
213 void ObjectMgr::AddGuild(Guild* guild)
215 mGuildMap[guild->GetId()] = guild;
218 void ObjectMgr::RemoveGuild(uint32 Id)
220 mGuildMap.erase(Id);
223 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
225 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
226 if (itr != mArenaTeamMap.end())
227 return itr->second;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
234 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
235 if (itr->second->GetName() == arenateamname)
236 return itr->second;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
243 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
244 if (itr->second->GetCaptain() == guid)
245 return itr->second;
247 return NULL;
250 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
252 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
255 void ObjectMgr::RemoveArenaTeam(uint32 Id)
257 mArenaTeamMap.erase(Id);
260 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
262 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
265 void ObjectMgr::LoadCreatureLocales()
267 mCreatureLocaleMap.clear(); // need for reload case
269 QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,subname_loc1,name_loc2,subname_loc2,name_loc3,subname_loc3,name_loc4,subname_loc4,name_loc5,subname_loc5,name_loc6,subname_loc6,name_loc7,subname_loc7,name_loc8,subname_loc8 FROM locales_creature");
271 if(!result)
273 barGoLink bar(1);
275 bar.step();
277 sLog.outString();
278 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
279 return;
282 barGoLink bar(result->GetRowCount());
286 Field *fields = result->Fetch();
287 bar.step();
289 uint32 entry = fields[0].GetUInt32();
291 CreatureLocale& data = mCreatureLocaleMap[entry];
293 for(int i = 1; i < MAX_LOCALE; ++i)
295 std::string str = fields[1+2*(i-1)].GetCppString();
296 if(!str.empty())
298 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
299 if(idx >= 0)
301 if(data.Name.size() <= idx)
302 data.Name.resize(idx+1);
304 data.Name[idx] = str;
307 str = fields[1+2*(i-1)+1].GetCppString();
308 if(!str.empty())
310 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
311 if(idx >= 0)
313 if(data.SubName.size() <= idx)
314 data.SubName.resize(idx+1);
316 data.SubName[idx] = str;
320 } while (result->NextRow());
322 delete result;
324 sLog.outString();
325 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
328 void ObjectMgr::LoadNpcOptionLocales()
330 mNpcOptionLocaleMap.clear(); // need for reload case
332 QueryResult *result = WorldDatabase.Query("SELECT entry,"
333 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
334 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
335 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
336 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
337 "FROM locales_npc_option");
339 if(!result)
341 barGoLink bar(1);
343 bar.step();
345 sLog.outString();
346 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
347 return;
350 barGoLink bar(result->GetRowCount());
354 Field *fields = result->Fetch();
355 bar.step();
357 uint32 entry = fields[0].GetUInt32();
359 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
361 for(int i = 1; i < MAX_LOCALE; ++i)
363 std::string str = fields[1+2*(i-1)].GetCppString();
364 if(!str.empty())
366 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
367 if(idx >= 0)
369 if(data.OptionText.size() <= idx)
370 data.OptionText.resize(idx+1);
372 data.OptionText[idx] = str;
375 str = fields[1+2*(i-1)+1].GetCppString();
376 if(!str.empty())
378 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
379 if(idx >= 0)
381 if(data.BoxText.size() <= idx)
382 data.BoxText.resize(idx+1);
384 data.BoxText[idx] = str;
388 } while (result->NextRow());
390 delete result;
392 sLog.outString();
393 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
396 void ObjectMgr::LoadPointOfInterestLocales()
398 mPointOfInterestLocaleMap.clear(); // need for reload case
400 QueryResult *result = WorldDatabase.Query("SELECT entry,icon_name_loc1,icon_name_loc2,icon_name_loc3,icon_name_loc4,icon_name_loc5,icon_name_loc6,icon_name_loc7,icon_name_loc8 FROM locales_points_of_interest");
402 if(!result)
404 barGoLink bar(1);
406 bar.step();
408 sLog.outString();
409 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
410 return;
413 barGoLink bar(result->GetRowCount());
417 Field *fields = result->Fetch();
418 bar.step();
420 uint32 entry = fields[0].GetUInt32();
422 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
424 for(int i = 1; i < MAX_LOCALE; ++i)
426 std::string str = fields[i].GetCppString();
427 if(str.empty())
428 continue;
430 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
431 if(idx >= 0)
433 if(data.IconName.size() <= idx)
434 data.IconName.resize(idx+1);
436 data.IconName[idx] = str;
439 } while (result->NextRow());
441 delete result;
443 sLog.outString();
444 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
447 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
449 template<class D>
450 void convert_from_str(uint32 field_pos, char *src, D &dst)
452 dst = D(objmgr.GetScriptId(src));
456 void ObjectMgr::LoadCreatureTemplates()
458 SQLCreatureLoader loader;
459 loader.Load(sCreatureStorage);
461 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
462 sLog.outString();
464 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
465 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
467 // check data correctness
468 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
470 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
471 if(!cInfo)
472 continue;
474 if(cInfo->HeroicEntry)
476 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
477 if(!heroicInfo)
479 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
480 continue;
483 if(heroicEntries.find(i)!=heroicEntries.end())
485 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
486 continue;
489 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
491 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
492 continue;
495 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
497 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
498 continue;
501 if(cInfo->npcflag != heroicInfo->npcflag)
503 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
504 continue;
507 if(cInfo->classNum != heroicInfo->classNum)
509 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
510 continue;
513 if(cInfo->race != heroicInfo->race)
515 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
516 continue;
519 if(cInfo->trainer_type != heroicInfo->trainer_type)
521 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
522 continue;
525 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
527 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
528 continue;
531 if(heroicInfo->AIName && *heroicInfo->AIName)
533 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `AIName`, but in any case will used normal mode creature (Entry: %u) AIName.",cInfo->HeroicEntry,i);
534 continue;
537 if(heroicInfo->ScriptID)
539 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `ScriptName`, but in any case will used normal mode creature (Entry: %u) ScriptName.",cInfo->HeroicEntry,i);
540 continue;
543 hasHeroicEntries.insert(i);
544 heroicEntries.insert(cInfo->HeroicEntry);
547 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
548 if(!factionTemplate)
549 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
551 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
552 if(!factionTemplate)
553 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
555 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
556 if (!minfo)
557 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
558 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
559 if (!minfo)
560 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
562 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
564 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
565 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
568 if(cInfo->baseattacktime == 0)
569 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
571 if(cInfo->rangeattacktime == 0)
572 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
574 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
575 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
577 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
579 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
580 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
583 // must exist or used hidden but used in data horse case
584 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
586 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
587 const_cast<CreatureInfo*>(cInfo)->family = 0;
590 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
592 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
593 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
596 if(cInfo->PetSpellDataId)
598 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
599 if(!spellDataId)
600 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
603 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
605 if(cInfo->spells[i] && !sSpellStore.LookupEntry(cInfo->spells[i]))
607 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, i+1,cInfo->spells[i]);
608 const_cast<CreatureInfo*>(cInfo)->spells[i] = 0;
612 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
614 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
615 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
618 if(cInfo->equipmentId > 0) // 0 no equipment
620 if(!GetEquipmentInfo(cInfo->equipmentId))
622 sLog.outErrorDb("Table `creature_template` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", cInfo->Entry, cInfo->equipmentId);
623 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
627 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
628 if(cInfo->scale <= 0.0f)
630 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
631 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
636 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
638 // Now add the auras, format "spellid effectindex spellid effectindex..."
639 char *p,*s;
640 std::vector<int> val;
641 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
642 if(p)
644 while (p[0]!=0)
646 ++p;
647 if (p[0]==' ')
649 val.push_back(atoi(s));
650 s=++p;
653 if (p!=s)
654 val.push_back(atoi(s));
656 // free char* loaded memory
657 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
659 // wrong list
660 if (val.size()%2)
662 addon->auras = NULL;
663 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
664 return;
668 // empty list
669 if(val.empty())
671 addon->auras = NULL;
672 return;
675 // replace by new structures array
676 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
678 int i=0;
679 for(int j=0;j<val.size()/2;++j)
681 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
682 cAura.spell_id = (uint32)val[2*j+0];
683 cAura.effect_idx = (uint32)val[2*j+1];
684 if ( cAura.effect_idx > 2 )
686 sLog.outErrorDb("Creature (%s: %u) has wrong effect %u for spell %u in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
687 continue;
689 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
690 if (!AdditionalSpellInfo)
692 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
693 continue;
696 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
698 sLog.outErrorDb("Creature (%s: %u) has not aura effect %u of spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
699 continue;
702 ++i;
705 // fill terminator element (after last added)
706 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
707 endAura.spell_id = 0;
708 endAura.effect_idx = 0;
711 void ObjectMgr::LoadCreatureAddons()
713 sCreatureInfoAddonStorage.Load();
715 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
716 sLog.outString();
718 // check data correctness and convert 'auras'
719 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
721 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
722 if(!addon)
723 continue;
725 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
727 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
728 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
731 sCreatureDataAddonStorage.Load();
733 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
734 sLog.outString();
736 // check data correctness and convert 'auras'
737 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
739 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
740 if(!addon)
741 continue;
743 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
745 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
746 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
750 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
752 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
755 void ObjectMgr::LoadEquipmentTemplates()
757 sEquipmentStorage.Load();
759 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
761 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
763 if(!eqInfo)
764 continue;
766 for(uint8 j=0; j<3; j++)
768 if(!eqInfo->equipentry[j])
769 continue;
771 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
773 if(!dbcitem)
775 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
776 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
777 continue;
780 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
781 dbcitem->InventoryType != INVTYPE_SHIELD &&
782 dbcitem->InventoryType != INVTYPE_RANGED &&
783 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
784 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
785 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
786 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
787 dbcitem->InventoryType != INVTYPE_THROWN &&
788 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
790 sLog.outErrorDb("Item (entry=%u) in creature_equip_template.equipentry%u for entry = %u is not equipable in a hand, forced to 0.", eqInfo->equipentry[j], j+1, i);
791 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
795 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
796 sLog.outString();
798 // This DBC is currently only used for item templates and creature equipments checks.
799 sItemStore.Clear();
802 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
804 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
807 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
809 // Load creature model (display id)
810 uint32 display_id;
811 if (!data || data->displayid == 0) // use defaults from the template
813 // DisplayID_A is used if no team is given
814 if (team == HORDE)
815 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
816 else
817 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
819 else // overridden in creature data
820 display_id = data->displayid;
822 return display_id;
825 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
827 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
828 if(!minfo)
829 return NULL;
831 // If a model for another gender exists, 50% chance to use it
832 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
834 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
835 if(!minfo_tmp)
837 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
838 return minfo; // not fatal, just use the previous one
840 else
841 return minfo_tmp;
843 else
844 return minfo;
847 void ObjectMgr::LoadCreatureModelInfo()
849 sCreatureModelStorage.Load();
851 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
852 sLog.outString();
855 void ObjectMgr::LoadCreatures()
857 uint32 count = 0;
858 // 0 1 2 3
859 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
860 // 4 5 6 7 8 9 10 11
861 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
862 // 12 13 14 15 16 17 18 19
863 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
864 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
865 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
867 if(!result)
869 barGoLink bar(1);
871 bar.step();
873 sLog.outString();
874 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
875 return;
878 // build single time for check creature data
879 std::set<uint32> heroicCreatures;
880 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
881 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
882 if(cInfo->HeroicEntry)
883 heroicCreatures.insert(cInfo->HeroicEntry);
885 barGoLink bar(result->GetRowCount());
889 Field *fields = result->Fetch();
890 bar.step();
892 uint32 guid = fields[ 0].GetUInt32();
893 uint32 entry = fields[ 1].GetUInt32();
895 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
896 if(!cInfo)
898 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
899 continue;
902 CreatureData& data = mCreatureDataMap[guid];
904 data.id = entry;
905 data.mapid = fields[ 2].GetUInt32();
906 data.displayid = fields[ 3].GetUInt32();
907 data.equipmentId = fields[ 4].GetUInt32();
908 data.posX = fields[ 5].GetFloat();
909 data.posY = fields[ 6].GetFloat();
910 data.posZ = fields[ 7].GetFloat();
911 data.orientation = fields[ 8].GetFloat();
912 data.spawntimesecs = fields[ 9].GetUInt32();
913 data.spawndist = fields[10].GetFloat();
914 data.currentwaypoint= fields[11].GetUInt32();
915 data.curhealth = fields[12].GetUInt32();
916 data.curmana = fields[13].GetUInt32();
917 data.is_dead = fields[14].GetBool();
918 data.movementType = fields[15].GetUInt8();
919 data.spawnMask = fields[16].GetUInt8();
920 data.phaseMask = fields[17].GetUInt16();
921 int16 gameEvent = fields[18].GetInt16();
922 int16 PoolId = fields[19].GetInt16();
924 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
926 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
927 continue;
930 if(data.equipmentId > 0) // -1 no equipment, 0 use default
932 if(!GetEquipmentInfo(data.equipmentId))
934 sLog.outErrorDb("Table `creature` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", data.id, data.equipmentId);
935 data.equipmentId = -1;
939 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
941 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`RegenHealth`=1 and low current health (%u), `creature_template`.`minhealth`=%u.",guid,data.id,data.curhealth, cInfo->minhealth );
942 data.curhealth = cInfo->minhealth;
945 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
947 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
948 if(!map || !map->IsDungeon())
949 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`flags_extra` including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.",guid,data.id);
952 if(data.curmana < cInfo->minmana)
954 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with low current mana (%u), `creature_template`.`minmana`=%u.",guid,data.id,data.curmana, cInfo->minmana );
955 data.curmana = cInfo->minmana;
958 if(data.spawndist < 0.0f)
960 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
961 data.spawndist = 0.0f;
963 else if(data.movementType == RANDOM_MOTION_TYPE)
965 if(data.spawndist == 0.0f)
967 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=1 (random movement) but with `spawndist`=0, replace by idle movement type (0).",guid,data.id );
968 data.movementType = IDLE_MOTION_TYPE;
971 else if(data.movementType == IDLE_MOTION_TYPE)
973 if(data.spawndist != 0.0f)
975 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
976 data.spawndist = 0.0f;
980 if(data.phaseMask==0)
982 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
983 data.phaseMask = 1;
986 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
987 AddCreatureToGrid(guid, &data);
989 ++count;
991 } while (result->NextRow());
993 delete result;
995 sLog.outString();
996 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
999 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1001 uint8 mask = data->spawnMask;
1002 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1004 if(mask & 1)
1006 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1007 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1009 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1010 cell_guids.creatures.insert(guid);
1015 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1017 uint8 mask = data->spawnMask;
1018 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1020 if(mask & 1)
1022 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1023 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1025 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1026 cell_guids.creatures.erase(guid);
1031 void ObjectMgr::LoadGameobjects()
1033 uint32 count = 0;
1035 // 0 1 2 3 4 5 6
1036 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1037 // 7 8 9 10 11 12 13 14 15 16 17
1038 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1039 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1040 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1042 if(!result)
1044 barGoLink bar(1);
1046 bar.step();
1048 sLog.outString();
1049 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1050 return;
1053 barGoLink bar(result->GetRowCount());
1057 Field *fields = result->Fetch();
1058 bar.step();
1060 uint32 guid = fields[ 0].GetUInt32();
1061 uint32 entry = fields[ 1].GetUInt32();
1063 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1064 if(!gInfo)
1066 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1067 continue;
1070 GameObjectData& data = mGameObjectDataMap[guid];
1072 data.id = entry;
1073 data.mapid = fields[ 2].GetUInt32();
1074 data.posX = fields[ 3].GetFloat();
1075 data.posY = fields[ 4].GetFloat();
1076 data.posZ = fields[ 5].GetFloat();
1077 data.orientation = fields[ 6].GetFloat();
1078 data.rotation0 = fields[ 7].GetFloat();
1079 data.rotation1 = fields[ 8].GetFloat();
1080 data.rotation2 = fields[ 9].GetFloat();
1081 data.rotation3 = fields[10].GetFloat();
1082 data.spawntimesecs = fields[11].GetInt32();
1083 data.animprogress = fields[12].GetUInt32();
1084 data.go_state = fields[13].GetUInt32();
1085 data.spawnMask = fields[14].GetUInt8();
1086 data.phaseMask = fields[15].GetUInt16();
1087 int16 gameEvent = fields[16].GetInt16();
1088 int16 PoolId = fields[17].GetInt16();
1090 if(data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1092 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip",guid,data.id,data.rotation2 );
1093 continue;
1096 if(data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1098 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip",guid,data.id,data.rotation3 );
1099 continue;
1102 if(!MapManager::IsValidMapCoord(data.mapid,data.posX,data.posY,data.posZ,data.orientation))
1104 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip",guid,data.id );
1105 continue;
1108 if(data.phaseMask==0)
1110 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1111 data.phaseMask = 1;
1114 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1115 AddGameobjectToGrid(guid, &data);
1116 ++count;
1118 } while (result->NextRow());
1120 delete result;
1122 sLog.outString();
1123 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1126 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1128 uint8 mask = data->spawnMask;
1129 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1131 if(mask & 1)
1133 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1134 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1136 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1137 cell_guids.gameobjects.insert(guid);
1142 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1144 uint8 mask = data->spawnMask;
1145 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1147 if(mask & 1)
1149 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1150 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1152 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1153 cell_guids.gameobjects.erase(guid);
1158 void ObjectMgr::LoadCreatureRespawnTimes()
1160 // remove outdated data
1161 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1163 uint32 count = 0;
1165 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1167 if(!result)
1169 barGoLink bar(1);
1171 bar.step();
1173 sLog.outString();
1174 sLog.outString(">> Loaded 0 creature respawn time.");
1175 return;
1178 barGoLink bar(result->GetRowCount());
1182 Field *fields = result->Fetch();
1183 bar.step();
1185 uint32 loguid = fields[0].GetUInt32();
1186 uint64 respawn_time = fields[1].GetUInt64();
1187 uint32 instance = fields[2].GetUInt32();
1189 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1191 ++count;
1192 } while (result->NextRow());
1194 delete result;
1196 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1197 sLog.outString();
1200 void ObjectMgr::LoadGameobjectRespawnTimes()
1202 // remove outdated data
1203 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1205 uint32 count = 0;
1207 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1209 if(!result)
1211 barGoLink bar(1);
1213 bar.step();
1215 sLog.outString();
1216 sLog.outString(">> Loaded 0 gameobject respawn time.");
1217 return;
1220 barGoLink bar(result->GetRowCount());
1224 Field *fields = result->Fetch();
1225 bar.step();
1227 uint32 loguid = fields[0].GetUInt32();
1228 uint64 respawn_time = fields[1].GetUInt64();
1229 uint32 instance = fields[2].GetUInt32();
1231 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1233 ++count;
1234 } while (result->NextRow());
1236 delete result;
1238 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1239 sLog.outString();
1242 // name must be checked to correctness (if received) before call this function
1243 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1245 uint64 guid = 0;
1247 CharacterDatabase.escape_string(name);
1249 // Player name safe to sending to DB (checked at login) and this function using
1250 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1251 if(result)
1253 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1255 delete result;
1258 return guid;
1261 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1263 // prevent DB access for online player
1264 if(Player* player = GetPlayer(guid))
1266 name = player->GetName();
1267 return true;
1270 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1272 if(result)
1274 name = (*result)[0].GetCppString();
1275 delete result;
1276 return true;
1279 return false;
1282 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1284 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1286 if(result)
1288 uint8 race = (*result)[0].GetUInt8();
1289 delete result;
1290 return Player::TeamForRace(race);
1293 return 0;
1296 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1298 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1299 if(result)
1301 uint32 acc = (*result)[0].GetUInt32();
1302 delete result;
1303 return acc;
1306 return 0;
1309 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1311 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1312 if(result)
1314 uint32 acc = (*result)[0].GetUInt32();
1315 delete result;
1316 return acc;
1319 return 0;
1322 void ObjectMgr::LoadItemLocales()
1324 mItemLocaleMap.clear(); // need for reload case
1326 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");
1328 if(!result)
1330 barGoLink bar(1);
1332 bar.step();
1334 sLog.outString();
1335 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1336 return;
1339 barGoLink bar(result->GetRowCount());
1343 Field *fields = result->Fetch();
1344 bar.step();
1346 uint32 entry = fields[0].GetUInt32();
1348 ItemLocale& data = mItemLocaleMap[entry];
1350 for(int i = 1; i < MAX_LOCALE; ++i)
1352 std::string str = fields[1+2*(i-1)].GetCppString();
1353 if(!str.empty())
1355 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1356 if(idx >= 0)
1358 if(data.Name.size() <= idx)
1359 data.Name.resize(idx+1);
1361 data.Name[idx] = str;
1365 str = fields[1+2*(i-1)+1].GetCppString();
1366 if(!str.empty())
1368 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1369 if(idx >= 0)
1371 if(data.Description.size() <= idx)
1372 data.Description.resize(idx+1);
1374 data.Description[idx] = str;
1378 } while (result->NextRow());
1380 delete result;
1382 sLog.outString();
1383 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1386 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1388 template<class D>
1389 void convert_from_str(uint32 field_pos, char *src, D &dst)
1391 dst = D(objmgr.GetScriptId(src));
1395 void ObjectMgr::LoadItemPrototypes()
1397 SQLItemLoader loader;
1398 loader.Load(sItemStorage);
1399 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1400 sLog.outString();
1402 // check data correctness
1403 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1405 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1406 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1407 if(!proto)
1409 /* to many errors, and possible not all items really used in game
1410 if (dbcitem)
1411 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1413 continue;
1416 if(dbcitem)
1418 if(proto->Class != dbcitem->Class)
1420 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1421 // It safe let use Class from DB
1423 /* disabled: have some strange wrong cases for Subclass values.
1424 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1425 if(proto->SubClass != dbcitem->SubClass)
1427 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);
1428 // It safe let use Subclass from DB
1432 if(proto->Unk0 != dbcitem->Unk0)
1434 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1435 // It safe let use Unk0 from DB
1438 if(proto->Material != dbcitem->Material)
1440 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1441 // It safe let use Material from DB
1444 if(proto->InventoryType != dbcitem->InventoryType)
1446 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1447 // It safe let use InventoryType from DB
1450 if(proto->DisplayInfoID != dbcitem->DisplayId)
1452 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1453 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1455 if(proto->Sheath != dbcitem->Sheath)
1457 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1458 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1461 else
1463 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1466 if(proto->Class >= MAX_ITEM_CLASS)
1468 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1469 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1472 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1474 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1475 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1478 if(proto->Quality >= MAX_ITEM_QUALITY)
1480 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1481 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1484 if(proto->BuyCount <= 0)
1486 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1487 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1490 if(proto->InventoryType >= MAX_INVTYPE)
1492 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1493 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1496 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1498 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1499 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1504 // can be used in equip slot, as page read use in inventory, or spell casting at use
1505 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1506 if(!req)
1508 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1510 if(proto->Spells[j].SpellId)
1512 req = true;
1513 break;
1518 if(req)
1520 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1521 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1523 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1524 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1528 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1530 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1531 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1534 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1535 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1537 if(proto->RequiredReputationFaction)
1539 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1541 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1542 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1545 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1546 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1548 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1549 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1551 if(proto->MaxCount < -1)
1553 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1554 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1557 if(proto->Stackable==0)
1559 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1560 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1562 else if(proto->Stackable < -1)
1564 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1565 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1567 else if(proto->Stackable > 255)
1569 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1570 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1573 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1575 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1576 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1579 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1581 // for ItemStatValue != 0
1582 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1584 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1585 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1589 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1591 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1593 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1594 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1598 // special format
1599 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1601 // spell_1
1602 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1604 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);
1605 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1606 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1607 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1608 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1611 // spell_2 have learning spell
1612 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1614 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);
1615 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1616 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1617 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1619 else if(!proto->Spells[1].SpellId)
1621 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1622 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1623 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1625 else
1627 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1628 if(!spellInfo)
1630 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1631 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1632 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1633 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1635 // allowed only in special format
1636 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1638 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1639 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1640 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1641 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1645 // spell_3*,spell_4*,spell_5* is empty
1646 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1648 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1650 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1651 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1652 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1654 else if(proto->Spells[j].SpellId != 0)
1656 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1657 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1661 // normal spell list
1662 else
1664 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1666 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1668 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1669 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1670 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1673 if(proto->Spells[j].SpellId)
1675 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1676 if(!spellInfo)
1678 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1679 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1681 // allowed only in special format
1682 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1684 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1685 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1691 if(proto->Bonding >= MAX_BIND_TYPE)
1692 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1694 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1695 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1697 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1698 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1700 if(proto->Sheath >= MAX_SHEATHETYPE)
1702 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1703 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1706 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1708 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1709 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1712 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1714 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1715 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1718 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1720 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1721 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1724 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1725 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1727 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1728 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1730 if(proto->BagFamily)
1732 // check bits
1733 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1735 uint32 mask = 1 << j;
1736 if((proto->BagFamily & mask)==0)
1737 continue;
1739 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1740 if(!bf)
1742 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
1743 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1744 continue;
1747 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
1749 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
1750 if(!ctEntry)
1752 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
1753 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1759 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1760 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1762 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; j++)
1764 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1766 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1767 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1771 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1772 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1774 if(proto->FoodType >= MAX_PET_DIET)
1776 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1777 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1780 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1782 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1783 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1788 void ObjectMgr::LoadPetLevelInfo()
1790 // Loading levels data
1792 // 0 1 2 3 4 5 6 7 8 9
1793 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1795 uint32 count = 0;
1797 if (!result)
1799 barGoLink bar( 1 );
1801 sLog.outString();
1802 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1803 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1804 return;
1807 barGoLink bar( result->GetRowCount() );
1811 Field* fields = result->Fetch();
1813 uint32 creature_id = fields[0].GetUInt32();
1814 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1816 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1817 continue;
1820 uint32 current_level = fields[1].GetUInt32();
1821 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1823 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1824 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1825 else
1827 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1828 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
1830 continue;
1832 else if(current_level < 1)
1834 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1835 continue;
1838 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1840 if(pInfoMapEntry==NULL)
1841 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1843 // data for level 1 stored in [0] array element, ...
1844 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1846 pLevelInfo->health = fields[2].GetUInt16();
1847 pLevelInfo->mana = fields[3].GetUInt16();
1848 pLevelInfo->armor = fields[9].GetUInt16();
1850 for (int i = 0; i < MAX_STATS; i++)
1852 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1855 bar.step();
1856 ++count;
1858 while (result->NextRow());
1860 delete result;
1862 sLog.outString();
1863 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1866 // Fill gaps and check integrity
1867 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1869 PetLevelInfo* pInfo = itr->second;
1871 // fatal error if no level 1 data
1872 if(!pInfo || pInfo[0].health == 0 )
1874 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1875 exit(1);
1878 // fill level gaps
1879 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1881 if(pInfo[level].health == 0)
1883 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1884 pInfo[level] = pInfo[level-1];
1890 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1892 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1893 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1895 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1896 if(itr == petInfo.end())
1897 return NULL;
1899 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1902 void ObjectMgr::LoadPlayerInfo()
1904 // Load playercreate
1906 // 0 1 2 3 4 5 6
1907 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1909 uint32 count = 0;
1911 if (!result)
1913 barGoLink bar( 1 );
1915 sLog.outString();
1916 sLog.outString( ">> Loaded %u player create definitions", count );
1917 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1918 exit(1);
1921 barGoLink bar( result->GetRowCount() );
1925 Field* fields = result->Fetch();
1927 uint32 current_race = fields[0].GetUInt32();
1928 uint32 current_class = fields[1].GetUInt32();
1929 uint32 mapId = fields[2].GetUInt32();
1930 uint32 zoneId = fields[3].GetUInt32();
1931 float positionX = fields[4].GetFloat();
1932 float positionY = fields[5].GetFloat();
1933 float positionZ = fields[6].GetFloat();
1935 if(current_race >= MAX_RACES)
1937 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1938 continue;
1941 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1942 if(!rEntry)
1944 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1945 continue;
1948 if(current_class >= MAX_CLASSES)
1950 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1951 continue;
1954 if(!sChrClassesStore.LookupEntry(current_class))
1956 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1957 continue;
1960 // accept DB data only for valid position (and non instanceable)
1961 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1963 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1964 continue;
1967 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1969 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1970 continue;
1973 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1975 pInfo->mapId = mapId;
1976 pInfo->zoneId = zoneId;
1977 pInfo->positionX = positionX;
1978 pInfo->positionY = positionY;
1979 pInfo->positionZ = positionZ;
1981 pInfo->displayId_m = rEntry->model_m;
1982 pInfo->displayId_f = rEntry->model_f;
1984 bar.step();
1985 ++count;
1987 while (result->NextRow());
1989 delete result;
1991 sLog.outString();
1992 sLog.outString( ">> Loaded %u player create definitions", count );
1995 // Load playercreate items
1997 // 0 1 2 3
1998 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2000 uint32 count = 0;
2002 if (!result)
2004 barGoLink bar( 1 );
2006 bar.step();
2008 sLog.outString();
2009 sLog.outString( ">> Loaded %u custom player create items", count );
2011 else
2013 barGoLink bar( result->GetRowCount() );
2017 Field* fields = result->Fetch();
2019 uint32 current_race = fields[0].GetUInt32();
2020 if(current_race >= MAX_RACES)
2022 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2023 continue;
2026 uint32 current_class = fields[1].GetUInt32();
2027 if(current_class >= MAX_CLASSES)
2029 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2030 continue;
2033 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2035 uint32 item_id = fields[2].GetUInt32();
2037 if(!GetItemPrototype(item_id))
2039 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);
2040 continue;
2043 uint32 amount = fields[3].GetUInt32();
2045 if(!amount)
2047 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2048 continue;
2051 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2053 bar.step();
2054 ++count;
2056 while(result->NextRow());
2058 delete result;
2060 sLog.outString();
2061 sLog.outString( ">> Loaded %u custom player create items", count );
2065 // Load playercreate spells
2067 // 0 1 2
2068 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2070 uint32 count = 0;
2072 if (!result)
2074 barGoLink bar( 1 );
2076 sLog.outString();
2077 sLog.outString( ">> Loaded %u player create spells", count );
2078 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2080 else
2082 barGoLink bar( result->GetRowCount() );
2086 Field* fields = result->Fetch();
2088 uint32 current_race = fields[0].GetUInt32();
2089 if(current_race >= MAX_RACES)
2091 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2092 continue;
2095 uint32 current_class = fields[1].GetUInt32();
2096 if(current_class >= MAX_CLASSES)
2098 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2099 continue;
2102 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2103 pInfo->spell.push_back(fields[2].GetUInt32());
2105 bar.step();
2106 ++count;
2108 while( result->NextRow() );
2110 delete result;
2112 sLog.outString();
2113 sLog.outString( ">> Loaded %u player create spells", count );
2117 // Load playercreate actions
2119 // 0 1 2 3 4 5
2120 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2122 uint32 count = 0;
2124 if (!result)
2126 barGoLink bar( 1 );
2128 sLog.outString();
2129 sLog.outString( ">> Loaded %u player create actions", count );
2130 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2132 else
2134 barGoLink bar( result->GetRowCount() );
2138 Field* fields = result->Fetch();
2140 uint32 current_race = fields[0].GetUInt32();
2141 if(current_race >= MAX_RACES)
2143 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2144 continue;
2147 uint32 current_class = fields[1].GetUInt32();
2148 if(current_class >= MAX_CLASSES)
2150 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2151 continue;
2154 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2155 pInfo->action[0].push_back(fields[2].GetUInt16());
2156 pInfo->action[1].push_back(fields[3].GetUInt16());
2157 pInfo->action[2].push_back(fields[4].GetUInt16());
2158 pInfo->action[3].push_back(fields[5].GetUInt16());
2160 bar.step();
2161 ++count;
2163 while( result->NextRow() );
2165 delete result;
2167 sLog.outString();
2168 sLog.outString( ">> Loaded %u player create actions", count );
2172 // Loading levels data (class only dependent)
2174 // 0 1 2 3
2175 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2177 uint32 count = 0;
2179 if (!result)
2181 barGoLink bar( 1 );
2183 sLog.outString();
2184 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2185 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2186 exit(1);
2189 barGoLink bar( result->GetRowCount() );
2193 Field* fields = result->Fetch();
2195 uint32 current_class = fields[0].GetUInt32();
2196 if(current_class >= MAX_CLASSES)
2198 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2199 continue;
2202 uint32 current_level = fields[1].GetUInt32();
2203 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2205 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2206 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2207 else
2209 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2210 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2212 continue;
2215 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2217 if(!pClassInfo->levelInfo)
2218 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2220 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2222 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2223 pClassLevelInfo->basemana = fields[3].GetUInt16();
2225 bar.step();
2226 ++count;
2228 while (result->NextRow());
2230 delete result;
2232 sLog.outString();
2233 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2236 // Fill gaps and check integrity
2237 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2239 // skip non existed classes
2240 if(!sChrClassesStore.LookupEntry(class_))
2241 continue;
2243 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2245 // fatal error if no level 1 data
2246 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2248 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2249 exit(1);
2252 // fill level gaps
2253 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2255 if(pClassInfo->levelInfo[level].basehealth == 0)
2257 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2258 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2263 // Loading levels data (class/race dependent)
2265 // 0 1 2 3 4 5 6 7
2266 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2268 uint32 count = 0;
2270 if (!result)
2272 barGoLink bar( 1 );
2274 sLog.outString();
2275 sLog.outString( ">> Loaded %u level stats definitions", count );
2276 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2277 exit(1);
2280 barGoLink bar( result->GetRowCount() );
2284 Field* fields = result->Fetch();
2286 uint32 current_race = fields[0].GetUInt32();
2287 if(current_race >= MAX_RACES)
2289 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2290 continue;
2293 uint32 current_class = fields[1].GetUInt32();
2294 if(current_class >= MAX_CLASSES)
2296 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2297 continue;
2300 uint32 current_level = fields[2].GetUInt32();
2301 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2303 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2304 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2305 else
2307 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2308 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2310 continue;
2313 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2315 if(!pInfo->levelInfo)
2316 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2318 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2320 for (int i = 0; i < MAX_STATS; i++)
2322 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2325 bar.step();
2326 ++count;
2328 while (result->NextRow());
2330 delete result;
2332 sLog.outString();
2333 sLog.outString( ">> Loaded %u level stats definitions", count );
2336 // Fill gaps and check integrity
2337 for (int race = 0; race < MAX_RACES; ++race)
2339 // skip non existed races
2340 if(!sChrRacesStore.LookupEntry(race))
2341 continue;
2343 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2345 // skip non existed classes
2346 if(!sChrClassesStore.LookupEntry(class_))
2347 continue;
2349 PlayerInfo* pInfo = &playerInfo[race][class_];
2351 // skip non loaded combinations
2352 if(!pInfo->displayId_m || !pInfo->displayId_f)
2353 continue;
2355 // skip expansion races if not playing with expansion
2356 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2357 continue;
2359 // skip expansion classes if not playing with expansion
2360 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2361 continue;
2363 // fatal error if no level 1 data
2364 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2366 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2367 exit(1);
2370 // fill level gaps
2371 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2373 if(pInfo->levelInfo[level].stats[0] == 0)
2375 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2376 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2382 // Loading xp per level data
2384 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2385 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2386 mPlayerXPperLevel[level] = 0;
2388 // 0 1
2389 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2391 uint32 count = 0;
2393 if (!result)
2395 barGoLink bar( 1 );
2397 sLog.outString();
2398 sLog.outString( ">> Loaded %u xp for level definitions", count );
2399 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2400 exit(1);
2403 barGoLink bar( result->GetRowCount() );
2407 Field* fields = result->Fetch();
2409 uint32 current_level = fields[0].GetUInt32();
2410 uint32 current_xp = fields[1].GetUInt32();
2412 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2414 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2415 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2416 else
2418 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2419 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2421 continue;
2423 //PlayerXPperLevel
2424 mPlayerXPperLevel[current_level] = current_xp;
2425 bar.step();
2426 ++count;
2428 while (result->NextRow());
2430 delete result;
2432 sLog.outString();
2433 sLog.outString( ">> Loaded %u xp for level definitions", count );
2436 // fill level gaps
2437 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2439 if( mPlayerXPperLevel[level] == 0)
2441 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2442 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2447 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2449 if(level < 1 || class_ >= MAX_CLASSES)
2450 return;
2452 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2454 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2455 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2457 *info = pInfo->levelInfo[level-1];
2460 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2462 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2463 return;
2465 PlayerInfo const* pInfo = &playerInfo[race][class_];
2466 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2467 return;
2469 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2470 *info = pInfo->levelInfo[level-1];
2471 else
2472 BuildPlayerLevelInfo(race,class_,level,info);
2475 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2477 // base data (last known level)
2478 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2480 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2482 switch(_class)
2484 case CLASS_WARRIOR:
2485 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2486 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2487 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2488 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2489 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2490 break;
2491 case CLASS_PALADIN:
2492 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2493 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2494 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2495 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2496 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2497 break;
2498 case CLASS_HUNTER:
2499 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2500 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2501 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2502 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2503 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2504 break;
2505 case CLASS_ROGUE:
2506 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2507 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2508 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2509 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2510 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2511 break;
2512 case CLASS_PRIEST:
2513 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2514 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2515 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2516 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2517 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2518 break;
2519 case CLASS_SHAMAN:
2520 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2521 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2522 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2523 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2524 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2525 break;
2526 case CLASS_MAGE:
2527 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2528 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2529 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2530 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2531 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2532 break;
2533 case CLASS_WARLOCK:
2534 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2535 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2536 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2537 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2538 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2539 break;
2540 case CLASS_DRUID:
2541 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2542 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2543 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2544 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2545 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2550 void ObjectMgr::LoadGuilds()
2552 Guild *newguild;
2553 uint32 count = 0;
2555 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2557 if( !result )
2560 barGoLink bar( 1 );
2562 bar.step();
2564 sLog.outString();
2565 sLog.outString( ">> Loaded %u guild definitions", count );
2566 return;
2569 barGoLink bar( result->GetRowCount() );
2573 Field *fields = result->Fetch();
2575 bar.step();
2576 ++count;
2578 newguild = new Guild;
2579 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2581 newguild->Disband();
2582 delete newguild;
2583 continue;
2585 AddGuild(newguild);
2587 }while( result->NextRow() );
2589 delete result;
2591 sLog.outString();
2592 sLog.outString( ">> Loaded %u guild definitions", count );
2595 void ObjectMgr::LoadArenaTeams()
2597 uint32 count = 0;
2599 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2601 if( !result )
2604 barGoLink bar( 1 );
2606 bar.step();
2608 sLog.outString();
2609 sLog.outString( ">> Loaded %u arenateam definitions", count );
2610 return;
2613 barGoLink bar( result->GetRowCount() );
2617 Field *fields = result->Fetch();
2619 bar.step();
2620 ++count;
2622 ArenaTeam *newarenateam = new ArenaTeam;
2623 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2625 delete newarenateam;
2626 continue;
2628 AddArenaTeam(newarenateam);
2629 }while( result->NextRow() );
2631 delete result;
2633 sLog.outString();
2634 sLog.outString( ">> Loaded %u arenateam definitions", count );
2637 void ObjectMgr::LoadGroups()
2639 // -- loading groups --
2640 Group *group = NULL;
2641 uint64 leaderGuid = 0;
2642 uint32 count = 0;
2643 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2644 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2646 if( !result )
2648 barGoLink bar( 1 );
2650 bar.step();
2652 sLog.outString();
2653 sLog.outString( ">> Loaded %u group definitions", count );
2654 return;
2657 barGoLink bar( result->GetRowCount() );
2661 bar.step();
2662 Field *fields = result->Fetch();
2663 ++count;
2664 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2666 group = new Group;
2667 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2669 group->Disband();
2670 delete group;
2671 continue;
2673 AddGroup(group);
2674 }while( result->NextRow() );
2676 delete result;
2678 sLog.outString();
2679 sLog.outString( ">> Loaded %u group definitions", count );
2681 // -- loading members --
2682 count = 0;
2683 group = NULL;
2684 leaderGuid = 0;
2685 // 0 1 2 3
2686 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2687 if(!result)
2689 barGoLink bar( 1 );
2690 bar.step();
2692 else
2694 barGoLink bar( result->GetRowCount() );
2697 bar.step();
2698 Field *fields = result->Fetch();
2699 count++;
2700 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2701 if(!group || group->GetLeaderGUID() != leaderGuid)
2703 group = GetGroupByLeader(leaderGuid);
2704 if(!group)
2706 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2707 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2708 continue;
2712 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2714 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2715 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2717 }while( result->NextRow() );
2718 delete result;
2721 // clean groups
2722 // TODO: maybe delete from the DB before loading in this case
2723 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2725 if((*itr)->GetMembersCount() < 2)
2727 (*itr)->Disband();
2728 delete *itr;
2729 mGroupSet.erase(itr++);
2731 else
2732 ++itr;
2735 // -- loading instances --
2736 count = 0;
2737 group = NULL;
2738 leaderGuid = 0;
2739 result = CharacterDatabase.Query(
2740 // 0 1 2 3 4 5
2741 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2742 // 6
2743 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2744 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2747 if(!result)
2749 barGoLink bar( 1 );
2750 bar.step();
2752 else
2754 barGoLink bar( result->GetRowCount() );
2757 bar.step();
2758 Field *fields = result->Fetch();
2759 count++;
2760 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2761 if(!group || group->GetLeaderGUID() != leaderGuid)
2763 group = GetGroupByLeader(leaderGuid);
2764 if(!group)
2766 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2767 continue;
2771 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
2772 if(!mapEntry || !mapEntry->IsDungeon())
2774 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
2775 continue;
2778 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2779 group->BindToInstance(save, fields[3].GetBool(), true);
2780 }while( result->NextRow() );
2781 delete result;
2784 sLog.outString();
2785 sLog.outString( ">> Loaded %u group-instance binds total", count );
2787 sLog.outString();
2788 sLog.outString( ">> Loaded %u group members total", count );
2791 void ObjectMgr::LoadQuests()
2793 // For reload case
2794 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2795 delete itr->second;
2796 mQuestTemplates.clear();
2798 mExclusiveQuestGroups.clear();
2800 // 0 1 2 3 4 5 6 7 8
2801 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2802 // 9 10 11 12 13 14 15 16
2803 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2804 // 17 18 19 20 21 22 23 24 25 26 27 28
2805 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2806 // 29 30 31 32 33 34 35 36 37 38
2807 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2808 // 39 40 41 42 43 44 45 46
2809 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2810 // 47 48 49 50 51 52 53 54
2811 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
2812 // 55 56 57 58 59 60 61 62
2813 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2814 // 63 64 65 66
2815 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2816 // 67 68 69 70 71 72
2817 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2818 // 73 74 75 76 77 78
2819 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2820 // 79 80 81 82 83 84 85 86
2821 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2822 // 87 88 89 90 91 92 93 94 95 96
2823 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2824 // 97 98 99 100 101 102 103 104 105 106 107
2825 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2826 // 108 109 110 111 112 113 114 115 116 117
2827 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2828 // 118 119
2829 "StartScript, CompleteScript"
2830 " FROM quest_template");
2831 if(result == NULL)
2833 barGoLink bar( 1 );
2834 bar.step();
2836 sLog.outString();
2837 sLog.outString( ">> Loaded 0 quests definitions" );
2838 sLog.outErrorDb("`quest_template` table is empty!");
2839 return;
2842 // create multimap previous quest for each existed quest
2843 // some quests can have many previous maps set by NextQuestId in previous quest
2844 // for example set of race quests can lead to single not race specific quest
2845 barGoLink bar( result->GetRowCount() );
2848 bar.step();
2849 Field *fields = result->Fetch();
2851 Quest * newQuest = new Quest(fields);
2852 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2853 } while( result->NextRow() );
2855 delete result;
2857 // Post processing
2858 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2860 Quest * qinfo = iter->second;
2862 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2864 if( qinfo->GetQuestMethod() >= 3 )
2866 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2869 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2871 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2872 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2873 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2876 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2878 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2880 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2881 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2885 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2887 // at auto-reward can be rewarded only RewChoiceItemId[0]
2888 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2890 if(uint32 id = qinfo->RewChoiceItemId[j])
2892 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2893 qinfo->GetQuestId(),j+1,id,j+1);
2894 // no changes, quest ignore this data
2899 // client quest log visual (area case)
2900 if( qinfo->ZoneOrSort > 0 )
2902 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2904 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2905 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2906 // no changes, quest not dependent from this value but can have problems at client
2909 // client quest log visual (sort case)
2910 if( qinfo->ZoneOrSort < 0 )
2912 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2913 if( !qSort )
2915 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2916 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2917 // 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)
2919 //check SkillOrClass value (class case).
2920 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2922 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2923 if(qinfo->SkillOrClass < 0)
2925 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2926 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2929 //check for proper SkillOrClass value (skill case)
2930 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2932 // skill is positive value in SkillOrClass
2933 if(qinfo->SkillOrClass != skill_id )
2935 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2936 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2937 //override, and force proper value here?
2942 // SkillOrClass (class case)
2943 if( qinfo->SkillOrClass < 0 )
2945 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2947 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2948 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2951 // SkillOrClass (skill case)
2952 if( qinfo->SkillOrClass > 0 )
2954 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2956 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2957 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2961 if( qinfo->RequiredSkillValue )
2963 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2965 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2966 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2967 // no changes, quest can't be done for this requirement
2970 if( qinfo->SkillOrClass <= 0 )
2972 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2973 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2974 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2977 // else Skill quests can have 0 skill level, this is ok
2979 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2981 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2982 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2983 // no changes, quest can't be done for this requirement
2986 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2988 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2989 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2990 // no changes, quest can't be done for this requirement
2993 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2995 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2996 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2997 // no changes, quest can't be done for this requirement
3000 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3002 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3003 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3004 // no changes, quest can't be done for this requirement
3007 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3009 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3010 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3011 // no changes, quest can't be done for this requirement
3014 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3016 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3017 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3018 // warning
3021 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3023 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3024 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3025 // warning
3028 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3030 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3031 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3032 // warning
3035 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3037 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3038 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3039 qinfo->CharTitleId = 0;
3040 // quest can't reward this title
3043 if(qinfo->SrcItemId)
3045 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3047 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3048 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3049 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3051 else if(qinfo->SrcItemCount==0)
3053 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3054 qinfo->GetQuestId(),qinfo->SrcItemId);
3055 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3058 else if(qinfo->SrcItemCount>0)
3060 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3061 qinfo->GetQuestId(),qinfo->SrcItemCount);
3062 qinfo->SrcItemCount=0; // no quest work changes in fact
3065 if(qinfo->SrcSpell)
3067 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3068 if(!spellInfo)
3070 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3071 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3072 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3074 else if(!SpellMgr::IsSpellValid(spellInfo))
3076 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3077 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3078 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3082 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3084 uint32 id = qinfo->ReqItemId[j];
3085 if(id)
3087 if(qinfo->ReqItemCount[j]==0)
3089 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3090 qinfo->GetQuestId(),j+1,id,j+1);
3091 // no changes, quest can't be done for this requirement
3094 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3096 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3098 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3099 qinfo->GetQuestId(),j+1,id,id);
3100 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3103 else if(qinfo->ReqItemCount[j]>0)
3105 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3106 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3107 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3111 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3113 uint32 id = qinfo->ReqSourceId[j];
3114 if(id)
3116 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3118 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3119 qinfo->GetQuestId(),j+1,id,id);
3120 // no changes, quest can't be done for this requirement
3123 else
3125 if(qinfo->ReqSourceCount[j]>0)
3127 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3128 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3129 // no changes, quest ignore this data
3134 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3136 uint32 id = qinfo->ReqSpell[j];
3137 if(id)
3139 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3140 if(!spellInfo)
3142 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3143 qinfo->GetQuestId(),j+1,id,id);
3144 // no changes, quest can't be done for this requirement
3147 if(!qinfo->ReqCreatureOrGOId[j])
3149 bool found = false;
3150 for(int k = 0; k < 3; ++k)
3152 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3153 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3155 found = true;
3156 break;
3160 if(found)
3162 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3164 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);
3166 // this will prevent quest completing without objective
3167 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3170 else
3172 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.",
3173 qinfo->GetQuestId(),j+1,id,j+1,id);
3174 // no changes, quest can't be done for this requirement
3180 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3182 int32 id = qinfo->ReqCreatureOrGOId[j];
3183 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3185 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3186 qinfo->GetQuestId(),j+1,id,uint32(-id));
3187 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3190 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3192 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3193 qinfo->GetQuestId(),j+1,id,uint32(id));
3194 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3197 if(id)
3199 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3201 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3203 if(!qinfo->ReqCreatureOrGOCount[j])
3205 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3206 qinfo->GetQuestId(),j+1,id,j+1);
3207 // no changes, quest can be incorrectly done, but we already report this
3210 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3212 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3213 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3214 // no changes, quest ignore this data
3218 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3220 uint32 id = qinfo->RewChoiceItemId[j];
3221 if(id)
3223 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3225 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3226 qinfo->GetQuestId(),j+1,id,id);
3227 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3230 if(!qinfo->RewChoiceItemCount[j])
3232 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3233 qinfo->GetQuestId(),j+1,id,j+1);
3234 // no changes, quest can't be done
3237 else if(qinfo->RewChoiceItemCount[j]>0)
3239 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3240 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3241 // no changes, quest ignore this data
3245 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3247 uint32 id = qinfo->RewItemId[j];
3248 if(id)
3250 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3252 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3253 qinfo->GetQuestId(),j+1,id,id);
3254 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3257 if(!qinfo->RewItemCount[j])
3259 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3260 qinfo->GetQuestId(),j+1,id,j+1);
3261 // no changes
3264 else if(qinfo->RewItemCount[j]>0)
3266 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3267 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3268 // no changes, quest ignore this data
3272 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3274 if(qinfo->RewRepFaction[j])
3276 if(!qinfo->RewRepValue[j])
3278 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3279 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3280 // no changes
3283 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3285 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.",
3286 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3287 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3290 else if(qinfo->RewRepValue[j]!=0)
3292 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3293 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3294 // no changes, quest ignore this data
3298 if(qinfo->RewSpell)
3300 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3302 if(!spellInfo)
3304 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3305 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3306 qinfo->RewSpell = 0; // no spell reward will display for this quest
3309 else if(!SpellMgr::IsSpellValid(spellInfo))
3311 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3312 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3313 qinfo->RewSpell = 0; // no spell reward will display for this quest
3318 if(qinfo->RewSpellCast)
3320 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3322 if(!spellInfo)
3324 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3325 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3326 qinfo->RewSpellCast = 0; // no spell will be casted on player
3329 else if(!SpellMgr::IsSpellValid(spellInfo))
3331 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3332 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3333 qinfo->RewSpellCast = 0; // no spell will be casted on player
3338 if(qinfo->RewMailTemplateId)
3340 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3342 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3343 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3344 qinfo->RewMailTemplateId = 0; // no mail will send to player
3345 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3349 if(qinfo->NextQuestInChain)
3351 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3352 if(qNextItr == mQuestTemplates.end())
3354 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3355 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3356 qinfo->NextQuestInChain = 0;
3358 else
3359 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3362 // fill additional data stores
3363 if(qinfo->PrevQuestId)
3365 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3367 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3369 else
3371 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3375 if(qinfo->NextQuestId)
3377 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3378 if (qNextItr == mQuestTemplates.end())
3380 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3382 else
3384 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3385 qNextItr->second->prevQuests.push_back(signedQuestId);
3389 if(qinfo->ExclusiveGroup)
3390 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3391 if(qinfo->LimitTime)
3392 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3395 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3396 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3398 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3399 if(!spellInfo)
3400 continue;
3402 for(int j = 0; j < 3; ++j)
3404 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3405 continue;
3407 uint32 quest_id = spellInfo->EffectMiscValue[j];
3409 Quest const* quest = GetQuestTemplate(quest_id);
3411 // some quest referenced in spells not exist (outdated spells)
3412 if(!quest)
3413 continue;
3415 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3417 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);
3419 // this will prevent quest completing without objective
3420 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3425 sLog.outString();
3426 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3429 void ObjectMgr::LoadQuestLocales()
3431 mQuestLocaleMap.clear(); // need for reload case
3433 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3434 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3435 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3436 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3437 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3438 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3439 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3440 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3441 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3442 " FROM locales_quest"
3445 if(!result)
3447 barGoLink bar(1);
3449 bar.step();
3451 sLog.outString();
3452 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3453 return;
3456 barGoLink bar(result->GetRowCount());
3460 Field *fields = result->Fetch();
3461 bar.step();
3463 uint32 entry = fields[0].GetUInt32();
3465 QuestLocale& data = mQuestLocaleMap[entry];
3467 for(int i = 1; i < MAX_LOCALE; ++i)
3469 std::string str = fields[1+10*(i-1)].GetCppString();
3470 if(!str.empty())
3472 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3473 if(idx >= 0)
3475 if(data.Title.size() <= idx)
3476 data.Title.resize(idx+1);
3478 data.Title[idx] = str;
3481 str = fields[1+10*(i-1)+1].GetCppString();
3482 if(!str.empty())
3484 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3485 if(idx >= 0)
3487 if(data.Details.size() <= idx)
3488 data.Details.resize(idx+1);
3490 data.Details[idx] = str;
3493 str = fields[1+10*(i-1)+2].GetCppString();
3494 if(!str.empty())
3496 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3497 if(idx >= 0)
3499 if(data.Objectives.size() <= idx)
3500 data.Objectives.resize(idx+1);
3502 data.Objectives[idx] = str;
3505 str = fields[1+10*(i-1)+3].GetCppString();
3506 if(!str.empty())
3508 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3509 if(idx >= 0)
3511 if(data.OfferRewardText.size() <= idx)
3512 data.OfferRewardText.resize(idx+1);
3514 data.OfferRewardText[idx] = str;
3517 str = fields[1+10*(i-1)+4].GetCppString();
3518 if(!str.empty())
3520 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3521 if(idx >= 0)
3523 if(data.RequestItemsText.size() <= idx)
3524 data.RequestItemsText.resize(idx+1);
3526 data.RequestItemsText[idx] = str;
3529 str = fields[1+10*(i-1)+5].GetCppString();
3530 if(!str.empty())
3532 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3533 if(idx >= 0)
3535 if(data.EndText.size() <= idx)
3536 data.EndText.resize(idx+1);
3538 data.EndText[idx] = str;
3541 for(int k = 0; k < 4; ++k)
3543 str = fields[1+10*(i-1)+6+k].GetCppString();
3544 if(!str.empty())
3546 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3547 if(idx >= 0)
3549 if(data.ObjectiveText[k].size() <= idx)
3550 data.ObjectiveText[k].resize(idx+1);
3552 data.ObjectiveText[k][idx] = str;
3557 } while (result->NextRow());
3559 delete result;
3561 sLog.outString();
3562 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3565 void ObjectMgr::LoadPetCreateSpells()
3567 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3568 if(!result)
3570 barGoLink bar( 1 );
3571 bar.step();
3573 sLog.outString();
3574 sLog.outString( ">> Loaded 0 pet create spells" );
3575 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3576 return;
3579 uint32 count = 0;
3581 barGoLink bar( result->GetRowCount() );
3583 mPetCreateSpell.clear();
3587 Field *fields = result->Fetch();
3588 bar.step();
3590 uint32 creature_id = fields[0].GetUInt32();
3592 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3593 continue;
3595 PetCreateSpellEntry PetCreateSpell;
3596 for(int i = 0; i < 4; i++)
3598 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3600 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3601 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3604 mPetCreateSpell[creature_id] = PetCreateSpell;
3606 ++count;
3608 while (result->NextRow());
3610 delete result;
3612 sLog.outString();
3613 sLog.outString( ">> Loaded %u pet create spells", count );
3616 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3618 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3619 return;
3621 sLog.outString( "%s :", tablename);
3623 scripts.clear(); // need for reload support
3625 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3627 uint32 count = 0;
3629 if( !result )
3631 barGoLink bar( 1 );
3632 bar.step();
3634 sLog.outString();
3635 sLog.outString( ">> Loaded %u script definitions", count );
3636 return;
3639 barGoLink bar( result->GetRowCount() );
3643 bar.step();
3645 Field *fields = result->Fetch();
3646 ScriptInfo tmp;
3647 tmp.id = fields[0].GetUInt32();
3648 tmp.delay = fields[1].GetUInt32();
3649 tmp.command = fields[2].GetUInt32();
3650 tmp.datalong = fields[3].GetUInt32();
3651 tmp.datalong2 = fields[4].GetUInt32();
3652 tmp.dataint = fields[5].GetInt32();
3653 tmp.x = fields[6].GetFloat();
3654 tmp.y = fields[7].GetFloat();
3655 tmp.z = fields[8].GetFloat();
3656 tmp.o = fields[9].GetFloat();
3658 // generic command args check
3659 switch(tmp.command)
3661 case SCRIPT_COMMAND_TALK:
3663 if(tmp.datalong > 3)
3665 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3666 continue;
3668 if(tmp.dataint==0)
3670 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3671 continue;
3673 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3675 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);
3676 continue;
3679 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3680 break;
3683 case SCRIPT_COMMAND_EMOTE:
3685 if(!sEmotesStore.LookupEntry(tmp.datalong))
3687 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
3688 continue;
3690 break;
3693 case SCRIPT_COMMAND_TELEPORT_TO:
3695 if(!sMapStore.LookupEntry(tmp.datalong))
3697 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3698 continue;
3701 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3703 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);
3704 continue;
3706 break;
3709 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3711 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3713 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);
3714 continue;
3717 if(!GetCreatureTemplate(tmp.datalong))
3719 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3720 continue;
3722 break;
3725 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3727 GameObjectData const* data = GetGOData(tmp.datalong);
3728 if(!data)
3730 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3731 continue;
3734 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3735 if(!info)
3737 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);
3738 continue;
3741 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3742 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3743 info->type==GAMEOBJECT_TYPE_DOOR ||
3744 info->type==GAMEOBJECT_TYPE_BUTTON ||
3745 info->type==GAMEOBJECT_TYPE_TRAP )
3747 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3748 continue;
3750 break;
3752 case SCRIPT_COMMAND_OPEN_DOOR:
3753 case SCRIPT_COMMAND_CLOSE_DOOR:
3755 GameObjectData const* data = GetGOData(tmp.datalong);
3756 if(!data)
3758 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);
3759 continue;
3762 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3763 if(!info)
3765 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);
3766 continue;
3769 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3771 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);
3772 continue;
3775 break;
3777 case SCRIPT_COMMAND_QUEST_EXPLORED:
3779 Quest const* quest = GetQuestTemplate(tmp.datalong);
3780 if(!quest)
3782 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);
3783 continue;
3786 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3788 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);
3790 // this will prevent quest completing without objective
3791 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3793 // continue; - quest objective requirement set and command can be allowed
3796 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3798 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",
3799 tablename,tmp.datalong2,tmp.id);
3800 continue;
3803 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3805 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",
3806 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3807 continue;
3810 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3812 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",
3813 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3814 continue;
3817 break;
3820 case SCRIPT_COMMAND_REMOVE_AURA:
3822 if(!sSpellStore.LookupEntry(tmp.datalong))
3824 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3825 tablename,tmp.datalong,tmp.id);
3826 continue;
3828 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3830 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3831 tablename,tmp.datalong2,tmp.id);
3832 continue;
3834 break;
3836 case SCRIPT_COMMAND_CAST_SPELL:
3838 if(!sSpellStore.LookupEntry(tmp.datalong))
3840 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3841 tablename,tmp.datalong,tmp.id);
3842 continue;
3844 if(tmp.datalong2 & ~0x3) // 2 bits
3846 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3847 tablename,tmp.datalong2,tmp.id);
3848 continue;
3850 break;
3854 if (scripts.find(tmp.id) == scripts.end())
3856 ScriptMap emptyMap;
3857 scripts[tmp.id] = emptyMap;
3859 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3861 ++count;
3862 } while( result->NextRow() );
3864 delete result;
3866 sLog.outString();
3867 sLog.outString( ">> Loaded %u script definitions", count );
3870 void ObjectMgr::LoadGameObjectScripts()
3872 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3874 // check ids
3875 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3877 if(!GetGOData(itr->first))
3878 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3882 void ObjectMgr::LoadQuestEndScripts()
3884 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3886 // check ids
3887 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3889 if(!GetQuestTemplate(itr->first))
3890 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3894 void ObjectMgr::LoadQuestStartScripts()
3896 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3898 // check ids
3899 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3901 if(!GetQuestTemplate(itr->first))
3902 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3906 void ObjectMgr::LoadSpellScripts()
3908 LoadScripts(sSpellScripts, "spell_scripts");
3910 // check ids
3911 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3913 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3915 if(!spellInfo)
3917 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3918 continue;
3921 //check for correct spellEffect
3922 bool found = false;
3923 for(int i=0; i<3; ++i)
3925 // skip empty effects
3926 if( !spellInfo->Effect[i] )
3927 continue;
3929 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3931 found = true;
3932 break;
3936 if(!found)
3937 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3941 void ObjectMgr::LoadEventScripts()
3943 LoadScripts(sEventScripts, "event_scripts");
3945 std::set<uint32> evt_scripts;
3946 // Load all possible script entries from gameobjects
3947 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3949 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3950 if (goInfo)
3952 switch(goInfo->type)
3954 case GAMEOBJECT_TYPE_GOOBER:
3955 if(goInfo->goober.eventId)
3956 evt_scripts.insert(goInfo->goober.eventId);
3957 break;
3958 case GAMEOBJECT_TYPE_CHEST:
3959 if(goInfo->chest.eventId)
3960 evt_scripts.insert(goInfo->chest.eventId);
3961 break;
3962 default:
3963 break;
3967 // Load all possible script entries from spells
3968 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3970 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3971 if (spell)
3973 for(int j=0; j<3; ++j)
3975 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3977 if (spell->EffectMiscValue[j])
3978 evt_scripts.insert(spell->EffectMiscValue[j]);
3983 // Then check if all scripts are in above list of possible script entries
3984 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3986 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3987 if (itr2 == evt_scripts.end())
3988 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);
3992 void ObjectMgr::LoadItemTexts()
3994 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3996 uint32 count = 0;
3998 if( !result )
4000 barGoLink bar( 1 );
4001 bar.step();
4003 sLog.outString();
4004 sLog.outString( ">> Loaded %u item pages", count );
4005 return;
4008 barGoLink bar( result->GetRowCount() );
4010 Field* fields;
4013 bar.step();
4015 fields = result->Fetch();
4017 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4019 ++count;
4021 } while ( result->NextRow() );
4023 delete result;
4025 sLog.outString();
4026 sLog.outString( ">> Loaded %u item texts", count );
4029 void ObjectMgr::LoadPageTexts()
4031 sPageTextStore.Free(); // for reload case
4033 sPageTextStore.Load();
4034 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4035 sLog.outString();
4037 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4039 // check data correctness
4040 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4041 if(!page)
4042 continue;
4044 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4046 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4047 continue;
4050 // detect circular reference
4051 std::set<uint32> checkedPages;
4052 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4054 if(!pageItr->Next_Page)
4055 break;
4056 checkedPages.insert(pageItr->Page_ID);
4057 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4059 std::ostringstream ss;
4060 ss<< "The text page(s) ";
4061 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4062 ss << *itr << " ";
4063 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4064 << pageItr->Page_ID <<" to 0";
4065 sLog.outErrorDb(ss.str().c_str());
4066 const_cast<PageText*>(pageItr)->Next_Page = 0;
4067 break;
4073 void ObjectMgr::LoadPageTextLocales()
4075 mPageTextLocaleMap.clear(); // need for reload case
4077 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");
4079 if(!result)
4081 barGoLink bar(1);
4083 bar.step();
4085 sLog.outString();
4086 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4087 return;
4090 barGoLink bar(result->GetRowCount());
4094 Field *fields = result->Fetch();
4095 bar.step();
4097 uint32 entry = fields[0].GetUInt32();
4099 PageTextLocale& data = mPageTextLocaleMap[entry];
4101 for(int i = 1; i < MAX_LOCALE; ++i)
4103 std::string str = fields[i].GetCppString();
4104 if(str.empty())
4105 continue;
4107 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4108 if(idx >= 0)
4110 if(data.Text.size() <= idx)
4111 data.Text.resize(idx+1);
4113 data.Text[idx] = str;
4117 } while (result->NextRow());
4119 delete result;
4121 sLog.outString();
4122 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4125 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4127 template<class D>
4128 void convert_from_str(uint32 field_pos, char *src, D &dst)
4130 dst = D(objmgr.GetScriptId(src));
4134 void ObjectMgr::LoadInstanceTemplate()
4136 SQLInstanceLoader loader;
4137 loader.Load(sInstanceTemplate);
4139 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4141 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4142 if(!temp) continue;
4143 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4144 if(!entry)
4146 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4147 continue;
4149 else if(!entry->HasResetTime())
4150 continue;
4152 //FIXME: now exist heroic instance, normal/heroic raid instances
4153 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4154 // entry->resetTimeRaid store reset time for normal raid only
4155 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4156 // but at some point wee need implement reset time dependent from raid instance mode
4157 if(temp->reset_delay == 0)
4159 // use defaults from the DBC
4160 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4162 temp->reset_delay = entry->resetTimeHeroic / DAY;
4164 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4165 // for normal raid only
4167 temp->reset_delay = entry->resetTimeRaid / DAY;
4171 // the reset_delay must be at least one day
4172 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4175 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4176 sLog.outString();
4179 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4181 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4182 if(itr != mGossipText.end())
4183 return &itr->second;
4184 return NULL;
4187 void ObjectMgr::LoadGossipText()
4189 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4191 int count = 0;
4192 if( !result )
4194 barGoLink bar( 1 );
4195 bar.step();
4197 sLog.outString();
4198 sLog.outString( ">> Loaded %u npc texts", count );
4199 return;
4202 int cic;
4204 barGoLink bar( result->GetRowCount() );
4208 ++count;
4209 cic = 0;
4211 Field *fields = result->Fetch();
4213 bar.step();
4215 uint32 Text_ID = fields[cic++].GetUInt32();
4216 if(!Text_ID)
4218 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4219 continue;
4222 GossipText& gText = mGossipText[Text_ID];
4224 for (int i=0; i< 8; i++)
4226 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4227 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4229 gText.Options[i].Language = fields[cic++].GetUInt32();
4230 gText.Options[i].Probability = fields[cic++].GetFloat();
4232 for(int j=0; j < 3; ++j)
4234 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4235 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4238 } while( result->NextRow() );
4240 sLog.outString();
4241 sLog.outString( ">> Loaded %u npc texts", count );
4242 delete result;
4245 void ObjectMgr::LoadNpcTextLocales()
4247 mNpcTextLocaleMap.clear(); // need for reload case
4249 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4250 "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,"
4251 "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,"
4252 "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,"
4253 "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,"
4254 "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,"
4255 "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,"
4256 "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, "
4257 "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 "
4258 " FROM locales_npc_text");
4260 if(!result)
4262 barGoLink bar(1);
4264 bar.step();
4266 sLog.outString();
4267 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4268 return;
4271 barGoLink bar(result->GetRowCount());
4275 Field *fields = result->Fetch();
4276 bar.step();
4278 uint32 entry = fields[0].GetUInt32();
4280 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4282 for(int i=1; i<MAX_LOCALE; ++i)
4284 for(int j=0; j<8; ++j)
4286 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4287 if(!str0.empty())
4289 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4290 if(idx >= 0)
4292 if(data.Text_0[j].size() <= idx)
4293 data.Text_0[j].resize(idx+1);
4295 data.Text_0[j][idx] = str0;
4298 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4299 if(!str1.empty())
4301 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4302 if(idx >= 0)
4304 if(data.Text_1[j].size() <= idx)
4305 data.Text_1[j].resize(idx+1);
4307 data.Text_1[j][idx] = str1;
4312 } while (result->NextRow());
4314 delete result;
4316 sLog.outString();
4317 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4320 //not very fast function but it is called only once a day, or on starting-up
4321 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4323 time_t basetime = time(NULL);
4324 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4325 //delete all old mails without item and without body immediately, if starting server
4326 if (!serverUp)
4327 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4328 // 0 1 2 3 4 5 6 7 8 9
4329 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);
4330 if ( !result )
4332 barGoLink bar(1);
4333 bar.step();
4334 sLog.outString();
4335 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4336 return; // any mails need to be returned or deleted
4339 //std::ostringstream delitems, delmails; //will be here for optimization
4340 //bool deletemail = false, deleteitem = false;
4341 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4342 //delmails << "DELETE FROM mail WHERE id IN ( "
4344 barGoLink bar( result->GetRowCount() );
4345 uint32 count = 0;
4346 Field *fields;
4350 bar.step();
4352 fields = result->Fetch();
4353 Mail *m = new Mail;
4354 m->messageID = fields[0].GetUInt32();
4355 m->messageType = fields[1].GetUInt8();
4356 m->sender = fields[2].GetUInt32();
4357 m->receiver = fields[3].GetUInt32();
4358 m->itemTextId = fields[4].GetUInt32();
4359 bool has_items = fields[5].GetBool();
4360 m->expire_time = (time_t)fields[6].GetUInt64();
4361 m->deliver_time = 0;
4362 m->COD = fields[7].GetUInt32();
4363 m->checked = fields[8].GetUInt32();
4364 m->mailTemplateId = fields[9].GetInt16();
4366 Player *pl = 0;
4367 if (serverUp)
4368 pl = GetPlayer((uint64)m->receiver);
4369 if (pl && pl->m_mailsLoaded)
4370 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4371 //his in mailbox and he has already listed his mails )
4372 delete m;
4373 continue;
4375 //delete or return mail:
4376 if (has_items)
4378 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4379 if(resultItems)
4383 Field *fields2 = resultItems->Fetch();
4385 uint32 item_guid_low = fields2[0].GetUInt32();
4386 uint32 item_template = fields2[1].GetUInt32();
4388 m->AddItem(item_guid_low, item_template);
4390 while (resultItems->NextRow());
4392 delete resultItems;
4394 //if it is mail from AH, it shouldn't be returned, but deleted
4395 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4397 // mail open and then not returned
4398 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4399 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4401 else
4403 //mail will be returned:
4404 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);
4405 delete m;
4406 continue;
4410 if (m->itemTextId)
4411 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4413 //deletemail = true;
4414 //delmails << m->messageID << ", ";
4415 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4416 delete m;
4417 ++count;
4418 } while (result->NextRow());
4419 delete result;
4421 sLog.outString();
4422 sLog.outString( ">> Loaded %u mails", count );
4425 void ObjectMgr::LoadQuestAreaTriggers()
4427 mQuestAreaTriggerMap.clear(); // need for reload case
4429 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4431 uint32 count = 0;
4433 if( !result )
4435 barGoLink bar( 1 );
4436 bar.step();
4438 sLog.outString();
4439 sLog.outString( ">> Loaded %u quest trigger points", count );
4440 return;
4443 barGoLink bar( result->GetRowCount() );
4447 ++count;
4448 bar.step();
4450 Field *fields = result->Fetch();
4452 uint32 trigger_ID = fields[0].GetUInt32();
4453 uint32 quest_ID = fields[1].GetUInt32();
4455 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4456 if(!atEntry)
4458 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4459 continue;
4462 Quest const* quest = GetQuestTemplate(quest_ID);
4464 if(!quest)
4466 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4467 continue;
4470 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4472 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);
4474 // this will prevent quest completing without objective
4475 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4477 // continue; - quest modified to required objective and trigger can be allowed.
4480 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4482 } while( result->NextRow() );
4484 delete result;
4486 sLog.outString();
4487 sLog.outString( ">> Loaded %u quest trigger points", count );
4490 void ObjectMgr::LoadTavernAreaTriggers()
4492 mTavernAreaTriggerSet.clear(); // need for reload case
4494 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4496 uint32 count = 0;
4498 if( !result )
4500 barGoLink bar( 1 );
4501 bar.step();
4503 sLog.outString();
4504 sLog.outString( ">> Loaded %u tavern triggers", count );
4505 return;
4508 barGoLink bar( result->GetRowCount() );
4512 ++count;
4513 bar.step();
4515 Field *fields = result->Fetch();
4517 uint32 Trigger_ID = fields[0].GetUInt32();
4519 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4520 if(!atEntry)
4522 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4523 continue;
4526 mTavernAreaTriggerSet.insert(Trigger_ID);
4527 } while( result->NextRow() );
4529 delete result;
4531 sLog.outString();
4532 sLog.outString( ">> Loaded %u tavern triggers", count );
4535 void ObjectMgr::LoadAreaTriggerScripts()
4537 mAreaTriggerScripts.clear(); // need for reload case
4538 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4540 uint32 count = 0;
4542 if( !result )
4544 barGoLink bar( 1 );
4545 bar.step();
4547 sLog.outString();
4548 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4549 return;
4552 barGoLink bar( result->GetRowCount() );
4556 ++count;
4557 bar.step();
4559 Field *fields = result->Fetch();
4561 uint32 Trigger_ID = fields[0].GetUInt32();
4562 const char *scriptName = fields[1].GetString();
4564 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4565 if(!atEntry)
4567 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4568 continue;
4570 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4571 } while( result->NextRow() );
4573 delete result;
4575 sLog.outString();
4576 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4579 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4581 bool found = false;
4582 float dist;
4583 uint32 id = 0;
4585 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4587 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4588 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4589 continue;
4591 uint8 field = (uint8)((i - 1) / 32);
4592 uint32 submask = 1<<((i-1)%32);
4594 // skip not taxi network nodes
4595 if((sTaxiNodesMask[field] & submask)==0)
4596 continue;
4598 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4599 if(found)
4601 if(dist2 < dist)
4603 dist = dist2;
4604 id = i;
4607 else
4609 found = true;
4610 dist = dist2;
4611 id = i;
4615 return id;
4618 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4620 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4621 if(src_i==sTaxiPathSetBySource.end())
4623 path = 0;
4624 cost = 0;
4625 return;
4628 TaxiPathSetForSource& pathSet = src_i->second;
4630 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4631 if(dest_i==pathSet.end())
4633 path = 0;
4634 cost = 0;
4635 return;
4638 cost = dest_i->second.price;
4639 path = dest_i->second.ID;
4642 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4644 uint16 mount_entry = 0;
4645 uint16 mount_id = 0;
4647 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4648 if(node)
4650 if (team == ALLIANCE)
4652 mount_entry = node->MountCreatureID[1];
4653 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4654 if(ci)
4655 mount_id = ci->DisplayID_A;
4657 if (team == HORDE)
4659 mount_entry = node->MountCreatureID[0];
4660 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4661 if(ci)
4662 mount_id = ci->DisplayID_H;
4666 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4667 if(!minfo)
4669 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. ",
4670 mount_entry,id,team,mount_id);
4672 return false;
4674 if(minfo->modelid_other_gender!=0)
4675 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4677 return mount_id;
4680 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4682 if(path >= sTaxiPathNodesByPath.size())
4683 return;
4685 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4687 pathnodes.Resize(nodeList.size());
4688 mapIds.resize(nodeList.size());
4690 for(size_t i = 0; i < nodeList.size(); ++i)
4692 pathnodes[ i ].x = nodeList[i].x;
4693 pathnodes[ i ].y = nodeList[i].y;
4694 pathnodes[ i ].z = nodeList[i].z;
4696 mapIds[i] = nodeList[i].mapid;
4700 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4702 if(path >= sTaxiPathNodesByPath.size())
4703 return;
4705 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4707 pathnodes.Resize(nodeList.size());
4709 for(size_t i = 0; i < nodeList.size(); ++i)
4711 pathnodes[ i ].mapid = nodeList[i].mapid;
4712 pathnodes[ i ].x = nodeList[i].x;
4713 pathnodes[ i ].y = nodeList[i].y;
4714 pathnodes[ i ].z = nodeList[i].z;
4715 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4716 pathnodes[ i ].delay = nodeList[i].delay;
4720 void ObjectMgr::LoadGraveyardZones()
4722 mGraveYardMap.clear(); // need for reload case
4724 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4726 uint32 count = 0;
4728 if( !result )
4730 barGoLink bar( 1 );
4731 bar.step();
4733 sLog.outString();
4734 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4735 return;
4738 barGoLink bar( result->GetRowCount() );
4742 ++count;
4743 bar.step();
4745 Field *fields = result->Fetch();
4747 uint32 safeLocId = fields[0].GetUInt32();
4748 uint32 zoneId = fields[1].GetUInt32();
4749 uint32 team = fields[2].GetUInt32();
4751 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4752 if(!entry)
4754 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4755 continue;
4758 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4759 if(!areaEntry)
4761 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4762 continue;
4765 if(areaEntry->zone != 0)
4767 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4768 continue;
4771 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4773 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4774 continue;
4777 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4778 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4779 } while( result->NextRow() );
4781 delete result;
4783 sLog.outString();
4784 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4787 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4789 // search for zone associated closest graveyard
4790 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4792 // Simulate std. algorithm:
4793 // found some graveyard associated to (ghost_zone,ghost_map)
4795 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4796 // then check faction
4797 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4798 // then check faction
4799 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4800 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4801 if(graveLow==graveUp)
4803 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4804 return NULL;
4807 // at corpse map
4808 bool foundNear = false;
4809 float distNear;
4810 WorldSafeLocsEntry const* entryNear = NULL;
4812 // at entrance map for corpse map
4813 bool foundEntr = false;
4814 float distEntr;
4815 WorldSafeLocsEntry const* entryEntr = NULL;
4817 // some where other
4818 WorldSafeLocsEntry const* entryFar = NULL;
4820 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4822 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4824 GraveYardData const& data = itr->second;
4826 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4827 if(!entry)
4829 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4830 continue;
4833 // skip enemy faction graveyard
4834 // team == 0 case can be at call from .neargrave
4835 if(data.team != 0 && team != 0 && data.team != team)
4836 continue;
4838 // find now nearest graveyard at other map
4839 if(MapId != entry->map_id)
4841 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4842 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4843 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4845 // not have any corrdinates for check distance anyway
4846 entryFar = entry;
4847 continue;
4850 // at entrance map calculate distance (2D);
4851 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4852 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4853 if(foundEntr)
4855 if(dist2 < distEntr)
4857 distEntr = dist2;
4858 entryEntr = entry;
4861 else
4863 foundEntr = true;
4864 distEntr = dist2;
4865 entryEntr = entry;
4868 // find now nearest graveyard at same map
4869 else
4871 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4872 if(foundNear)
4874 if(dist2 < distNear)
4876 distNear = dist2;
4877 entryNear = entry;
4880 else
4882 foundNear = true;
4883 distNear = dist2;
4884 entryNear = entry;
4889 if(entryNear)
4890 return entryNear;
4892 if(entryEntr)
4893 return entryEntr;
4895 return entryFar;
4898 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4900 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4901 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4903 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4905 if(itr->second.safeLocId==id)
4906 return &itr->second;
4909 return NULL;
4912 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4914 if(FindGraveYardData(id,zoneId))
4915 return false;
4917 // add link to loaded data
4918 GraveYardData data;
4919 data.safeLocId = id;
4920 data.team = team;
4922 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4924 // add link to DB
4925 if(inDB)
4927 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4928 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4931 return true;
4934 void ObjectMgr::LoadAreaTriggerTeleports()
4936 mAreaTriggers.clear(); // need for reload case
4938 uint32 count = 0;
4940 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4941 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");
4942 if( !result )
4945 barGoLink bar( 1 );
4947 bar.step();
4949 sLog.outString();
4950 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4951 return;
4954 barGoLink bar( result->GetRowCount() );
4958 Field *fields = result->Fetch();
4960 bar.step();
4962 ++count;
4964 uint32 Trigger_ID = fields[0].GetUInt32();
4966 AreaTrigger at;
4968 at.requiredLevel = fields[1].GetUInt8();
4969 at.requiredItem = fields[2].GetUInt32();
4970 at.requiredItem2 = fields[3].GetUInt32();
4971 at.heroicKey = fields[4].GetUInt32();
4972 at.heroicKey2 = fields[5].GetUInt32();
4973 at.requiredQuest = fields[6].GetUInt32();
4974 at.requiredQuestHeroic = fields[7].GetUInt32();
4975 at.requiredFailedText = fields[8].GetCppString();
4976 at.target_mapId = fields[9].GetUInt32();
4977 at.target_X = fields[10].GetFloat();
4978 at.target_Y = fields[11].GetFloat();
4979 at.target_Z = fields[12].GetFloat();
4980 at.target_Orientation = fields[13].GetFloat();
4982 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4983 if(!atEntry)
4985 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4986 continue;
4989 if(at.requiredItem)
4991 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4992 if(!pProto)
4994 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4995 at.requiredItem = 0;
4998 if(at.requiredItem2)
5000 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5001 if(!pProto)
5003 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5004 at.requiredItem2 = 0;
5008 if(at.heroicKey)
5010 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5011 if(!pProto)
5013 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5014 at.heroicKey = 0;
5018 if(at.heroicKey2)
5020 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5021 if(!pProto)
5023 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5024 at.heroicKey2 = 0;
5028 if(at.requiredQuest)
5030 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5031 if(qReqItr == mQuestTemplates.end())
5033 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5034 at.requiredQuest = 0;
5038 if(at.requiredQuestHeroic)
5040 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5041 if(qReqItr == mQuestTemplates.end())
5043 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5044 at.requiredQuestHeroic = 0;
5048 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5049 if(!mapEntry)
5051 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5052 continue;
5055 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5057 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5058 continue;
5061 mAreaTriggers[Trigger_ID] = at;
5063 } while( result->NextRow() );
5065 delete result;
5067 sLog.outString();
5068 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5072 * Searches for the areatrigger which teleports players out of the given map
5074 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5076 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5077 if(!mapEntry) return NULL;
5078 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5080 if(itr->second.target_mapId == mapEntry->entrance_map)
5082 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5083 if(atEntry && atEntry->mapid == Map)
5084 return &itr->second;
5087 return NULL;
5091 * Searches for the areatrigger which teleports players to the given map
5093 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5095 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5097 if(itr->second.target_mapId == Map)
5099 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5100 if(atEntry)
5101 return &itr->second;
5104 return NULL;
5107 void ObjectMgr::SetHighestGuids()
5109 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5110 if( result )
5112 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5113 delete result;
5116 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5117 if( result )
5119 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5120 delete result;
5123 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5124 if( result )
5126 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5127 delete result;
5130 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5131 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5132 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5133 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5134 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5136 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5137 if( result )
5139 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5140 delete result;
5143 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5144 if( result )
5146 m_auctionid = (*result)[0].GetUInt32()+1;
5147 delete result;
5150 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5151 if( result )
5153 m_mailid = (*result)[0].GetUInt32()+1;
5154 delete result;
5157 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5158 if( result )
5160 m_ItemTextId = (*result)[0].GetUInt32()+1;
5161 delete result;
5164 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5165 if( result )
5167 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5168 delete result;
5171 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5172 if (result)
5174 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5175 delete result;
5178 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5179 if (result)
5181 m_guildId = (*result)[0].GetUInt32()+1;
5182 delete result;
5186 uint32 ObjectMgr::GenerateArenaTeamId()
5188 if(m_arenaTeamId>=0xFFFFFFFE)
5190 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5191 World::StopNow(ERROR_EXIT_CODE);
5193 return m_arenaTeamId++;
5196 uint32 ObjectMgr::GenerateAuctionID()
5198 if(m_auctionid>=0xFFFFFFFE)
5200 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5201 World::StopNow(ERROR_EXIT_CODE);
5203 return m_auctionid++;
5206 uint32 ObjectMgr::GenerateGuildId()
5208 if(m_guildId>=0xFFFFFFFE)
5210 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5211 World::StopNow(ERROR_EXIT_CODE);
5213 return m_guildId++;
5216 uint32 ObjectMgr::GenerateMailID()
5218 if(m_mailid>=0xFFFFFFFE)
5220 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5221 World::StopNow(ERROR_EXIT_CODE);
5223 return m_mailid++;
5226 uint32 ObjectMgr::GenerateItemTextID()
5228 if(m_ItemTextId>=0xFFFFFFFE)
5230 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5231 World::StopNow(ERROR_EXIT_CODE);
5233 return m_ItemTextId++;
5236 uint32 ObjectMgr::CreateItemText(std::string text)
5238 uint32 newItemTextId = GenerateItemTextID();
5239 //insert new itempage to container
5240 mItemTexts[ newItemTextId ] = text;
5241 //save new itempage
5242 CharacterDatabase.escape_string(text);
5243 //any Delete query needed, itemTextId is maximum of all ids
5244 std::ostringstream query;
5245 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5246 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5247 return newItemTextId;
5250 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5252 switch(guidhigh)
5254 case HIGHGUID_ITEM:
5255 if(m_hiItemGuid>=0xFFFFFFFE)
5257 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5258 World::StopNow(ERROR_EXIT_CODE);
5260 return m_hiItemGuid++;
5261 case HIGHGUID_UNIT:
5262 if(m_hiCreatureGuid>=0x00FFFFFE)
5264 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5265 World::StopNow(ERROR_EXIT_CODE);
5267 return m_hiCreatureGuid++;
5268 case HIGHGUID_PET:
5269 if(m_hiPetGuid>=0x00FFFFFE)
5271 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5272 World::StopNow(ERROR_EXIT_CODE);
5274 return m_hiPetGuid++;
5275 case HIGHGUID_VEHICLE:
5276 if(m_hiVehicleGuid>=0x00FFFFFF)
5278 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5279 World::StopNow(ERROR_EXIT_CODE);
5281 return m_hiVehicleGuid++;
5282 case HIGHGUID_PLAYER:
5283 if(m_hiCharGuid>=0xFFFFFFFE)
5285 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5286 World::StopNow(ERROR_EXIT_CODE);
5288 return m_hiCharGuid++;
5289 case HIGHGUID_GAMEOBJECT:
5290 if(m_hiGoGuid>=0x00FFFFFE)
5292 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5293 World::StopNow(ERROR_EXIT_CODE);
5295 return m_hiGoGuid++;
5296 case HIGHGUID_CORPSE:
5297 if(m_hiCorpseGuid>=0xFFFFFFFE)
5299 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5300 World::StopNow(ERROR_EXIT_CODE);
5302 return m_hiCorpseGuid++;
5303 case HIGHGUID_DYNAMICOBJECT:
5304 if(m_hiDoGuid>=0xFFFFFFFE)
5306 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5307 World::StopNow(ERROR_EXIT_CODE);
5309 return m_hiDoGuid++;
5310 default:
5311 ASSERT(0);
5314 ASSERT(0);
5315 return 0;
5318 void ObjectMgr::LoadGameObjectLocales()
5320 mGameObjectLocaleMap.clear(); // need for reload case
5322 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5323 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5324 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5325 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5327 if(!result)
5329 barGoLink bar(1);
5331 bar.step();
5333 sLog.outString();
5334 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5335 return;
5338 barGoLink bar(result->GetRowCount());
5342 Field *fields = result->Fetch();
5343 bar.step();
5345 uint32 entry = fields[0].GetUInt32();
5347 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5349 for(int i = 1; i < MAX_LOCALE; ++i)
5351 std::string str = fields[i].GetCppString();
5352 if(!str.empty())
5354 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5355 if(idx >= 0)
5357 if(data.Name.size() <= idx)
5358 data.Name.resize(idx+1);
5360 data.Name[idx] = str;
5365 for(int i = 1; i < MAX_LOCALE; ++i)
5367 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5368 if(!str.empty())
5370 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5371 if(idx >= 0)
5373 if(data.CastBarCaption.size() <= idx)
5374 data.CastBarCaption.resize(idx+1);
5376 data.CastBarCaption[idx] = str;
5381 } while (result->NextRow());
5383 delete result;
5385 sLog.outString();
5386 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5389 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5391 template<class D>
5392 void convert_from_str(uint32 field_pos, char *src, D &dst)
5394 dst = D(objmgr.GetScriptId(src));
5398 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5400 if (sLockStore.LookupEntry(dataN))
5401 return;
5403 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5404 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5407 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5409 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5411 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5412 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5413 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5415 /* disable check for while (too many error reports baout not existed in trap templates
5416 else
5417 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5418 goInfo->id,goInfo->type,N,dataN,dataN);
5422 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5424 if (sSpellStore.LookupEntry(dataN))
5425 return;
5427 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5428 goInfo->id,goInfo->type,N,dataN,dataN);
5431 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5433 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5434 return;
5436 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5437 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5439 // prevent client and server unexpected work
5440 const_cast<uint32&>(dataN) = 0;
5443 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5445 // 0/1 correct values
5446 if (dataN <= 1)
5447 return;
5449 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5450 goInfo->id,goInfo->type,N,dataN);
5453 void ObjectMgr::LoadGameobjectInfo()
5455 SQLGameObjectLoader loader;
5456 loader.Load(sGOStorage);
5458 // some checks
5459 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5461 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5462 if (!goInfo)
5463 continue;
5465 switch(goInfo->type)
5467 case GAMEOBJECT_TYPE_DOOR: //0
5469 if (goInfo->door.lockId)
5470 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5471 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5472 break;
5474 case GAMEOBJECT_TYPE_BUTTON: //1
5476 if (goInfo->button.lockId)
5477 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5478 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5479 break;
5481 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5483 if (goInfo->questgiver.lockId)
5484 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5485 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5486 break;
5488 case GAMEOBJECT_TYPE_CHEST: //3
5490 if (goInfo->chest.lockId)
5491 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5493 if (goInfo->chest.linkedTrapId) // linked trap
5494 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5495 break;
5497 case GAMEOBJECT_TYPE_TRAP: //6
5499 if (goInfo->trap.lockId)
5500 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5501 /* disable check for while, too many not existed spells
5502 if (goInfo->trap.spellId) // spell
5503 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5505 break;
5507 case GAMEOBJECT_TYPE_CHAIR: //7
5508 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5509 break;
5510 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5512 if (goInfo->spellFocus.focusId)
5514 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5515 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5516 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5519 if (goInfo->spellFocus.linkedTrapId) // linked trap
5520 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5521 break;
5523 case GAMEOBJECT_TYPE_GOOBER: //10
5525 if (goInfo->goober.lockId)
5526 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5528 if (goInfo->goober.pageId) // pageId
5530 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5531 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5532 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5534 /* disable check for while, too many not existed spells
5535 if (goInfo->goober.spellId) // spell
5536 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5538 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5539 if (goInfo->goober.linkedTrapId) // linked trap
5540 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5541 break;
5543 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5545 if (goInfo->areadamage.lockId)
5546 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5547 break;
5549 case GAMEOBJECT_TYPE_CAMERA: //13
5551 if (goInfo->camera.lockId)
5552 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5553 break;
5555 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5557 if (goInfo->moTransport.taxiPathId)
5559 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5560 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5561 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5563 break;
5565 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5567 /* disable check for while, too many not existed spells
5568 // always must have spell
5569 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5571 break;
5573 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5575 // always must have spell
5576 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5577 break;
5579 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5581 if (goInfo->flagstand.lockId)
5582 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5583 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5584 break;
5586 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5588 if (goInfo->fishinghole.lockId)
5589 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5590 break;
5592 case GAMEOBJECT_TYPE_FLAGDROP: //26
5594 if (goInfo->flagdrop.lockId)
5595 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5596 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5597 break;
5599 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5600 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5601 break;
5605 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5606 sLog.outString();
5609 void ObjectMgr::LoadExplorationBaseXP()
5611 uint32 count = 0;
5612 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5614 if( !result )
5616 barGoLink bar( 1 );
5618 bar.step();
5620 sLog.outString();
5621 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5622 return;
5625 barGoLink bar( result->GetRowCount() );
5629 bar.step();
5631 Field *fields = result->Fetch();
5632 uint32 level = fields[0].GetUInt32();
5633 uint32 basexp = fields[1].GetUInt32();
5634 mBaseXPTable[level] = basexp;
5635 ++count;
5637 while (result->NextRow());
5639 delete result;
5641 sLog.outString();
5642 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5645 uint32 ObjectMgr::GetBaseXP(uint32 level)
5647 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5650 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5652 if (level < mPlayerXPperLevel.size())
5653 return mPlayerXPperLevel[level];
5654 return 0;
5657 void ObjectMgr::LoadPetNames()
5659 uint32 count = 0;
5660 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5662 if( !result )
5664 barGoLink bar( 1 );
5666 bar.step();
5668 sLog.outString();
5669 sLog.outString( ">> Loaded %u pet name parts", count );
5670 return;
5673 barGoLink bar( result->GetRowCount() );
5677 bar.step();
5679 Field *fields = result->Fetch();
5680 std::string word = fields[0].GetString();
5681 uint32 entry = fields[1].GetUInt32();
5682 bool half = fields[2].GetBool();
5683 if(half)
5684 PetHalfName1[entry].push_back(word);
5685 else
5686 PetHalfName0[entry].push_back(word);
5687 ++count;
5689 while (result->NextRow());
5690 delete result;
5692 sLog.outString();
5693 sLog.outString( ">> Loaded %u pet name parts", count );
5696 void ObjectMgr::LoadPetNumber()
5698 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5699 if(result)
5701 Field *fields = result->Fetch();
5702 m_hiPetNumber = fields[0].GetUInt32()+1;
5703 delete result;
5706 barGoLink bar( 1 );
5707 bar.step();
5709 sLog.outString();
5710 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5713 std::string ObjectMgr::GeneratePetName(uint32 entry)
5715 std::vector<std::string> & list0 = PetHalfName0[entry];
5716 std::vector<std::string> & list1 = PetHalfName1[entry];
5718 if(list0.empty() || list1.empty())
5720 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5721 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5722 if(!petname)
5723 petname = cinfo->Name;
5724 return std::string(petname);
5727 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5730 uint32 ObjectMgr::GeneratePetNumber()
5732 return ++m_hiPetNumber;
5735 void ObjectMgr::LoadCorpses()
5737 uint32 count = 0;
5738 // 0 1 2 3 4 5 6 7 8 10
5739 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");
5741 if( !result )
5743 barGoLink bar( 1 );
5745 bar.step();
5747 sLog.outString();
5748 sLog.outString( ">> Loaded %u corpses", count );
5749 return;
5752 barGoLink bar( result->GetRowCount() );
5756 bar.step();
5758 Field *fields = result->Fetch();
5760 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5762 Corpse *corpse = new Corpse;
5763 if(!corpse->LoadFromDB(guid,fields))
5765 delete corpse;
5766 continue;
5769 ObjectAccessor::Instance().AddCorpse(corpse);
5771 ++count;
5773 while (result->NextRow());
5774 delete result;
5776 sLog.outString();
5777 sLog.outString( ">> Loaded %u corpses", count );
5780 void ObjectMgr::LoadReputationOnKill()
5782 uint32 count = 0;
5784 // 0 1 2
5785 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5786 // 3 4 5 6 7 8 9
5787 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5788 "FROM creature_onkill_reputation");
5790 if(!result)
5792 barGoLink bar(1);
5794 bar.step();
5796 sLog.outString();
5797 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5798 return;
5801 barGoLink bar(result->GetRowCount());
5805 Field *fields = result->Fetch();
5806 bar.step();
5808 uint32 creature_id = fields[0].GetUInt32();
5810 ReputationOnKillEntry repOnKill;
5811 repOnKill.repfaction1 = fields[1].GetUInt32();
5812 repOnKill.repfaction2 = fields[2].GetUInt32();
5813 repOnKill.is_teamaward1 = fields[3].GetBool();
5814 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5815 repOnKill.repvalue1 = fields[5].GetInt32();
5816 repOnKill.is_teamaward2 = fields[6].GetBool();
5817 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5818 repOnKill.repvalue2 = fields[8].GetInt32();
5819 repOnKill.team_dependent = fields[9].GetUInt8();
5821 if(!GetCreatureTemplate(creature_id))
5823 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5824 continue;
5827 if(repOnKill.repfaction1)
5829 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5830 if(!factionEntry1)
5832 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5833 continue;
5837 if(repOnKill.repfaction2)
5839 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5840 if(!factionEntry2)
5842 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5843 continue;
5847 mRepOnKill[creature_id] = repOnKill;
5849 ++count;
5850 } while (result->NextRow());
5852 delete result;
5854 sLog.outString();
5855 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5858 void ObjectMgr::LoadPointsOfInterest()
5860 uint32 count = 0;
5862 // 0 1 2 3 4 5
5863 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5865 if(!result)
5867 barGoLink bar(1);
5869 bar.step();
5871 sLog.outString();
5872 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5873 return;
5876 barGoLink bar(result->GetRowCount());
5880 Field *fields = result->Fetch();
5881 bar.step();
5883 uint32 point_id = fields[0].GetUInt32();
5885 PointOfInterest POI;
5886 POI.x = fields[1].GetFloat();
5887 POI.y = fields[2].GetFloat();
5888 POI.icon = fields[3].GetUInt32();
5889 POI.flags = fields[4].GetUInt32();
5890 POI.data = fields[5].GetUInt32();
5891 POI.icon_name = fields[6].GetCppString();
5893 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5895 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5896 continue;
5899 mPointsOfInterest[point_id] = POI;
5901 ++count;
5902 } while (result->NextRow());
5904 delete result;
5906 sLog.outString();
5907 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5910 void ObjectMgr::LoadWeatherZoneChances()
5912 uint32 count = 0;
5914 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5915 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");
5917 if(!result)
5919 barGoLink bar(1);
5921 bar.step();
5923 sLog.outString();
5924 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5925 return;
5928 barGoLink bar(result->GetRowCount());
5932 Field *fields = result->Fetch();
5933 bar.step();
5935 uint32 zone_id = fields[0].GetUInt32();
5937 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5939 for(int season = 0; season < WEATHER_SEASONS; ++season)
5941 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5942 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5943 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5945 if(wzc.data[season].rainChance > 100)
5947 wzc.data[season].rainChance = 25;
5948 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
5951 if(wzc.data[season].snowChance > 100)
5953 wzc.data[season].snowChance = 25;
5954 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
5957 if(wzc.data[season].stormChance > 100)
5959 wzc.data[season].stormChance = 25;
5960 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
5964 ++count;
5965 } while (result->NextRow());
5967 delete result;
5969 sLog.outString();
5970 sLog.outString(">> Loaded %u weather definitions", count);
5973 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5975 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5976 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5977 if(t)
5978 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5981 void ObjectMgr::DeleteCreatureData(uint32 guid)
5983 // remove mapid*cellid -> guid_set map
5984 CreatureData const* data = GetCreatureData(guid);
5985 if(data)
5986 RemoveCreatureFromGrid(guid, data);
5988 mCreatureDataMap.erase(guid);
5991 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5993 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5994 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5995 if(t)
5996 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5999 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6001 RespawnTimes::iterator next;
6003 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6005 next = itr;
6006 ++next;
6008 if(GUID_HIPART(itr->first)==instance)
6009 mGORespawnTimes.erase(itr);
6012 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6014 next = itr;
6015 ++next;
6017 if(GUID_HIPART(itr->first)==instance)
6018 mCreatureRespawnTimes.erase(itr);
6021 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6022 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6025 void ObjectMgr::DeleteGOData(uint32 guid)
6027 // remove mapid*cellid -> guid_set map
6028 GameObjectData const* data = GetGOData(guid);
6029 if(data)
6030 RemoveGameobjectFromGrid(guid, data);
6032 mGameObjectDataMap.erase(guid);
6035 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6037 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6038 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6039 cell_guids.corpses[player_guid] = instance;
6042 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6044 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6045 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6046 cell_guids.corpses.erase(player_guid);
6049 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6051 map.clear(); // need for reload case
6053 uint32 count = 0;
6055 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6057 if(!result)
6059 barGoLink bar(1);
6061 bar.step();
6063 sLog.outString();
6064 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6065 return;
6068 barGoLink bar(result->GetRowCount());
6072 Field *fields = result->Fetch();
6073 bar.step();
6075 uint32 id = fields[0].GetUInt32();
6076 uint32 quest = fields[1].GetUInt32();
6078 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6080 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6081 continue;
6084 map.insert(QuestRelations::value_type(id,quest));
6086 ++count;
6087 } while (result->NextRow());
6089 delete result;
6091 sLog.outString();
6092 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6095 void ObjectMgr::LoadGameobjectQuestRelations()
6097 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6099 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6101 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6102 if(!goInfo)
6103 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6104 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6105 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6109 void ObjectMgr::LoadGameobjectInvolvedRelations()
6111 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6113 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6115 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6116 if(!goInfo)
6117 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6118 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6119 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6123 void ObjectMgr::LoadCreatureQuestRelations()
6125 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6127 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6129 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6130 if(!cInfo)
6131 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6132 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6133 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);
6137 void ObjectMgr::LoadCreatureInvolvedRelations()
6139 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6141 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6143 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6144 if(!cInfo)
6145 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6146 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6147 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);
6151 void ObjectMgr::LoadReservedPlayersNames()
6153 m_ReservedNames.clear(); // need for reload case
6155 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6157 uint32 count = 0;
6159 if( !result )
6161 barGoLink bar( 1 );
6162 bar.step();
6164 sLog.outString();
6165 sLog.outString( ">> Loaded %u reserved player names", count );
6166 return;
6169 barGoLink bar( result->GetRowCount() );
6171 Field* fields;
6174 bar.step();
6175 fields = result->Fetch();
6176 std::string name= fields[0].GetCppString();
6178 std::wstring wstr;
6179 if(!Utf8toWStr (name,wstr))
6181 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6182 continue;
6185 wstrToLower(wstr);
6187 m_ReservedNames.insert(wstr);
6188 ++count;
6189 } while ( result->NextRow() );
6191 delete result;
6193 sLog.outString();
6194 sLog.outString( ">> Loaded %u reserved player names", count );
6197 bool ObjectMgr::IsReservedName( const std::string& name ) const
6199 std::wstring wstr;
6200 if(!Utf8toWStr (name,wstr))
6201 return false;
6203 wstrToLower(wstr);
6205 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6208 enum LanguageType
6210 LT_BASIC_LATIN = 0x0000,
6211 LT_EXTENDEN_LATIN = 0x0001,
6212 LT_CYRILLIC = 0x0002,
6213 LT_EAST_ASIA = 0x0004,
6214 LT_ANY = 0xFFFF
6217 static LanguageType GetRealmLanguageType(bool create)
6219 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6221 case REALM_ZONE_UNKNOWN: // any language
6222 case REALM_ZONE_DEVELOPMENT:
6223 case REALM_ZONE_TEST_SERVER:
6224 case REALM_ZONE_QA_SERVER:
6225 return LT_ANY;
6226 case REALM_ZONE_UNITED_STATES: // extended-Latin
6227 case REALM_ZONE_OCEANIC:
6228 case REALM_ZONE_LATIN_AMERICA:
6229 case REALM_ZONE_ENGLISH:
6230 case REALM_ZONE_GERMAN:
6231 case REALM_ZONE_FRENCH:
6232 case REALM_ZONE_SPANISH:
6233 return LT_EXTENDEN_LATIN;
6234 case REALM_ZONE_KOREA: // East-Asian
6235 case REALM_ZONE_TAIWAN:
6236 case REALM_ZONE_CHINA:
6237 return LT_EAST_ASIA;
6238 case REALM_ZONE_RUSSIAN: // Cyrillic
6239 return LT_CYRILLIC;
6240 default:
6241 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6245 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6247 if(strictMask==0) // any language, ignore realm
6249 if(isExtendedLatinString(wstr,numericOrSpace))
6250 return true;
6251 if(isCyrillicString(wstr,numericOrSpace))
6252 return true;
6253 if(isEastAsianString(wstr,numericOrSpace))
6254 return true;
6255 return false;
6258 if(strictMask & 0x2) // realm zone specific
6260 LanguageType lt = GetRealmLanguageType(create);
6261 if(lt & LT_EXTENDEN_LATIN)
6262 if(isExtendedLatinString(wstr,numericOrSpace))
6263 return true;
6264 if(lt & LT_CYRILLIC)
6265 if(isCyrillicString(wstr,numericOrSpace))
6266 return true;
6267 if(lt & LT_EAST_ASIA)
6268 if(isEastAsianString(wstr,numericOrSpace))
6269 return true;
6272 if(strictMask & 0x1) // basic Latin
6274 if(isBasicLatinString(wstr,numericOrSpace))
6275 return true;
6278 return false;
6281 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6283 std::wstring wname;
6284 if(!Utf8toWStr(name,wname))
6285 return false;
6287 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6288 return false;
6290 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6292 return isValidString(wname,strictMask,false,create);
6295 bool ObjectMgr::IsValidCharterName( const std::string& name )
6297 std::wstring wname;
6298 if(!Utf8toWStr(name,wname))
6299 return false;
6301 if(wname.size() < 1)
6302 return false;
6304 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6306 return isValidString(wname,strictMask,true);
6309 bool ObjectMgr::IsValidPetName( const std::string& name )
6311 std::wstring wname;
6312 if(!Utf8toWStr(name,wname))
6313 return false;
6315 if(wname.size() < 1)
6316 return false;
6318 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6320 return isValidString(wname,strictMask,false);
6323 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6325 if(loc==LOCALE_enUS)
6326 return -1;
6328 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6329 if(m_LocalForIndex[i]==loc)
6330 return i;
6332 return -1;
6335 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6337 if (i<0 || i>=m_LocalForIndex.size())
6338 return LOCALE_enUS;
6340 return m_LocalForIndex[i];
6343 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6345 if(loc==LOCALE_enUS)
6346 return -1;
6348 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6349 if(m_LocalForIndex[i]==loc)
6350 return i;
6352 m_LocalForIndex.push_back(loc);
6353 return m_LocalForIndex.size()-1;
6356 void ObjectMgr::LoadGameObjectForQuests()
6358 mGameObjectForQuestSet.clear(); // need for reload case
6360 if( !sGOStorage.MaxEntry )
6362 barGoLink bar( 1 );
6363 bar.step();
6364 sLog.outString();
6365 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6366 return;
6369 barGoLink bar( sGOStorage.MaxEntry - 1 );
6370 uint32 count = 0;
6372 // collect GO entries for GO that must activated
6373 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6375 bar.step();
6376 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6377 if(!goInfo)
6378 continue;
6380 switch(goInfo->type)
6382 // scan GO chest with loot including quest items
6383 case GAMEOBJECT_TYPE_CHEST:
6385 uint32 loot_id = GameObject::GetLootId(goInfo);
6387 // find quest loot for GO
6388 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6390 mGameObjectForQuestSet.insert(go_entry);
6391 ++count;
6393 break;
6395 case GAMEOBJECT_TYPE_GOOBER:
6397 if(goInfo->goober.questId) //quests objects
6399 mGameObjectForQuestSet.insert(go_entry);
6400 count++;
6402 break;
6404 default:
6405 break;
6409 sLog.outString();
6410 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6413 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6415 // cleanup affected map part for reloading case
6416 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6418 if(itr->first >= min_value && itr->first <= max_value)
6420 MangosStringLocaleMap::iterator itr2 = itr;
6421 ++itr;
6422 mMangosStringLocaleMap.erase(itr2);
6424 else
6425 ++itr;
6428 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);
6430 if(!result)
6432 barGoLink bar(1);
6434 bar.step();
6436 sLog.outString();
6437 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6438 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6439 else
6440 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6441 return false;
6444 uint32 count = 0;
6446 barGoLink bar(result->GetRowCount());
6450 Field *fields = result->Fetch();
6451 bar.step();
6453 int32 entry = fields[0].GetInt32();
6455 if(entry==0)
6457 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6458 continue;
6460 else if(entry < min_value || entry > max_value)
6462 int32 start = min_value > 0 ? min_value : max_value;
6463 int32 end = min_value > 0 ? max_value : min_value;
6464 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6465 continue;
6468 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6470 if(data.Content.size() > 0)
6472 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6473 continue;
6476 data.Content.resize(1);
6477 ++count;
6479 // 0 -> default, idx in to idx+1
6480 data.Content[0] = fields[1].GetCppString();
6482 for(int i = 1; i < MAX_LOCALE; ++i)
6484 std::string str = fields[i+1].GetCppString();
6485 if(!str.empty())
6487 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6488 if(idx >= 0)
6490 // 0 -> default, idx in to idx+1
6491 if(data.Content.size() <= idx+1)
6492 data.Content.resize(idx+2);
6494 data.Content[idx+1] = str;
6498 } while (result->NextRow());
6500 delete result;
6502 sLog.outString();
6503 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6504 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6505 else
6506 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6508 return true;
6511 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6513 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6514 // Content[0] always exist if exist MangosStringLocale
6515 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6517 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6518 return msl->Content[locale_idx+1].c_str();
6519 else
6520 return msl->Content[0].c_str();
6523 if(entry > 0)
6524 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6525 else
6526 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6527 return "<error>";
6530 void ObjectMgr::LoadFishingBaseSkillLevel()
6532 mFishingBaseForArea.clear(); // for reload case
6534 uint32 count = 0;
6535 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6537 if( !result )
6539 barGoLink bar( 1 );
6541 bar.step();
6543 sLog.outString();
6544 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6545 return;
6548 barGoLink bar( result->GetRowCount() );
6552 bar.step();
6554 Field *fields = result->Fetch();
6555 uint32 entry = fields[0].GetUInt32();
6556 int32 skill = fields[1].GetInt32();
6558 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6559 if(!fArea)
6561 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6562 continue;
6565 mFishingBaseForArea[entry] = skill;
6566 ++count;
6568 while (result->NextRow());
6570 delete result;
6572 sLog.outString();
6573 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6576 // Searches for the same condition already in Conditions store
6577 // Returns Id if found, else adds it to Conditions and returns Id
6578 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6580 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6581 for (uint16 i=0; i < mConditions.size(); ++i)
6583 if (lc == mConditions[i])
6584 return i;
6587 mConditions.push_back(lc);
6589 if(mConditions.size() > 0xFFFF)
6591 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6592 return 0;
6595 return mConditions.size() - 1;
6598 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6600 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6602 std::wstring wname;
6603 if(!Utf8toWStr(names.name[i],wname))
6604 return false;
6606 if(mainpart!=GetMainPartOfName(wname,i+1))
6607 return false;
6609 return true;
6612 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6614 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6615 if(i!= mAreaTriggerScripts.end())
6616 return i->second;
6617 return 0;
6620 // Checks if player meets the condition
6621 bool PlayerCondition::Meets(Player const * player) const
6623 if( !player )
6624 return false; // player not present, return false
6626 switch (condition)
6628 case CONDITION_NONE:
6629 return true; // empty condition, always met
6630 case CONDITION_AURA:
6631 return player->HasAura(value1, value2);
6632 case CONDITION_ITEM:
6633 return player->HasItemCount(value1, value2);
6634 case CONDITION_ITEM_EQUIPPED:
6635 return player->HasItemOrGemWithIdEquipped(value1,1);
6636 case CONDITION_ZONEID:
6637 return player->GetZoneId() == value1;
6638 case CONDITION_REPUTATION_RANK:
6640 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6641 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6643 case CONDITION_TEAM:
6644 return player->GetTeam() == value1;
6645 case CONDITION_SKILL:
6646 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6647 case CONDITION_QUESTREWARDED:
6648 return player->GetQuestRewardStatus(value1);
6649 case CONDITION_QUESTTAKEN:
6651 QuestStatus status = player->GetQuestStatus(value1);
6652 return (status == QUEST_STATUS_INCOMPLETE);
6654 case CONDITION_AD_COMMISSION_AURA:
6656 Unit::AuraMap const& auras = player->GetAuras();
6657 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6658 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6659 return true;
6660 return false;
6662 case CONDITION_NO_AURA:
6663 return !player->HasAura(value1, value2);
6664 case CONDITION_ACTIVE_EVENT:
6665 return gameeventmgr.IsActiveEvent(value1);
6666 default:
6667 return false;
6671 // Verification of condition values validity
6672 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6674 if( condition >= MAX_CONDITION) // Wrong condition type
6676 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6677 return false;
6680 switch (condition)
6682 case CONDITION_AURA:
6684 if(!sSpellStore.LookupEntry(value1))
6686 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6687 return false;
6689 if(value2 > 2)
6691 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6692 return false;
6694 break;
6696 case CONDITION_ITEM:
6698 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6699 if(!proto)
6701 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6702 return false;
6704 break;
6706 case CONDITION_ITEM_EQUIPPED:
6708 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6709 if(!proto)
6711 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6712 return false;
6714 break;
6716 case CONDITION_ZONEID:
6718 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6719 if(!areaEntry)
6721 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6722 return false;
6724 if(areaEntry->zone != 0)
6726 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6727 return false;
6729 break;
6731 case CONDITION_REPUTATION_RANK:
6733 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6734 if(!factionEntry)
6736 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6737 return false;
6739 break;
6741 case CONDITION_TEAM:
6743 if (value1 != ALLIANCE && value1 != HORDE)
6745 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6746 return false;
6748 break;
6750 case CONDITION_SKILL:
6752 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6753 if (!pSkill)
6755 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6756 return false;
6758 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6760 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6761 return false;
6763 break;
6765 case CONDITION_QUESTREWARDED:
6766 case CONDITION_QUESTTAKEN:
6768 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6769 if (!Quest)
6771 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6772 return false;
6774 if(value2)
6775 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6776 break;
6778 case CONDITION_AD_COMMISSION_AURA:
6780 if(value1)
6781 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6782 if(value2)
6783 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6784 break;
6786 case CONDITION_NO_AURA:
6788 if(!sSpellStore.LookupEntry(value1))
6790 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6791 return false;
6793 if(value2 > 2)
6795 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6796 return false;
6798 break;
6800 case CONDITION_ACTIVE_EVENT:
6802 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6803 if(value1 >=events.size() || !events[value1].isValid())
6805 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6806 return false;
6808 break;
6811 return true;
6814 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6816 switch(pSkill->categoryId)
6818 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6819 case SKILL_CATEGORY_WEAPON:
6820 if(pSkill->id!=SKILL_FIST_WEAPONS)
6821 return SKILL_RANGE_LEVEL;
6822 else
6823 return SKILL_RANGE_MONO;
6824 case SKILL_CATEGORY_ARMOR:
6825 case SKILL_CATEGORY_CLASS:
6826 if(pSkill->id != SKILL_LOCKPICKING)
6827 return SKILL_RANGE_MONO;
6828 else
6829 return SKILL_RANGE_LEVEL;
6830 case SKILL_CATEGORY_SECONDARY:
6831 case SKILL_CATEGORY_PROFESSION:
6832 // not set skills for professions and racial abilities
6833 if(IsProfessionSkill(pSkill->id))
6834 return SKILL_RANGE_RANK;
6835 else if(racial)
6836 return SKILL_RANGE_NONE;
6837 else
6838 return SKILL_RANGE_MONO;
6839 default:
6840 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6841 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6842 return SKILL_RANGE_NONE;
6846 void ObjectMgr::LoadGameTele()
6848 m_GameTeleMap.clear(); // for reload case
6850 uint32 count = 0;
6851 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6853 if( !result )
6855 barGoLink bar( 1 );
6857 bar.step();
6859 sLog.outString();
6860 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6861 return;
6864 barGoLink bar( result->GetRowCount() );
6868 bar.step();
6870 Field *fields = result->Fetch();
6872 uint32 id = fields[0].GetUInt32();
6874 GameTele gt;
6876 gt.position_x = fields[1].GetFloat();
6877 gt.position_y = fields[2].GetFloat();
6878 gt.position_z = fields[3].GetFloat();
6879 gt.orientation = fields[4].GetFloat();
6880 gt.mapId = fields[5].GetUInt32();
6881 gt.name = fields[6].GetCppString();
6883 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6885 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6886 continue;
6889 if(!Utf8toWStr(gt.name,gt.wnameLow))
6891 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6892 continue;
6895 wstrToLower( gt.wnameLow );
6897 m_GameTeleMap[id] = gt;
6899 ++count;
6901 while (result->NextRow());
6902 delete result;
6904 sLog.outString();
6905 sLog.outString( ">> Loaded %u GameTeleports", count );
6908 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6910 // explicit name case
6911 std::wstring wname;
6912 if(!Utf8toWStr(name,wname))
6913 return false;
6915 // converting string that we try to find to lower case
6916 wstrToLower( wname );
6918 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6919 const GameTele* alt = NULL;
6920 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6921 if(itr->second.wnameLow == wname)
6922 return &itr->second;
6923 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6924 alt = &itr->second;
6926 return alt;
6929 bool ObjectMgr::AddGameTele(GameTele& tele)
6931 // find max id
6932 uint32 new_id = 0;
6933 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6934 if(itr->first > new_id)
6935 new_id = itr->first;
6937 // use next
6938 ++new_id;
6940 if(!Utf8toWStr(tele.name,tele.wnameLow))
6941 return false;
6943 wstrToLower( tele.wnameLow );
6945 m_GameTeleMap[new_id] = tele;
6947 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')",
6948 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6951 bool ObjectMgr::DeleteGameTele(const std::string& name)
6953 // explicit name case
6954 std::wstring wname;
6955 if(!Utf8toWStr(name,wname))
6956 return false;
6958 // converting string that we try to find to lower case
6959 wstrToLower( wname );
6961 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6963 if(itr->second.wnameLow == wname)
6965 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6966 m_GameTeleMap.erase(itr);
6967 return true;
6971 return false;
6974 void ObjectMgr::LoadTrainerSpell()
6976 // For reload case
6977 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6978 itr->second.Clear();
6979 m_mCacheTrainerSpellMap.clear();
6981 std::set<uint32> skip_trainers;
6983 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6985 if( !result )
6987 barGoLink bar( 1 );
6989 bar.step();
6991 sLog.outString();
6992 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6993 return;
6996 barGoLink bar( result->GetRowCount() );
6998 uint32 count = 0;
7001 bar.step();
7003 Field* fields = result->Fetch();
7005 uint32 entry = fields[0].GetUInt32();
7006 uint32 spell = fields[1].GetUInt32();
7008 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7010 if(!cInfo)
7012 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7013 continue;
7016 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7018 if(skip_trainers.count(entry) == 0)
7020 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7021 skip_trainers.insert(entry);
7023 continue;
7026 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7027 if(!spellinfo)
7029 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7030 continue;
7033 if(!SpellMgr::IsSpellValid(spellinfo))
7035 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7036 continue;
7039 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7041 TrainerSpell& trainerSpell = data.spellList[spell];
7042 trainerSpell.spell = spell;
7043 trainerSpell.spellCost = fields[2].GetUInt32();
7044 trainerSpell.reqSkill = fields[3].GetUInt32();
7045 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7046 trainerSpell.reqLevel = fields[5].GetUInt32();
7048 if(!trainerSpell.reqLevel)
7049 trainerSpell.reqLevel = spellinfo->spellLevel;
7051 // calculate learned spell for profession case when stored cast-spell
7052 trainerSpell.learnedSpell = spell;
7053 for(int i = 0; i <3; ++i)
7055 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7056 continue;
7057 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7059 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7060 break;
7064 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7065 data.trainerType = 2;
7067 ++count;
7069 } while (result->NextRow());
7070 delete result;
7072 sLog.outString();
7073 sLog.outString( ">> Loaded %d Trainers", count );
7076 void ObjectMgr::LoadVendors()
7078 // For reload case
7079 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7080 itr->second.Clear();
7081 m_mCacheVendorItemMap.clear();
7083 std::set<uint32> skip_vendors;
7085 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7086 if( !result )
7088 barGoLink bar( 1 );
7090 bar.step();
7092 sLog.outString();
7093 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7094 return;
7097 barGoLink bar( result->GetRowCount() );
7099 uint32 count = 0;
7102 bar.step();
7103 Field* fields = result->Fetch();
7105 uint32 entry = fields[0].GetUInt32();
7106 uint32 item_id = fields[1].GetUInt32();
7107 uint32 maxcount = fields[2].GetUInt32();
7108 uint32 incrtime = fields[3].GetUInt32();
7109 uint32 ExtendedCost = fields[4].GetUInt32();
7111 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7112 continue;
7114 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7116 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7117 ++count;
7119 } while (result->NextRow());
7120 delete result;
7122 sLog.outString();
7123 sLog.outString( ">> Loaded %d Vendors ", count );
7126 void ObjectMgr::LoadNpcTextId()
7129 m_mCacheNpcTextIdMap.clear();
7131 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7132 if( !result )
7134 barGoLink bar( 1 );
7136 bar.step();
7138 sLog.outString();
7139 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7140 return;
7143 barGoLink bar( result->GetRowCount() );
7145 uint32 count = 0;
7146 uint32 guid,textid;
7149 bar.step();
7151 Field* fields = result->Fetch();
7153 guid = fields[0].GetUInt32();
7154 textid = fields[1].GetUInt32();
7156 if (!GetCreatureData(guid))
7158 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7159 continue;
7161 if (!GetGossipText(textid))
7163 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7164 continue;
7167 m_mCacheNpcTextIdMap[guid] = textid ;
7168 ++count;
7170 } while (result->NextRow());
7171 delete result;
7173 sLog.outString();
7174 sLog.outString( ">> Loaded %d NpcTextId ", count );
7177 void ObjectMgr::LoadNpcOptions()
7179 m_mCacheNpcOptionList.clear(); // For reload case
7181 QueryResult *result = WorldDatabase.Query(
7182 // 0 1 2 3 4 5 6 7 8
7183 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7184 "FROM npc_option");
7186 if( !result )
7188 barGoLink bar( 1 );
7190 bar.step();
7192 sLog.outString();
7193 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7194 return;
7197 barGoLink bar( result->GetRowCount() );
7199 uint32 count = 0;
7203 bar.step();
7205 Field* fields = result->Fetch();
7207 GossipOption go;
7208 go.Id = fields[0].GetUInt32();
7209 go.GossipId = fields[1].GetUInt32();
7210 go.NpcFlag = fields[2].GetUInt32();
7211 go.Icon = fields[3].GetUInt32();
7212 go.Action = fields[4].GetUInt32();
7213 go.BoxMoney = fields[5].GetUInt32();
7214 go.Coded = fields[6].GetUInt8()!=0;
7215 go.OptionText = fields[7].GetCppString();
7216 go.BoxText = fields[8].GetCppString();
7218 m_mCacheNpcOptionList.push_back(go);
7220 ++count;
7222 } while (result->NextRow());
7223 delete result;
7225 sLog.outString();
7226 sLog.outString( ">> Loaded %d npc_option entries", count );
7229 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7231 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7232 vList.AddItem(item,maxcount,incrtime,extendedcost);
7234 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7237 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7239 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7240 if(iter == m_mCacheVendorItemMap.end())
7241 return false;
7243 if(!iter->second.FindItem(item))
7244 return false;
7246 iter->second.RemoveItem(item);
7247 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7248 return true;
7251 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7253 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7254 if(!cInfo)
7256 if(pl)
7257 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7258 else
7259 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7260 return false;
7263 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7265 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7267 if(pl)
7268 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7269 else
7270 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7272 if(skip_vendors)
7273 skip_vendors->insert(vendor_entry);
7275 return false;
7278 if(!GetItemPrototype(item_id))
7280 if(pl)
7281 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7282 else
7283 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7284 return false;
7287 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7289 if(pl)
7290 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7291 else
7292 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7293 return false;
7296 if(maxcount > 0 && incrtime == 0)
7298 if(pl)
7299 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7300 else
7301 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7302 return false;
7304 else if(maxcount==0 && incrtime > 0)
7306 if(pl)
7307 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7308 else
7309 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7310 return false;
7313 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7314 if(!vItems)
7315 return true; // later checks for non-empty lists
7317 if(vItems->FindItem(item_id))
7319 if(pl)
7320 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7321 else
7322 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7323 return false;
7326 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7328 if(pl)
7329 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7330 else
7331 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7332 return false;
7335 return true;
7338 void ObjectMgr::LoadScriptNames()
7340 m_scriptNames.push_back("");
7341 QueryResult *result = WorldDatabase.Query(
7342 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7343 "UNION "
7344 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7345 "UNION "
7346 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7347 "UNION "
7348 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7349 "UNION "
7350 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7352 if( !result )
7354 barGoLink bar( 1 );
7355 bar.step();
7356 sLog.outString();
7357 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7358 return;
7361 barGoLink bar( result->GetRowCount() );
7362 uint32 count = 0;
7366 bar.step();
7367 m_scriptNames.push_back((*result)[0].GetString());
7368 ++count;
7369 } while (result->NextRow());
7370 delete result;
7372 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7373 sLog.outString();
7374 sLog.outString( ">> Loaded %d Script Names", count );
7377 uint32 ObjectMgr::GetScriptId(const char *name)
7379 // use binary search to find the script name in the sorted vector
7380 // assume "" is the first element
7381 if(!name) return 0;
7382 ScriptNameMap::const_iterator itr =
7383 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7384 if(itr == m_scriptNames.end() || *itr != name) return 0;
7385 return itr - m_scriptNames.begin();
7388 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7390 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7392 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7394 switch(itrM->second.command)
7396 case SCRIPT_COMMAND_TALK:
7398 if(!GetMangosStringLocale (itrM->second.dataint))
7399 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7401 if(ids.count(itrM->second.dataint))
7402 ids.erase(itrM->second.dataint);
7409 void ObjectMgr::LoadDbScriptStrings()
7411 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7413 std::set<int32> ids;
7415 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7416 if(GetMangosStringLocale(i))
7417 ids.insert(i);
7419 CheckScripts(sQuestEndScripts,ids);
7420 CheckScripts(sQuestStartScripts,ids);
7421 CheckScripts(sSpellScripts,ids);
7422 CheckScripts(sGameObjectScripts,ids);
7423 CheckScripts(sEventScripts,ids);
7425 WaypointMgr.CheckTextsExistance(ids);
7427 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7428 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7431 // Functions for scripting access
7432 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7434 return objmgr.GetAreaTriggerScriptId(trigger_id);
7437 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7439 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7441 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());
7442 start_value = -1;
7443 end_value = std::numeric_limits<int32>::min();
7446 // for scripting localized strings allowed use _only_ negative entries
7447 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7450 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7452 return objmgr.GetScriptId(name);
7455 ObjectMgr::ScriptNameMap & GetScriptNames()
7457 return objmgr.GetScriptNames();
7460 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7462 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7465 Quest const* GetQuestTemplateStore(uint32 entry)
7467 return objmgr.GetQuestTemplate(entry);