[7292] Implement storage for points of interest data in DB.
[getmangos.git] / src / game / ObjectMgr.cpp
blob9cd6dfcfe44a4a6471ffabcef61e4ee2233605b9
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 "WorldSession.h"
32 #include "Group.h"
33 #include "Guild.h"
34 #include "ArenaTeam.h"
35 #include "Transports.h"
36 #include "ProgressBar.h"
37 #include "Language.h"
38 #include "GameEvent.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
45 #include "WaypointManager.h"
46 #include "BattleGround.h"
48 INSTANTIATE_SINGLETON_1(ObjectMgr);
50 ScriptMapMap sQuestEndScripts;
51 ScriptMapMap sQuestStartScripts;
52 ScriptMapMap sSpellScripts;
53 ScriptMapMap sGameObjectScripts;
54 ScriptMapMap sEventScripts;
56 bool normalizePlayerName(std::string& name)
58 if(name.empty())
59 return false;
61 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
62 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
64 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
65 return false;
67 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
68 for(size_t i = 1; i < wstr_len; ++i)
69 wstr_buf[i] = wcharToLower(wstr_buf[i]);
71 if(!WStrToUtf8(wstr_buf,wstr_len,name))
72 return false;
74 return true;
77 LanguageDesc lang_description[LANGUAGES_COUNT] =
79 { LANG_ADDON, 0, 0 },
80 { LANG_UNIVERSAL, 0, 0 },
81 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
82 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
83 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
84 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
85 { LANG_COMMON, 668, SKILL_LANG_COMMON },
86 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
87 { LANG_TITAN, 816, SKILL_LANG_TITAN },
88 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
89 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
90 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
91 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
92 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
93 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
94 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
95 { LANG_ZOMBIE, 0, 0 },
96 { LANG_GNOMISH_BINARY, 0, 0 },
97 { LANG_GOBLIN_BINARY, 0, 0 }
100 LanguageDesc const* GetLanguageDescByID(uint32 lang)
102 for(int i = 0; i < LANGUAGES_COUNT; ++i)
104 if(uint32(lang_description[i].lang_id) == lang)
105 return &lang_description[i];
108 return NULL;
111 ObjectMgr::ObjectMgr()
113 m_hiCharGuid = 1;
114 m_hiCreatureGuid = 1;
115 m_hiPetGuid = 1;
116 m_hiVehicleGuid = 1;
117 m_hiItemGuid = 1;
118 m_hiGoGuid = 1;
119 m_hiDoGuid = 1;
120 m_hiCorpseGuid = 1;
121 m_hiPetNumber = 1;
122 m_ItemTextId = 1;
123 m_mailid = 1;
124 m_guildId = 1;
125 m_arenaTeamId = 1;
126 m_auctionid = 1;
128 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
129 mGuildBankTabPrice[0] = 100;
130 mGuildBankTabPrice[1] = 250;
131 mGuildBankTabPrice[2] = 500;
132 mGuildBankTabPrice[3] = 1000;
133 mGuildBankTabPrice[4] = 2500;
134 mGuildBankTabPrice[5] = 5000;
136 // Only zero condition left, others will be added while loading DB tables
137 mConditions.resize(1);
140 ObjectMgr::~ObjectMgr()
142 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
143 delete i->second;
145 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
146 delete[] i->second;
148 // free only if loaded
149 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
150 delete[] playerClassInfo[class_].levelInfo;
152 for (int race = 0; race < MAX_RACES; ++race)
153 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
154 delete[] playerInfo[race][class_].levelInfo;
156 // free group and guild objects
157 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
158 delete (*itr);
160 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
161 delete itr->second;
163 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
164 itr->second.Clear();
166 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
167 itr->second.Clear();
170 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
172 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
173 if ((*itr)->GetLeaderGUID() == guid)
174 return *itr;
176 return NULL;
179 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
181 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
182 if (itr != mGuildMap.end())
183 return itr->second;
185 return NULL;
188 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
190 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
191 if (itr->second->GetName() == guildname)
192 return itr->second;
194 return NULL;
197 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
199 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
200 if (itr != mGuildMap.end())
201 return itr->second->GetName();
203 return "";
206 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
208 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
209 if (itr->second->GetLeader() == guid)
210 return itr->second;
212 return NULL;
215 void ObjectMgr::AddGuild(Guild* guild)
217 mGuildMap[guild->GetId()] = guild;
220 void ObjectMgr::RemoveGuild(uint32 Id)
222 mGuildMap.erase(Id);
225 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
227 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
228 if (itr != mArenaTeamMap.end())
229 return itr->second;
231 return NULL;
234 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
236 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
237 if (itr->second->GetName() == arenateamname)
238 return itr->second;
240 return NULL;
243 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
245 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
246 if (itr->second->GetCaptain() == guid)
247 return itr->second;
249 return NULL;
252 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
254 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
257 void ObjectMgr::RemoveArenaTeam(uint32 Id)
259 mArenaTeamMap.erase(Id);
262 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
264 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
267 void ObjectMgr::LoadCreatureLocales()
269 mCreatureLocaleMap.clear(); // need for reload case
271 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");
273 if(!result)
275 barGoLink bar(1);
277 bar.step();
279 sLog.outString("");
280 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
281 return;
284 barGoLink bar(result->GetRowCount());
288 Field *fields = result->Fetch();
289 bar.step();
291 uint32 entry = fields[0].GetUInt32();
293 CreatureLocale& data = mCreatureLocaleMap[entry];
295 for(int i = 1; i < MAX_LOCALE; ++i)
297 std::string str = fields[1+2*(i-1)].GetCppString();
298 if(!str.empty())
300 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
301 if(idx >= 0)
303 if(data.Name.size() <= idx)
304 data.Name.resize(idx+1);
306 data.Name[idx] = str;
309 str = fields[1+2*(i-1)+1].GetCppString();
310 if(!str.empty())
312 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
313 if(idx >= 0)
315 if(data.SubName.size() <= idx)
316 data.SubName.resize(idx+1);
318 data.SubName[idx] = str;
322 } while (result->NextRow());
324 delete result;
326 sLog.outString();
327 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
330 void ObjectMgr::LoadNpcOptionLocales()
332 mNpcOptionLocaleMap.clear(); // need for reload case
334 QueryResult *result = WorldDatabase.Query("SELECT entry,"
335 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
336 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
337 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
338 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
339 "FROM locales_npc_option");
341 if(!result)
343 barGoLink bar(1);
345 bar.step();
347 sLog.outString("");
348 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
349 return;
352 barGoLink bar(result->GetRowCount());
356 Field *fields = result->Fetch();
357 bar.step();
359 uint32 entry = fields[0].GetUInt32();
361 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
363 for(int i = 1; i < MAX_LOCALE; ++i)
365 std::string str = fields[1+2*(i-1)].GetCppString();
366 if(!str.empty())
368 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
369 if(idx >= 0)
371 if(data.OptionText.size() <= idx)
372 data.OptionText.resize(idx+1);
374 data.OptionText[idx] = str;
377 str = fields[1+2*(i-1)+1].GetCppString();
378 if(!str.empty())
380 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
381 if(idx >= 0)
383 if(data.BoxText.size() <= idx)
384 data.BoxText.resize(idx+1);
386 data.BoxText[idx] = str;
390 } while (result->NextRow());
392 delete result;
394 sLog.outString();
395 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
398 void ObjectMgr::LoadPointOfInterestLocales()
400 mPointOfInterestLocaleMap.clear(); // need for reload case
402 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");
404 if(!result)
406 barGoLink bar(1);
408 bar.step();
410 sLog.outString("");
411 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
412 return;
415 barGoLink bar(result->GetRowCount());
419 Field *fields = result->Fetch();
420 bar.step();
422 uint32 entry = fields[0].GetUInt32();
424 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
426 for(int i = 1; i < MAX_LOCALE; ++i)
428 std::string str = fields[i].GetCppString();
429 if(str.empty())
430 continue;
432 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
433 if(idx >= 0)
435 if(data.IconName.size() <= idx)
436 data.IconName.resize(idx+1);
438 data.IconName[idx] = str;
441 } while (result->NextRow());
443 delete result;
445 sLog.outString();
446 sLog.outString( ">> Loaded %u points_of_interest locale strings", mPointOfInterestLocaleMap.size() );
449 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
451 template<class D>
452 void convert_from_str(uint32 field_pos, char *src, D &dst)
454 dst = D(objmgr.GetScriptId(src));
458 void ObjectMgr::LoadCreatureTemplates()
460 SQLCreatureLoader loader;
461 loader.Load(sCreatureStorage);
463 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
464 sLog.outString();
466 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
467 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
469 // check data correctness
470 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
472 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
473 if(!cInfo)
474 continue;
476 if(cInfo->HeroicEntry)
478 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
479 if(!heroicInfo)
481 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
482 continue;
485 if(heroicEntries.find(i)!=heroicEntries.end())
487 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
488 continue;
491 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
493 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
494 continue;
497 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
499 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
500 continue;
503 if(cInfo->npcflag != heroicInfo->npcflag)
505 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
506 continue;
509 if(cInfo->classNum != heroicInfo->classNum)
511 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
512 continue;
515 if(cInfo->race != heroicInfo->race)
517 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
518 continue;
521 if(cInfo->trainer_type != heroicInfo->trainer_type)
523 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
524 continue;
527 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
529 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
530 continue;
533 hasHeroicEntries.insert(i);
534 heroicEntries.insert(cInfo->HeroicEntry);
537 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
538 if(!factionTemplate)
539 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
541 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
542 if(!factionTemplate)
543 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
545 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
546 if (!minfo)
547 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
548 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
549 if (!minfo)
550 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
552 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
554 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
555 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
558 if(cInfo->baseattacktime == 0)
559 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
561 if(cInfo->rangeattacktime == 0)
562 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
564 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
565 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
567 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
569 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
570 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
573 // must exist or used hidden but used in data horse case
574 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
576 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
577 const_cast<CreatureInfo*>(cInfo)->family = 0;
580 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
582 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
583 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
586 if(cInfo->PetSpellDataId)
588 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
589 if(!spellDataId)
590 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
593 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
595 if(cInfo->spells[i] && !sSpellStore.LookupEntry(cInfo->spells[i]))
597 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, i+1,cInfo->spells[i]);
598 const_cast<CreatureInfo*>(cInfo)->spells[i] = 0;
602 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
604 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
605 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
608 if(cInfo->equipmentId > 0) // 0 no equipment
610 if(!GetEquipmentInfo(cInfo->equipmentId))
612 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);
613 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
617 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
618 if(cInfo->scale <= 0.0f)
620 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
621 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
626 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
628 // Now add the auras, format "spellid effectindex spellid effectindex..."
629 char *p,*s;
630 std::vector<int> val;
631 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
632 if(p)
634 while (p[0]!=0)
636 ++p;
637 if (p[0]==' ')
639 val.push_back(atoi(s));
640 s=++p;
643 if (p!=s)
644 val.push_back(atoi(s));
646 // free char* loaded memory
647 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
649 // wrong list
650 if (val.size()%2)
652 addon->auras = NULL;
653 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
654 return;
658 // empty list
659 if(val.empty())
661 addon->auras = NULL;
662 return;
665 // replace by new structures array
666 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
668 int i=0;
669 for(int j=0;j<val.size()/2;++j)
671 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
672 cAura.spell_id = (uint32)val[2*j+0];
673 cAura.effect_idx = (uint32)val[2*j+1];
674 if ( cAura.effect_idx > 2 )
676 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);
677 continue;
679 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
680 if (!AdditionalSpellInfo)
682 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
683 continue;
686 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
688 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);
689 continue;
692 ++i;
695 // fill terminator element (after last added)
696 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
697 endAura.spell_id = 0;
698 endAura.effect_idx = 0;
701 void ObjectMgr::LoadCreatureAddons()
703 sCreatureInfoAddonStorage.Load();
705 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
706 sLog.outString();
708 // check data correctness and convert 'auras'
709 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
711 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
712 if(!addon)
713 continue;
715 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
717 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
718 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
721 sCreatureDataAddonStorage.Load();
723 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
724 sLog.outString();
726 // check data correctness and convert 'auras'
727 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
729 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
730 if(!addon)
731 continue;
733 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
735 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
736 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
740 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
742 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
745 void ObjectMgr::LoadEquipmentTemplates()
747 sEquipmentStorage.Load();
749 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
751 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
753 if(!eqInfo)
754 continue;
756 for(uint8 j=0; j<3; j++)
758 if(!eqInfo->equipentry[j])
759 continue;
761 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
763 if(!dbcitem)
765 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
766 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
767 continue;
770 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
771 dbcitem->InventoryType != INVTYPE_SHIELD &&
772 dbcitem->InventoryType != INVTYPE_RANGED &&
773 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
774 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
775 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
776 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
777 dbcitem->InventoryType != INVTYPE_THROWN &&
778 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
780 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);
781 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
785 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
786 sLog.outString();
788 // This DBC is currently only used for item templates and creature equipments checks.
789 sItemStore.Clear();
792 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
794 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
797 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
799 // Load creature model (display id)
800 uint32 display_id;
801 if (!data || data->displayid == 0) // use defaults from the template
803 // DisplayID_A is used if no team is given
804 if (team == HORDE)
805 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
806 else
807 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
809 else // overridden in creature data
810 display_id = data->displayid;
812 return display_id;
815 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
817 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
818 if(!minfo)
819 return NULL;
821 // If a model for another gender exists, 50% chance to use it
822 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
824 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
825 if(!minfo_tmp)
827 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
828 return minfo; // not fatal, just use the previous one
830 else
831 return minfo_tmp;
833 else
834 return minfo;
837 void ObjectMgr::LoadCreatureModelInfo()
839 sCreatureModelStorage.Load();
841 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
842 sLog.outString();
845 void ObjectMgr::LoadCreatures()
847 uint32 count = 0;
848 // 0 1 2 3
849 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
850 // 4 5 6 7 8 9 10 11
851 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
852 // 12 13 14 15 16 17 18
853 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event "
854 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
856 if(!result)
858 barGoLink bar(1);
860 bar.step();
862 sLog.outString("");
863 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
864 return;
867 // build single time for check creature data
868 std::set<uint32> heroicCreatures;
869 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
870 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
871 if(cInfo->HeroicEntry)
872 heroicCreatures.insert(cInfo->HeroicEntry);
874 barGoLink bar(result->GetRowCount());
878 Field *fields = result->Fetch();
879 bar.step();
881 uint32 guid = fields[0].GetUInt32();
883 CreatureData& data = mCreatureDataMap[guid];
885 data.id = fields[ 1].GetUInt32();
886 data.mapid = fields[ 2].GetUInt32();
887 data.displayid = fields[ 3].GetUInt32();
888 data.equipmentId = fields[ 4].GetUInt32();
889 data.posX = fields[ 5].GetFloat();
890 data.posY = fields[ 6].GetFloat();
891 data.posZ = fields[ 7].GetFloat();
892 data.orientation = fields[ 8].GetFloat();
893 data.spawntimesecs = fields[ 9].GetUInt32();
894 data.spawndist = fields[10].GetFloat();
895 data.currentwaypoint= fields[11].GetUInt32();
896 data.curhealth = fields[12].GetUInt32();
897 data.curmana = fields[13].GetUInt32();
898 data.is_dead = fields[14].GetBool();
899 data.movementType = fields[15].GetUInt8();
900 data.spawnMask = fields[16].GetUInt8();
901 data.phaseMask = fields[17].GetUInt16();
902 int16 gameEvent = fields[18].GetInt16();
904 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
905 if(!cInfo)
907 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
908 continue;
911 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
913 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
914 continue;
917 if(data.equipmentId > 0) // -1 no equipment, 0 use default
919 if(!GetEquipmentInfo(data.equipmentId))
921 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);
922 data.equipmentId = -1;
926 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
928 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 );
929 data.curhealth = cInfo->minhealth;
932 if(data.curmana < cInfo->minmana)
934 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 );
935 data.curmana = cInfo->minmana;
938 if(data.spawndist < 0.0f)
940 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
941 data.spawndist = 0.0f;
943 else if(data.movementType == RANDOM_MOTION_TYPE)
945 if(data.spawndist == 0.0f)
947 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 );
948 data.movementType = IDLE_MOTION_TYPE;
951 else if(data.movementType == IDLE_MOTION_TYPE)
953 if(data.spawndist != 0.0f)
955 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
956 data.spawndist = 0.0f;
960 if(data.phaseMask==0)
962 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
963 data.phaseMask = 1;
965 else
967 int count = 0;
968 for(int i=0; i < sizeof(data.phaseMask)*8; ++i)
969 if(data.phaseMask & (1 << i))
970 ++count;
972 if(count > 1)
974 uint32 phaseMask = data.phaseMask & ~PHASEMASK_NORMAL;
975 count = 0;
976 for(int i=0; i < sizeof(phaseMask)*8; ++i)
977 if(phaseMask & (1 << i))
978 ++count;
980 if(count > 1)
982 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with more single bit set in `phaseMask` (not visible for anyone), set to 1.",guid,data.id );
983 data.phaseMask = phaseMask;
985 else
987 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with more single bit set in `phaseMask` (not visible for anyone), set to %u (possible expected).",guid,data.id,phaseMask);
988 data.phaseMask = 1;
994 if (gameEvent==0) // if not this is to be managed by GameEvent System
995 AddCreatureToGrid(guid, &data);
996 ++count;
998 } while (result->NextRow());
1000 delete result;
1002 sLog.outString();
1003 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1006 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1008 uint8 mask = data->spawnMask;
1009 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1011 if(mask & 1)
1013 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1014 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1016 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1017 cell_guids.creatures.insert(guid);
1022 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1024 uint8 mask = data->spawnMask;
1025 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1027 if(mask & 1)
1029 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1030 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1032 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1033 cell_guids.creatures.erase(guid);
1038 void ObjectMgr::LoadGameobjects()
1040 uint32 count = 0;
1042 // 0 1 2 3 4 5 6
1043 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1044 // 7 8 9 10 11 12 13 14 15 16
1045 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event "
1046 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1048 if(!result)
1050 barGoLink bar(1);
1052 bar.step();
1054 sLog.outString();
1055 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1056 return;
1059 barGoLink bar(result->GetRowCount());
1063 Field *fields = result->Fetch();
1064 bar.step();
1066 uint32 guid = fields[0].GetUInt32();
1068 GameObjectData& data = mGameObjectDataMap[guid];
1070 data.id = fields[ 1].GetUInt32();
1071 data.mapid = fields[ 2].GetUInt32();
1072 data.posX = fields[ 3].GetFloat();
1073 data.posY = fields[ 4].GetFloat();
1074 data.posZ = fields[ 5].GetFloat();
1075 data.orientation = fields[ 6].GetFloat();
1076 data.rotation0 = fields[ 7].GetFloat();
1077 data.rotation1 = fields[ 8].GetFloat();
1078 data.rotation2 = fields[ 9].GetFloat();
1079 data.rotation3 = fields[10].GetFloat();
1080 data.spawntimesecs = fields[11].GetInt32();
1081 data.animprogress = fields[12].GetUInt32();
1082 data.go_state = fields[13].GetUInt32();
1083 data.spawnMask = fields[14].GetUInt8();
1084 data.phaseMask = fields[15].GetUInt16();
1085 int16 gameEvent = fields[16].GetInt16();
1087 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1088 if(!gInfo)
1090 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1091 continue;
1094 if(data.phaseMask==0)
1096 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1097 data.phaseMask = 1;
1100 if (gameEvent==0) // if not this is to be managed by GameEvent System
1101 AddGameobjectToGrid(guid, &data);
1102 ++count;
1104 } while (result->NextRow());
1106 delete result;
1108 sLog.outString();
1109 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1112 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1114 uint8 mask = data->spawnMask;
1115 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1117 if(mask & 1)
1119 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1120 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1122 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1123 cell_guids.gameobjects.insert(guid);
1128 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1130 uint8 mask = data->spawnMask;
1131 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1133 if(mask & 1)
1135 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1136 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1138 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1139 cell_guids.gameobjects.erase(guid);
1144 void ObjectMgr::LoadCreatureRespawnTimes()
1146 // remove outdated data
1147 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1149 uint32 count = 0;
1151 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1153 if(!result)
1155 barGoLink bar(1);
1157 bar.step();
1159 sLog.outString();
1160 sLog.outString(">> Loaded 0 creature respawn time.");
1161 return;
1164 barGoLink bar(result->GetRowCount());
1168 Field *fields = result->Fetch();
1169 bar.step();
1171 uint32 loguid = fields[0].GetUInt32();
1172 uint64 respawn_time = fields[1].GetUInt64();
1173 uint32 instance = fields[2].GetUInt32();
1175 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1177 ++count;
1178 } while (result->NextRow());
1180 delete result;
1182 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1183 sLog.outString();
1186 void ObjectMgr::LoadGameobjectRespawnTimes()
1188 // remove outdated data
1189 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1191 uint32 count = 0;
1193 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1195 if(!result)
1197 barGoLink bar(1);
1199 bar.step();
1201 sLog.outString();
1202 sLog.outString(">> Loaded 0 gameobject respawn time.");
1203 return;
1206 barGoLink bar(result->GetRowCount());
1210 Field *fields = result->Fetch();
1211 bar.step();
1213 uint32 loguid = fields[0].GetUInt32();
1214 uint64 respawn_time = fields[1].GetUInt64();
1215 uint32 instance = fields[2].GetUInt32();
1217 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1219 ++count;
1220 } while (result->NextRow());
1222 delete result;
1224 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1225 sLog.outString();
1228 // name must be checked to correctness (if received) before call this function
1229 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1231 uint64 guid = 0;
1233 CharacterDatabase.escape_string(name);
1235 // Player name safe to sending to DB (checked at login) and this function using
1236 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1237 if(result)
1239 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1241 delete result;
1244 return guid;
1247 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1249 // prevent DB access for online player
1250 if(Player* player = GetPlayer(guid))
1252 name = player->GetName();
1253 return true;
1256 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1258 if(result)
1260 name = (*result)[0].GetCppString();
1261 delete result;
1262 return true;
1265 return false;
1268 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1270 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1272 if(result)
1274 uint8 race = (*result)[0].GetUInt8();
1275 delete result;
1276 return Player::TeamForRace(race);
1279 return 0;
1282 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1284 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1285 if(result)
1287 uint32 acc = (*result)[0].GetUInt32();
1288 delete result;
1289 return acc;
1292 return 0;
1295 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1297 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1298 if(result)
1300 uint32 acc = (*result)[0].GetUInt32();
1301 delete result;
1302 return acc;
1305 return 0;
1308 void ObjectMgr::LoadItemLocales()
1310 mItemLocaleMap.clear(); // need for reload case
1312 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");
1314 if(!result)
1316 barGoLink bar(1);
1318 bar.step();
1320 sLog.outString("");
1321 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1322 return;
1325 barGoLink bar(result->GetRowCount());
1329 Field *fields = result->Fetch();
1330 bar.step();
1332 uint32 entry = fields[0].GetUInt32();
1334 ItemLocale& data = mItemLocaleMap[entry];
1336 for(int i = 1; i < MAX_LOCALE; ++i)
1338 std::string str = fields[1+2*(i-1)].GetCppString();
1339 if(!str.empty())
1341 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1342 if(idx >= 0)
1344 if(data.Name.size() <= idx)
1345 data.Name.resize(idx+1);
1347 data.Name[idx] = str;
1351 str = fields[1+2*(i-1)+1].GetCppString();
1352 if(!str.empty())
1354 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1355 if(idx >= 0)
1357 if(data.Description.size() <= idx)
1358 data.Description.resize(idx+1);
1360 data.Description[idx] = str;
1364 } while (result->NextRow());
1366 delete result;
1368 sLog.outString();
1369 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1372 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1374 template<class D>
1375 void convert_from_str(uint32 field_pos, char *src, D &dst)
1377 dst = D(objmgr.GetScriptId(src));
1381 void ObjectMgr::LoadItemPrototypes()
1383 SQLItemLoader loader;
1384 loader.Load(sItemStorage);
1385 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1386 sLog.outString();
1388 // check data correctness
1389 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1391 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1392 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1393 if(!proto)
1395 /* to many errors, and possible not all items really used in game
1396 if (dbcitem)
1397 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1399 continue;
1402 if(dbcitem)
1404 if(proto->Class != dbcitem->Class)
1406 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1407 // It safe let use Class from DB
1409 /* disabled: have some strange wrong cases for Subclass values.
1410 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1411 if(proto->SubClass != dbcitem->SubClass)
1413 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);
1414 // It safe let use Subclass from DB
1418 if(proto->Unk0 != dbcitem->Unk0)
1420 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1421 // It safe let use Unk0 from DB
1424 if(proto->Material != dbcitem->Material)
1426 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1427 // It safe let use Material from DB
1430 if(proto->InventoryType != dbcitem->InventoryType)
1432 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1433 // It safe let use InventoryType from DB
1436 if(proto->DisplayInfoID != dbcitem->DisplayId)
1438 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1439 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1441 if(proto->Sheath != dbcitem->Sheath)
1443 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1444 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1447 else
1449 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1452 if(proto->Class >= MAX_ITEM_CLASS)
1454 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1455 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1458 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1460 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1461 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1464 if(proto->Quality >= MAX_ITEM_QUALITY)
1466 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1467 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1470 if(proto->BuyCount <= 0)
1472 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1473 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1476 if(proto->InventoryType >= MAX_INVTYPE)
1478 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1479 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1482 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1484 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1485 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1490 // can be used in equip slot, as page read use in inventory, or spell casting at use
1491 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1492 if(!req)
1494 for (int j = 0; j < 5; ++j)
1496 if(proto->Spells[j].SpellId)
1498 req = true;
1499 break;
1504 if(req)
1506 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1507 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1509 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1510 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1514 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1516 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1517 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1520 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1521 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1523 if(proto->RequiredReputationFaction)
1525 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1527 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1528 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1531 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1532 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1534 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1535 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1537 if(proto->MaxCount < -1)
1539 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1540 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1543 if(proto->Stackable==0)
1545 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1546 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1548 else if(proto->Stackable < -1)
1550 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1551 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1553 else if(proto->Stackable > 255)
1555 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1556 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1559 for (int j = 0; j < 10; j++)
1561 // for ItemStatValue != 0
1562 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1564 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1565 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1569 for (int j = 0; j < 5; j++)
1571 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1573 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1574 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1578 // special format
1579 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1581 // spell_1
1582 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1584 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);
1585 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1586 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1587 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1588 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1591 // spell_2 have learning spell
1592 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1594 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);
1595 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1596 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1597 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1599 else if(!proto->Spells[1].SpellId)
1601 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1602 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1603 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1605 else
1607 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1608 if(!spellInfo)
1610 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1611 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1612 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1613 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1615 // allowed only in special format
1616 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1618 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1619 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1620 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1621 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1625 // spell_3*,spell_4*,spell_5* is empty
1626 for (int j = 2; j < 5; j++)
1628 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1630 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1631 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1632 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1634 else if(proto->Spells[j].SpellId != 0)
1636 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1637 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1641 // normal spell list
1642 else
1644 for (int j = 0; j < 5; j++)
1646 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1648 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1649 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1650 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1653 if(proto->Spells[j].SpellId)
1655 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1656 if(!spellInfo)
1658 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1659 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1661 // allowed only in special format
1662 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1664 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1665 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1671 if(proto->Bonding >= MAX_BIND_TYPE)
1672 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1674 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1675 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1677 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1678 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1680 if(proto->Sheath >= MAX_SHEATHETYPE)
1682 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1683 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1686 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1688 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1689 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1692 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1694 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1695 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1698 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1700 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1701 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1704 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1705 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1707 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1708 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1710 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1711 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1713 for (int j = 0; j < 3; j++)
1715 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1717 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1718 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1722 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1723 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1725 if(proto->FoodType >= MAX_PET_DIET)
1727 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1728 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1731 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1733 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1734 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1739 void ObjectMgr::LoadPetLevelInfo()
1741 // Loading levels data
1743 // 0 1 2 3 4 5 6 7 8 9
1744 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1746 uint32 count = 0;
1748 if (!result)
1750 barGoLink bar( 1 );
1752 sLog.outString();
1753 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1754 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1755 return;
1758 barGoLink bar( result->GetRowCount() );
1762 Field* fields = result->Fetch();
1764 uint32 creature_id = fields[0].GetUInt32();
1765 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1767 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1768 continue;
1771 uint32 current_level = fields[1].GetUInt32();
1772 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1774 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1775 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1776 else
1777 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1778 continue;
1780 else if(current_level < 1)
1782 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1783 continue;
1786 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1788 if(pInfoMapEntry==NULL)
1789 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1791 // data for level 1 stored in [0] array element, ...
1792 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1794 pLevelInfo->health = fields[2].GetUInt16();
1795 pLevelInfo->mana = fields[3].GetUInt16();
1796 pLevelInfo->armor = fields[9].GetUInt16();
1798 for (int i = 0; i < MAX_STATS; i++)
1800 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1803 bar.step();
1804 ++count;
1806 while (result->NextRow());
1808 delete result;
1810 sLog.outString();
1811 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1814 // Fill gaps and check integrity
1815 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1817 PetLevelInfo* pInfo = itr->second;
1819 // fatal error if no level 1 data
1820 if(!pInfo || pInfo[0].health == 0 )
1822 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1823 exit(1);
1826 // fill level gaps
1827 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1829 if(pInfo[level].health == 0)
1831 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1832 pInfo[level] = pInfo[level-1];
1838 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1840 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1841 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1843 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1844 if(itr == petInfo.end())
1845 return NULL;
1847 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1850 void ObjectMgr::LoadPlayerInfo()
1852 // Load playercreate
1854 // 0 1 2 3 4 5 6
1855 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1857 uint32 count = 0;
1859 if (!result)
1861 barGoLink bar( 1 );
1863 sLog.outString();
1864 sLog.outString( ">> Loaded %u player create definitions", count );
1865 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1866 exit(1);
1869 barGoLink bar( result->GetRowCount() );
1873 Field* fields = result->Fetch();
1875 uint32 current_race = fields[0].GetUInt32();
1876 uint32 current_class = fields[1].GetUInt32();
1877 uint32 mapId = fields[2].GetUInt32();
1878 uint32 zoneId = fields[3].GetUInt32();
1879 float positionX = fields[4].GetFloat();
1880 float positionY = fields[5].GetFloat();
1881 float positionZ = fields[6].GetFloat();
1883 if(current_race >= MAX_RACES)
1885 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1886 continue;
1889 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1890 if(!rEntry)
1892 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1893 continue;
1896 if(current_class >= MAX_CLASSES)
1898 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1899 continue;
1902 if(!sChrClassesStore.LookupEntry(current_class))
1904 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1905 continue;
1908 // accept DB data only for valid position (and non instanceable)
1909 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1911 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1912 continue;
1915 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1917 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1918 continue;
1921 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1923 pInfo->mapId = mapId;
1924 pInfo->zoneId = zoneId;
1925 pInfo->positionX = positionX;
1926 pInfo->positionY = positionY;
1927 pInfo->positionZ = positionZ;
1929 pInfo->displayId_m = rEntry->model_m;
1930 pInfo->displayId_f = rEntry->model_f;
1932 bar.step();
1933 ++count;
1935 while (result->NextRow());
1937 delete result;
1939 sLog.outString();
1940 sLog.outString( ">> Loaded %u player create definitions", count );
1943 // Load playercreate items
1945 // 0 1 2 3
1946 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
1948 uint32 count = 0;
1950 if (!result)
1952 barGoLink bar( 1 );
1954 bar.step();
1956 sLog.outString();
1957 sLog.outString( ">> Loaded %u custom player create items", count );
1959 else
1961 barGoLink bar( result->GetRowCount() );
1965 Field* fields = result->Fetch();
1967 uint32 current_race = fields[0].GetUInt32();
1968 if(current_race >= MAX_RACES)
1970 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
1971 continue;
1974 uint32 current_class = fields[1].GetUInt32();
1975 if(current_class >= MAX_CLASSES)
1977 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
1978 continue;
1981 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1983 uint32 item_id = fields[2].GetUInt32();
1985 if(!GetItemPrototype(item_id))
1987 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);
1988 continue;
1991 uint32 amount = fields[3].GetUInt32();
1993 if(!amount)
1995 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
1996 continue;
1999 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2001 bar.step();
2002 ++count;
2004 while(result->NextRow());
2006 delete result;
2008 sLog.outString();
2009 sLog.outString( ">> Loaded %u custom player create items", count );
2013 // Load playercreate spells
2015 // 0 1 2
2016 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2018 uint32 count = 0;
2020 if (!result)
2022 barGoLink bar( 1 );
2024 sLog.outString();
2025 sLog.outString( ">> Loaded %u player create spells", count );
2026 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2028 else
2030 barGoLink bar( result->GetRowCount() );
2034 Field* fields = result->Fetch();
2036 uint32 current_race = fields[0].GetUInt32();
2037 if(current_race >= MAX_RACES)
2039 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2040 continue;
2043 uint32 current_class = fields[1].GetUInt32();
2044 if(current_class >= MAX_CLASSES)
2046 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2047 continue;
2050 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2051 pInfo->spell.push_back(fields[2].GetUInt32());
2053 bar.step();
2054 ++count;
2056 while( result->NextRow() );
2058 delete result;
2060 sLog.outString();
2061 sLog.outString( ">> Loaded %u player create spells", count );
2065 // Load playercreate actions
2067 // 0 1 2 3 4 5
2068 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2070 uint32 count = 0;
2072 if (!result)
2074 barGoLink bar( 1 );
2076 sLog.outString();
2077 sLog.outString( ">> Loaded %u player create actions", count );
2078 sLog.outErrorDb( "Error loading `playercreateinfo_action` 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_action` 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_action` table, ignoring.",current_class);
2099 continue;
2102 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2103 pInfo->action[0].push_back(fields[2].GetUInt16());
2104 pInfo->action[1].push_back(fields[3].GetUInt16());
2105 pInfo->action[2].push_back(fields[4].GetUInt16());
2106 pInfo->action[3].push_back(fields[5].GetUInt16());
2108 bar.step();
2109 ++count;
2111 while( result->NextRow() );
2113 delete result;
2115 sLog.outString();
2116 sLog.outString( ">> Loaded %u player create actions", count );
2120 // Loading levels data (class only dependent)
2122 // 0 1 2 3
2123 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2125 uint32 count = 0;
2127 if (!result)
2129 barGoLink bar( 1 );
2131 sLog.outString();
2132 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2133 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2134 exit(1);
2137 barGoLink bar( result->GetRowCount() );
2141 Field* fields = result->Fetch();
2143 uint32 current_class = fields[0].GetUInt32();
2144 if(current_class >= MAX_CLASSES)
2146 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2147 continue;
2150 uint32 current_level = fields[1].GetUInt32();
2151 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2153 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2154 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2155 else
2156 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2157 continue;
2160 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2162 if(!pClassInfo->levelInfo)
2163 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2165 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2167 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2168 pClassLevelInfo->basemana = fields[3].GetUInt16();
2170 bar.step();
2171 ++count;
2173 while (result->NextRow());
2175 delete result;
2177 sLog.outString();
2178 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2181 // Fill gaps and check integrity
2182 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2184 // skip non existed classes
2185 if(!sChrClassesStore.LookupEntry(class_))
2186 continue;
2188 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2190 // fatal error if no level 1 data
2191 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2193 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2194 exit(1);
2197 // fill level gaps
2198 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2200 if(pClassInfo->levelInfo[level].basehealth == 0)
2202 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2203 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2208 // Loading levels data (class/race dependent)
2210 // 0 1 2 3 4 5 6 7
2211 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2213 uint32 count = 0;
2215 if (!result)
2217 barGoLink bar( 1 );
2219 sLog.outString();
2220 sLog.outString( ">> Loaded %u level stats definitions", count );
2221 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2222 exit(1);
2225 barGoLink bar( result->GetRowCount() );
2229 Field* fields = result->Fetch();
2231 uint32 current_race = fields[0].GetUInt32();
2232 if(current_race >= MAX_RACES)
2234 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2235 continue;
2238 uint32 current_class = fields[1].GetUInt32();
2239 if(current_class >= MAX_CLASSES)
2241 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2242 continue;
2245 uint32 current_level = fields[2].GetUInt32();
2246 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2248 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2249 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2250 else
2251 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2252 continue;
2255 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2257 if(!pInfo->levelInfo)
2258 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2260 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2262 for (int i = 0; i < MAX_STATS; i++)
2264 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2267 bar.step();
2268 ++count;
2270 while (result->NextRow());
2272 delete result;
2274 sLog.outString();
2275 sLog.outString( ">> Loaded %u level stats definitions", count );
2278 // Fill gaps and check integrity
2279 for (int race = 0; race < MAX_RACES; ++race)
2281 // skip non existed races
2282 if(!sChrRacesStore.LookupEntry(race))
2283 continue;
2285 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2287 // skip non existed classes
2288 if(!sChrClassesStore.LookupEntry(class_))
2289 continue;
2291 PlayerInfo* pInfo = &playerInfo[race][class_];
2293 // skip non loaded combinations
2294 if(!pInfo->displayId_m || !pInfo->displayId_f)
2295 continue;
2297 // skip expansion races if not playing with expansion
2298 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2299 continue;
2301 // skip expansion classes if not playing with expansion
2302 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2303 continue;
2305 // fatal error if no level 1 data
2306 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2308 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2309 exit(1);
2312 // fill level gaps
2313 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2315 if(pInfo->levelInfo[level].stats[0] == 0)
2317 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2318 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2324 // Loading xp per level data
2326 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2327 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2328 mPlayerXPperLevel[level] = 0;
2330 // 0 1
2331 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2333 uint32 count = 0;
2335 if (!result)
2337 barGoLink bar( 1 );
2339 sLog.outString();
2340 sLog.outString( ">> Loaded %u xp for level definitions", count );
2341 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2342 exit(1);
2345 barGoLink bar( result->GetRowCount() );
2349 Field* fields = result->Fetch();
2351 uint32 current_level = fields[0].GetUInt32();
2352 uint32 current_xp = fields[1].GetUInt32();
2354 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2356 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2357 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2358 else
2359 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2360 continue;
2362 //PlayerXPperLevel
2363 mPlayerXPperLevel[current_level] = current_xp;
2364 bar.step();
2365 ++count;
2367 while (result->NextRow());
2369 delete result;
2371 sLog.outString();
2372 sLog.outString( ">> Loaded %u xp for level definitions", count );
2375 // fill level gaps
2376 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2378 if( mPlayerXPperLevel[level] == 0)
2380 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2381 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2386 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2388 if(level < 1 || class_ >= MAX_CLASSES)
2389 return;
2391 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2393 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2394 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2396 *info = pInfo->levelInfo[level-1];
2399 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2401 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2402 return;
2404 PlayerInfo const* pInfo = &playerInfo[race][class_];
2405 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2406 return;
2408 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2409 *info = pInfo->levelInfo[level-1];
2410 else
2411 BuildPlayerLevelInfo(race,class_,level,info);
2414 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2416 // base data (last known level)
2417 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2419 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2421 switch(_class)
2423 case CLASS_WARRIOR:
2424 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2425 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2426 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2427 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2428 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2429 break;
2430 case CLASS_PALADIN:
2431 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2432 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2433 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2434 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2435 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2436 break;
2437 case CLASS_HUNTER:
2438 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2439 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2440 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2441 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2442 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2443 break;
2444 case CLASS_ROGUE:
2445 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2446 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2447 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2448 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2449 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2450 break;
2451 case CLASS_PRIEST:
2452 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2453 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2454 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2455 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2456 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2457 break;
2458 case CLASS_SHAMAN:
2459 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2460 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2461 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2462 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2463 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2464 break;
2465 case CLASS_MAGE:
2466 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2467 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2468 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2469 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2470 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2471 break;
2472 case CLASS_WARLOCK:
2473 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2474 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2475 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2476 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2477 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2478 break;
2479 case CLASS_DRUID:
2480 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2481 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2482 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2483 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2484 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2489 void ObjectMgr::LoadGuilds()
2491 Guild *newguild;
2492 uint32 count = 0;
2494 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2496 if( !result )
2499 barGoLink bar( 1 );
2501 bar.step();
2503 sLog.outString();
2504 sLog.outString( ">> Loaded %u guild definitions", count );
2505 return;
2508 barGoLink bar( result->GetRowCount() );
2512 Field *fields = result->Fetch();
2514 bar.step();
2515 ++count;
2517 newguild = new Guild;
2518 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2520 newguild->Disband();
2521 delete newguild;
2522 continue;
2524 AddGuild(newguild);
2526 }while( result->NextRow() );
2528 delete result;
2530 sLog.outString();
2531 sLog.outString( ">> Loaded %u guild definitions", count );
2534 void ObjectMgr::LoadArenaTeams()
2536 uint32 count = 0;
2538 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2540 if( !result )
2543 barGoLink bar( 1 );
2545 bar.step();
2547 sLog.outString();
2548 sLog.outString( ">> Loaded %u arenateam definitions", count );
2549 return;
2552 barGoLink bar( result->GetRowCount() );
2556 Field *fields = result->Fetch();
2558 bar.step();
2559 ++count;
2561 ArenaTeam *newarenateam = new ArenaTeam;
2562 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2564 delete newarenateam;
2565 continue;
2567 AddArenaTeam(newarenateam);
2568 }while( result->NextRow() );
2570 delete result;
2572 sLog.outString();
2573 sLog.outString( ">> Loaded %u arenateam definitions", count );
2576 void ObjectMgr::LoadGroups()
2578 // -- loading groups --
2579 Group *group = NULL;
2580 uint64 leaderGuid = 0;
2581 uint32 count = 0;
2582 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2583 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2585 if( !result )
2587 barGoLink bar( 1 );
2589 bar.step();
2591 sLog.outString();
2592 sLog.outString( ">> Loaded %u group definitions", count );
2593 return;
2596 barGoLink bar( result->GetRowCount() );
2600 bar.step();
2601 Field *fields = result->Fetch();
2602 ++count;
2603 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2605 group = new Group;
2606 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2608 group->Disband();
2609 delete group;
2610 continue;
2612 AddGroup(group);
2613 }while( result->NextRow() );
2615 delete result;
2617 sLog.outString();
2618 sLog.outString( ">> Loaded %u group definitions", count );
2620 // -- loading members --
2621 count = 0;
2622 group = NULL;
2623 leaderGuid = 0;
2624 // 0 1 2 3
2625 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2626 if(!result)
2628 barGoLink bar( 1 );
2629 bar.step();
2631 else
2633 barGoLink bar( result->GetRowCount() );
2636 bar.step();
2637 Field *fields = result->Fetch();
2638 count++;
2639 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2640 if(!group || group->GetLeaderGUID() != leaderGuid)
2642 group = GetGroupByLeader(leaderGuid);
2643 if(!group)
2645 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2646 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2647 continue;
2651 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2653 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2654 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2656 }while( result->NextRow() );
2657 delete result;
2660 // clean groups
2661 // TODO: maybe delete from the DB before loading in this case
2662 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2664 if((*itr)->GetMembersCount() < 2)
2666 (*itr)->Disband();
2667 delete *itr;
2668 mGroupSet.erase(itr++);
2670 else
2671 ++itr;
2674 // -- loading instances --
2675 count = 0;
2676 group = NULL;
2677 leaderGuid = 0;
2678 result = CharacterDatabase.Query(
2679 // 0 1 2 3 4 5
2680 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2681 // 6
2682 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2683 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2686 if(!result)
2688 barGoLink bar( 1 );
2689 bar.step();
2691 else
2693 barGoLink bar( result->GetRowCount() );
2696 bar.step();
2697 Field *fields = result->Fetch();
2698 count++;
2699 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2700 if(!group || group->GetLeaderGUID() != leaderGuid)
2702 group = GetGroupByLeader(leaderGuid);
2703 if(!group)
2705 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2706 continue;
2710 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2711 group->BindToInstance(save, fields[3].GetBool(), true);
2712 }while( result->NextRow() );
2713 delete result;
2716 sLog.outString();
2717 sLog.outString( ">> Loaded %u group-instance binds total", count );
2719 sLog.outString();
2720 sLog.outString( ">> Loaded %u group members total", count );
2723 void ObjectMgr::LoadQuests()
2725 // For reload case
2726 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2727 delete itr->second;
2728 mQuestTemplates.clear();
2730 mExclusiveQuestGroups.clear();
2732 // 0 1 2 3 4 5 6 7 8
2733 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2734 // 9 10 11 12 13 14 15 16
2735 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2736 // 17 18 19 20 21 22 23 24 25 26 27 28
2737 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2738 // 29 30 31 32 33 34 35 36 37 38
2739 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2740 // 39 40 41 42 43 44 45 46
2741 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2742 // 47 48 49 50 51 52 53 54 55 56 57 58
2743 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2744 // 59 60 61 62 63 64 65 66
2745 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2746 // 67 68 69 70
2747 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2748 // 71 72 73 74 75 76
2749 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2750 // 77 78 79 80 81 82
2751 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2752 // 83 84 85 86 87 88 89 90
2753 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2754 // 91 92 93 94 95 96 97 98 99 100
2755 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2756 // 101 102 103 104 105 106 107 108 109 110 111
2757 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2758 // 112 113 114 115 116 117 118 119 120 121
2759 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2760 // 122 123
2761 "StartScript, CompleteScript"
2762 " FROM quest_template");
2763 if(result == NULL)
2765 barGoLink bar( 1 );
2766 bar.step();
2768 sLog.outString();
2769 sLog.outString( ">> Loaded 0 quests definitions" );
2770 sLog.outErrorDb("`quest_template` table is empty!");
2771 return;
2774 // create multimap previous quest for each existed quest
2775 // some quests can have many previous maps set by NextQuestId in previous quest
2776 // for example set of race quests can lead to single not race specific quest
2777 barGoLink bar( result->GetRowCount() );
2780 bar.step();
2781 Field *fields = result->Fetch();
2783 Quest * newQuest = new Quest(fields);
2784 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2785 } while( result->NextRow() );
2787 delete result;
2789 // Post processing
2790 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2792 Quest * qinfo = iter->second;
2794 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2796 if( qinfo->GetQuestMethod() >= 3 )
2798 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2801 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2803 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2804 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2805 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2808 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2810 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2812 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2813 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2817 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2819 // at auto-reward can be rewarded only RewChoiceItemId[0]
2820 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2822 if(uint32 id = qinfo->RewChoiceItemId[j])
2824 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2825 qinfo->GetQuestId(),j+1,id,j+1);
2826 // no changes, quest ignore this data
2831 // client quest log visual (area case)
2832 if( qinfo->ZoneOrSort > 0 )
2834 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2836 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2837 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2838 // no changes, quest not dependent from this value but can have problems at client
2841 // client quest log visual (sort case)
2842 if( qinfo->ZoneOrSort < 0 )
2844 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2845 if( !qSort )
2847 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2848 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2849 // 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)
2851 //check SkillOrClass value (class case).
2852 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2854 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2855 if(qinfo->SkillOrClass < 0)
2857 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2858 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2861 //check for proper SkillOrClass value (skill case)
2862 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2864 // skill is positive value in SkillOrClass
2865 if(qinfo->SkillOrClass != skill_id )
2867 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2868 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2869 //override, and force proper value here?
2874 // SkillOrClass (class case)
2875 if( qinfo->SkillOrClass < 0 )
2877 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2879 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2880 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2883 // SkillOrClass (skill case)
2884 if( qinfo->SkillOrClass > 0 )
2886 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2888 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2889 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2893 if( qinfo->RequiredSkillValue )
2895 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2897 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2898 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2899 // no changes, quest can't be done for this requirement
2902 if( qinfo->SkillOrClass <= 0 )
2904 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2905 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2906 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2909 // else Skill quests can have 0 skill level, this is ok
2911 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2913 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2914 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2915 // no changes, quest can't be done for this requirement
2918 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2920 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2921 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2922 // no changes, quest can't be done for this requirement
2925 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2927 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2928 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2929 // no changes, quest can't be done for this requirement
2932 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2934 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2935 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2936 // no changes, quest can't be done for this requirement
2939 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2941 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2942 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2943 // no changes, quest can't be done for this requirement
2946 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2948 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2949 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2950 // warning
2953 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2955 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2956 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2957 // warning
2960 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2962 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2963 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2964 // warning
2967 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2969 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2970 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2971 qinfo->CharTitleId = 0;
2972 // quest can't reward this title
2975 if(qinfo->SrcItemId)
2977 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2979 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2980 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2981 qinfo->SrcItemId = 0; // quest can't be done for this requirement
2983 else if(qinfo->SrcItemCount==0)
2985 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2986 qinfo->GetQuestId(),qinfo->SrcItemId);
2987 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
2990 else if(qinfo->SrcItemCount>0)
2992 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
2993 qinfo->GetQuestId(),qinfo->SrcItemCount);
2994 qinfo->SrcItemCount=0; // no quest work changes in fact
2997 if(qinfo->SrcSpell)
2999 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3000 if(!spellInfo)
3002 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3003 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3004 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3006 else if(!SpellMgr::IsSpellValid(spellInfo))
3008 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3009 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3010 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3014 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3016 uint32 id = qinfo->ReqItemId[j];
3017 if(id)
3019 if(qinfo->ReqItemCount[j]==0)
3021 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3022 qinfo->GetQuestId(),j+1,id,j+1);
3023 // no changes, quest can't be done for this requirement
3026 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3028 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3030 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3031 qinfo->GetQuestId(),j+1,id,id);
3032 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3035 else if(qinfo->ReqItemCount[j]>0)
3037 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3038 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3039 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3043 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3045 uint32 id = qinfo->ReqSourceId[j];
3046 if(id)
3048 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3050 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3051 qinfo->GetQuestId(),j+1,id,id);
3052 // no changes, quest can't be done for this requirement
3055 if(!qinfo->ReqSourceCount[j])
3057 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3058 qinfo->GetQuestId(),j+1,id,j+1);
3059 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3062 if(!qinfo->ReqSourceRef[j])
3064 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3065 qinfo->GetQuestId(),j+1,id,j+1);
3066 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3069 else
3071 if(qinfo->ReqSourceCount[j]>0)
3073 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3074 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3075 // no changes, quest ignore this data
3078 if(qinfo->ReqSourceRef[j]>0)
3080 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3081 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3082 // no changes, quest ignore this data
3087 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3089 uint32 ref = qinfo->ReqSourceRef[j];
3090 if(ref)
3092 if(ref > QUEST_OBJECTIVES_COUNT)
3094 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3095 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3096 // no changes, quest can't be done for this requirement
3098 else
3099 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3101 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3102 qinfo->GetQuestId(),j+1,ref,ref,ref);
3103 // no changes, quest can't be done for this requirement
3105 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3107 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3108 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3109 // no changes, quest can't be done for this requirement
3110 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3115 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3117 uint32 id = qinfo->ReqSpell[j];
3118 if(id)
3120 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3121 if(!spellInfo)
3123 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3124 qinfo->GetQuestId(),j+1,id,id);
3125 // no changes, quest can't be done for this requirement
3128 if(!qinfo->ReqCreatureOrGOId[j])
3130 bool found = false;
3131 for(int k = 0; k < 3; ++k)
3133 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3134 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3136 found = true;
3137 break;
3141 if(found)
3143 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3145 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);
3147 // this will prevent quest completing without objective
3148 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3151 else
3153 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.",
3154 qinfo->GetQuestId(),j+1,id,j+1,id);
3155 // no changes, quest can't be done for this requirement
3161 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3163 int32 id = qinfo->ReqCreatureOrGOId[j];
3164 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3166 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3167 qinfo->GetQuestId(),j+1,id,uint32(-id));
3168 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3171 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3173 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3174 qinfo->GetQuestId(),j+1,id,uint32(id));
3175 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3178 if(id)
3180 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3182 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3184 if(!qinfo->ReqCreatureOrGOCount[j])
3186 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3187 qinfo->GetQuestId(),j+1,id,j+1);
3188 // no changes, quest can be incorrectly done, but we already report this
3191 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3193 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3194 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3195 // no changes, quest ignore this data
3199 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3201 uint32 id = qinfo->RewChoiceItemId[j];
3202 if(id)
3204 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3206 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3207 qinfo->GetQuestId(),j+1,id,id);
3208 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3211 if(!qinfo->RewChoiceItemCount[j])
3213 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3214 qinfo->GetQuestId(),j+1,id,j+1);
3215 // no changes, quest can't be done
3218 else if(qinfo->RewChoiceItemCount[j]>0)
3220 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3221 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3222 // no changes, quest ignore this data
3226 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3228 uint32 id = qinfo->RewItemId[j];
3229 if(id)
3231 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3233 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3234 qinfo->GetQuestId(),j+1,id,id);
3235 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3238 if(!qinfo->RewItemCount[j])
3240 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3241 qinfo->GetQuestId(),j+1,id,j+1);
3242 // no changes
3245 else if(qinfo->RewItemCount[j]>0)
3247 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3248 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3249 // no changes, quest ignore this data
3253 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3255 if(qinfo->RewRepFaction[j])
3257 if(!qinfo->RewRepValue[j])
3259 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3260 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3261 // no changes
3264 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3266 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.",
3267 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3268 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3271 else if(qinfo->RewRepValue[j]!=0)
3273 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3274 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3275 // no changes, quest ignore this data
3279 if(qinfo->RewSpell)
3281 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3283 if(!spellInfo)
3285 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3286 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3287 qinfo->RewSpell = 0; // no spell reward will display for this quest
3290 else if(!SpellMgr::IsSpellValid(spellInfo))
3292 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3293 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3294 qinfo->RewSpell = 0; // no spell reward will display for this quest
3299 if(qinfo->RewSpellCast)
3301 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3303 if(!spellInfo)
3305 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3306 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3307 qinfo->RewSpellCast = 0; // no spell will be casted on player
3310 else if(!SpellMgr::IsSpellValid(spellInfo))
3312 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3313 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3314 qinfo->RewSpellCast = 0; // no spell will be casted on player
3319 if(qinfo->RewMailTemplateId)
3321 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3323 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3324 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3325 qinfo->RewMailTemplateId = 0; // no mail will send to player
3326 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3330 if(qinfo->NextQuestInChain)
3332 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3334 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3335 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3336 qinfo->NextQuestInChain = 0;
3338 else
3339 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3342 // fill additional data stores
3343 if(qinfo->PrevQuestId)
3345 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3347 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3349 else
3351 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3355 if(qinfo->NextQuestId)
3357 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3359 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3361 else
3363 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3364 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3368 if(qinfo->ExclusiveGroup)
3369 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3370 if(qinfo->LimitTime)
3371 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3374 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3375 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3377 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3378 if(!spellInfo)
3379 continue;
3381 for(int j = 0; j < 3; ++j)
3383 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3384 continue;
3386 uint32 quest_id = spellInfo->EffectMiscValue[j];
3388 Quest const* quest = GetQuestTemplate(quest_id);
3390 // some quest referenced in spells not exist (outdated spells)
3391 if(!quest)
3392 continue;
3394 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3396 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);
3398 // this will prevent quest completing without objective
3399 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3404 sLog.outString();
3405 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3408 void ObjectMgr::LoadQuestLocales()
3410 mQuestLocaleMap.clear(); // need for reload case
3412 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3413 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3414 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3415 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3416 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3417 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3418 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3419 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3420 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3421 " FROM locales_quest"
3424 if(!result)
3426 barGoLink bar(1);
3428 bar.step();
3430 sLog.outString("");
3431 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3432 return;
3435 barGoLink bar(result->GetRowCount());
3439 Field *fields = result->Fetch();
3440 bar.step();
3442 uint32 entry = fields[0].GetUInt32();
3444 QuestLocale& data = mQuestLocaleMap[entry];
3446 for(int i = 1; i < MAX_LOCALE; ++i)
3448 std::string str = fields[1+10*(i-1)].GetCppString();
3449 if(!str.empty())
3451 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3452 if(idx >= 0)
3454 if(data.Title.size() <= idx)
3455 data.Title.resize(idx+1);
3457 data.Title[idx] = str;
3460 str = fields[1+10*(i-1)+1].GetCppString();
3461 if(!str.empty())
3463 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3464 if(idx >= 0)
3466 if(data.Details.size() <= idx)
3467 data.Details.resize(idx+1);
3469 data.Details[idx] = str;
3472 str = fields[1+10*(i-1)+2].GetCppString();
3473 if(!str.empty())
3475 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3476 if(idx >= 0)
3478 if(data.Objectives.size() <= idx)
3479 data.Objectives.resize(idx+1);
3481 data.Objectives[idx] = str;
3484 str = fields[1+10*(i-1)+3].GetCppString();
3485 if(!str.empty())
3487 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3488 if(idx >= 0)
3490 if(data.OfferRewardText.size() <= idx)
3491 data.OfferRewardText.resize(idx+1);
3493 data.OfferRewardText[idx] = str;
3496 str = fields[1+10*(i-1)+4].GetCppString();
3497 if(!str.empty())
3499 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3500 if(idx >= 0)
3502 if(data.RequestItemsText.size() <= idx)
3503 data.RequestItemsText.resize(idx+1);
3505 data.RequestItemsText[idx] = str;
3508 str = fields[1+10*(i-1)+5].GetCppString();
3509 if(!str.empty())
3511 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3512 if(idx >= 0)
3514 if(data.EndText.size() <= idx)
3515 data.EndText.resize(idx+1);
3517 data.EndText[idx] = str;
3520 for(int k = 0; k < 4; ++k)
3522 str = fields[1+10*(i-1)+6+k].GetCppString();
3523 if(!str.empty())
3525 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3526 if(idx >= 0)
3528 if(data.ObjectiveText[k].size() <= idx)
3529 data.ObjectiveText[k].resize(idx+1);
3531 data.ObjectiveText[k][idx] = str;
3536 } while (result->NextRow());
3538 delete result;
3540 sLog.outString();
3541 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3544 void ObjectMgr::LoadPetCreateSpells()
3546 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3547 if(!result)
3549 barGoLink bar( 1 );
3550 bar.step();
3552 sLog.outString();
3553 sLog.outString( ">> Loaded 0 pet create spells" );
3554 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3555 return;
3558 uint32 count = 0;
3560 barGoLink bar( result->GetRowCount() );
3562 mPetCreateSpell.clear();
3566 Field *fields = result->Fetch();
3567 bar.step();
3569 uint32 creature_id = fields[0].GetUInt32();
3571 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3572 continue;
3574 PetCreateSpellEntry PetCreateSpell;
3575 for(int i = 0; i < 4; i++)
3577 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3579 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3580 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3583 mPetCreateSpell[creature_id] = PetCreateSpell;
3585 ++count;
3587 while (result->NextRow());
3589 delete result;
3591 sLog.outString();
3592 sLog.outString( ">> Loaded %u pet create spells", count );
3595 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3597 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3598 return;
3600 sLog.outString( "%s :", tablename);
3602 scripts.clear(); // need for reload support
3604 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3606 uint32 count = 0;
3608 if( !result )
3610 barGoLink bar( 1 );
3611 bar.step();
3613 sLog.outString();
3614 sLog.outString( ">> Loaded %u script definitions", count );
3615 return;
3618 barGoLink bar( result->GetRowCount() );
3622 bar.step();
3624 Field *fields = result->Fetch();
3625 ScriptInfo tmp;
3626 tmp.id = fields[0].GetUInt32();
3627 tmp.delay = fields[1].GetUInt32();
3628 tmp.command = fields[2].GetUInt32();
3629 tmp.datalong = fields[3].GetUInt32();
3630 tmp.datalong2 = fields[4].GetUInt32();
3631 tmp.dataint = fields[5].GetInt32();
3632 tmp.x = fields[6].GetFloat();
3633 tmp.y = fields[7].GetFloat();
3634 tmp.z = fields[8].GetFloat();
3635 tmp.o = fields[9].GetFloat();
3637 // generic command args check
3638 switch(tmp.command)
3640 case SCRIPT_COMMAND_TALK:
3642 if(tmp.datalong > 3)
3644 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3645 continue;
3647 if(tmp.dataint==0)
3649 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3650 continue;
3652 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3654 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);
3655 continue;
3658 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3659 break;
3662 case SCRIPT_COMMAND_TELEPORT_TO:
3664 if(!sMapStore.LookupEntry(tmp.datalong))
3666 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3667 continue;
3670 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3672 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);
3673 continue;
3675 break;
3678 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3680 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3682 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);
3683 continue;
3686 if(!GetCreatureTemplate(tmp.datalong))
3688 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3689 continue;
3691 break;
3694 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3696 GameObjectData const* data = GetGOData(tmp.datalong);
3697 if(!data)
3699 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3700 continue;
3703 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3704 if(!info)
3706 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);
3707 continue;
3710 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3711 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3712 info->type==GAMEOBJECT_TYPE_DOOR ||
3713 info->type==GAMEOBJECT_TYPE_BUTTON ||
3714 info->type==GAMEOBJECT_TYPE_TRAP )
3716 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3717 continue;
3719 break;
3721 case SCRIPT_COMMAND_OPEN_DOOR:
3722 case SCRIPT_COMMAND_CLOSE_DOOR:
3724 GameObjectData const* data = GetGOData(tmp.datalong);
3725 if(!data)
3727 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);
3728 continue;
3731 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3732 if(!info)
3734 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);
3735 continue;
3738 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3740 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);
3741 continue;
3744 break;
3746 case SCRIPT_COMMAND_QUEST_EXPLORED:
3748 Quest const* quest = GetQuestTemplate(tmp.datalong);
3749 if(!quest)
3751 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);
3752 continue;
3755 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3757 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);
3759 // this will prevent quest completing without objective
3760 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3762 // continue; - quest objective requirement set and command can be allowed
3765 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3767 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",
3768 tablename,tmp.datalong2,tmp.id);
3769 continue;
3772 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3774 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",
3775 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3776 continue;
3779 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3781 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",
3782 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3783 continue;
3786 break;
3789 case SCRIPT_COMMAND_REMOVE_AURA:
3790 case SCRIPT_COMMAND_CAST_SPELL:
3792 if(!sSpellStore.LookupEntry(tmp.datalong))
3794 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3795 tablename,tmp.datalong,tmp.id);
3796 continue;
3798 break;
3802 if (scripts.find(tmp.id) == scripts.end())
3804 ScriptMap emptyMap;
3805 scripts[tmp.id] = emptyMap;
3807 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3809 ++count;
3810 } while( result->NextRow() );
3812 delete result;
3814 sLog.outString();
3815 sLog.outString( ">> Loaded %u script definitions", count );
3818 void ObjectMgr::LoadGameObjectScripts()
3820 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3822 // check ids
3823 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3825 if(!GetGOData(itr->first))
3826 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3830 void ObjectMgr::LoadQuestEndScripts()
3832 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3834 // check ids
3835 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3837 if(!GetQuestTemplate(itr->first))
3838 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3842 void ObjectMgr::LoadQuestStartScripts()
3844 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3846 // check ids
3847 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3849 if(!GetQuestTemplate(itr->first))
3850 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3854 void ObjectMgr::LoadSpellScripts()
3856 LoadScripts(sSpellScripts, "spell_scripts");
3858 // check ids
3859 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3861 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3863 if(!spellInfo)
3865 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3866 continue;
3869 //check for correct spellEffect
3870 bool found = false;
3871 for(int i=0; i<3; ++i)
3873 // skip empty effects
3874 if( !spellInfo->Effect[i] )
3875 continue;
3877 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3879 found = true;
3880 break;
3884 if(!found)
3885 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3889 void ObjectMgr::LoadEventScripts()
3891 LoadScripts(sEventScripts, "event_scripts");
3893 std::set<uint32> evt_scripts;
3894 // Load all possible script entries from gameobjects
3895 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3897 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3898 if (goInfo)
3900 switch(goInfo->type)
3902 case GAMEOBJECT_TYPE_GOOBER:
3903 if(goInfo->goober.eventId)
3904 evt_scripts.insert(goInfo->goober.eventId);
3905 break;
3906 case GAMEOBJECT_TYPE_CHEST:
3907 if(goInfo->chest.eventId)
3908 evt_scripts.insert(goInfo->chest.eventId);
3909 break;
3910 default:
3911 break;
3915 // Load all possible script entries from spells
3916 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3918 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3919 if (spell)
3921 for(int j=0; j<3; ++j)
3923 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3925 if (spell->EffectMiscValue[j])
3926 evt_scripts.insert(spell->EffectMiscValue[j]);
3931 // Then check if all scripts are in above list of possible script entries
3932 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3934 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3935 if (itr2 == evt_scripts.end())
3936 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);
3940 void ObjectMgr::LoadItemTexts()
3942 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3944 uint32 count = 0;
3946 if( !result )
3948 barGoLink bar( 1 );
3949 bar.step();
3951 sLog.outString();
3952 sLog.outString( ">> Loaded %u item pages", count );
3953 return;
3956 barGoLink bar( result->GetRowCount() );
3958 Field* fields;
3961 bar.step();
3963 fields = result->Fetch();
3965 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3967 ++count;
3969 } while ( result->NextRow() );
3971 delete result;
3973 sLog.outString();
3974 sLog.outString( ">> Loaded %u item texts", count );
3977 void ObjectMgr::LoadPageTexts()
3979 sPageTextStore.Free(); // for reload case
3981 sPageTextStore.Load();
3982 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3983 sLog.outString();
3985 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3987 // check data correctness
3988 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3989 if(!page)
3990 continue;
3992 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3994 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3995 continue;
3998 // detect circular reference
3999 std::set<uint32> checkedPages;
4000 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4002 if(!pageItr->Next_Page)
4003 break;
4004 checkedPages.insert(pageItr->Page_ID);
4005 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4007 std::ostringstream ss;
4008 ss<< "The text page(s) ";
4009 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4010 ss << *itr << " ";
4011 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4012 << pageItr->Page_ID <<" to 0";
4013 sLog.outErrorDb(ss.str().c_str());
4014 const_cast<PageText*>(pageItr)->Next_Page = 0;
4015 break;
4021 void ObjectMgr::LoadPageTextLocales()
4023 mPageTextLocaleMap.clear(); // need for reload case
4025 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");
4027 if(!result)
4029 barGoLink bar(1);
4031 bar.step();
4033 sLog.outString("");
4034 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4035 return;
4038 barGoLink bar(result->GetRowCount());
4042 Field *fields = result->Fetch();
4043 bar.step();
4045 uint32 entry = fields[0].GetUInt32();
4047 PageTextLocale& data = mPageTextLocaleMap[entry];
4049 for(int i = 1; i < MAX_LOCALE; ++i)
4051 std::string str = fields[i].GetCppString();
4052 if(str.empty())
4053 continue;
4055 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4056 if(idx >= 0)
4058 if(data.Text.size() <= idx)
4059 data.Text.resize(idx+1);
4061 data.Text[idx] = str;
4065 } while (result->NextRow());
4067 delete result;
4069 sLog.outString();
4070 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4073 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4075 template<class D>
4076 void convert_from_str(uint32 field_pos, char *src, D &dst)
4078 dst = D(objmgr.GetScriptId(src));
4082 void ObjectMgr::LoadInstanceTemplate()
4084 SQLInstanceLoader loader;
4085 loader.Load(sInstanceTemplate);
4087 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4089 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4090 if(!temp) continue;
4091 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4092 if(!entry)
4094 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4095 continue;
4097 else if(!entry->HasResetTime())
4098 continue;
4100 //FIXME: now exist heroic instance, normal/heroic raid instances
4101 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4102 // entry->resetTimeRaid store reset time for normal raid only
4103 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4104 // but at some point wee need implement reset time dependent from raid instance mode
4105 if(temp->reset_delay == 0)
4107 // use defaults from the DBC
4108 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4110 temp->reset_delay = entry->resetTimeHeroic / DAY;
4112 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4113 // for normal raid only
4115 temp->reset_delay = entry->resetTimeRaid / DAY;
4119 // the reset_delay must be at least one day
4120 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4123 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4124 sLog.outString();
4127 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4129 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4130 if(itr != mGossipText.end())
4131 return &itr->second;
4132 return NULL;
4135 void ObjectMgr::LoadGossipText()
4137 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4139 int count = 0;
4140 if( !result )
4142 barGoLink bar( 1 );
4143 bar.step();
4145 sLog.outString();
4146 sLog.outString( ">> Loaded %u npc texts", count );
4147 return;
4150 int cic;
4152 barGoLink bar( result->GetRowCount() );
4156 ++count;
4157 cic = 0;
4159 Field *fields = result->Fetch();
4161 bar.step();
4163 uint32 Text_ID = fields[cic++].GetUInt32();
4164 if(!Text_ID)
4166 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4167 continue;
4170 GossipText& gText = mGossipText[Text_ID];
4172 for (int i=0; i< 8; i++)
4174 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4175 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4177 gText.Options[i].Language = fields[cic++].GetUInt32();
4178 gText.Options[i].Probability = fields[cic++].GetFloat();
4180 for(int j=0; j < 3; ++j)
4182 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4183 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4186 } while( result->NextRow() );
4188 sLog.outString();
4189 sLog.outString( ">> Loaded %u npc texts", count );
4190 delete result;
4193 void ObjectMgr::LoadNpcTextLocales()
4195 mNpcTextLocaleMap.clear(); // need for reload case
4197 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4198 "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,"
4199 "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,"
4200 "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,"
4201 "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,"
4202 "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,"
4203 "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,"
4204 "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, "
4205 "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 "
4206 " FROM locales_npc_text");
4208 if(!result)
4210 barGoLink bar(1);
4212 bar.step();
4214 sLog.outString("");
4215 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4216 return;
4219 barGoLink bar(result->GetRowCount());
4223 Field *fields = result->Fetch();
4224 bar.step();
4226 uint32 entry = fields[0].GetUInt32();
4228 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4230 for(int i=1; i<MAX_LOCALE; ++i)
4232 for(int j=0; j<8; ++j)
4234 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4235 if(!str0.empty())
4237 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4238 if(idx >= 0)
4240 if(data.Text_0[j].size() <= idx)
4241 data.Text_0[j].resize(idx+1);
4243 data.Text_0[j][idx] = str0;
4246 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4247 if(!str1.empty())
4249 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4250 if(idx >= 0)
4252 if(data.Text_1[j].size() <= idx)
4253 data.Text_1[j].resize(idx+1);
4255 data.Text_1[j][idx] = str1;
4260 } while (result->NextRow());
4262 delete result;
4264 sLog.outString();
4265 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4268 //not very fast function but it is called only once a day, or on starting-up
4269 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4271 time_t basetime = time(NULL);
4272 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4273 //delete all old mails without item and without body immediately, if starting server
4274 if (!serverUp)
4275 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4276 // 0 1 2 3 4 5 6 7 8 9
4277 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);
4278 if ( !result )
4280 barGoLink bar(1);
4281 bar.step();
4282 sLog.outString("");
4283 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4284 return; // any mails need to be returned or deleted
4287 //std::ostringstream delitems, delmails; //will be here for optimization
4288 //bool deletemail = false, deleteitem = false;
4289 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4290 //delmails << "DELETE FROM mail WHERE id IN ( "
4292 barGoLink bar( result->GetRowCount() );
4293 uint32 count = 0;
4294 Field *fields;
4298 bar.step();
4300 fields = result->Fetch();
4301 Mail *m = new Mail;
4302 m->messageID = fields[0].GetUInt32();
4303 m->messageType = fields[1].GetUInt8();
4304 m->sender = fields[2].GetUInt32();
4305 m->receiver = fields[3].GetUInt32();
4306 m->itemTextId = fields[4].GetUInt32();
4307 bool has_items = fields[5].GetBool();
4308 m->expire_time = (time_t)fields[6].GetUInt64();
4309 m->deliver_time = 0;
4310 m->COD = fields[7].GetUInt32();
4311 m->checked = fields[8].GetUInt32();
4312 m->mailTemplateId = fields[9].GetInt16();
4314 Player *pl = 0;
4315 if (serverUp)
4316 pl = GetPlayer((uint64)m->receiver);
4317 if (pl && pl->m_mailsLoaded)
4318 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4319 //his in mailbox and he has already listed his mails )
4320 delete m;
4321 continue;
4323 //delete or return mail:
4324 if (has_items)
4326 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4327 if(resultItems)
4331 Field *fields2 = resultItems->Fetch();
4333 uint32 item_guid_low = fields2[0].GetUInt32();
4334 uint32 item_template = fields2[1].GetUInt32();
4336 m->AddItem(item_guid_low, item_template);
4338 while (resultItems->NextRow());
4340 delete resultItems;
4342 //if it is mail from AH, it shouldn't be returned, but deleted
4343 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4345 // mail open and then not returned
4346 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4347 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4349 else
4351 //mail will be returned:
4352 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);
4353 delete m;
4354 continue;
4358 if (m->itemTextId)
4359 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4361 //deletemail = true;
4362 //delmails << m->messageID << ", ";
4363 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4364 delete m;
4365 ++count;
4366 } while (result->NextRow());
4367 delete result;
4369 sLog.outString();
4370 sLog.outString( ">> Loaded %u mails", count );
4373 void ObjectMgr::LoadQuestAreaTriggers()
4375 mQuestAreaTriggerMap.clear(); // need for reload case
4377 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4379 uint32 count = 0;
4381 if( !result )
4383 barGoLink bar( 1 );
4384 bar.step();
4386 sLog.outString();
4387 sLog.outString( ">> Loaded %u quest trigger points", count );
4388 return;
4391 barGoLink bar( result->GetRowCount() );
4395 ++count;
4396 bar.step();
4398 Field *fields = result->Fetch();
4400 uint32 trigger_ID = fields[0].GetUInt32();
4401 uint32 quest_ID = fields[1].GetUInt32();
4403 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4404 if(!atEntry)
4406 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4407 continue;
4410 Quest const* quest = GetQuestTemplate(quest_ID);
4412 if(!quest)
4414 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4415 continue;
4418 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4420 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);
4422 // this will prevent quest completing without objective
4423 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4425 // continue; - quest modified to required objective and trigger can be allowed.
4428 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4430 } while( result->NextRow() );
4432 delete result;
4434 sLog.outString();
4435 sLog.outString( ">> Loaded %u quest trigger points", count );
4438 void ObjectMgr::LoadTavernAreaTriggers()
4440 mTavernAreaTriggerSet.clear(); // need for reload case
4442 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4444 uint32 count = 0;
4446 if( !result )
4448 barGoLink bar( 1 );
4449 bar.step();
4451 sLog.outString();
4452 sLog.outString( ">> Loaded %u tavern triggers", count );
4453 return;
4456 barGoLink bar( result->GetRowCount() );
4460 ++count;
4461 bar.step();
4463 Field *fields = result->Fetch();
4465 uint32 Trigger_ID = fields[0].GetUInt32();
4467 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4468 if(!atEntry)
4470 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4471 continue;
4474 mTavernAreaTriggerSet.insert(Trigger_ID);
4475 } while( result->NextRow() );
4477 delete result;
4479 sLog.outString();
4480 sLog.outString( ">> Loaded %u tavern triggers", count );
4483 void ObjectMgr::LoadAreaTriggerScripts()
4485 mAreaTriggerScripts.clear(); // need for reload case
4486 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4488 uint32 count = 0;
4490 if( !result )
4492 barGoLink bar( 1 );
4493 bar.step();
4495 sLog.outString();
4496 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4497 return;
4500 barGoLink bar( result->GetRowCount() );
4504 ++count;
4505 bar.step();
4507 Field *fields = result->Fetch();
4509 uint32 Trigger_ID = fields[0].GetUInt32();
4510 const char *scriptName = fields[1].GetString();
4512 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4513 if(!atEntry)
4515 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4516 continue;
4518 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4519 } while( result->NextRow() );
4521 delete result;
4523 sLog.outString();
4524 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4527 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4529 bool found = false;
4530 float dist;
4531 uint32 id = 0;
4533 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4535 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4536 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4537 continue;
4539 uint8 field = (uint8)((i - 1) / 32);
4540 uint32 submask = 1<<((i-1)%32);
4542 // skip not taxi network nodes
4543 if((sTaxiNodesMask[field] & submask)==0)
4544 continue;
4546 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4547 if(found)
4549 if(dist2 < dist)
4551 dist = dist2;
4552 id = i;
4555 else
4557 found = true;
4558 dist = dist2;
4559 id = i;
4563 return id;
4566 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4568 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4569 if(src_i==sTaxiPathSetBySource.end())
4571 path = 0;
4572 cost = 0;
4573 return;
4576 TaxiPathSetForSource& pathSet = src_i->second;
4578 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4579 if(dest_i==pathSet.end())
4581 path = 0;
4582 cost = 0;
4583 return;
4586 cost = dest_i->second.price;
4587 path = dest_i->second.ID;
4590 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4592 uint16 mount_entry = 0;
4593 uint16 mount_id = 0;
4595 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4596 if(node)
4598 if (team == ALLIANCE)
4600 mount_entry = node->MountCreatureID[1];
4601 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4602 if(ci)
4603 mount_id = ci->DisplayID_A;
4605 if (team == HORDE)
4607 mount_entry = node->MountCreatureID[0];
4608 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4609 if(ci)
4610 mount_id = ci->DisplayID_H;
4614 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4615 if(!minfo)
4617 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. ",
4618 mount_entry,id,team,mount_id);
4620 return false;
4622 if(minfo->modelid_other_gender!=0)
4623 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4625 return mount_id;
4628 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4630 if(path >= sTaxiPathNodesByPath.size())
4631 return;
4633 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4635 pathnodes.Resize(nodeList.size());
4636 mapIds.resize(nodeList.size());
4638 for(size_t i = 0; i < nodeList.size(); ++i)
4640 pathnodes[ i ].x = nodeList[i].x;
4641 pathnodes[ i ].y = nodeList[i].y;
4642 pathnodes[ i ].z = nodeList[i].z;
4644 mapIds[i] = nodeList[i].mapid;
4648 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4650 if(path >= sTaxiPathNodesByPath.size())
4651 return;
4653 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4655 pathnodes.Resize(nodeList.size());
4657 for(size_t i = 0; i < nodeList.size(); ++i)
4659 pathnodes[ i ].mapid = nodeList[i].mapid;
4660 pathnodes[ i ].x = nodeList[i].x;
4661 pathnodes[ i ].y = nodeList[i].y;
4662 pathnodes[ i ].z = nodeList[i].z;
4663 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4664 pathnodes[ i ].delay = nodeList[i].delay;
4668 void ObjectMgr::LoadGraveyardZones()
4670 mGraveYardMap.clear(); // need for reload case
4672 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4674 uint32 count = 0;
4676 if( !result )
4678 barGoLink bar( 1 );
4679 bar.step();
4681 sLog.outString();
4682 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4683 return;
4686 barGoLink bar( result->GetRowCount() );
4690 ++count;
4691 bar.step();
4693 Field *fields = result->Fetch();
4695 uint32 safeLocId = fields[0].GetUInt32();
4696 uint32 zoneId = fields[1].GetUInt32();
4697 uint32 team = fields[2].GetUInt32();
4699 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4700 if(!entry)
4702 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4703 continue;
4706 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4707 if(!areaEntry)
4709 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4710 continue;
4713 if(areaEntry->zone != 0)
4715 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4716 continue;
4719 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4721 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4722 continue;
4725 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4726 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4727 } while( result->NextRow() );
4729 delete result;
4731 sLog.outString();
4732 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4735 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4737 // search for zone associated closest graveyard
4738 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4740 // Simulate std. algorithm:
4741 // found some graveyard associated to (ghost_zone,ghost_map)
4743 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4744 // then check faction
4745 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4746 // then check faction
4747 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4748 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4749 if(graveLow==graveUp)
4751 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4752 return NULL;
4755 // at corpse map
4756 bool foundNear = false;
4757 float distNear;
4758 WorldSafeLocsEntry const* entryNear = NULL;
4760 // at entrance map for corpse map
4761 bool foundEntr = false;
4762 float distEntr;
4763 WorldSafeLocsEntry const* entryEntr = NULL;
4765 // some where other
4766 WorldSafeLocsEntry const* entryFar = NULL;
4768 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4770 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4772 GraveYardData const& data = itr->second;
4774 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4775 if(!entry)
4777 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4778 continue;
4781 // skip enemy faction graveyard
4782 // team == 0 case can be at call from .neargrave
4783 if(data.team != 0 && team != 0 && data.team != team)
4784 continue;
4786 // find now nearest graveyard at other map
4787 if(MapId != entry->map_id)
4789 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4790 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4791 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4793 // not have any corrdinates for check distance anyway
4794 entryFar = entry;
4795 continue;
4798 // at entrance map calculate distance (2D);
4799 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4800 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4801 if(foundEntr)
4803 if(dist2 < distEntr)
4805 distEntr = dist2;
4806 entryEntr = entry;
4809 else
4811 foundEntr = true;
4812 distEntr = dist2;
4813 entryEntr = entry;
4816 // find now nearest graveyard at same map
4817 else
4819 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4820 if(foundNear)
4822 if(dist2 < distNear)
4824 distNear = dist2;
4825 entryNear = entry;
4828 else
4830 foundNear = true;
4831 distNear = dist2;
4832 entryNear = entry;
4837 if(entryNear)
4838 return entryNear;
4840 if(entryEntr)
4841 return entryEntr;
4843 return entryFar;
4846 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4848 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4849 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4851 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4853 if(itr->second.safeLocId==id)
4854 return &itr->second;
4857 return NULL;
4860 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4862 if(FindGraveYardData(id,zoneId))
4863 return false;
4865 // add link to loaded data
4866 GraveYardData data;
4867 data.safeLocId = id;
4868 data.team = team;
4870 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4872 // add link to DB
4873 if(inDB)
4875 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4876 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4879 return true;
4882 void ObjectMgr::LoadAreaTriggerTeleports()
4884 mAreaTriggers.clear(); // need for reload case
4886 uint32 count = 0;
4888 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4889 QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
4890 if( !result )
4893 barGoLink bar( 1 );
4895 bar.step();
4897 sLog.outString();
4898 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4899 return;
4902 barGoLink bar( result->GetRowCount() );
4906 Field *fields = result->Fetch();
4908 bar.step();
4910 ++count;
4912 uint32 Trigger_ID = fields[0].GetUInt32();
4914 AreaTrigger at;
4916 at.requiredLevel = fields[1].GetUInt8();
4917 at.requiredItem = fields[2].GetUInt32();
4918 at.requiredItem2 = fields[3].GetUInt32();
4919 at.heroicKey = fields[4].GetUInt32();
4920 at.heroicKey2 = fields[5].GetUInt32();
4921 at.requiredQuest = fields[6].GetUInt32();
4922 at.requiredFailedText = fields[7].GetCppString();
4923 at.target_mapId = fields[8].GetUInt32();
4924 at.target_X = fields[9].GetFloat();
4925 at.target_Y = fields[10].GetFloat();
4926 at.target_Z = fields[11].GetFloat();
4927 at.target_Orientation = fields[12].GetFloat();
4929 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4930 if(!atEntry)
4932 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4933 continue;
4936 if(at.requiredItem)
4938 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4939 if(!pProto)
4941 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4942 at.requiredItem = 0;
4945 if(at.requiredItem2)
4947 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4948 if(!pProto)
4950 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4951 at.requiredItem2 = 0;
4955 if(at.heroicKey)
4957 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4958 if(!pProto)
4960 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4961 at.heroicKey = 0;
4965 if(at.heroicKey2)
4967 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4968 if(!pProto)
4970 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4971 at.heroicKey2 = 0;
4975 if(at.requiredQuest)
4977 if(!mQuestTemplates[at.requiredQuest])
4979 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4980 at.requiredQuest = 0;
4984 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4985 if(!mapEntry)
4987 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4988 continue;
4991 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4993 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4994 continue;
4997 mAreaTriggers[Trigger_ID] = at;
4999 } while( result->NextRow() );
5001 delete result;
5003 sLog.outString();
5004 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5008 * Searches for the areatrigger which teleports players out of the given map
5010 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5012 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5013 if(!mapEntry) return NULL;
5014 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5016 if(itr->second.target_mapId == mapEntry->entrance_map)
5018 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5019 if(atEntry && atEntry->mapid == Map)
5020 return &itr->second;
5023 return NULL;
5027 * Searches for the areatrigger which teleports players to the given map
5029 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5031 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5033 if(itr->second.target_mapId == Map)
5035 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5036 if(atEntry)
5037 return &itr->second;
5040 return NULL;
5043 void ObjectMgr::SetHighestGuids()
5045 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5046 if( result )
5048 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5049 delete result;
5052 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5053 if( result )
5055 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5056 delete result;
5059 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5060 if( result )
5062 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5063 delete result;
5066 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5067 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5068 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5069 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5070 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5072 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5073 if( result )
5075 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5076 delete result;
5079 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5080 if( result )
5082 m_auctionid = (*result)[0].GetUInt32()+1;
5083 delete result;
5086 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5087 if( result )
5089 m_mailid = (*result)[0].GetUInt32()+1;
5090 delete result;
5093 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5094 if( result )
5096 m_ItemTextId = (*result)[0].GetUInt32()+1;
5097 delete result;
5100 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5101 if( result )
5103 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5104 delete result;
5107 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5108 if (result)
5110 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5111 delete result;
5114 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5115 if (result)
5117 m_guildId = (*result)[0].GetUInt32()+1;
5118 delete result;
5122 uint32 ObjectMgr::GenerateArenaTeamId()
5124 if(m_arenaTeamId>=0xFFFFFFFE)
5126 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5127 World::StopNow(ERROR_EXIT_CODE);
5129 return m_arenaTeamId++;
5132 uint32 ObjectMgr::GenerateAuctionID()
5134 if(m_auctionid>=0xFFFFFFFE)
5136 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5137 World::StopNow(ERROR_EXIT_CODE);
5139 return m_auctionid++;
5142 uint32 ObjectMgr::GenerateGuildId()
5144 if(m_guildId>=0xFFFFFFFE)
5146 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5147 World::StopNow(ERROR_EXIT_CODE);
5149 return m_guildId++;
5152 uint32 ObjectMgr::GenerateMailID()
5154 if(m_mailid>=0xFFFFFFFE)
5156 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5157 World::StopNow(ERROR_EXIT_CODE);
5159 return m_mailid++;
5162 uint32 ObjectMgr::GenerateItemTextID()
5164 if(m_ItemTextId>=0xFFFFFFFE)
5166 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5167 World::StopNow(ERROR_EXIT_CODE);
5169 return m_ItemTextId++;
5172 uint32 ObjectMgr::CreateItemText(std::string text)
5174 uint32 newItemTextId = GenerateItemTextID();
5175 //insert new itempage to container
5176 mItemTexts[ newItemTextId ] = text;
5177 //save new itempage
5178 CharacterDatabase.escape_string(text);
5179 //any Delete query needed, itemTextId is maximum of all ids
5180 std::ostringstream query;
5181 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5182 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5183 return newItemTextId;
5186 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5188 switch(guidhigh)
5190 case HIGHGUID_ITEM:
5191 if(m_hiItemGuid>=0xFFFFFFFE)
5193 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5194 World::StopNow(ERROR_EXIT_CODE);
5196 return m_hiItemGuid++;
5197 case HIGHGUID_UNIT:
5198 if(m_hiCreatureGuid>=0x00FFFFFE)
5200 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5201 World::StopNow(ERROR_EXIT_CODE);
5203 return m_hiCreatureGuid++;
5204 case HIGHGUID_PET:
5205 if(m_hiPetGuid>=0x00FFFFFE)
5207 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5208 World::StopNow(ERROR_EXIT_CODE);
5210 return m_hiPetGuid++;
5211 case HIGHGUID_VEHICLE:
5212 if(m_hiVehicleGuid>=0x00FFFFFF)
5214 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5215 World::StopNow(ERROR_EXIT_CODE);
5217 return m_hiVehicleGuid++;
5218 case HIGHGUID_PLAYER:
5219 if(m_hiCharGuid>=0xFFFFFFFE)
5221 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5222 World::StopNow(ERROR_EXIT_CODE);
5224 return m_hiCharGuid++;
5225 case HIGHGUID_GAMEOBJECT:
5226 if(m_hiGoGuid>=0x00FFFFFE)
5228 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5229 World::StopNow(ERROR_EXIT_CODE);
5231 return m_hiGoGuid++;
5232 case HIGHGUID_CORPSE:
5233 if(m_hiCorpseGuid>=0xFFFFFFFE)
5235 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5236 World::StopNow(ERROR_EXIT_CODE);
5238 return m_hiCorpseGuid++;
5239 case HIGHGUID_DYNAMICOBJECT:
5240 if(m_hiDoGuid>=0xFFFFFFFE)
5242 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5243 World::StopNow(ERROR_EXIT_CODE);
5245 return m_hiDoGuid++;
5246 default:
5247 ASSERT(0);
5250 ASSERT(0);
5251 return 0;
5254 void ObjectMgr::LoadGameObjectLocales()
5256 mGameObjectLocaleMap.clear(); // need for reload case
5258 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5259 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5260 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5261 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5263 if(!result)
5265 barGoLink bar(1);
5267 bar.step();
5269 sLog.outString("");
5270 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5271 return;
5274 barGoLink bar(result->GetRowCount());
5278 Field *fields = result->Fetch();
5279 bar.step();
5281 uint32 entry = fields[0].GetUInt32();
5283 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5285 for(int i = 1; i < MAX_LOCALE; ++i)
5287 std::string str = fields[i].GetCppString();
5288 if(!str.empty())
5290 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5291 if(idx >= 0)
5293 if(data.Name.size() <= idx)
5294 data.Name.resize(idx+1);
5296 data.Name[idx] = str;
5301 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5303 std::string str = fields[i].GetCppString();
5304 if(!str.empty())
5306 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5307 if(idx >= 0)
5309 if(data.CastBarCaption.size() <= idx)
5310 data.CastBarCaption.resize(idx+1);
5312 data.CastBarCaption[idx] = str;
5317 } while (result->NextRow());
5319 delete result;
5321 sLog.outString();
5322 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5325 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5327 template<class D>
5328 void convert_from_str(uint32 field_pos, char *src, D &dst)
5330 dst = D(objmgr.GetScriptId(src));
5334 void ObjectMgr::LoadGameobjectInfo()
5336 SQLGameObjectLoader loader;
5337 loader.Load(sGOStorage);
5339 // some checks
5340 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5342 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5343 if(!goInfo)
5344 continue;
5346 switch(goInfo->type)
5348 case GAMEOBJECT_TYPE_DOOR: //0
5350 if(goInfo->door.lockId)
5352 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5353 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5354 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5356 break;
5358 case GAMEOBJECT_TYPE_BUTTON: //1
5360 if(goInfo->button.lockId)
5362 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5363 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5364 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5366 break;
5368 case GAMEOBJECT_TYPE_CHEST: //3
5370 if(goInfo->chest.lockId)
5372 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5373 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5374 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5376 if(goInfo->chest.linkedTrapId) // linked trap
5378 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5380 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5381 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5382 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5384 /* disable check for while
5385 else
5386 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5387 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5390 break;
5392 case GAMEOBJECT_TYPE_TRAP: //6
5394 /* disable check for while
5395 if(goInfo->trap.spellId) // spell
5397 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5398 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5399 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5402 break;
5404 case GAMEOBJECT_TYPE_CHAIR: //7
5405 if(goInfo->chair.height > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5407 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5408 id,goInfo->type,goInfo->chair.height,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5410 // prevent client and server unexpected work
5411 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5413 break;
5414 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5416 if(goInfo->spellFocus.focusId)
5418 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5419 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5420 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5423 if(goInfo->spellFocus.linkedTrapId) // linked trap
5425 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5427 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5428 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5429 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5431 /* disable check for while
5432 else
5433 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5434 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5437 break;
5439 case GAMEOBJECT_TYPE_GOOBER: //10
5441 if(goInfo->goober.pageId) // pageId
5443 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5444 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5445 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5447 /* disable check for while
5448 if(goInfo->goober.spellId) // spell
5450 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5451 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5452 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5455 if(goInfo->goober.linkedTrapId) // linked trap
5457 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5459 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5460 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5461 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5463 /* disable check for while
5464 else
5465 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5466 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5469 break;
5471 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5473 if(goInfo->moTransport.taxiPathId)
5475 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5476 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5477 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5479 break;
5481 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5483 /* disabled
5484 if(goInfo->summoningRitual.spellId)
5486 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5487 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5488 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5491 break;
5493 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5495 if(goInfo->spellcaster.spellId) // spell
5497 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5498 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5499 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5501 break;
5503 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5504 if(goInfo->barberChair.chairheight > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5506 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5507 id,goInfo->type,goInfo->barberChair.chairheight,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5509 // prevent client and server unexpected work
5510 const_cast<GameObjectInfo*>(goInfo)->barberChair.chairheight = 0;
5512 break;
5516 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5517 sLog.outString();
5520 void ObjectMgr::LoadExplorationBaseXP()
5522 uint32 count = 0;
5523 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5525 if( !result )
5527 barGoLink bar( 1 );
5529 bar.step();
5531 sLog.outString();
5532 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5533 return;
5536 barGoLink bar( result->GetRowCount() );
5540 bar.step();
5542 Field *fields = result->Fetch();
5543 uint32 level = fields[0].GetUInt32();
5544 uint32 basexp = fields[1].GetUInt32();
5545 mBaseXPTable[level] = basexp;
5546 ++count;
5548 while (result->NextRow());
5550 delete result;
5552 sLog.outString();
5553 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5556 uint32 ObjectMgr::GetBaseXP(uint32 level)
5558 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5561 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5563 if (level < mPlayerXPperLevel.size())
5564 return mPlayerXPperLevel[level];
5565 return 0;
5568 void ObjectMgr::LoadPetNames()
5570 uint32 count = 0;
5571 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5573 if( !result )
5575 barGoLink bar( 1 );
5577 bar.step();
5579 sLog.outString();
5580 sLog.outString( ">> Loaded %u pet name parts", count );
5581 return;
5584 barGoLink bar( result->GetRowCount() );
5588 bar.step();
5590 Field *fields = result->Fetch();
5591 std::string word = fields[0].GetString();
5592 uint32 entry = fields[1].GetUInt32();
5593 bool half = fields[2].GetBool();
5594 if(half)
5595 PetHalfName1[entry].push_back(word);
5596 else
5597 PetHalfName0[entry].push_back(word);
5598 ++count;
5600 while (result->NextRow());
5601 delete result;
5603 sLog.outString();
5604 sLog.outString( ">> Loaded %u pet name parts", count );
5607 void ObjectMgr::LoadPetNumber()
5609 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5610 if(result)
5612 Field *fields = result->Fetch();
5613 m_hiPetNumber = fields[0].GetUInt32()+1;
5614 delete result;
5617 barGoLink bar( 1 );
5618 bar.step();
5620 sLog.outString();
5621 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5624 std::string ObjectMgr::GeneratePetName(uint32 entry)
5626 std::vector<std::string> & list0 = PetHalfName0[entry];
5627 std::vector<std::string> & list1 = PetHalfName1[entry];
5629 if(list0.empty() || list1.empty())
5631 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5632 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5633 if(!petname)
5634 petname = cinfo->Name;
5635 return std::string(petname);
5638 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5641 uint32 ObjectMgr::GeneratePetNumber()
5643 return ++m_hiPetNumber;
5646 void ObjectMgr::LoadCorpses()
5648 uint32 count = 0;
5649 // 0 1 2 3 4 5 6 7 8 10
5650 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");
5652 if( !result )
5654 barGoLink bar( 1 );
5656 bar.step();
5658 sLog.outString();
5659 sLog.outString( ">> Loaded %u corpses", count );
5660 return;
5663 barGoLink bar( result->GetRowCount() );
5667 bar.step();
5669 Field *fields = result->Fetch();
5671 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5673 Corpse *corpse = new Corpse;
5674 if(!corpse->LoadFromDB(guid,fields))
5676 delete corpse;
5677 continue;
5680 ObjectAccessor::Instance().AddCorpse(corpse);
5682 ++count;
5684 while (result->NextRow());
5685 delete result;
5687 sLog.outString();
5688 sLog.outString( ">> Loaded %u corpses", count );
5691 void ObjectMgr::LoadReputationOnKill()
5693 uint32 count = 0;
5695 // 0 1 2
5696 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5697 // 3 4 5 6 7 8 9
5698 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5699 "FROM creature_onkill_reputation");
5701 if(!result)
5703 barGoLink bar(1);
5705 bar.step();
5707 sLog.outString();
5708 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5709 return;
5712 barGoLink bar(result->GetRowCount());
5716 Field *fields = result->Fetch();
5717 bar.step();
5719 uint32 creature_id = fields[0].GetUInt32();
5721 ReputationOnKillEntry repOnKill;
5722 repOnKill.repfaction1 = fields[1].GetUInt32();
5723 repOnKill.repfaction2 = fields[2].GetUInt32();
5724 repOnKill.is_teamaward1 = fields[3].GetBool();
5725 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5726 repOnKill.repvalue1 = fields[5].GetInt32();
5727 repOnKill.is_teamaward2 = fields[6].GetBool();
5728 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5729 repOnKill.repvalue2 = fields[8].GetInt32();
5730 repOnKill.team_dependent = fields[9].GetUInt8();
5732 if(!GetCreatureTemplate(creature_id))
5734 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5735 continue;
5738 if(repOnKill.repfaction1)
5740 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5741 if(!factionEntry1)
5743 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5744 continue;
5748 if(repOnKill.repfaction2)
5750 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5751 if(!factionEntry2)
5753 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5754 continue;
5758 mRepOnKill[creature_id] = repOnKill;
5760 ++count;
5761 } while (result->NextRow());
5763 delete result;
5765 sLog.outString();
5766 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5769 void ObjectMgr::LoadPointsOfInterest()
5771 uint32 count = 0;
5773 // 0 1 2 3 4 5
5774 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5776 if(!result)
5778 barGoLink bar(1);
5780 bar.step();
5782 sLog.outString();
5783 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5784 return;
5787 barGoLink bar(result->GetRowCount());
5791 Field *fields = result->Fetch();
5792 bar.step();
5794 uint32 point_id = fields[0].GetUInt32();
5796 PointOfInterest POI;
5797 POI.x = fields[1].GetFloat();
5798 POI.y = fields[2].GetFloat();
5799 POI.icon = fields[3].GetUInt32();
5800 POI.flags = fields[4].GetUInt32();
5801 POI.data = fields[5].GetUInt32();
5802 POI.icon_name = fields[6].GetCppString();
5804 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5806 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5807 continue;
5810 mPointsOfInterest[point_id] = POI;
5812 ++count;
5813 } while (result->NextRow());
5815 delete result;
5817 sLog.outString();
5818 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5821 void ObjectMgr::LoadWeatherZoneChances()
5823 uint32 count = 0;
5825 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5826 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");
5828 if(!result)
5830 barGoLink bar(1);
5832 bar.step();
5834 sLog.outString();
5835 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5836 return;
5839 barGoLink bar(result->GetRowCount());
5843 Field *fields = result->Fetch();
5844 bar.step();
5846 uint32 zone_id = fields[0].GetUInt32();
5848 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5850 for(int season = 0; season < WEATHER_SEASONS; ++season)
5852 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5853 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5854 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5856 if(wzc.data[season].rainChance > 100)
5858 wzc.data[season].rainChance = 25;
5859 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5862 if(wzc.data[season].snowChance > 100)
5864 wzc.data[season].snowChance = 25;
5865 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5868 if(wzc.data[season].stormChance > 100)
5870 wzc.data[season].stormChance = 25;
5871 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5875 ++count;
5876 } while (result->NextRow());
5878 delete result;
5880 sLog.outString();
5881 sLog.outString(">> Loaded %u weather definitions", count);
5884 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5886 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5887 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5888 if(t)
5889 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5892 void ObjectMgr::DeleteCreatureData(uint32 guid)
5894 // remove mapid*cellid -> guid_set map
5895 CreatureData const* data = GetCreatureData(guid);
5896 if(data)
5897 RemoveCreatureFromGrid(guid, data);
5899 mCreatureDataMap.erase(guid);
5902 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5904 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5905 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5906 if(t)
5907 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5910 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5912 RespawnTimes::iterator next;
5914 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5916 next = itr;
5917 ++next;
5919 if(GUID_HIPART(itr->first)==instance)
5920 mGORespawnTimes.erase(itr);
5923 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5925 next = itr;
5926 ++next;
5928 if(GUID_HIPART(itr->first)==instance)
5929 mCreatureRespawnTimes.erase(itr);
5932 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5933 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5936 void ObjectMgr::DeleteGOData(uint32 guid)
5938 // remove mapid*cellid -> guid_set map
5939 GameObjectData const* data = GetGOData(guid);
5940 if(data)
5941 RemoveGameobjectFromGrid(guid, data);
5943 mGameObjectDataMap.erase(guid);
5946 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5948 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5949 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5950 cell_guids.corpses[player_guid] = instance;
5953 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5955 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5956 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5957 cell_guids.corpses.erase(player_guid);
5960 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5962 map.clear(); // need for reload case
5964 uint32 count = 0;
5966 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5968 if(!result)
5970 barGoLink bar(1);
5972 bar.step();
5974 sLog.outString();
5975 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5976 return;
5979 barGoLink bar(result->GetRowCount());
5983 Field *fields = result->Fetch();
5984 bar.step();
5986 uint32 id = fields[0].GetUInt32();
5987 uint32 quest = fields[1].GetUInt32();
5989 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5991 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5992 continue;
5995 map.insert(QuestRelations::value_type(id,quest));
5997 ++count;
5998 } while (result->NextRow());
6000 delete result;
6002 sLog.outString();
6003 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6006 void ObjectMgr::LoadGameobjectQuestRelations()
6008 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6010 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6012 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6013 if(!goInfo)
6014 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6015 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6016 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6020 void ObjectMgr::LoadGameobjectInvolvedRelations()
6022 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6024 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6026 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6027 if(!goInfo)
6028 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6029 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6030 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6034 void ObjectMgr::LoadCreatureQuestRelations()
6036 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6038 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6040 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6041 if(!cInfo)
6042 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6043 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6044 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);
6048 void ObjectMgr::LoadCreatureInvolvedRelations()
6050 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6052 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6054 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6055 if(!cInfo)
6056 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6057 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6058 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);
6062 void ObjectMgr::LoadReservedPlayersNames()
6064 m_ReservedNames.clear(); // need for reload case
6066 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6068 uint32 count = 0;
6070 if( !result )
6072 barGoLink bar( 1 );
6073 bar.step();
6075 sLog.outString();
6076 sLog.outString( ">> Loaded %u reserved player names", count );
6077 return;
6080 barGoLink bar( result->GetRowCount() );
6082 Field* fields;
6085 bar.step();
6086 fields = result->Fetch();
6087 std::string name= fields[0].GetCppString();
6089 std::wstring wstr;
6090 if(!Utf8toWStr (name,wstr))
6092 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6093 continue;
6096 wstrToLower(wstr);
6098 m_ReservedNames.insert(wstr);
6099 ++count;
6100 } while ( result->NextRow() );
6102 delete result;
6104 sLog.outString();
6105 sLog.outString( ">> Loaded %u reserved player names", count );
6108 bool ObjectMgr::IsReservedName( const std::string& name ) const
6110 std::wstring wstr;
6111 if(!Utf8toWStr (name,wstr))
6112 return false;
6114 wstrToLower(wstr);
6116 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6119 enum LanguageType
6121 LT_BASIC_LATIN = 0x0000,
6122 LT_EXTENDEN_LATIN = 0x0001,
6123 LT_CYRILLIC = 0x0002,
6124 LT_EAST_ASIA = 0x0004,
6125 LT_ANY = 0xFFFF
6128 static LanguageType GetRealmLanguageType(bool create)
6130 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6132 case REALM_ZONE_UNKNOWN: // any language
6133 case REALM_ZONE_DEVELOPMENT:
6134 case REALM_ZONE_TEST_SERVER:
6135 case REALM_ZONE_QA_SERVER:
6136 return LT_ANY;
6137 case REALM_ZONE_UNITED_STATES: // extended-Latin
6138 case REALM_ZONE_OCEANIC:
6139 case REALM_ZONE_LATIN_AMERICA:
6140 case REALM_ZONE_ENGLISH:
6141 case REALM_ZONE_GERMAN:
6142 case REALM_ZONE_FRENCH:
6143 case REALM_ZONE_SPANISH:
6144 return LT_EXTENDEN_LATIN;
6145 case REALM_ZONE_KOREA: // East-Asian
6146 case REALM_ZONE_TAIWAN:
6147 case REALM_ZONE_CHINA:
6148 return LT_EAST_ASIA;
6149 case REALM_ZONE_RUSSIAN: // Cyrillic
6150 return LT_CYRILLIC;
6151 default:
6152 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6156 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6158 if(strictMask==0) // any language, ignore realm
6160 if(isExtendedLatinString(wstr,numericOrSpace))
6161 return true;
6162 if(isCyrillicString(wstr,numericOrSpace))
6163 return true;
6164 if(isEastAsianString(wstr,numericOrSpace))
6165 return true;
6166 return false;
6169 if(strictMask & 0x2) // realm zone specific
6171 LanguageType lt = GetRealmLanguageType(create);
6172 if(lt & LT_EXTENDEN_LATIN)
6173 if(isExtendedLatinString(wstr,numericOrSpace))
6174 return true;
6175 if(lt & LT_CYRILLIC)
6176 if(isCyrillicString(wstr,numericOrSpace))
6177 return true;
6178 if(lt & LT_EAST_ASIA)
6179 if(isEastAsianString(wstr,numericOrSpace))
6180 return true;
6183 if(strictMask & 0x1) // basic Latin
6185 if(isBasicLatinString(wstr,numericOrSpace))
6186 return true;
6189 return false;
6192 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6194 std::wstring wname;
6195 if(!Utf8toWStr(name,wname))
6196 return false;
6198 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6199 return false;
6201 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6203 return isValidString(wname,strictMask,false,create);
6206 bool ObjectMgr::IsValidCharterName( const std::string& name )
6208 std::wstring wname;
6209 if(!Utf8toWStr(name,wname))
6210 return false;
6212 if(wname.size() < 1)
6213 return false;
6215 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6217 return isValidString(wname,strictMask,true);
6220 bool ObjectMgr::IsValidPetName( const std::string& name )
6222 std::wstring wname;
6223 if(!Utf8toWStr(name,wname))
6224 return false;
6226 if(wname.size() < 1)
6227 return false;
6229 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6231 return isValidString(wname,strictMask,false);
6234 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6236 if(loc==LOCALE_enUS)
6237 return -1;
6239 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6240 if(m_LocalForIndex[i]==loc)
6241 return i;
6243 return -1;
6246 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6248 if (i<0 || i>=m_LocalForIndex.size())
6249 return LOCALE_enUS;
6251 return m_LocalForIndex[i];
6254 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6256 if(loc==LOCALE_enUS)
6257 return -1;
6259 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6260 if(m_LocalForIndex[i]==loc)
6261 return i;
6263 m_LocalForIndex.push_back(loc);
6264 return m_LocalForIndex.size()-1;
6267 void ObjectMgr::LoadGameObjectForQuests()
6269 mGameObjectForQuestSet.clear(); // need for reload case
6271 if( !sGOStorage.MaxEntry )
6273 barGoLink bar( 1 );
6274 bar.step();
6275 sLog.outString();
6276 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6277 return;
6280 barGoLink bar( sGOStorage.MaxEntry - 1 );
6281 uint32 count = 0;
6283 // collect GO entries for GO that must activated
6284 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6286 bar.step();
6287 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6288 if(!goInfo)
6289 continue;
6291 switch(goInfo->type)
6293 // scan GO chest with loot including quest items
6294 case GAMEOBJECT_TYPE_CHEST:
6296 uint32 loot_id = GameObject::GetLootId(goInfo);
6298 // find quest loot for GO
6299 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6301 mGameObjectForQuestSet.insert(go_entry);
6302 ++count;
6304 break;
6306 case GAMEOBJECT_TYPE_GOOBER:
6308 if(goInfo->goober.questId) //quests objects
6310 mGameObjectForQuestSet.insert(go_entry);
6311 count++;
6313 break;
6315 default:
6316 break;
6320 sLog.outString();
6321 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6324 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6326 // cleanup affected map part for reloading case
6327 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6329 if(itr->first >= min_value && itr->first <= max_value)
6331 MangosStringLocaleMap::iterator itr2 = itr;
6332 ++itr;
6333 mMangosStringLocaleMap.erase(itr2);
6335 else
6336 ++itr;
6339 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);
6341 if(!result)
6343 barGoLink bar(1);
6345 bar.step();
6347 sLog.outString("");
6348 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6349 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6350 else
6351 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6352 return false;
6355 uint32 count = 0;
6357 barGoLink bar(result->GetRowCount());
6361 Field *fields = result->Fetch();
6362 bar.step();
6364 int32 entry = fields[0].GetInt32();
6366 if(entry==0)
6368 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6369 continue;
6371 else if(entry < min_value || entry > max_value)
6373 int32 start = min_value > 0 ? min_value : max_value;
6374 int32 end = min_value > 0 ? max_value : min_value;
6375 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6376 continue;
6379 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6381 if(data.Content.size() > 0)
6383 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6384 continue;
6387 data.Content.resize(1);
6388 ++count;
6390 // 0 -> default, idx in to idx+1
6391 data.Content[0] = fields[1].GetCppString();
6393 for(int i = 1; i < MAX_LOCALE; ++i)
6395 std::string str = fields[i+1].GetCppString();
6396 if(!str.empty())
6398 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6399 if(idx >= 0)
6401 // 0 -> default, idx in to idx+1
6402 if(data.Content.size() <= idx+1)
6403 data.Content.resize(idx+2);
6405 data.Content[idx+1] = str;
6409 } while (result->NextRow());
6411 delete result;
6413 sLog.outString();
6414 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6415 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6416 else
6417 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6419 return true;
6422 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6424 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6425 // Content[0] always exist if exist MangosStringLocale
6426 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6428 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6429 return msl->Content[locale_idx+1].c_str();
6430 else
6431 return msl->Content[0].c_str();
6434 if(entry > 0)
6435 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6436 else
6437 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6438 return "<error>";
6441 void ObjectMgr::LoadFishingBaseSkillLevel()
6443 mFishingBaseForArea.clear(); // for reload case
6445 uint32 count = 0;
6446 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6448 if( !result )
6450 barGoLink bar( 1 );
6452 bar.step();
6454 sLog.outString();
6455 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6456 return;
6459 barGoLink bar( result->GetRowCount() );
6463 bar.step();
6465 Field *fields = result->Fetch();
6466 uint32 entry = fields[0].GetUInt32();
6467 int32 skill = fields[1].GetInt32();
6469 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6470 if(!fArea)
6472 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6473 continue;
6476 mFishingBaseForArea[entry] = skill;
6477 ++count;
6479 while (result->NextRow());
6481 delete result;
6483 sLog.outString();
6484 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6487 // Searches for the same condition already in Conditions store
6488 // Returns Id if found, else adds it to Conditions and returns Id
6489 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6491 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6492 for (uint16 i=0; i < mConditions.size(); ++i)
6494 if (lc == mConditions[i])
6495 return i;
6498 mConditions.push_back(lc);
6500 if(mConditions.size() > 0xFFFF)
6502 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6503 return 0;
6506 return mConditions.size() - 1;
6509 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6511 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6513 std::wstring wname;
6514 if(!Utf8toWStr(names.name[i],wname))
6515 return false;
6517 if(mainpart!=GetMainPartOfName(wname,i+1))
6518 return false;
6520 return true;
6523 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6525 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6526 if(i!= mAreaTriggerScripts.end())
6527 return i->second;
6528 return 0;
6531 // Checks if player meets the condition
6532 bool PlayerCondition::Meets(Player const * player) const
6534 if( !player )
6535 return false; // player not present, return false
6537 switch (condition)
6539 case CONDITION_NONE:
6540 return true; // empty condition, always met
6541 case CONDITION_AURA:
6542 return player->HasAura(value1, value2);
6543 case CONDITION_ITEM:
6544 return player->HasItemCount(value1, value2);
6545 case CONDITION_ITEM_EQUIPPED:
6546 return player->HasItemOrGemWithIdEquipped(value1,1);
6547 case CONDITION_ZONEID:
6548 return player->GetZoneId() == value1;
6549 case CONDITION_REPUTATION_RANK:
6551 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6552 return faction && player->GetReputationRank(faction) >= value2;
6554 case CONDITION_TEAM:
6555 return player->GetTeam() == value1;
6556 case CONDITION_SKILL:
6557 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6558 case CONDITION_QUESTREWARDED:
6559 return player->GetQuestRewardStatus(value1);
6560 case CONDITION_QUESTTAKEN:
6562 QuestStatus status = player->GetQuestStatus(value1);
6563 return (status == QUEST_STATUS_INCOMPLETE);
6565 case CONDITION_AD_COMMISSION_AURA:
6567 Unit::AuraMap const& auras = player->GetAuras();
6568 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6569 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6570 return true;
6571 return false;
6573 case CONDITION_NO_AURA:
6574 return !player->HasAura(value1, value2);
6575 case CONDITION_ACTIVE_EVENT:
6576 return gameeventmgr.IsActiveEvent(value1);
6577 default:
6578 return false;
6582 // Verification of condition values validity
6583 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6585 if( condition >= MAX_CONDITION) // Wrong condition type
6587 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6588 return false;
6591 switch (condition)
6593 case CONDITION_AURA:
6595 if(!sSpellStore.LookupEntry(value1))
6597 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6598 return false;
6600 if(value2 > 2)
6602 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6603 return false;
6605 break;
6607 case CONDITION_ITEM:
6609 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6610 if(!proto)
6612 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6613 return false;
6615 break;
6617 case CONDITION_ITEM_EQUIPPED:
6619 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6620 if(!proto)
6622 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6623 return false;
6625 break;
6627 case CONDITION_ZONEID:
6629 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6630 if(!areaEntry)
6632 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6633 return false;
6635 if(areaEntry->zone != 0)
6637 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6638 return false;
6640 break;
6642 case CONDITION_REPUTATION_RANK:
6644 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6645 if(!factionEntry)
6647 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6648 return false;
6650 break;
6652 case CONDITION_TEAM:
6654 if (value1 != ALLIANCE && value1 != HORDE)
6656 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6657 return false;
6659 break;
6661 case CONDITION_SKILL:
6663 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6664 if (!pSkill)
6666 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6667 return false;
6669 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6671 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6672 return false;
6674 break;
6676 case CONDITION_QUESTREWARDED:
6677 case CONDITION_QUESTTAKEN:
6679 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6680 if (!Quest)
6682 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6683 return false;
6685 if(value2)
6686 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6687 break;
6689 case CONDITION_AD_COMMISSION_AURA:
6691 if(value1)
6692 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6693 if(value2)
6694 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6695 break;
6697 case CONDITION_NO_AURA:
6699 if(!sSpellStore.LookupEntry(value1))
6701 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6702 return false;
6704 if(value2 > 2)
6706 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6707 return false;
6709 break;
6711 case CONDITION_ACTIVE_EVENT:
6713 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6714 if(value1 >=events.size() || !events[value1].isValid())
6716 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6717 return false;
6719 break;
6722 return true;
6725 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6727 switch(pSkill->categoryId)
6729 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6730 case SKILL_CATEGORY_WEAPON:
6731 if(pSkill->id!=SKILL_FIST_WEAPONS)
6732 return SKILL_RANGE_LEVEL;
6733 else
6734 return SKILL_RANGE_MONO;
6735 case SKILL_CATEGORY_ARMOR:
6736 case SKILL_CATEGORY_CLASS:
6737 if(pSkill->id != SKILL_LOCKPICKING)
6738 return SKILL_RANGE_MONO;
6739 else
6740 return SKILL_RANGE_LEVEL;
6741 case SKILL_CATEGORY_SECONDARY:
6742 case SKILL_CATEGORY_PROFESSION:
6743 // not set skills for professions and racial abilities
6744 if(IsProfessionSkill(pSkill->id))
6745 return SKILL_RANGE_RANK;
6746 else if(racial)
6747 return SKILL_RANGE_NONE;
6748 else
6749 return SKILL_RANGE_MONO;
6750 default:
6751 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6752 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6753 return SKILL_RANGE_NONE;
6757 void ObjectMgr::LoadGameTele()
6759 m_GameTeleMap.clear(); // for reload case
6761 uint32 count = 0;
6762 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6764 if( !result )
6766 barGoLink bar( 1 );
6768 bar.step();
6770 sLog.outString();
6771 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6772 return;
6775 barGoLink bar( result->GetRowCount() );
6779 bar.step();
6781 Field *fields = result->Fetch();
6783 uint32 id = fields[0].GetUInt32();
6785 GameTele gt;
6787 gt.position_x = fields[1].GetFloat();
6788 gt.position_y = fields[2].GetFloat();
6789 gt.position_z = fields[3].GetFloat();
6790 gt.orientation = fields[4].GetFloat();
6791 gt.mapId = fields[5].GetUInt32();
6792 gt.name = fields[6].GetCppString();
6794 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6796 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6797 continue;
6800 if(!Utf8toWStr(gt.name,gt.wnameLow))
6802 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6803 continue;
6806 wstrToLower( gt.wnameLow );
6808 m_GameTeleMap[id] = gt;
6810 ++count;
6812 while (result->NextRow());
6813 delete result;
6815 sLog.outString();
6816 sLog.outString( ">> Loaded %u GameTeleports", count );
6819 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6821 // explicit name case
6822 std::wstring wname;
6823 if(!Utf8toWStr(name,wname))
6824 return false;
6826 // converting string that we try to find to lower case
6827 wstrToLower( wname );
6829 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6830 const GameTele* alt = NULL;
6831 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6832 if(itr->second.wnameLow == wname)
6833 return &itr->second;
6834 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6835 alt = &itr->second;
6837 return alt;
6840 bool ObjectMgr::AddGameTele(GameTele& tele)
6842 // find max id
6843 uint32 new_id = 0;
6844 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6845 if(itr->first > new_id)
6846 new_id = itr->first;
6848 // use next
6849 ++new_id;
6851 if(!Utf8toWStr(tele.name,tele.wnameLow))
6852 return false;
6854 wstrToLower( tele.wnameLow );
6856 m_GameTeleMap[new_id] = tele;
6858 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')",
6859 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6862 bool ObjectMgr::DeleteGameTele(const std::string& name)
6864 // explicit name case
6865 std::wstring wname;
6866 if(!Utf8toWStr(name,wname))
6867 return false;
6869 // converting string that we try to find to lower case
6870 wstrToLower( wname );
6872 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6874 if(itr->second.wnameLow == wname)
6876 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6877 m_GameTeleMap.erase(itr);
6878 return true;
6882 return false;
6885 void ObjectMgr::LoadTrainerSpell()
6887 // For reload case
6888 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6889 itr->second.Clear();
6890 m_mCacheTrainerSpellMap.clear();
6892 std::set<uint32> skip_trainers;
6894 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6896 if( !result )
6898 barGoLink bar( 1 );
6900 bar.step();
6902 sLog.outString();
6903 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6904 return;
6907 barGoLink bar( result->GetRowCount() );
6909 uint32 count = 0;
6912 bar.step();
6914 Field* fields = result->Fetch();
6916 uint32 entry = fields[0].GetUInt32();
6917 uint32 spell = fields[1].GetUInt32();
6919 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6921 if(!cInfo)
6923 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6924 continue;
6927 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6929 if(skip_trainers.count(entry) == 0)
6931 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6932 skip_trainers.insert(entry);
6934 continue;
6937 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6938 if(!spellinfo)
6940 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6941 continue;
6944 if(!SpellMgr::IsSpellValid(spellinfo))
6946 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6947 continue;
6950 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6952 if(SpellMgr::IsProfessionSpell(spell))
6953 data.trainerType = 2;
6955 TrainerSpell& trainerSpell = data.spellList[spell];
6956 trainerSpell.spell = spell;
6957 trainerSpell.spellCost = fields[2].GetUInt32();
6958 trainerSpell.reqSkill = fields[3].GetUInt32();
6959 trainerSpell.reqSkillValue = fields[4].GetUInt32();
6960 trainerSpell.reqLevel = fields[5].GetUInt32();
6962 if(!trainerSpell.reqLevel)
6963 trainerSpell.reqLevel = spellinfo->spellLevel;
6965 // calculate learned spell for profession case when stored cast-spell
6966 trainerSpell.learnedSpell = spell;
6967 for(int i = 0; i <3; ++i)
6969 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
6970 continue;
6971 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
6973 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
6974 break;
6978 ++count;
6980 } while (result->NextRow());
6981 delete result;
6983 sLog.outString();
6984 sLog.outString( ">> Loaded %d Trainers", count );
6987 void ObjectMgr::LoadVendors()
6989 // For reload case
6990 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6991 itr->second.Clear();
6992 m_mCacheVendorItemMap.clear();
6994 std::set<uint32> skip_vendors;
6996 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6997 if( !result )
6999 barGoLink bar( 1 );
7001 bar.step();
7003 sLog.outString();
7004 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7005 return;
7008 barGoLink bar( result->GetRowCount() );
7010 uint32 count = 0;
7013 bar.step();
7014 Field* fields = result->Fetch();
7016 uint32 entry = fields[0].GetUInt32();
7017 uint32 item_id = fields[1].GetUInt32();
7018 uint32 maxcount = fields[2].GetUInt32();
7019 uint32 incrtime = fields[3].GetUInt32();
7020 uint32 ExtendedCost = fields[4].GetUInt32();
7022 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7023 continue;
7025 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7027 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7028 ++count;
7030 } while (result->NextRow());
7031 delete result;
7033 sLog.outString();
7034 sLog.outString( ">> Loaded %d Vendors ", count );
7037 void ObjectMgr::LoadNpcTextId()
7040 m_mCacheNpcTextIdMap.clear();
7042 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7043 if( !result )
7045 barGoLink bar( 1 );
7047 bar.step();
7049 sLog.outString();
7050 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7051 return;
7054 barGoLink bar( result->GetRowCount() );
7056 uint32 count = 0;
7057 uint32 guid,textid;
7060 bar.step();
7062 Field* fields = result->Fetch();
7064 guid = fields[0].GetUInt32();
7065 textid = fields[1].GetUInt32();
7067 if (!GetCreatureData(guid))
7069 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7070 continue;
7072 if (!GetGossipText(textid))
7074 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7075 continue;
7078 m_mCacheNpcTextIdMap[guid] = textid ;
7079 ++count;
7081 } while (result->NextRow());
7082 delete result;
7084 sLog.outString();
7085 sLog.outString( ">> Loaded %d NpcTextId ", count );
7088 void ObjectMgr::LoadNpcOptions()
7090 m_mCacheNpcOptionList.clear(); // For reload case
7092 QueryResult *result = WorldDatabase.Query(
7093 // 0 1 2 3 4 5 6 7 8
7094 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7095 "FROM npc_option");
7097 if( !result )
7099 barGoLink bar( 1 );
7101 bar.step();
7103 sLog.outString();
7104 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7105 return;
7108 barGoLink bar( result->GetRowCount() );
7110 uint32 count = 0;
7114 bar.step();
7116 Field* fields = result->Fetch();
7118 GossipOption go;
7119 go.Id = fields[0].GetUInt32();
7120 go.GossipId = fields[1].GetUInt32();
7121 go.NpcFlag = fields[2].GetUInt32();
7122 go.Icon = fields[3].GetUInt32();
7123 go.Action = fields[4].GetUInt32();
7124 go.BoxMoney = fields[5].GetUInt32();
7125 go.Coded = fields[6].GetUInt8()!=0;
7126 go.OptionText = fields[7].GetCppString();
7127 go.BoxText = fields[8].GetCppString();
7129 m_mCacheNpcOptionList.push_back(go);
7131 ++count;
7133 } while (result->NextRow());
7134 delete result;
7136 sLog.outString();
7137 sLog.outString( ">> Loaded %d npc_option entries", count );
7140 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7142 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7143 vList.AddItem(item,maxcount,incrtime,extendedcost);
7145 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7148 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7150 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7151 if(iter == m_mCacheVendorItemMap.end())
7152 return false;
7154 if(!iter->second.FindItem(item))
7155 return false;
7157 iter->second.RemoveItem(item);
7158 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7159 return true;
7162 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7164 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7165 if(!cInfo)
7167 if(pl)
7168 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7169 else
7170 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7171 return false;
7174 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7176 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7178 if(pl)
7179 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7180 else
7181 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7183 if(skip_vendors)
7184 skip_vendors->insert(vendor_entry);
7186 return false;
7189 if(!GetItemPrototype(item_id))
7191 if(pl)
7192 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7193 else
7194 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7195 return false;
7198 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7200 if(pl)
7201 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7202 else
7203 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7204 return false;
7207 if(maxcount > 0 && incrtime == 0)
7209 if(pl)
7210 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7211 else
7212 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7213 return false;
7215 else if(maxcount==0 && incrtime > 0)
7217 if(pl)
7218 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7219 else
7220 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7221 return false;
7224 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7225 if(!vItems)
7226 return true; // later checks for non-empty lists
7228 if(vItems->FindItem(item_id))
7230 if(pl)
7231 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7232 else
7233 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7234 return false;
7237 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7239 if(pl)
7240 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7241 else
7242 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7243 return false;
7246 return true;
7249 void ObjectMgr::LoadScriptNames()
7251 m_scriptNames.push_back("");
7252 QueryResult *result = WorldDatabase.Query(
7253 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7254 "UNION "
7255 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7256 "UNION "
7257 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7258 "UNION "
7259 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7260 "UNION "
7261 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7263 if( !result )
7265 barGoLink bar( 1 );
7266 bar.step();
7267 sLog.outString();
7268 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7269 return;
7272 barGoLink bar( result->GetRowCount() );
7273 uint32 count = 0;
7277 bar.step();
7278 m_scriptNames.push_back((*result)[0].GetString());
7279 ++count;
7280 } while (result->NextRow());
7281 delete result;
7283 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7284 sLog.outString();
7285 sLog.outString( ">> Loaded %d Script Names", count );
7288 uint32 ObjectMgr::GetScriptId(const char *name)
7290 // use binary search to find the script name in the sorted vector
7291 // assume "" is the first element
7292 if(!name) return 0;
7293 ScriptNameMap::const_iterator itr =
7294 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7295 if(itr == m_scriptNames.end() || *itr != name) return 0;
7296 return itr - m_scriptNames.begin();
7299 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7301 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7303 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7305 if(itrM->second.dataint)
7307 if(!GetMangosStringLocale (itrM->second.dataint))
7308 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7310 if(ids.count(itrM->second.dataint))
7311 ids.erase(itrM->second.dataint);
7317 void ObjectMgr::LoadDbScriptStrings()
7319 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7321 std::set<int32> ids;
7323 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7324 if(GetMangosStringLocale(i))
7325 ids.insert(i);
7327 CheckScripts(sQuestEndScripts,ids);
7328 CheckScripts(sQuestStartScripts,ids);
7329 CheckScripts(sSpellScripts,ids);
7330 CheckScripts(sGameObjectScripts,ids);
7331 CheckScripts(sEventScripts,ids);
7333 WaypointMgr.CheckTextsExistance(ids);
7335 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7336 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7339 // Functions for scripting access
7340 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7342 return objmgr.GetAreaTriggerScriptId(trigger_id);
7345 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7347 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7349 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());
7350 start_value = -1;
7351 end_value = std::numeric_limits<int32>::min();
7354 // for scripting localized strings allowed use _only_ negative entries
7355 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7358 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7360 return objmgr.GetScriptId(name);
7363 ObjectMgr::ScriptNameMap & GetScriptNames()
7365 return objmgr.GetScriptNames();