[7832] Better check at `petcreateinfo_spell` loading for errors and redundend data.
[getmangos.git] / src / game / ObjectMgr.cpp
blobe70902299f93e2d81b2ad918b34dc60d936311d0
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 // Only zero condition left, others will be added while loading DB tables
127 mConditions.resize(1);
130 ObjectMgr::~ObjectMgr()
132 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
133 delete i->second;
135 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
136 delete[] i->second;
138 // free only if loaded
139 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
140 delete[] playerClassInfo[class_].levelInfo;
142 for (int race = 0; race < MAX_RACES; ++race)
143 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
144 delete[] playerInfo[race][class_].levelInfo;
146 // free group and guild objects
147 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
148 delete (*itr);
150 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
151 delete itr->second;
153 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
154 itr->second.Clear();
156 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
157 itr->second.Clear();
160 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
162 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
163 if ((*itr)->GetLeaderGUID() == guid)
164 return *itr;
166 return NULL;
169 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
171 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
172 if (itr != mGuildMap.end())
173 return itr->second;
175 return NULL;
178 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
180 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
181 if (itr->second->GetName() == guildname)
182 return itr->second;
184 return NULL;
187 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
189 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
190 if (itr != mGuildMap.end())
191 return itr->second->GetName();
193 return "";
196 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
198 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
199 if (itr->second->GetLeader() == guid)
200 return itr->second;
202 return NULL;
205 void ObjectMgr::AddGuild(Guild* guild)
207 mGuildMap[guild->GetId()] = guild;
210 void ObjectMgr::RemoveGuild(uint32 Id)
212 mGuildMap.erase(Id);
215 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
217 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
218 if (itr != mArenaTeamMap.end())
219 return itr->second;
221 return NULL;
224 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
226 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
227 if (itr->second->GetName() == arenateamname)
228 return itr->second;
230 return NULL;
233 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
235 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
236 if (itr->second->GetCaptain() == guid)
237 return itr->second;
239 return NULL;
242 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
244 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
247 void ObjectMgr::RemoveArenaTeam(uint32 Id)
249 mArenaTeamMap.erase(Id);
252 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
254 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
257 void ObjectMgr::LoadCreatureLocales()
259 mCreatureLocaleMap.clear(); // need for reload case
261 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");
263 if(!result)
265 barGoLink bar(1);
267 bar.step();
269 sLog.outString();
270 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
271 return;
274 barGoLink bar(result->GetRowCount());
278 Field *fields = result->Fetch();
279 bar.step();
281 uint32 entry = fields[0].GetUInt32();
283 CreatureLocale& data = mCreatureLocaleMap[entry];
285 for(int i = 1; i < MAX_LOCALE; ++i)
287 std::string str = fields[1+2*(i-1)].GetCppString();
288 if(!str.empty())
290 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
291 if(idx >= 0)
293 if(data.Name.size() <= idx)
294 data.Name.resize(idx+1);
296 data.Name[idx] = str;
299 str = fields[1+2*(i-1)+1].GetCppString();
300 if(!str.empty())
302 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
303 if(idx >= 0)
305 if(data.SubName.size() <= idx)
306 data.SubName.resize(idx+1);
308 data.SubName[idx] = str;
312 } while (result->NextRow());
314 delete result;
316 sLog.outString();
317 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
320 void ObjectMgr::LoadNpcOptionLocales()
322 mNpcOptionLocaleMap.clear(); // need for reload case
324 QueryResult *result = WorldDatabase.Query("SELECT entry,"
325 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
326 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
327 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
328 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
329 "FROM locales_npc_option");
331 if(!result)
333 barGoLink bar(1);
335 bar.step();
337 sLog.outString();
338 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
339 return;
342 barGoLink bar(result->GetRowCount());
346 Field *fields = result->Fetch();
347 bar.step();
349 uint32 entry = fields[0].GetUInt32();
351 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
353 for(int i = 1; i < MAX_LOCALE; ++i)
355 std::string str = fields[1+2*(i-1)].GetCppString();
356 if(!str.empty())
358 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
359 if(idx >= 0)
361 if(data.OptionText.size() <= idx)
362 data.OptionText.resize(idx+1);
364 data.OptionText[idx] = str;
367 str = fields[1+2*(i-1)+1].GetCppString();
368 if(!str.empty())
370 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
371 if(idx >= 0)
373 if(data.BoxText.size() <= idx)
374 data.BoxText.resize(idx+1);
376 data.BoxText[idx] = str;
380 } while (result->NextRow());
382 delete result;
384 sLog.outString();
385 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
388 void ObjectMgr::LoadPointOfInterestLocales()
390 mPointOfInterestLocaleMap.clear(); // need for reload case
392 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");
394 if(!result)
396 barGoLink bar(1);
398 bar.step();
400 sLog.outString();
401 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
402 return;
405 barGoLink bar(result->GetRowCount());
409 Field *fields = result->Fetch();
410 bar.step();
412 uint32 entry = fields[0].GetUInt32();
414 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
416 for(int i = 1; i < MAX_LOCALE; ++i)
418 std::string str = fields[i].GetCppString();
419 if(str.empty())
420 continue;
422 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
423 if(idx >= 0)
425 if(data.IconName.size() <= idx)
426 data.IconName.resize(idx+1);
428 data.IconName[idx] = str;
431 } while (result->NextRow());
433 delete result;
435 sLog.outString();
436 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
439 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
441 template<class D>
442 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
444 dst = D(objmgr.GetScriptId(src));
448 void ObjectMgr::LoadCreatureTemplates()
450 SQLCreatureLoader loader;
451 loader.Load(sCreatureStorage);
453 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
454 sLog.outString();
456 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
457 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
459 // check data correctness
460 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
462 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
463 if(!cInfo)
464 continue;
466 if(cInfo->HeroicEntry)
468 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
469 if(!heroicInfo)
471 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
472 continue;
475 if(heroicEntries.find(i)!=heroicEntries.end())
477 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
478 continue;
481 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
483 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
484 continue;
487 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
489 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
490 continue;
493 if(cInfo->npcflag != heroicInfo->npcflag)
495 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
496 continue;
499 if(cInfo->classNum != heroicInfo->classNum)
501 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
502 continue;
505 if(cInfo->race != heroicInfo->race)
507 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
508 continue;
511 if(cInfo->trainer_type != heroicInfo->trainer_type)
513 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
514 continue;
517 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
519 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
520 continue;
523 if(heroicInfo->AIName && *heroicInfo->AIName)
525 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `AIName`, but in any case will used normal mode creature (Entry: %u) AIName.",cInfo->HeroicEntry,i);
526 continue;
529 if(heroicInfo->ScriptID)
531 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `ScriptName`, but in any case will used normal mode creature (Entry: %u) ScriptName.",cInfo->HeroicEntry,i);
532 continue;
535 hasHeroicEntries.insert(i);
536 heroicEntries.insert(cInfo->HeroicEntry);
539 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
540 if(!factionTemplate)
541 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
543 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
544 if(!factionTemplate)
545 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
547 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
548 if (!minfo)
549 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
550 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
551 if (!minfo)
552 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
554 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
556 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
557 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
560 if(cInfo->baseattacktime == 0)
561 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
563 if(cInfo->rangeattacktime == 0)
564 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
566 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
567 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
569 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
571 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
572 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
575 // must exist or used hidden but used in data horse case
576 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
578 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
579 const_cast<CreatureInfo*>(cInfo)->family = 0;
582 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
584 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
585 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
588 if(cInfo->PetSpellDataId)
590 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
591 if(!spellDataId)
592 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
595 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
597 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
599 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
600 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
604 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
606 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
607 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
610 if(cInfo->equipmentId > 0) // 0 no equipment
612 if(!GetEquipmentInfo(cInfo->equipmentId))
614 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);
615 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
619 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
620 if(cInfo->scale <= 0.0f)
622 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
623 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
628 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
630 // Now add the auras, format "spellid effectindex spellid effectindex..."
631 char *p,*s;
632 std::vector<int> val;
633 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
634 if(p)
636 while (p[0]!=0)
638 ++p;
639 if (p[0]==' ')
641 val.push_back(atoi(s));
642 s=++p;
645 if (p!=s)
646 val.push_back(atoi(s));
648 // free char* loaded memory
649 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
651 // wrong list
652 if (val.size()%2)
654 addon->auras = NULL;
655 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
656 return;
660 // empty list
661 if(val.empty())
663 addon->auras = NULL;
664 return;
667 // replace by new structures array
668 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
670 int i=0;
671 for(int j=0;j<val.size()/2;++j)
673 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
674 cAura.spell_id = (uint32)val[2*j+0];
675 cAura.effect_idx = (uint32)val[2*j+1];
676 if ( cAura.effect_idx > 2 )
678 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);
679 continue;
681 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
682 if (!AdditionalSpellInfo)
684 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
685 continue;
688 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
690 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);
691 continue;
694 ++i;
697 // fill terminator element (after last added)
698 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
699 endAura.spell_id = 0;
700 endAura.effect_idx = 0;
703 void ObjectMgr::LoadCreatureAddons()
705 sCreatureInfoAddonStorage.Load();
707 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
708 sLog.outString();
710 // check data correctness and convert 'auras'
711 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
713 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
714 if(!addon)
715 continue;
717 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
719 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
720 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
723 sCreatureDataAddonStorage.Load();
725 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
726 sLog.outString();
728 // check data correctness and convert 'auras'
729 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
731 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
732 if(!addon)
733 continue;
735 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
737 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
738 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
742 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
744 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
747 void ObjectMgr::LoadEquipmentTemplates()
749 sEquipmentStorage.Load();
751 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
753 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
755 if(!eqInfo)
756 continue;
758 for(uint8 j=0; j<3; j++)
760 if(!eqInfo->equipentry[j])
761 continue;
763 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
765 if(!dbcitem)
767 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
768 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
769 continue;
772 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
773 dbcitem->InventoryType != INVTYPE_SHIELD &&
774 dbcitem->InventoryType != INVTYPE_RANGED &&
775 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
776 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
777 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
778 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
779 dbcitem->InventoryType != INVTYPE_THROWN &&
780 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
782 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);
783 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
787 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
788 sLog.outString();
790 // This DBC is currently only used for item templates and creature equipments checks.
791 sItemStore.Clear();
794 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
796 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
799 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
801 // Load creature model (display id)
802 uint32 display_id;
803 if (!data || data->displayid == 0) // use defaults from the template
805 // DisplayID_A is used if no team is given
806 if (team == HORDE)
807 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
808 else
809 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
811 else // overridden in creature data
812 display_id = data->displayid;
814 return display_id;
817 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
819 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
820 if(!minfo)
821 return NULL;
823 // If a model for another gender exists, 50% chance to use it
824 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
826 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
827 if(!minfo_tmp)
829 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
830 return minfo; // not fatal, just use the previous one
832 else
833 return minfo_tmp;
835 else
836 return minfo;
839 void ObjectMgr::LoadCreatureModelInfo()
841 sCreatureModelStorage.Load();
843 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
844 sLog.outString();
847 void ObjectMgr::LoadCreatures()
849 uint32 count = 0;
850 // 0 1 2 3
851 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
852 // 4 5 6 7 8 9 10 11
853 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
854 // 12 13 14 15 16 17 18 19
855 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
856 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
857 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
859 if(!result)
861 barGoLink bar(1);
863 bar.step();
865 sLog.outString();
866 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
867 return;
870 // build single time for check creature data
871 std::set<uint32> heroicCreatures;
872 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
873 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
874 if(cInfo->HeroicEntry)
875 heroicCreatures.insert(cInfo->HeroicEntry);
877 barGoLink bar(result->GetRowCount());
881 Field *fields = result->Fetch();
882 bar.step();
884 uint32 guid = fields[ 0].GetUInt32();
885 uint32 entry = fields[ 1].GetUInt32();
887 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
888 if(!cInfo)
890 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
891 continue;
894 CreatureData& data = mCreatureDataMap[guid];
896 data.id = entry;
897 data.mapid = fields[ 2].GetUInt32();
898 data.displayid = fields[ 3].GetUInt32();
899 data.equipmentId = fields[ 4].GetUInt32();
900 data.posX = fields[ 5].GetFloat();
901 data.posY = fields[ 6].GetFloat();
902 data.posZ = fields[ 7].GetFloat();
903 data.orientation = fields[ 8].GetFloat();
904 data.spawntimesecs = fields[ 9].GetUInt32();
905 data.spawndist = fields[10].GetFloat();
906 data.currentwaypoint= fields[11].GetUInt32();
907 data.curhealth = fields[12].GetUInt32();
908 data.curmana = fields[13].GetUInt32();
909 data.is_dead = fields[14].GetBool();
910 data.movementType = fields[15].GetUInt8();
911 data.spawnMask = fields[16].GetUInt8();
912 data.phaseMask = fields[17].GetUInt16();
913 int16 gameEvent = fields[18].GetInt16();
914 int16 PoolId = fields[19].GetInt16();
916 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
918 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
919 continue;
922 if(data.equipmentId > 0) // -1 no equipment, 0 use default
924 if(!GetEquipmentInfo(data.equipmentId))
926 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);
927 data.equipmentId = -1;
931 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
933 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 );
934 data.curhealth = cInfo->minhealth;
937 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
939 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
940 if(!map || !map->IsDungeon())
941 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);
944 if(data.curmana < cInfo->minmana)
946 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 );
947 data.curmana = cInfo->minmana;
950 if(data.spawndist < 0.0f)
952 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
953 data.spawndist = 0.0f;
955 else if(data.movementType == RANDOM_MOTION_TYPE)
957 if(data.spawndist == 0.0f)
959 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 );
960 data.movementType = IDLE_MOTION_TYPE;
963 else if(data.movementType == IDLE_MOTION_TYPE)
965 if(data.spawndist != 0.0f)
967 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
968 data.spawndist = 0.0f;
972 if(data.phaseMask==0)
974 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
975 data.phaseMask = 1;
978 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
979 AddCreatureToGrid(guid, &data);
981 ++count;
983 } while (result->NextRow());
985 delete result;
987 sLog.outString();
988 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
991 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
993 uint8 mask = data->spawnMask;
994 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
996 if(mask & 1)
998 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
999 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1001 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1002 cell_guids.creatures.insert(guid);
1007 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1009 uint8 mask = data->spawnMask;
1010 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1012 if(mask & 1)
1014 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1015 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1017 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1018 cell_guids.creatures.erase(guid);
1023 void ObjectMgr::LoadGameobjects()
1025 uint32 count = 0;
1027 // 0 1 2 3 4 5 6
1028 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1029 // 7 8 9 10 11 12 13 14 15 16 17
1030 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1031 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1032 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1034 if(!result)
1036 barGoLink bar(1);
1038 bar.step();
1040 sLog.outString();
1041 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1042 return;
1045 barGoLink bar(result->GetRowCount());
1049 Field *fields = result->Fetch();
1050 bar.step();
1052 uint32 guid = fields[ 0].GetUInt32();
1053 uint32 entry = fields[ 1].GetUInt32();
1055 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1056 if(!gInfo)
1058 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1059 continue;
1062 GameObjectData& data = mGameObjectDataMap[guid];
1064 data.id = entry;
1065 data.mapid = fields[ 2].GetUInt32();
1066 data.posX = fields[ 3].GetFloat();
1067 data.posY = fields[ 4].GetFloat();
1068 data.posZ = fields[ 5].GetFloat();
1069 data.orientation = fields[ 6].GetFloat();
1070 data.rotation0 = fields[ 7].GetFloat();
1071 data.rotation1 = fields[ 8].GetFloat();
1072 data.rotation2 = fields[ 9].GetFloat();
1073 data.rotation3 = fields[10].GetFloat();
1074 data.spawntimesecs = fields[11].GetInt32();
1075 data.animprogress = fields[12].GetUInt32();
1077 uint32 go_state = fields[13].GetUInt32();
1078 if (go_state >= MAX_GO_STATE)
1080 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip",guid,data.id,go_state);
1081 continue;
1083 data.go_state = GOState(go_state);
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 bar2( 1 );
2690 bar2.step();
2692 else
2694 barGoLink bar2( result->GetRowCount() );
2697 bar2.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 bar2( 1 );
2750 bar2.step();
2752 else
2754 barGoLink bar2( result->GetRowCount() );
2757 bar2.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 continue;
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)
3594 sLog.outErrorDb("Creature id %u listed in `petcreateinfo_spell` not exist.",creature_id);
3595 continue;
3598 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(creature_id);
3599 if(!cInfo)
3601 sLog.outErrorDb("Creature id %u listed in `petcreateinfo_spell` not exist.",creature_id);
3602 continue;
3605 PetCreateSpellEntry PetCreateSpell;
3607 bool have_spell = false;
3608 bool have_spell_db = false;
3609 for(int i = 0; i < 4; i++)
3611 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3613 if(!PetCreateSpell.spellid[i])
3614 continue;
3616 have_spell_db = true;
3618 SpellEntry const* i_spell = sSpellStore.LookupEntry(PetCreateSpell.spellid[i]);
3619 if(!i_spell)
3621 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3622 PetCreateSpell.spellid[i] = 0;
3623 continue;
3626 have_spell = true;
3629 if(!have_spell_db)
3631 sLog.outErrorDb("Creature %u listed in `petcreateinfo_spell` have only 0 spell data, why it listed?",creature_id);
3632 continue;
3635 if(!have_spell)
3636 continue;
3638 mPetCreateSpell[creature_id] = PetCreateSpell;
3639 ++count;
3641 while (result->NextRow());
3643 delete result;
3645 sLog.outString();
3646 sLog.outString( ">> Loaded %u pet create spells", count );
3649 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3651 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3652 return;
3654 sLog.outString( "%s :", tablename);
3656 scripts.clear(); // need for reload support
3658 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3660 uint32 count = 0;
3662 if( !result )
3664 barGoLink bar( 1 );
3665 bar.step();
3667 sLog.outString();
3668 sLog.outString( ">> Loaded %u script definitions", count );
3669 return;
3672 barGoLink bar( result->GetRowCount() );
3676 bar.step();
3678 Field *fields = result->Fetch();
3679 ScriptInfo tmp;
3680 tmp.id = fields[0].GetUInt32();
3681 tmp.delay = fields[1].GetUInt32();
3682 tmp.command = fields[2].GetUInt32();
3683 tmp.datalong = fields[3].GetUInt32();
3684 tmp.datalong2 = fields[4].GetUInt32();
3685 tmp.dataint = fields[5].GetInt32();
3686 tmp.x = fields[6].GetFloat();
3687 tmp.y = fields[7].GetFloat();
3688 tmp.z = fields[8].GetFloat();
3689 tmp.o = fields[9].GetFloat();
3691 // generic command args check
3692 switch(tmp.command)
3694 case SCRIPT_COMMAND_TALK:
3696 if(tmp.datalong > 3)
3698 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3699 continue;
3701 if(tmp.dataint==0)
3703 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3704 continue;
3706 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3708 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);
3709 continue;
3712 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3713 break;
3716 case SCRIPT_COMMAND_EMOTE:
3718 if(!sEmotesStore.LookupEntry(tmp.datalong))
3720 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
3721 continue;
3723 break;
3726 case SCRIPT_COMMAND_TELEPORT_TO:
3728 if(!sMapStore.LookupEntry(tmp.datalong))
3730 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3731 continue;
3734 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3736 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);
3737 continue;
3739 break;
3742 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3744 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3746 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);
3747 continue;
3750 if(!GetCreatureTemplate(tmp.datalong))
3752 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3753 continue;
3755 break;
3758 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3760 GameObjectData const* data = GetGOData(tmp.datalong);
3761 if(!data)
3763 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3764 continue;
3767 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3768 if(!info)
3770 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);
3771 continue;
3774 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3775 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3776 info->type==GAMEOBJECT_TYPE_DOOR ||
3777 info->type==GAMEOBJECT_TYPE_BUTTON ||
3778 info->type==GAMEOBJECT_TYPE_TRAP )
3780 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3781 continue;
3783 break;
3785 case SCRIPT_COMMAND_OPEN_DOOR:
3786 case SCRIPT_COMMAND_CLOSE_DOOR:
3788 GameObjectData const* data = GetGOData(tmp.datalong);
3789 if(!data)
3791 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);
3792 continue;
3795 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3796 if(!info)
3798 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);
3799 continue;
3802 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3804 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);
3805 continue;
3808 break;
3810 case SCRIPT_COMMAND_QUEST_EXPLORED:
3812 Quest const* quest = GetQuestTemplate(tmp.datalong);
3813 if(!quest)
3815 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);
3816 continue;
3819 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3821 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);
3823 // this will prevent quest completing without objective
3824 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3826 // continue; - quest objective requirement set and command can be allowed
3829 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3831 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",
3832 tablename,tmp.datalong2,tmp.id);
3833 continue;
3836 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3838 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",
3839 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3840 continue;
3843 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3845 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",
3846 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3847 continue;
3850 break;
3853 case SCRIPT_COMMAND_REMOVE_AURA:
3855 if(!sSpellStore.LookupEntry(tmp.datalong))
3857 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3858 tablename,tmp.datalong,tmp.id);
3859 continue;
3861 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3863 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3864 tablename,tmp.datalong2,tmp.id);
3865 continue;
3867 break;
3869 case SCRIPT_COMMAND_CAST_SPELL:
3871 if(!sSpellStore.LookupEntry(tmp.datalong))
3873 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3874 tablename,tmp.datalong,tmp.id);
3875 continue;
3877 if(tmp.datalong2 & ~0x3) // 2 bits
3879 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3880 tablename,tmp.datalong2,tmp.id);
3881 continue;
3883 break;
3887 if (scripts.find(tmp.id) == scripts.end())
3889 ScriptMap emptyMap;
3890 scripts[tmp.id] = emptyMap;
3892 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3894 ++count;
3895 } while( result->NextRow() );
3897 delete result;
3899 sLog.outString();
3900 sLog.outString( ">> Loaded %u script definitions", count );
3903 void ObjectMgr::LoadGameObjectScripts()
3905 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3907 // check ids
3908 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3910 if(!GetGOData(itr->first))
3911 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3915 void ObjectMgr::LoadQuestEndScripts()
3917 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3919 // check ids
3920 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3922 if(!GetQuestTemplate(itr->first))
3923 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3927 void ObjectMgr::LoadQuestStartScripts()
3929 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3931 // check ids
3932 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3934 if(!GetQuestTemplate(itr->first))
3935 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3939 void ObjectMgr::LoadSpellScripts()
3941 LoadScripts(sSpellScripts, "spell_scripts");
3943 // check ids
3944 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3946 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3948 if(!spellInfo)
3950 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3951 continue;
3954 //check for correct spellEffect
3955 bool found = false;
3956 for(int i=0; i<3; ++i)
3958 // skip empty effects
3959 if( !spellInfo->Effect[i] )
3960 continue;
3962 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3964 found = true;
3965 break;
3969 if(!found)
3970 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3974 void ObjectMgr::LoadEventScripts()
3976 LoadScripts(sEventScripts, "event_scripts");
3978 std::set<uint32> evt_scripts;
3979 // Load all possible script entries from gameobjects
3980 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3982 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3983 if (goInfo)
3985 switch(goInfo->type)
3987 case GAMEOBJECT_TYPE_GOOBER:
3988 if(goInfo->goober.eventId)
3989 evt_scripts.insert(goInfo->goober.eventId);
3990 break;
3991 case GAMEOBJECT_TYPE_CHEST:
3992 if(goInfo->chest.eventId)
3993 evt_scripts.insert(goInfo->chest.eventId);
3994 break;
3995 default:
3996 break;
4000 // Load all possible script entries from spells
4001 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4003 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4004 if (spell)
4006 for(int j=0; j<3; ++j)
4008 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4010 if (spell->EffectMiscValue[j])
4011 evt_scripts.insert(spell->EffectMiscValue[j]);
4016 // Then check if all scripts are in above list of possible script entries
4017 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4019 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4020 if (itr2 == evt_scripts.end())
4021 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);
4025 void ObjectMgr::LoadItemTexts()
4027 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4029 uint32 count = 0;
4031 if( !result )
4033 barGoLink bar( 1 );
4034 bar.step();
4036 sLog.outString();
4037 sLog.outString( ">> Loaded %u item pages", count );
4038 return;
4041 barGoLink bar( result->GetRowCount() );
4043 Field* fields;
4046 bar.step();
4048 fields = result->Fetch();
4050 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4052 ++count;
4054 } while ( result->NextRow() );
4056 delete result;
4058 sLog.outString();
4059 sLog.outString( ">> Loaded %u item texts", count );
4062 void ObjectMgr::LoadPageTexts()
4064 sPageTextStore.Free(); // for reload case
4066 sPageTextStore.Load();
4067 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4068 sLog.outString();
4070 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4072 // check data correctness
4073 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4074 if(!page)
4075 continue;
4077 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4079 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4080 continue;
4083 // detect circular reference
4084 std::set<uint32> checkedPages;
4085 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4087 if(!pageItr->Next_Page)
4088 break;
4089 checkedPages.insert(pageItr->Page_ID);
4090 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4092 std::ostringstream ss;
4093 ss<< "The text page(s) ";
4094 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4095 ss << *itr << " ";
4096 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4097 << pageItr->Page_ID <<" to 0";
4098 sLog.outErrorDb(ss.str().c_str());
4099 const_cast<PageText*>(pageItr)->Next_Page = 0;
4100 break;
4106 void ObjectMgr::LoadPageTextLocales()
4108 mPageTextLocaleMap.clear(); // need for reload case
4110 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");
4112 if(!result)
4114 barGoLink bar(1);
4116 bar.step();
4118 sLog.outString();
4119 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4120 return;
4123 barGoLink bar(result->GetRowCount());
4127 Field *fields = result->Fetch();
4128 bar.step();
4130 uint32 entry = fields[0].GetUInt32();
4132 PageTextLocale& data = mPageTextLocaleMap[entry];
4134 for(int i = 1; i < MAX_LOCALE; ++i)
4136 std::string str = fields[i].GetCppString();
4137 if(str.empty())
4138 continue;
4140 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4141 if(idx >= 0)
4143 if(data.Text.size() <= idx)
4144 data.Text.resize(idx+1);
4146 data.Text[idx] = str;
4150 } while (result->NextRow());
4152 delete result;
4154 sLog.outString();
4155 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4158 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4160 template<class D>
4161 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4163 dst = D(objmgr.GetScriptId(src));
4167 void ObjectMgr::LoadInstanceTemplate()
4169 SQLInstanceLoader loader;
4170 loader.Load(sInstanceTemplate);
4172 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4174 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4175 if(!temp) continue;
4176 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4177 if(!entry)
4179 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4180 continue;
4182 else if(!entry->HasResetTime())
4183 continue;
4185 //FIXME: now exist heroic instance, normal/heroic raid instances
4186 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4187 // entry->resetTimeRaid store reset time for normal raid only
4188 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4189 // but at some point wee need implement reset time dependent from raid instance mode
4190 if(temp->reset_delay == 0)
4192 // use defaults from the DBC
4193 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4195 temp->reset_delay = entry->resetTimeHeroic / DAY;
4197 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4198 // for normal raid only
4200 temp->reset_delay = entry->resetTimeRaid / DAY;
4204 // the reset_delay must be at least one day
4205 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4208 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4209 sLog.outString();
4212 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4214 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4215 if(itr != mGossipText.end())
4216 return &itr->second;
4217 return NULL;
4220 void ObjectMgr::LoadGossipText()
4222 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4224 int count = 0;
4225 if( !result )
4227 barGoLink bar( 1 );
4228 bar.step();
4230 sLog.outString();
4231 sLog.outString( ">> Loaded %u npc texts", count );
4232 return;
4235 int cic;
4237 barGoLink bar( result->GetRowCount() );
4241 ++count;
4242 cic = 0;
4244 Field *fields = result->Fetch();
4246 bar.step();
4248 uint32 Text_ID = fields[cic++].GetUInt32();
4249 if(!Text_ID)
4251 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4252 continue;
4255 GossipText& gText = mGossipText[Text_ID];
4257 for (int i=0; i< 8; i++)
4259 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4260 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4262 gText.Options[i].Language = fields[cic++].GetUInt32();
4263 gText.Options[i].Probability = fields[cic++].GetFloat();
4265 for(int j=0; j < 3; ++j)
4267 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4268 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4271 } while( result->NextRow() );
4273 sLog.outString();
4274 sLog.outString( ">> Loaded %u npc texts", count );
4275 delete result;
4278 void ObjectMgr::LoadNpcTextLocales()
4280 mNpcTextLocaleMap.clear(); // need for reload case
4282 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4283 "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,"
4284 "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,"
4285 "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,"
4286 "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,"
4287 "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,"
4288 "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,"
4289 "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, "
4290 "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 "
4291 " FROM locales_npc_text");
4293 if(!result)
4295 barGoLink bar(1);
4297 bar.step();
4299 sLog.outString();
4300 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4301 return;
4304 barGoLink bar(result->GetRowCount());
4308 Field *fields = result->Fetch();
4309 bar.step();
4311 uint32 entry = fields[0].GetUInt32();
4313 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4315 for(int i=1; i<MAX_LOCALE; ++i)
4317 for(int j=0; j<8; ++j)
4319 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4320 if(!str0.empty())
4322 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4323 if(idx >= 0)
4325 if(data.Text_0[j].size() <= idx)
4326 data.Text_0[j].resize(idx+1);
4328 data.Text_0[j][idx] = str0;
4331 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4332 if(!str1.empty())
4334 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4335 if(idx >= 0)
4337 if(data.Text_1[j].size() <= idx)
4338 data.Text_1[j].resize(idx+1);
4340 data.Text_1[j][idx] = str1;
4345 } while (result->NextRow());
4347 delete result;
4349 sLog.outString();
4350 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4353 //not very fast function but it is called only once a day, or on starting-up
4354 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4356 time_t basetime = time(NULL);
4357 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4358 //delete all old mails without item and without body immediately, if starting server
4359 if (!serverUp)
4360 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4361 // 0 1 2 3 4 5 6 7 8 9
4362 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);
4363 if ( !result )
4365 barGoLink bar(1);
4366 bar.step();
4367 sLog.outString();
4368 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4369 return; // any mails need to be returned or deleted
4372 //std::ostringstream delitems, delmails; //will be here for optimization
4373 //bool deletemail = false, deleteitem = false;
4374 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4375 //delmails << "DELETE FROM mail WHERE id IN ( "
4377 barGoLink bar( result->GetRowCount() );
4378 uint32 count = 0;
4379 Field *fields;
4383 bar.step();
4385 fields = result->Fetch();
4386 Mail *m = new Mail;
4387 m->messageID = fields[0].GetUInt32();
4388 m->messageType = fields[1].GetUInt8();
4389 m->sender = fields[2].GetUInt32();
4390 m->receiver = fields[3].GetUInt32();
4391 m->itemTextId = fields[4].GetUInt32();
4392 bool has_items = fields[5].GetBool();
4393 m->expire_time = (time_t)fields[6].GetUInt64();
4394 m->deliver_time = 0;
4395 m->COD = fields[7].GetUInt32();
4396 m->checked = fields[8].GetUInt32();
4397 m->mailTemplateId = fields[9].GetInt16();
4399 Player *pl = 0;
4400 if (serverUp)
4401 pl = GetPlayer((uint64)m->receiver);
4402 if (pl && pl->m_mailsLoaded)
4403 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4404 //his in mailbox and he has already listed his mails )
4405 delete m;
4406 continue;
4408 //delete or return mail:
4409 if (has_items)
4411 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4412 if(resultItems)
4416 Field *fields2 = resultItems->Fetch();
4418 uint32 item_guid_low = fields2[0].GetUInt32();
4419 uint32 item_template = fields2[1].GetUInt32();
4421 m->AddItem(item_guid_low, item_template);
4423 while (resultItems->NextRow());
4425 delete resultItems;
4427 //if it is mail from AH, it shouldn't be returned, but deleted
4428 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4430 // mail open and then not returned
4431 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4432 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4434 else
4436 //mail will be returned:
4437 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);
4438 delete m;
4439 continue;
4443 if (m->itemTextId)
4444 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4446 //deletemail = true;
4447 //delmails << m->messageID << ", ";
4448 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4449 delete m;
4450 ++count;
4451 } while (result->NextRow());
4452 delete result;
4454 sLog.outString();
4455 sLog.outString( ">> Loaded %u mails", count );
4458 void ObjectMgr::LoadQuestAreaTriggers()
4460 mQuestAreaTriggerMap.clear(); // need for reload case
4462 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4464 uint32 count = 0;
4466 if( !result )
4468 barGoLink bar( 1 );
4469 bar.step();
4471 sLog.outString();
4472 sLog.outString( ">> Loaded %u quest trigger points", count );
4473 return;
4476 barGoLink bar( result->GetRowCount() );
4480 ++count;
4481 bar.step();
4483 Field *fields = result->Fetch();
4485 uint32 trigger_ID = fields[0].GetUInt32();
4486 uint32 quest_ID = fields[1].GetUInt32();
4488 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4489 if(!atEntry)
4491 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4492 continue;
4495 Quest const* quest = GetQuestTemplate(quest_ID);
4497 if(!quest)
4499 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4500 continue;
4503 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4505 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);
4507 // this will prevent quest completing without objective
4508 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4510 // continue; - quest modified to required objective and trigger can be allowed.
4513 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4515 } while( result->NextRow() );
4517 delete result;
4519 sLog.outString();
4520 sLog.outString( ">> Loaded %u quest trigger points", count );
4523 void ObjectMgr::LoadTavernAreaTriggers()
4525 mTavernAreaTriggerSet.clear(); // need for reload case
4527 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4529 uint32 count = 0;
4531 if( !result )
4533 barGoLink bar( 1 );
4534 bar.step();
4536 sLog.outString();
4537 sLog.outString( ">> Loaded %u tavern triggers", count );
4538 return;
4541 barGoLink bar( result->GetRowCount() );
4545 ++count;
4546 bar.step();
4548 Field *fields = result->Fetch();
4550 uint32 Trigger_ID = fields[0].GetUInt32();
4552 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4553 if(!atEntry)
4555 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4556 continue;
4559 mTavernAreaTriggerSet.insert(Trigger_ID);
4560 } while( result->NextRow() );
4562 delete result;
4564 sLog.outString();
4565 sLog.outString( ">> Loaded %u tavern triggers", count );
4568 void ObjectMgr::LoadAreaTriggerScripts()
4570 mAreaTriggerScripts.clear(); // need for reload case
4571 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4573 uint32 count = 0;
4575 if( !result )
4577 barGoLink bar( 1 );
4578 bar.step();
4580 sLog.outString();
4581 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4582 return;
4585 barGoLink bar( result->GetRowCount() );
4589 ++count;
4590 bar.step();
4592 Field *fields = result->Fetch();
4594 uint32 Trigger_ID = fields[0].GetUInt32();
4595 const char *scriptName = fields[1].GetString();
4597 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4598 if(!atEntry)
4600 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4601 continue;
4603 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4604 } while( result->NextRow() );
4606 delete result;
4608 sLog.outString();
4609 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4612 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4614 bool found = false;
4615 float dist;
4616 uint32 id = 0;
4618 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4620 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4621 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4622 continue;
4624 uint8 field = (uint8)((i - 1) / 32);
4625 uint32 submask = 1<<((i-1)%32);
4627 // skip not taxi network nodes
4628 if((sTaxiNodesMask[field] & submask)==0)
4629 continue;
4631 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4632 if(found)
4634 if(dist2 < dist)
4636 dist = dist2;
4637 id = i;
4640 else
4642 found = true;
4643 dist = dist2;
4644 id = i;
4648 return id;
4651 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4653 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4654 if(src_i==sTaxiPathSetBySource.end())
4656 path = 0;
4657 cost = 0;
4658 return;
4661 TaxiPathSetForSource& pathSet = src_i->second;
4663 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4664 if(dest_i==pathSet.end())
4666 path = 0;
4667 cost = 0;
4668 return;
4671 cost = dest_i->second.price;
4672 path = dest_i->second.ID;
4675 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
4677 uint16 mount_entry = 0;
4678 uint16 mount_id = 0;
4680 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4681 if(node)
4683 if (team == ALLIANCE)
4685 mount_entry = node->MountCreatureID[1];
4686 if(!mount_entry && allowed_alt_team)
4687 mount_entry = node->MountCreatureID[0];
4689 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4690 if(ci)
4691 mount_id = ci->DisplayID_A;
4693 if (team == HORDE)
4695 mount_entry = node->MountCreatureID[0];
4697 if(!mount_entry && allowed_alt_team)
4698 mount_entry = node->MountCreatureID[1];
4700 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4701 if(ci)
4702 mount_id = ci->DisplayID_H;
4706 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4707 if(!minfo)
4709 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. ",
4710 mount_entry,id,team,mount_id);
4712 return false;
4714 if(minfo->modelid_other_gender!=0)
4715 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4717 return mount_id;
4720 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4722 if(path >= sTaxiPathNodesByPath.size())
4723 return;
4725 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4727 pathnodes.Resize(nodeList.size());
4728 mapIds.resize(nodeList.size());
4730 for(size_t i = 0; i < nodeList.size(); ++i)
4732 pathnodes[ i ].x = nodeList[i].x;
4733 pathnodes[ i ].y = nodeList[i].y;
4734 pathnodes[ i ].z = nodeList[i].z;
4736 mapIds[i] = nodeList[i].mapid;
4740 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4742 if(path >= sTaxiPathNodesByPath.size())
4743 return;
4745 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4747 pathnodes.Resize(nodeList.size());
4749 for(size_t i = 0; i < nodeList.size(); ++i)
4751 pathnodes[ i ].mapid = nodeList[i].mapid;
4752 pathnodes[ i ].x = nodeList[i].x;
4753 pathnodes[ i ].y = nodeList[i].y;
4754 pathnodes[ i ].z = nodeList[i].z;
4755 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4756 pathnodes[ i ].delay = nodeList[i].delay;
4760 void ObjectMgr::LoadGraveyardZones()
4762 mGraveYardMap.clear(); // need for reload case
4764 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4766 uint32 count = 0;
4768 if( !result )
4770 barGoLink bar( 1 );
4771 bar.step();
4773 sLog.outString();
4774 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4775 return;
4778 barGoLink bar( result->GetRowCount() );
4782 ++count;
4783 bar.step();
4785 Field *fields = result->Fetch();
4787 uint32 safeLocId = fields[0].GetUInt32();
4788 uint32 zoneId = fields[1].GetUInt32();
4789 uint32 team = fields[2].GetUInt32();
4791 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4792 if(!entry)
4794 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4795 continue;
4798 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4799 if(!areaEntry)
4801 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4802 continue;
4805 if(areaEntry->zone != 0)
4807 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4808 continue;
4811 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4813 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4814 continue;
4817 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4818 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4819 } while( result->NextRow() );
4821 delete result;
4823 sLog.outString();
4824 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4827 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4829 // search for zone associated closest graveyard
4830 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4832 // Simulate std. algorithm:
4833 // found some graveyard associated to (ghost_zone,ghost_map)
4835 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4836 // then check faction
4837 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4838 // then check faction
4839 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4840 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4841 if(graveLow==graveUp)
4843 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4844 return NULL;
4847 // at corpse map
4848 bool foundNear = false;
4849 float distNear;
4850 WorldSafeLocsEntry const* entryNear = NULL;
4852 // at entrance map for corpse map
4853 bool foundEntr = false;
4854 float distEntr;
4855 WorldSafeLocsEntry const* entryEntr = NULL;
4857 // some where other
4858 WorldSafeLocsEntry const* entryFar = NULL;
4860 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4862 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4864 GraveYardData const& data = itr->second;
4866 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4867 if(!entry)
4869 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4870 continue;
4873 // skip enemy faction graveyard
4874 // team == 0 case can be at call from .neargrave
4875 if(data.team != 0 && team != 0 && data.team != team)
4876 continue;
4878 // find now nearest graveyard at other map
4879 if(MapId != entry->map_id)
4881 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4882 if (!mapEntry ||
4883 mapEntry->entrance_map < 0 ||
4884 mapEntry->entrance_map != entry->map_id ||
4885 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
4887 // not have any corrdinates for check distance anyway
4888 entryFar = entry;
4889 continue;
4892 // at entrance map calculate distance (2D);
4893 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4894 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4895 if(foundEntr)
4897 if(dist2 < distEntr)
4899 distEntr = dist2;
4900 entryEntr = entry;
4903 else
4905 foundEntr = true;
4906 distEntr = dist2;
4907 entryEntr = entry;
4910 // find now nearest graveyard at same map
4911 else
4913 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4914 if(foundNear)
4916 if(dist2 < distNear)
4918 distNear = dist2;
4919 entryNear = entry;
4922 else
4924 foundNear = true;
4925 distNear = dist2;
4926 entryNear = entry;
4931 if(entryNear)
4932 return entryNear;
4934 if(entryEntr)
4935 return entryEntr;
4937 return entryFar;
4940 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4942 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4943 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4945 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4947 if(itr->second.safeLocId==id)
4948 return &itr->second;
4951 return NULL;
4954 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4956 if(FindGraveYardData(id,zoneId))
4957 return false;
4959 // add link to loaded data
4960 GraveYardData data;
4961 data.safeLocId = id;
4962 data.team = team;
4964 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4966 // add link to DB
4967 if(inDB)
4969 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4970 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4973 return true;
4976 void ObjectMgr::LoadAreaTriggerTeleports()
4978 mAreaTriggers.clear(); // need for reload case
4980 uint32 count = 0;
4982 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4983 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");
4984 if( !result )
4987 barGoLink bar( 1 );
4989 bar.step();
4991 sLog.outString();
4992 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4993 return;
4996 barGoLink bar( result->GetRowCount() );
5000 Field *fields = result->Fetch();
5002 bar.step();
5004 ++count;
5006 uint32 Trigger_ID = fields[0].GetUInt32();
5008 AreaTrigger at;
5010 at.requiredLevel = fields[1].GetUInt8();
5011 at.requiredItem = fields[2].GetUInt32();
5012 at.requiredItem2 = fields[3].GetUInt32();
5013 at.heroicKey = fields[4].GetUInt32();
5014 at.heroicKey2 = fields[5].GetUInt32();
5015 at.requiredQuest = fields[6].GetUInt32();
5016 at.requiredQuestHeroic = fields[7].GetUInt32();
5017 at.requiredFailedText = fields[8].GetCppString();
5018 at.target_mapId = fields[9].GetUInt32();
5019 at.target_X = fields[10].GetFloat();
5020 at.target_Y = fields[11].GetFloat();
5021 at.target_Z = fields[12].GetFloat();
5022 at.target_Orientation = fields[13].GetFloat();
5024 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5025 if(!atEntry)
5027 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5028 continue;
5031 if(at.requiredItem)
5033 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5034 if(!pProto)
5036 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5037 at.requiredItem = 0;
5040 if(at.requiredItem2)
5042 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5043 if(!pProto)
5045 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5046 at.requiredItem2 = 0;
5050 if(at.heroicKey)
5052 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5053 if(!pProto)
5055 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5056 at.heroicKey = 0;
5060 if(at.heroicKey2)
5062 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5063 if(!pProto)
5065 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5066 at.heroicKey2 = 0;
5070 if(at.requiredQuest)
5072 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5073 if(qReqItr == mQuestTemplates.end())
5075 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5076 at.requiredQuest = 0;
5080 if(at.requiredQuestHeroic)
5082 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5083 if(qReqItr == mQuestTemplates.end())
5085 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5086 at.requiredQuestHeroic = 0;
5090 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5091 if(!mapEntry)
5093 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5094 continue;
5097 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5099 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5100 continue;
5103 mAreaTriggers[Trigger_ID] = at;
5105 } while( result->NextRow() );
5107 delete result;
5109 sLog.outString();
5110 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5114 * Searches for the areatrigger which teleports players out of the given map
5116 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5118 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5119 if(!mapEntry) return NULL;
5120 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5122 if(itr->second.target_mapId == mapEntry->entrance_map)
5124 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5125 if(atEntry && atEntry->mapid == Map)
5126 return &itr->second;
5129 return NULL;
5133 * Searches for the areatrigger which teleports players to the given map
5135 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5137 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5139 if(itr->second.target_mapId == Map)
5141 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5142 if(atEntry)
5143 return &itr->second;
5146 return NULL;
5149 void ObjectMgr::SetHighestGuids()
5151 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5152 if( result )
5154 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5155 delete result;
5158 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5159 if( result )
5161 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5162 delete result;
5165 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5166 if( result )
5168 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5169 delete result;
5172 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5173 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5174 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5175 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5176 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5178 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5179 if( result )
5181 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5182 delete result;
5185 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5186 if( result )
5188 m_auctionid = (*result)[0].GetUInt32()+1;
5189 delete result;
5192 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5193 if( result )
5195 m_mailid = (*result)[0].GetUInt32()+1;
5196 delete result;
5199 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5200 if( result )
5202 m_ItemTextId = (*result)[0].GetUInt32()+1;
5203 delete result;
5206 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5207 if( result )
5209 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5210 delete result;
5213 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5214 if (result)
5216 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5217 delete result;
5220 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5221 if (result)
5223 m_guildId = (*result)[0].GetUInt32()+1;
5224 delete result;
5228 uint32 ObjectMgr::GenerateArenaTeamId()
5230 if(m_arenaTeamId>=0xFFFFFFFE)
5232 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5233 World::StopNow(ERROR_EXIT_CODE);
5235 return m_arenaTeamId++;
5238 uint32 ObjectMgr::GenerateAuctionID()
5240 if(m_auctionid>=0xFFFFFFFE)
5242 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5243 World::StopNow(ERROR_EXIT_CODE);
5245 return m_auctionid++;
5248 uint32 ObjectMgr::GenerateGuildId()
5250 if(m_guildId>=0xFFFFFFFE)
5252 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5253 World::StopNow(ERROR_EXIT_CODE);
5255 return m_guildId++;
5258 uint32 ObjectMgr::GenerateMailID()
5260 if(m_mailid>=0xFFFFFFFE)
5262 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5263 World::StopNow(ERROR_EXIT_CODE);
5265 return m_mailid++;
5268 uint32 ObjectMgr::GenerateItemTextID()
5270 if(m_ItemTextId>=0xFFFFFFFE)
5272 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5273 World::StopNow(ERROR_EXIT_CODE);
5275 return m_ItemTextId++;
5278 uint32 ObjectMgr::CreateItemText(std::string text)
5280 uint32 newItemTextId = GenerateItemTextID();
5281 //insert new itempage to container
5282 mItemTexts[ newItemTextId ] = text;
5283 //save new itempage
5284 CharacterDatabase.escape_string(text);
5285 //any Delete query needed, itemTextId is maximum of all ids
5286 std::ostringstream query;
5287 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5288 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5289 return newItemTextId;
5292 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5294 switch(guidhigh)
5296 case HIGHGUID_ITEM:
5297 if(m_hiItemGuid>=0xFFFFFFFE)
5299 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5300 World::StopNow(ERROR_EXIT_CODE);
5302 return m_hiItemGuid++;
5303 case HIGHGUID_UNIT:
5304 if(m_hiCreatureGuid>=0x00FFFFFE)
5306 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5307 World::StopNow(ERROR_EXIT_CODE);
5309 return m_hiCreatureGuid++;
5310 case HIGHGUID_PET:
5311 if(m_hiPetGuid>=0x00FFFFFE)
5313 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5314 World::StopNow(ERROR_EXIT_CODE);
5316 return m_hiPetGuid++;
5317 case HIGHGUID_VEHICLE:
5318 if(m_hiVehicleGuid>=0x00FFFFFF)
5320 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5321 World::StopNow(ERROR_EXIT_CODE);
5323 return m_hiVehicleGuid++;
5324 case HIGHGUID_PLAYER:
5325 if(m_hiCharGuid>=0xFFFFFFFE)
5327 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5328 World::StopNow(ERROR_EXIT_CODE);
5330 return m_hiCharGuid++;
5331 case HIGHGUID_GAMEOBJECT:
5332 if(m_hiGoGuid>=0x00FFFFFE)
5334 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5335 World::StopNow(ERROR_EXIT_CODE);
5337 return m_hiGoGuid++;
5338 case HIGHGUID_CORPSE:
5339 if(m_hiCorpseGuid>=0xFFFFFFFE)
5341 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5342 World::StopNow(ERROR_EXIT_CODE);
5344 return m_hiCorpseGuid++;
5345 case HIGHGUID_DYNAMICOBJECT:
5346 if(m_hiDoGuid>=0xFFFFFFFE)
5348 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5349 World::StopNow(ERROR_EXIT_CODE);
5351 return m_hiDoGuid++;
5352 default:
5353 ASSERT(0);
5356 ASSERT(0);
5357 return 0;
5360 void ObjectMgr::LoadGameObjectLocales()
5362 mGameObjectLocaleMap.clear(); // need for reload case
5364 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5365 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5366 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5367 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5369 if(!result)
5371 barGoLink bar(1);
5373 bar.step();
5375 sLog.outString();
5376 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5377 return;
5380 barGoLink bar(result->GetRowCount());
5384 Field *fields = result->Fetch();
5385 bar.step();
5387 uint32 entry = fields[0].GetUInt32();
5389 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5391 for(int i = 1; i < MAX_LOCALE; ++i)
5393 std::string str = fields[i].GetCppString();
5394 if(!str.empty())
5396 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5397 if(idx >= 0)
5399 if(data.Name.size() <= idx)
5400 data.Name.resize(idx+1);
5402 data.Name[idx] = str;
5407 for(int i = 1; i < MAX_LOCALE; ++i)
5409 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5410 if(!str.empty())
5412 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5413 if(idx >= 0)
5415 if(data.CastBarCaption.size() <= idx)
5416 data.CastBarCaption.resize(idx+1);
5418 data.CastBarCaption[idx] = str;
5423 } while (result->NextRow());
5425 delete result;
5427 sLog.outString();
5428 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5431 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5433 template<class D>
5434 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5436 dst = D(objmgr.GetScriptId(src));
5440 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5442 if (sLockStore.LookupEntry(dataN))
5443 return;
5445 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5446 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5449 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5451 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5453 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5454 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5455 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5457 /* disable check for while (too many error reports baout not existed in trap templates
5458 else
5459 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5460 goInfo->id,goInfo->type,N,dataN,dataN);
5464 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5466 if (sSpellStore.LookupEntry(dataN))
5467 return;
5469 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5470 goInfo->id,goInfo->type,N,dataN,dataN);
5473 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5475 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5476 return;
5478 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5479 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5481 // prevent client and server unexpected work
5482 const_cast<uint32&>(dataN) = 0;
5485 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5487 // 0/1 correct values
5488 if (dataN <= 1)
5489 return;
5491 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5492 goInfo->id,goInfo->type,N,dataN);
5495 void ObjectMgr::LoadGameobjectInfo()
5497 SQLGameObjectLoader loader;
5498 loader.Load(sGOStorage);
5500 // some checks
5501 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5503 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5504 if (!goInfo)
5505 continue;
5507 switch(goInfo->type)
5509 case GAMEOBJECT_TYPE_DOOR: //0
5511 if (goInfo->door.lockId)
5512 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5513 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5514 break;
5516 case GAMEOBJECT_TYPE_BUTTON: //1
5518 if (goInfo->button.lockId)
5519 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5520 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5521 break;
5523 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5525 if (goInfo->questgiver.lockId)
5526 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5527 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5528 break;
5530 case GAMEOBJECT_TYPE_CHEST: //3
5532 if (goInfo->chest.lockId)
5533 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5535 if (goInfo->chest.linkedTrapId) // linked trap
5536 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5537 break;
5539 case GAMEOBJECT_TYPE_TRAP: //6
5541 if (goInfo->trap.lockId)
5542 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5543 /* disable check for while, too many not existed spells
5544 if (goInfo->trap.spellId) // spell
5545 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5547 break;
5549 case GAMEOBJECT_TYPE_CHAIR: //7
5550 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5551 break;
5552 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5554 if (goInfo->spellFocus.focusId)
5556 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5557 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5558 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5561 if (goInfo->spellFocus.linkedTrapId) // linked trap
5562 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5563 break;
5565 case GAMEOBJECT_TYPE_GOOBER: //10
5567 if (goInfo->goober.lockId)
5568 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5570 if (goInfo->goober.pageId) // pageId
5572 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5573 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5574 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5576 /* disable check for while, too many not existed spells
5577 if (goInfo->goober.spellId) // spell
5578 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5580 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5581 if (goInfo->goober.linkedTrapId) // linked trap
5582 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5583 break;
5585 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5587 if (goInfo->areadamage.lockId)
5588 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5589 break;
5591 case GAMEOBJECT_TYPE_CAMERA: //13
5593 if (goInfo->camera.lockId)
5594 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5595 break;
5597 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5599 if (goInfo->moTransport.taxiPathId)
5601 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5602 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5603 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5605 break;
5607 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5609 /* disable check for while, too many not existed spells
5610 // always must have spell
5611 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5613 break;
5615 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5617 // always must have spell
5618 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5619 break;
5621 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5623 if (goInfo->flagstand.lockId)
5624 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5625 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5626 break;
5628 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5630 if (goInfo->fishinghole.lockId)
5631 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5632 break;
5634 case GAMEOBJECT_TYPE_FLAGDROP: //26
5636 if (goInfo->flagdrop.lockId)
5637 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5638 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5639 break;
5641 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5642 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5643 break;
5647 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5648 sLog.outString();
5651 void ObjectMgr::LoadExplorationBaseXP()
5653 uint32 count = 0;
5654 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5656 if( !result )
5658 barGoLink bar( 1 );
5660 bar.step();
5662 sLog.outString();
5663 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5664 return;
5667 barGoLink bar( result->GetRowCount() );
5671 bar.step();
5673 Field *fields = result->Fetch();
5674 uint32 level = fields[0].GetUInt32();
5675 uint32 basexp = fields[1].GetUInt32();
5676 mBaseXPTable[level] = basexp;
5677 ++count;
5679 while (result->NextRow());
5681 delete result;
5683 sLog.outString();
5684 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5687 uint32 ObjectMgr::GetBaseXP(uint32 level)
5689 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5692 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5694 if (level < mPlayerXPperLevel.size())
5695 return mPlayerXPperLevel[level];
5696 return 0;
5699 void ObjectMgr::LoadPetNames()
5701 uint32 count = 0;
5702 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5704 if( !result )
5706 barGoLink bar( 1 );
5708 bar.step();
5710 sLog.outString();
5711 sLog.outString( ">> Loaded %u pet name parts", count );
5712 return;
5715 barGoLink bar( result->GetRowCount() );
5719 bar.step();
5721 Field *fields = result->Fetch();
5722 std::string word = fields[0].GetString();
5723 uint32 entry = fields[1].GetUInt32();
5724 bool half = fields[2].GetBool();
5725 if(half)
5726 PetHalfName1[entry].push_back(word);
5727 else
5728 PetHalfName0[entry].push_back(word);
5729 ++count;
5731 while (result->NextRow());
5732 delete result;
5734 sLog.outString();
5735 sLog.outString( ">> Loaded %u pet name parts", count );
5738 void ObjectMgr::LoadPetNumber()
5740 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5741 if(result)
5743 Field *fields = result->Fetch();
5744 m_hiPetNumber = fields[0].GetUInt32()+1;
5745 delete result;
5748 barGoLink bar( 1 );
5749 bar.step();
5751 sLog.outString();
5752 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5755 std::string ObjectMgr::GeneratePetName(uint32 entry)
5757 std::vector<std::string> & list0 = PetHalfName0[entry];
5758 std::vector<std::string> & list1 = PetHalfName1[entry];
5760 if(list0.empty() || list1.empty())
5762 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5763 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5764 if(!petname)
5765 petname = cinfo->Name;
5766 return std::string(petname);
5769 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5772 uint32 ObjectMgr::GeneratePetNumber()
5774 return ++m_hiPetNumber;
5777 void ObjectMgr::LoadCorpses()
5779 uint32 count = 0;
5780 // 0 1 2 3 4 5 6 7 8 10
5781 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");
5783 if( !result )
5785 barGoLink bar( 1 );
5787 bar.step();
5789 sLog.outString();
5790 sLog.outString( ">> Loaded %u corpses", count );
5791 return;
5794 barGoLink bar( result->GetRowCount() );
5798 bar.step();
5800 Field *fields = result->Fetch();
5802 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5804 Corpse *corpse = new Corpse;
5805 if(!corpse->LoadFromDB(guid,fields))
5807 delete corpse;
5808 continue;
5811 ObjectAccessor::Instance().AddCorpse(corpse);
5813 ++count;
5815 while (result->NextRow());
5816 delete result;
5818 sLog.outString();
5819 sLog.outString( ">> Loaded %u corpses", count );
5822 void ObjectMgr::LoadReputationOnKill()
5824 uint32 count = 0;
5826 // 0 1 2
5827 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5828 // 3 4 5 6 7 8 9
5829 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5830 "FROM creature_onkill_reputation");
5832 if(!result)
5834 barGoLink bar(1);
5836 bar.step();
5838 sLog.outString();
5839 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5840 return;
5843 barGoLink bar(result->GetRowCount());
5847 Field *fields = result->Fetch();
5848 bar.step();
5850 uint32 creature_id = fields[0].GetUInt32();
5852 ReputationOnKillEntry repOnKill;
5853 repOnKill.repfaction1 = fields[1].GetUInt32();
5854 repOnKill.repfaction2 = fields[2].GetUInt32();
5855 repOnKill.is_teamaward1 = fields[3].GetBool();
5856 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5857 repOnKill.repvalue1 = fields[5].GetInt32();
5858 repOnKill.is_teamaward2 = fields[6].GetBool();
5859 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5860 repOnKill.repvalue2 = fields[8].GetInt32();
5861 repOnKill.team_dependent = fields[9].GetUInt8();
5863 if(!GetCreatureTemplate(creature_id))
5865 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5866 continue;
5869 if(repOnKill.repfaction1)
5871 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5872 if(!factionEntry1)
5874 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5875 continue;
5879 if(repOnKill.repfaction2)
5881 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5882 if(!factionEntry2)
5884 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5885 continue;
5889 mRepOnKill[creature_id] = repOnKill;
5891 ++count;
5892 } while (result->NextRow());
5894 delete result;
5896 sLog.outString();
5897 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5900 void ObjectMgr::LoadPointsOfInterest()
5902 uint32 count = 0;
5904 // 0 1 2 3 4 5
5905 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5907 if(!result)
5909 barGoLink bar(1);
5911 bar.step();
5913 sLog.outString();
5914 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5915 return;
5918 barGoLink bar(result->GetRowCount());
5922 Field *fields = result->Fetch();
5923 bar.step();
5925 uint32 point_id = fields[0].GetUInt32();
5927 PointOfInterest POI;
5928 POI.x = fields[1].GetFloat();
5929 POI.y = fields[2].GetFloat();
5930 POI.icon = fields[3].GetUInt32();
5931 POI.flags = fields[4].GetUInt32();
5932 POI.data = fields[5].GetUInt32();
5933 POI.icon_name = fields[6].GetCppString();
5935 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5937 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5938 continue;
5941 mPointsOfInterest[point_id] = POI;
5943 ++count;
5944 } while (result->NextRow());
5946 delete result;
5948 sLog.outString();
5949 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5952 void ObjectMgr::LoadNPCSpellClickSpells()
5954 uint32 count = 0;
5956 mSpellClickInfoMap.clear();
5958 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_id, cast_flags FROM npc_spellclick_spells");
5960 if(!result)
5962 barGoLink bar(1);
5964 bar.step();
5966 sLog.outString();
5967 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
5968 return;
5971 barGoLink bar(result->GetRowCount());
5975 Field *fields = result->Fetch();
5976 bar.step();
5978 uint32 npc_entry = fields[0].GetUInt32();
5979 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
5980 if (!cInfo)
5982 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
5983 continue;
5986 uint32 spellid = fields[1].GetUInt32();
5987 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
5988 if (!spellinfo)
5990 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
5991 continue;
5994 uint32 quest = fields[2].GetUInt32();
5996 // quest might be 0 to enable spellclick independent of any quest
5997 if (quest)
5999 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6001 sLog.outErrorDb("Table npc_spellclick_spells references unknown quest %u. Skipping entry.", spellid);
6002 continue;
6007 uint8 castFlags = fields[3].GetUInt8();
6008 SpellClickInfo info;
6009 info.spellId = spellid;
6010 info.questId = quest;
6011 info.castFlags = castFlags;
6012 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6013 ++count;
6014 } while (result->NextRow());
6016 delete result;
6018 sLog.outString();
6019 sLog.outString(">> Loaded %u spellclick definitions", count);
6022 void ObjectMgr::LoadWeatherZoneChances()
6024 uint32 count = 0;
6026 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6027 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");
6029 if(!result)
6031 barGoLink bar(1);
6033 bar.step();
6035 sLog.outString();
6036 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6037 return;
6040 barGoLink bar(result->GetRowCount());
6044 Field *fields = result->Fetch();
6045 bar.step();
6047 uint32 zone_id = fields[0].GetUInt32();
6049 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6051 for(int season = 0; season < WEATHER_SEASONS; ++season)
6053 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6054 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6055 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6057 if(wzc.data[season].rainChance > 100)
6059 wzc.data[season].rainChance = 25;
6060 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6063 if(wzc.data[season].snowChance > 100)
6065 wzc.data[season].snowChance = 25;
6066 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6069 if(wzc.data[season].stormChance > 100)
6071 wzc.data[season].stormChance = 25;
6072 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6076 ++count;
6077 } while (result->NextRow());
6079 delete result;
6081 sLog.outString();
6082 sLog.outString(">> Loaded %u weather definitions", count);
6085 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6087 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6088 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6089 if(t)
6090 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
6093 void ObjectMgr::DeleteCreatureData(uint32 guid)
6095 // remove mapid*cellid -> guid_set map
6096 CreatureData const* data = GetCreatureData(guid);
6097 if(data)
6098 RemoveCreatureFromGrid(guid, data);
6100 mCreatureDataMap.erase(guid);
6103 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6105 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6106 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6107 if(t)
6108 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
6111 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6113 RespawnTimes::iterator next;
6115 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6117 next = itr;
6118 ++next;
6120 if(GUID_HIPART(itr->first)==instance)
6121 mGORespawnTimes.erase(itr);
6124 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6126 next = itr;
6127 ++next;
6129 if(GUID_HIPART(itr->first)==instance)
6130 mCreatureRespawnTimes.erase(itr);
6133 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6134 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6137 void ObjectMgr::DeleteGOData(uint32 guid)
6139 // remove mapid*cellid -> guid_set map
6140 GameObjectData const* data = GetGOData(guid);
6141 if(data)
6142 RemoveGameobjectFromGrid(guid, data);
6144 mGameObjectDataMap.erase(guid);
6147 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6149 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6150 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6151 cell_guids.corpses[player_guid] = instance;
6154 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6156 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6157 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6158 cell_guids.corpses.erase(player_guid);
6161 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6163 map.clear(); // need for reload case
6165 uint32 count = 0;
6167 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6169 if(!result)
6171 barGoLink bar(1);
6173 bar.step();
6175 sLog.outString();
6176 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6177 return;
6180 barGoLink bar(result->GetRowCount());
6184 Field *fields = result->Fetch();
6185 bar.step();
6187 uint32 id = fields[0].GetUInt32();
6188 uint32 quest = fields[1].GetUInt32();
6190 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6192 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6193 continue;
6196 map.insert(QuestRelations::value_type(id,quest));
6198 ++count;
6199 } while (result->NextRow());
6201 delete result;
6203 sLog.outString();
6204 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6207 void ObjectMgr::LoadGameobjectQuestRelations()
6209 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6211 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6213 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6214 if(!goInfo)
6215 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6216 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6217 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6221 void ObjectMgr::LoadGameobjectInvolvedRelations()
6223 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6225 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6227 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6228 if(!goInfo)
6229 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6230 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6231 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6235 void ObjectMgr::LoadCreatureQuestRelations()
6237 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6239 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6241 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6242 if(!cInfo)
6243 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6244 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6245 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);
6249 void ObjectMgr::LoadCreatureInvolvedRelations()
6251 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6253 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6255 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6256 if(!cInfo)
6257 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6258 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6259 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);
6263 void ObjectMgr::LoadReservedPlayersNames()
6265 m_ReservedNames.clear(); // need for reload case
6267 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6269 uint32 count = 0;
6271 if( !result )
6273 barGoLink bar( 1 );
6274 bar.step();
6276 sLog.outString();
6277 sLog.outString( ">> Loaded %u reserved player names", count );
6278 return;
6281 barGoLink bar( result->GetRowCount() );
6283 Field* fields;
6286 bar.step();
6287 fields = result->Fetch();
6288 std::string name= fields[0].GetCppString();
6290 std::wstring wstr;
6291 if(!Utf8toWStr (name,wstr))
6293 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6294 continue;
6297 wstrToLower(wstr);
6299 m_ReservedNames.insert(wstr);
6300 ++count;
6301 } while ( result->NextRow() );
6303 delete result;
6305 sLog.outString();
6306 sLog.outString( ">> Loaded %u reserved player names", count );
6309 bool ObjectMgr::IsReservedName( const std::string& name ) const
6311 std::wstring wstr;
6312 if(!Utf8toWStr (name,wstr))
6313 return false;
6315 wstrToLower(wstr);
6317 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6320 enum LanguageType
6322 LT_BASIC_LATIN = 0x0000,
6323 LT_EXTENDEN_LATIN = 0x0001,
6324 LT_CYRILLIC = 0x0002,
6325 LT_EAST_ASIA = 0x0004,
6326 LT_ANY = 0xFFFF
6329 static LanguageType GetRealmLanguageType(bool create)
6331 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6333 case REALM_ZONE_UNKNOWN: // any language
6334 case REALM_ZONE_DEVELOPMENT:
6335 case REALM_ZONE_TEST_SERVER:
6336 case REALM_ZONE_QA_SERVER:
6337 return LT_ANY;
6338 case REALM_ZONE_UNITED_STATES: // extended-Latin
6339 case REALM_ZONE_OCEANIC:
6340 case REALM_ZONE_LATIN_AMERICA:
6341 case REALM_ZONE_ENGLISH:
6342 case REALM_ZONE_GERMAN:
6343 case REALM_ZONE_FRENCH:
6344 case REALM_ZONE_SPANISH:
6345 return LT_EXTENDEN_LATIN;
6346 case REALM_ZONE_KOREA: // East-Asian
6347 case REALM_ZONE_TAIWAN:
6348 case REALM_ZONE_CHINA:
6349 return LT_EAST_ASIA;
6350 case REALM_ZONE_RUSSIAN: // Cyrillic
6351 return LT_CYRILLIC;
6352 default:
6353 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6357 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6359 if(strictMask==0) // any language, ignore realm
6361 if(isExtendedLatinString(wstr,numericOrSpace))
6362 return true;
6363 if(isCyrillicString(wstr,numericOrSpace))
6364 return true;
6365 if(isEastAsianString(wstr,numericOrSpace))
6366 return true;
6367 return false;
6370 if(strictMask & 0x2) // realm zone specific
6372 LanguageType lt = GetRealmLanguageType(create);
6373 if(lt & LT_EXTENDEN_LATIN)
6374 if(isExtendedLatinString(wstr,numericOrSpace))
6375 return true;
6376 if(lt & LT_CYRILLIC)
6377 if(isCyrillicString(wstr,numericOrSpace))
6378 return true;
6379 if(lt & LT_EAST_ASIA)
6380 if(isEastAsianString(wstr,numericOrSpace))
6381 return true;
6384 if(strictMask & 0x1) // basic Latin
6386 if(isBasicLatinString(wstr,numericOrSpace))
6387 return true;
6390 return false;
6393 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6395 std::wstring wname;
6396 if(!Utf8toWStr(name,wname))
6397 return false;
6399 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6400 return false;
6402 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6404 return isValidString(wname,strictMask,false,create);
6407 bool ObjectMgr::IsValidCharterName( const std::string& name )
6409 std::wstring wname;
6410 if(!Utf8toWStr(name,wname))
6411 return false;
6413 if(wname.size() < 1)
6414 return false;
6416 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6418 return isValidString(wname,strictMask,true);
6421 bool ObjectMgr::IsValidPetName( const std::string& name )
6423 std::wstring wname;
6424 if(!Utf8toWStr(name,wname))
6425 return false;
6427 if(wname.size() < 1)
6428 return false;
6430 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6432 return isValidString(wname,strictMask,false);
6435 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6437 if(loc==LOCALE_enUS)
6438 return -1;
6440 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6441 if(m_LocalForIndex[i]==loc)
6442 return i;
6444 return -1;
6447 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6449 if (i<0 || i>=m_LocalForIndex.size())
6450 return LOCALE_enUS;
6452 return m_LocalForIndex[i];
6455 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6457 if(loc==LOCALE_enUS)
6458 return -1;
6460 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6461 if(m_LocalForIndex[i]==loc)
6462 return i;
6464 m_LocalForIndex.push_back(loc);
6465 return m_LocalForIndex.size()-1;
6468 void ObjectMgr::LoadGameObjectForQuests()
6470 mGameObjectForQuestSet.clear(); // need for reload case
6472 if( !sGOStorage.MaxEntry )
6474 barGoLink bar( 1 );
6475 bar.step();
6476 sLog.outString();
6477 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6478 return;
6481 barGoLink bar( sGOStorage.MaxEntry - 1 );
6482 uint32 count = 0;
6484 // collect GO entries for GO that must activated
6485 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6487 bar.step();
6488 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6489 if(!goInfo)
6490 continue;
6492 switch(goInfo->type)
6494 // scan GO chest with loot including quest items
6495 case GAMEOBJECT_TYPE_CHEST:
6497 uint32 loot_id = GameObject::GetLootId(goInfo);
6499 // find quest loot for GO
6500 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6502 mGameObjectForQuestSet.insert(go_entry);
6503 ++count;
6505 break;
6507 case GAMEOBJECT_TYPE_GOOBER:
6509 if(goInfo->goober.questId) //quests objects
6511 mGameObjectForQuestSet.insert(go_entry);
6512 count++;
6514 break;
6516 default:
6517 break;
6521 sLog.outString();
6522 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6525 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6527 // cleanup affected map part for reloading case
6528 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6530 if(itr->first >= min_value && itr->first <= max_value)
6532 MangosStringLocaleMap::iterator itr2 = itr;
6533 ++itr;
6534 mMangosStringLocaleMap.erase(itr2);
6536 else
6537 ++itr;
6540 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);
6542 if(!result)
6544 barGoLink bar(1);
6546 bar.step();
6548 sLog.outString();
6549 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6550 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6551 else
6552 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6553 return false;
6556 uint32 count = 0;
6558 barGoLink bar(result->GetRowCount());
6562 Field *fields = result->Fetch();
6563 bar.step();
6565 int32 entry = fields[0].GetInt32();
6567 if(entry==0)
6569 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6570 continue;
6572 else if(entry < min_value || entry > max_value)
6574 int32 start = min_value > 0 ? min_value : max_value;
6575 int32 end = min_value > 0 ? max_value : min_value;
6576 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6577 continue;
6580 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6582 if(data.Content.size() > 0)
6584 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6585 continue;
6588 data.Content.resize(1);
6589 ++count;
6591 // 0 -> default, idx in to idx+1
6592 data.Content[0] = fields[1].GetCppString();
6594 for(int i = 1; i < MAX_LOCALE; ++i)
6596 std::string str = fields[i+1].GetCppString();
6597 if(!str.empty())
6599 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6600 if(idx >= 0)
6602 // 0 -> default, idx in to idx+1
6603 if(data.Content.size() <= idx+1)
6604 data.Content.resize(idx+2);
6606 data.Content[idx+1] = str;
6610 } while (result->NextRow());
6612 delete result;
6614 sLog.outString();
6615 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6616 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6617 else
6618 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6620 return true;
6623 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6625 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6626 // Content[0] always exist if exist MangosStringLocale
6627 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6629 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6630 return msl->Content[locale_idx+1].c_str();
6631 else
6632 return msl->Content[0].c_str();
6635 if(entry > 0)
6636 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6637 else
6638 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6639 return "<error>";
6642 void ObjectMgr::LoadFishingBaseSkillLevel()
6644 mFishingBaseForArea.clear(); // for reload case
6646 uint32 count = 0;
6647 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6649 if( !result )
6651 barGoLink bar( 1 );
6653 bar.step();
6655 sLog.outString();
6656 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6657 return;
6660 barGoLink bar( result->GetRowCount() );
6664 bar.step();
6666 Field *fields = result->Fetch();
6667 uint32 entry = fields[0].GetUInt32();
6668 int32 skill = fields[1].GetInt32();
6670 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6671 if(!fArea)
6673 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6674 continue;
6677 mFishingBaseForArea[entry] = skill;
6678 ++count;
6680 while (result->NextRow());
6682 delete result;
6684 sLog.outString();
6685 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6688 // Searches for the same condition already in Conditions store
6689 // Returns Id if found, else adds it to Conditions and returns Id
6690 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6692 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6693 for (uint16 i=0; i < mConditions.size(); ++i)
6695 if (lc == mConditions[i])
6696 return i;
6699 mConditions.push_back(lc);
6701 if(mConditions.size() > 0xFFFF)
6703 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6704 return 0;
6707 return mConditions.size() - 1;
6710 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6712 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6714 std::wstring wname;
6715 if(!Utf8toWStr(names.name[i],wname))
6716 return false;
6718 if(mainpart!=GetMainPartOfName(wname,i+1))
6719 return false;
6721 return true;
6724 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6726 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6727 if(i!= mAreaTriggerScripts.end())
6728 return i->second;
6729 return 0;
6732 // Checks if player meets the condition
6733 bool PlayerCondition::Meets(Player const * player) const
6735 if( !player )
6736 return false; // player not present, return false
6738 switch (condition)
6740 case CONDITION_NONE:
6741 return true; // empty condition, always met
6742 case CONDITION_AURA:
6743 return player->HasAura(value1, value2);
6744 case CONDITION_ITEM:
6745 return player->HasItemCount(value1, value2);
6746 case CONDITION_ITEM_EQUIPPED:
6747 return player->HasItemOrGemWithIdEquipped(value1,1);
6748 case CONDITION_ZONEID:
6749 return player->GetZoneId() == value1;
6750 case CONDITION_REPUTATION_RANK:
6752 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6753 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6755 case CONDITION_TEAM:
6756 return player->GetTeam() == value1;
6757 case CONDITION_SKILL:
6758 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6759 case CONDITION_QUESTREWARDED:
6760 return player->GetQuestRewardStatus(value1);
6761 case CONDITION_QUESTTAKEN:
6763 QuestStatus status = player->GetQuestStatus(value1);
6764 return (status == QUEST_STATUS_INCOMPLETE);
6766 case CONDITION_AD_COMMISSION_AURA:
6768 Unit::AuraMap const& auras = player->GetAuras();
6769 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6770 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6771 return true;
6772 return false;
6774 case CONDITION_NO_AURA:
6775 return !player->HasAura(value1, value2);
6776 case CONDITION_ACTIVE_EVENT:
6777 return gameeventmgr.IsActiveEvent(value1);
6778 default:
6779 return false;
6783 // Verification of condition values validity
6784 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6786 if( condition >= MAX_CONDITION) // Wrong condition type
6788 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6789 return false;
6792 switch (condition)
6794 case CONDITION_AURA:
6796 if(!sSpellStore.LookupEntry(value1))
6798 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6799 return false;
6801 if(value2 > 2)
6803 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6804 return false;
6806 break;
6808 case CONDITION_ITEM:
6810 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6811 if(!proto)
6813 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6814 return false;
6816 break;
6818 case CONDITION_ITEM_EQUIPPED:
6820 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6821 if(!proto)
6823 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6824 return false;
6826 break;
6828 case CONDITION_ZONEID:
6830 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6831 if(!areaEntry)
6833 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6834 return false;
6836 if(areaEntry->zone != 0)
6838 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6839 return false;
6841 break;
6843 case CONDITION_REPUTATION_RANK:
6845 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6846 if(!factionEntry)
6848 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6849 return false;
6851 break;
6853 case CONDITION_TEAM:
6855 if (value1 != ALLIANCE && value1 != HORDE)
6857 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6858 return false;
6860 break;
6862 case CONDITION_SKILL:
6864 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6865 if (!pSkill)
6867 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6868 return false;
6870 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6872 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6873 return false;
6875 break;
6877 case CONDITION_QUESTREWARDED:
6878 case CONDITION_QUESTTAKEN:
6880 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6881 if (!Quest)
6883 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6884 return false;
6886 if(value2)
6887 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6888 break;
6890 case CONDITION_AD_COMMISSION_AURA:
6892 if(value1)
6893 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6894 if(value2)
6895 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6896 break;
6898 case CONDITION_NO_AURA:
6900 if(!sSpellStore.LookupEntry(value1))
6902 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6903 return false;
6905 if(value2 > 2)
6907 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6908 return false;
6910 break;
6912 case CONDITION_ACTIVE_EVENT:
6914 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6915 if(value1 >=events.size() || !events[value1].isValid())
6917 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6918 return false;
6920 break;
6922 case CONDITION_NONE:
6923 break;
6925 return true;
6928 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6930 switch(pSkill->categoryId)
6932 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6933 case SKILL_CATEGORY_WEAPON:
6934 if(pSkill->id!=SKILL_FIST_WEAPONS)
6935 return SKILL_RANGE_LEVEL;
6936 else
6937 return SKILL_RANGE_MONO;
6938 case SKILL_CATEGORY_ARMOR:
6939 case SKILL_CATEGORY_CLASS:
6940 if(pSkill->id != SKILL_LOCKPICKING)
6941 return SKILL_RANGE_MONO;
6942 else
6943 return SKILL_RANGE_LEVEL;
6944 case SKILL_CATEGORY_SECONDARY:
6945 case SKILL_CATEGORY_PROFESSION:
6946 // not set skills for professions and racial abilities
6947 if(IsProfessionSkill(pSkill->id))
6948 return SKILL_RANGE_RANK;
6949 else if(racial)
6950 return SKILL_RANGE_NONE;
6951 else
6952 return SKILL_RANGE_MONO;
6953 default:
6954 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6955 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6956 return SKILL_RANGE_NONE;
6960 void ObjectMgr::LoadGameTele()
6962 m_GameTeleMap.clear(); // for reload case
6964 uint32 count = 0;
6965 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6967 if( !result )
6969 barGoLink bar( 1 );
6971 bar.step();
6973 sLog.outString();
6974 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6975 return;
6978 barGoLink bar( result->GetRowCount() );
6982 bar.step();
6984 Field *fields = result->Fetch();
6986 uint32 id = fields[0].GetUInt32();
6988 GameTele gt;
6990 gt.position_x = fields[1].GetFloat();
6991 gt.position_y = fields[2].GetFloat();
6992 gt.position_z = fields[3].GetFloat();
6993 gt.orientation = fields[4].GetFloat();
6994 gt.mapId = fields[5].GetUInt32();
6995 gt.name = fields[6].GetCppString();
6997 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6999 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7000 continue;
7003 if(!Utf8toWStr(gt.name,gt.wnameLow))
7005 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7006 continue;
7009 wstrToLower( gt.wnameLow );
7011 m_GameTeleMap[id] = gt;
7013 ++count;
7015 while (result->NextRow());
7016 delete result;
7018 sLog.outString();
7019 sLog.outString( ">> Loaded %u GameTeleports", count );
7022 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7024 // explicit name case
7025 std::wstring wname;
7026 if(!Utf8toWStr(name,wname))
7027 return false;
7029 // converting string that we try to find to lower case
7030 wstrToLower( wname );
7032 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7033 const GameTele* alt = NULL;
7034 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7035 if(itr->second.wnameLow == wname)
7036 return &itr->second;
7037 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7038 alt = &itr->second;
7040 return alt;
7043 bool ObjectMgr::AddGameTele(GameTele& tele)
7045 // find max id
7046 uint32 new_id = 0;
7047 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7048 if(itr->first > new_id)
7049 new_id = itr->first;
7051 // use next
7052 ++new_id;
7054 if(!Utf8toWStr(tele.name,tele.wnameLow))
7055 return false;
7057 wstrToLower( tele.wnameLow );
7059 m_GameTeleMap[new_id] = tele;
7061 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')",
7062 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7065 bool ObjectMgr::DeleteGameTele(const std::string& name)
7067 // explicit name case
7068 std::wstring wname;
7069 if(!Utf8toWStr(name,wname))
7070 return false;
7072 // converting string that we try to find to lower case
7073 wstrToLower( wname );
7075 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7077 if(itr->second.wnameLow == wname)
7079 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7080 m_GameTeleMap.erase(itr);
7081 return true;
7085 return false;
7088 void ObjectMgr::LoadTrainerSpell()
7090 // For reload case
7091 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7092 itr->second.Clear();
7093 m_mCacheTrainerSpellMap.clear();
7095 std::set<uint32> skip_trainers;
7097 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7099 if( !result )
7101 barGoLink bar( 1 );
7103 bar.step();
7105 sLog.outString();
7106 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7107 return;
7110 barGoLink bar( result->GetRowCount() );
7112 uint32 count = 0;
7115 bar.step();
7117 Field* fields = result->Fetch();
7119 uint32 entry = fields[0].GetUInt32();
7120 uint32 spell = fields[1].GetUInt32();
7122 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7124 if(!cInfo)
7126 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7127 continue;
7130 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7132 if(skip_trainers.count(entry) == 0)
7134 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7135 skip_trainers.insert(entry);
7137 continue;
7140 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7141 if(!spellinfo)
7143 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7144 continue;
7147 if(!SpellMgr::IsSpellValid(spellinfo))
7149 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7150 continue;
7153 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7155 TrainerSpell& trainerSpell = data.spellList[spell];
7156 trainerSpell.spell = spell;
7157 trainerSpell.spellCost = fields[2].GetUInt32();
7158 trainerSpell.reqSkill = fields[3].GetUInt32();
7159 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7160 trainerSpell.reqLevel = fields[5].GetUInt32();
7162 if(!trainerSpell.reqLevel)
7163 trainerSpell.reqLevel = spellinfo->spellLevel;
7165 // calculate learned spell for profession case when stored cast-spell
7166 trainerSpell.learnedSpell = spell;
7167 for(int i = 0; i <3; ++i)
7169 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7170 continue;
7171 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7173 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7174 break;
7178 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7179 data.trainerType = 2;
7181 ++count;
7183 } while (result->NextRow());
7184 delete result;
7186 sLog.outString();
7187 sLog.outString( ">> Loaded %d Trainers", count );
7190 void ObjectMgr::LoadVendors()
7192 // For reload case
7193 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7194 itr->second.Clear();
7195 m_mCacheVendorItemMap.clear();
7197 std::set<uint32> skip_vendors;
7199 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7200 if( !result )
7202 barGoLink bar( 1 );
7204 bar.step();
7206 sLog.outString();
7207 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7208 return;
7211 barGoLink bar( result->GetRowCount() );
7213 uint32 count = 0;
7216 bar.step();
7217 Field* fields = result->Fetch();
7219 uint32 entry = fields[0].GetUInt32();
7220 uint32 item_id = fields[1].GetUInt32();
7221 uint32 maxcount = fields[2].GetUInt32();
7222 uint32 incrtime = fields[3].GetUInt32();
7223 uint32 ExtendedCost = fields[4].GetUInt32();
7225 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7226 continue;
7228 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7230 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7231 ++count;
7233 } while (result->NextRow());
7234 delete result;
7236 sLog.outString();
7237 sLog.outString( ">> Loaded %d Vendors ", count );
7240 void ObjectMgr::LoadNpcTextId()
7243 m_mCacheNpcTextIdMap.clear();
7245 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7246 if( !result )
7248 barGoLink bar( 1 );
7250 bar.step();
7252 sLog.outString();
7253 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7254 return;
7257 barGoLink bar( result->GetRowCount() );
7259 uint32 count = 0;
7260 uint32 guid,textid;
7263 bar.step();
7265 Field* fields = result->Fetch();
7267 guid = fields[0].GetUInt32();
7268 textid = fields[1].GetUInt32();
7270 if (!GetCreatureData(guid))
7272 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7273 continue;
7275 if (!GetGossipText(textid))
7277 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7278 continue;
7281 m_mCacheNpcTextIdMap[guid] = textid ;
7282 ++count;
7284 } while (result->NextRow());
7285 delete result;
7287 sLog.outString();
7288 sLog.outString( ">> Loaded %d NpcTextId ", count );
7291 void ObjectMgr::LoadNpcOptions()
7293 m_mCacheNpcOptionList.clear(); // For reload case
7295 QueryResult *result = WorldDatabase.Query(
7296 // 0 1 2 3 4 5 6 7 8
7297 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7298 "FROM npc_option");
7300 if( !result )
7302 barGoLink bar( 1 );
7304 bar.step();
7306 sLog.outString();
7307 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7308 return;
7311 barGoLink bar( result->GetRowCount() );
7313 uint32 count = 0;
7317 bar.step();
7319 Field* fields = result->Fetch();
7321 GossipOption go;
7322 go.Id = fields[0].GetUInt32();
7323 go.GossipId = fields[1].GetUInt32();
7324 go.NpcFlag = fields[2].GetUInt32();
7325 go.Icon = fields[3].GetUInt32();
7326 go.Action = fields[4].GetUInt32();
7327 go.BoxMoney = fields[5].GetUInt32();
7328 go.Coded = fields[6].GetUInt8()!=0;
7329 go.OptionText = fields[7].GetCppString();
7330 go.BoxText = fields[8].GetCppString();
7332 m_mCacheNpcOptionList.push_back(go);
7334 ++count;
7336 } while (result->NextRow());
7337 delete result;
7339 sLog.outString();
7340 sLog.outString( ">> Loaded %d npc_option entries", count );
7343 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7345 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7346 vList.AddItem(item,maxcount,incrtime,extendedcost);
7348 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7351 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7353 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7354 if(iter == m_mCacheVendorItemMap.end())
7355 return false;
7357 if(!iter->second.FindItem(item))
7358 return false;
7360 iter->second.RemoveItem(item);
7361 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7362 return true;
7365 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7367 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7368 if(!cInfo)
7370 if(pl)
7371 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7372 else
7373 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7374 return false;
7377 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7379 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7381 if(pl)
7382 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7383 else
7384 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7386 if(skip_vendors)
7387 skip_vendors->insert(vendor_entry);
7389 return false;
7392 if(!GetItemPrototype(item_id))
7394 if(pl)
7395 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7396 else
7397 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7398 return false;
7401 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7403 if(pl)
7404 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7405 else
7406 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7407 return false;
7410 if(maxcount > 0 && incrtime == 0)
7412 if(pl)
7413 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7414 else
7415 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7416 return false;
7418 else if(maxcount==0 && incrtime > 0)
7420 if(pl)
7421 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7422 else
7423 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7424 return false;
7427 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7428 if(!vItems)
7429 return true; // later checks for non-empty lists
7431 if(vItems->FindItem(item_id))
7433 if(pl)
7434 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7435 else
7436 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7437 return false;
7440 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7442 if(pl)
7443 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7444 else
7445 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7446 return false;
7449 return true;
7452 void ObjectMgr::LoadScriptNames()
7454 m_scriptNames.push_back("");
7455 QueryResult *result = WorldDatabase.Query(
7456 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7457 "UNION "
7458 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7459 "UNION "
7460 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7461 "UNION "
7462 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7463 "UNION "
7464 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7466 if( !result )
7468 barGoLink bar( 1 );
7469 bar.step();
7470 sLog.outString();
7471 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7472 return;
7475 barGoLink bar( result->GetRowCount() );
7476 uint32 count = 0;
7480 bar.step();
7481 m_scriptNames.push_back((*result)[0].GetString());
7482 ++count;
7483 } while (result->NextRow());
7484 delete result;
7486 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7487 sLog.outString();
7488 sLog.outString( ">> Loaded %d Script Names", count );
7491 uint32 ObjectMgr::GetScriptId(const char *name)
7493 // use binary search to find the script name in the sorted vector
7494 // assume "" is the first element
7495 if(!name) return 0;
7496 ScriptNameMap::const_iterator itr =
7497 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7498 if(itr == m_scriptNames.end() || *itr != name) return 0;
7499 return itr - m_scriptNames.begin();
7502 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7504 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7506 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7508 switch(itrM->second.command)
7510 case SCRIPT_COMMAND_TALK:
7512 if(!GetMangosStringLocale (itrM->second.dataint))
7513 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7515 if(ids.count(itrM->second.dataint))
7516 ids.erase(itrM->second.dataint);
7523 void ObjectMgr::LoadDbScriptStrings()
7525 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7527 std::set<int32> ids;
7529 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7530 if(GetMangosStringLocale(i))
7531 ids.insert(i);
7533 CheckScripts(sQuestEndScripts,ids);
7534 CheckScripts(sQuestStartScripts,ids);
7535 CheckScripts(sSpellScripts,ids);
7536 CheckScripts(sGameObjectScripts,ids);
7537 CheckScripts(sEventScripts,ids);
7539 WaypointMgr.CheckTextsExistance(ids);
7541 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7542 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7545 // Functions for scripting access
7546 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7548 return objmgr.GetAreaTriggerScriptId(trigger_id);
7551 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7553 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7555 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());
7556 start_value = -1;
7557 end_value = std::numeric_limits<int32>::min();
7560 // for scripting localized strings allowed use _only_ negative entries
7561 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7564 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7566 return objmgr.GetScriptId(name);
7569 ObjectMgr::ScriptNameMap & GetScriptNames()
7571 return objmgr.GetScriptNames();
7574 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7576 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7579 Quest const* GetQuestTemplateStore(uint32 entry)
7581 return objmgr.GetQuestTemplate(entry);