Use reset time for normal/heroic from new DBC. Improve basic support for raid diffica...
[getmangos.git] / src / game / ObjectMgr.cpp
blob6791db917a5898fdd4c13493e06ee01da7ce6728
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
23 #include "Policies/SingletonImp.h"
25 #include "Log.h"
26 #include "MapManager.h"
27 #include "ObjectMgr.h"
28 #include "SpellMgr.h"
29 #include "UpdateMask.h"
30 #include "World.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Language.h"
37 #include "GameEventMgr.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
44 #include "WaypointManager.h"
46 INSTANTIATE_SINGLETON_1(ObjectMgr);
48 ScriptMapMap sQuestEndScripts;
49 ScriptMapMap sQuestStartScripts;
50 ScriptMapMap sSpellScripts;
51 ScriptMapMap sGameObjectScripts;
52 ScriptMapMap sEventScripts;
54 bool normalizePlayerName(std::string& name)
56 if(name.empty())
57 return false;
59 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
60 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
62 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
63 return false;
65 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
66 for(size_t i = 1; i < wstr_len; ++i)
67 wstr_buf[i] = wcharToLower(wstr_buf[i]);
69 if(!WStrToUtf8(wstr_buf,wstr_len,name))
70 return false;
72 return true;
75 LanguageDesc lang_description[LANGUAGES_COUNT] =
77 { LANG_ADDON, 0, 0 },
78 { LANG_UNIVERSAL, 0, 0 },
79 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
80 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
81 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
82 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
83 { LANG_COMMON, 668, SKILL_LANG_COMMON },
84 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
85 { LANG_TITAN, 816, SKILL_LANG_TITAN },
86 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
87 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
88 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
89 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
90 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
91 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
92 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
93 { LANG_ZOMBIE, 0, 0 },
94 { LANG_GNOMISH_BINARY, 0, 0 },
95 { LANG_GOBLIN_BINARY, 0, 0 }
98 LanguageDesc const* GetLanguageDescByID(uint32 lang)
100 for(int i = 0; i < LANGUAGES_COUNT; ++i)
102 if(uint32(lang_description[i].lang_id) == lang)
103 return &lang_description[i];
106 return NULL;
109 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
111 if(questStart)
113 // not in expected required quest state
114 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
115 return false;
118 if(questEnd)
120 // not in expected forbidden quest state
121 if(!player || player->GetQuestRewardStatus(questEnd))
122 return false;
125 return true;
128 ObjectMgr::ObjectMgr()
130 m_hiCharGuid = 1;
131 m_hiCreatureGuid = 1;
132 m_hiPetGuid = 1;
133 m_hiVehicleGuid = 1;
134 m_hiItemGuid = 1;
135 m_hiGoGuid = 1;
136 m_hiDoGuid = 1;
137 m_hiCorpseGuid = 1;
138 m_hiPetNumber = 1;
139 m_ItemTextId = 1;
140 m_mailid = 1;
141 m_equipmentSetGuid = 1;
142 m_guildId = 1;
143 m_arenaTeamId = 1;
144 m_auctionid = 1;
146 // Only zero condition left, others will be added while loading DB tables
147 mConditions.resize(1);
150 ObjectMgr::~ObjectMgr()
152 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
153 delete i->second;
155 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
156 delete[] i->second;
158 // free only if loaded
159 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
160 delete[] playerClassInfo[class_].levelInfo;
162 for (int race = 0; race < MAX_RACES; ++race)
163 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
164 delete[] playerInfo[race][class_].levelInfo;
166 // free group and guild objects
167 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
168 delete (*itr);
170 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
171 delete itr->second;
173 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
174 delete itr->second;
176 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
177 itr->second.Clear();
179 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
180 itr->second.Clear();
183 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
185 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
186 if ((*itr)->GetLeaderGUID() == guid)
187 return *itr;
189 return NULL;
192 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
194 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
195 if (itr != mGuildMap.end())
196 return itr->second;
198 return NULL;
201 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
203 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
204 if (itr->second->GetName() == guildname)
205 return itr->second;
207 return NULL;
210 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
212 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
213 if (itr != mGuildMap.end())
214 return itr->second->GetName();
216 return "";
219 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
221 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
222 if (itr->second->GetLeader() == guid)
223 return itr->second;
225 return NULL;
228 void ObjectMgr::AddGuild(Guild* guild)
230 mGuildMap[guild->GetId()] = guild;
233 void ObjectMgr::RemoveGuild(uint32 Id)
235 mGuildMap.erase(Id);
238 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
240 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
241 if (itr != mArenaTeamMap.end())
242 return itr->second;
244 return NULL;
247 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
249 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
250 if (itr->second->GetName() == arenateamname)
251 return itr->second;
253 return NULL;
256 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
258 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
259 if (itr->second->GetCaptain() == guid)
260 return itr->second;
262 return NULL;
265 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
267 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
270 void ObjectMgr::RemoveArenaTeam(uint32 Id)
272 mArenaTeamMap.erase(Id);
275 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
277 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
280 void ObjectMgr::LoadCreatureLocales()
282 mCreatureLocaleMap.clear(); // need for reload case
284 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");
286 if(!result)
288 barGoLink bar(1);
290 bar.step();
292 sLog.outString();
293 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
294 return;
297 barGoLink bar(result->GetRowCount());
301 Field *fields = result->Fetch();
302 bar.step();
304 uint32 entry = fields[0].GetUInt32();
306 CreatureLocale& data = mCreatureLocaleMap[entry];
308 for(int i = 1; i < MAX_LOCALE; ++i)
310 std::string str = fields[1+2*(i-1)].GetCppString();
311 if(!str.empty())
313 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
314 if(idx >= 0)
316 if(data.Name.size() <= idx)
317 data.Name.resize(idx+1);
319 data.Name[idx] = str;
322 str = fields[1+2*(i-1)+1].GetCppString();
323 if(!str.empty())
325 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
326 if(idx >= 0)
328 if(data.SubName.size() <= idx)
329 data.SubName.resize(idx+1);
331 data.SubName[idx] = str;
335 } while (result->NextRow());
337 delete result;
339 sLog.outString();
340 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
343 void ObjectMgr::LoadNpcOptionLocales()
345 mNpcOptionLocaleMap.clear(); // need for reload case
347 QueryResult *result = WorldDatabase.Query("SELECT entry,"
348 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
349 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
350 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
351 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
352 "FROM locales_npc_option");
354 if(!result)
356 barGoLink bar(1);
358 bar.step();
360 sLog.outString();
361 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
362 return;
365 barGoLink bar(result->GetRowCount());
369 Field *fields = result->Fetch();
370 bar.step();
372 uint32 entry = fields[0].GetUInt32();
374 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
376 for(int i = 1; i < MAX_LOCALE; ++i)
378 std::string str = fields[1+2*(i-1)].GetCppString();
379 if(!str.empty())
381 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
382 if(idx >= 0)
384 if(data.OptionText.size() <= idx)
385 data.OptionText.resize(idx+1);
387 data.OptionText[idx] = str;
390 str = fields[1+2*(i-1)+1].GetCppString();
391 if(!str.empty())
393 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
394 if(idx >= 0)
396 if(data.BoxText.size() <= idx)
397 data.BoxText.resize(idx+1);
399 data.BoxText[idx] = str;
403 } while (result->NextRow());
405 delete result;
407 sLog.outString();
408 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
411 void ObjectMgr::LoadPointOfInterestLocales()
413 mPointOfInterestLocaleMap.clear(); // need for reload case
415 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");
417 if(!result)
419 barGoLink bar(1);
421 bar.step();
423 sLog.outString();
424 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
425 return;
428 barGoLink bar(result->GetRowCount());
432 Field *fields = result->Fetch();
433 bar.step();
435 uint32 entry = fields[0].GetUInt32();
437 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
439 for(int i = 1; i < MAX_LOCALE; ++i)
441 std::string str = fields[i].GetCppString();
442 if(str.empty())
443 continue;
445 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
446 if(idx >= 0)
448 if(data.IconName.size() <= idx)
449 data.IconName.resize(idx+1);
451 data.IconName[idx] = str;
454 } while (result->NextRow());
456 delete result;
458 sLog.outString();
459 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
462 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
464 template<class D>
465 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
467 dst = D(objmgr.GetScriptId(src));
471 void ObjectMgr::LoadCreatureTemplates()
473 SQLCreatureLoader loader;
474 loader.Load(sCreatureStorage);
476 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
477 sLog.outString();
479 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
480 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
482 // check data correctness
483 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
485 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
486 if (!cInfo)
487 continue;
489 if (cInfo->HeroicEntry)
491 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
492 if (!heroicInfo)
494 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.", i, cInfo->HeroicEntry, cInfo->HeroicEntry);
495 continue;
498 if (heroicEntries.find(i)!=heroicEntries.end())
500 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
501 continue;
504 if (heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
506 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
507 continue;
510 if (hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
512 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
513 continue;
516 if (cInfo->unit_class != heroicInfo->unit_class)
518 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in heroic mode (Entry: %u, class %u).",i, cInfo->unit_class, cInfo->HeroicEntry, heroicInfo->unit_class);
519 continue;
522 if (cInfo->npcflag != heroicInfo->npcflag)
524 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
525 continue;
528 if (cInfo->trainer_class != heroicInfo->trainer_class)
530 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
531 continue;
534 if (cInfo->trainer_race != heroicInfo->trainer_race)
536 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
537 continue;
540 if (cInfo->trainer_type != heroicInfo->trainer_type)
542 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
543 continue;
546 if (cInfo->trainer_spell != heroicInfo->trainer_spell)
548 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
549 continue;
552 if (heroicInfo->AIName && *heroicInfo->AIName)
554 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `AIName`, but in any case will used normal mode creature (Entry: %u) AIName.",cInfo->HeroicEntry,i);
555 continue;
558 if (heroicInfo->ScriptID)
560 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `ScriptName`, but in any case will used normal mode creature (Entry: %u) ScriptName.",cInfo->HeroicEntry,i);
561 continue;
564 hasHeroicEntries.insert(i);
565 heroicEntries.insert(cInfo->HeroicEntry);
568 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
569 if (!factionTemplate)
570 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
572 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
573 if (!factionTemplate)
574 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
576 // used later for scale
577 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
579 if (cInfo->DisplayID_A[0])
581 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
582 if(!displayEntry)
584 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
585 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
587 else if(!displayScaleEntry)
588 displayScaleEntry = displayEntry;
590 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
591 if (!minfo)
592 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A (%u)", cInfo->Entry, cInfo->DisplayID_A[0]);
595 if (cInfo->DisplayID_A[1])
597 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
598 if(!displayEntry)
600 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
601 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
603 else if(!displayScaleEntry)
604 displayScaleEntry = displayEntry;
606 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
607 if (!minfo)
608 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A2 (%u)", cInfo->Entry, cInfo->DisplayID_A[1]);
611 if (cInfo->DisplayID_H[0])
613 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
614 if(!displayEntry)
616 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
617 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
619 else if(!displayScaleEntry)
620 displayScaleEntry = displayEntry;
622 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
623 if (!minfo)
624 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H (%u)", cInfo->Entry, cInfo->DisplayID_H[0]);
627 if (cInfo->DisplayID_H[1])
629 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
630 if(!displayEntry)
632 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
633 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
635 else if(!displayScaleEntry)
636 displayScaleEntry = displayEntry;
638 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
639 if (!minfo)
640 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H2 (%u)", cInfo->Entry, cInfo->DisplayID_H[1]);
643 if (!displayScaleEntry)
644 sLog.outErrorDb("Creature (Entry: %u) not has any existed display id in DisplayID_A/DisplayID_A2/DisplayID_H/DisplayID_H2", cInfo->Entry);
646 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
648 if(cInfo->KillCredit[k])
650 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
652 sLog.outErrorDb("Creature (Entry: %u) has not existed creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
653 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
658 if (cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
659 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
661 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
663 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
664 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
667 if(cInfo->baseattacktime == 0)
668 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
670 if(cInfo->rangeattacktime == 0)
671 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
673 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
675 sLog.outErrorDb("Creature (Entry: %u) has dynamic flag UNIT_NPC_FLAG_SPELLCLICK (%u) set, it expect to be set by code base at `npc_spellclick_spells` content.",cInfo->Entry,UNIT_NPC_FLAG_SPELLCLICK);
676 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
679 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
680 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
682 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
684 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
685 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
688 // must exist or used hidden but used in data horse case
689 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
691 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
692 const_cast<CreatureInfo*>(cInfo)->family = 0;
695 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
697 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
698 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
701 if(cInfo->PetSpellDataId)
703 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
704 if(!spellDataId)
705 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
708 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
710 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
712 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
713 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
717 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
719 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
720 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
723 if(cInfo->equipmentId > 0) // 0 no equipment
725 if(!GetEquipmentInfo(cInfo->equipmentId))
727 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);
728 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
732 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
733 if(cInfo->scale <= 0.0f)
735 if(displayScaleEntry)
736 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
737 else
738 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
743 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
745 // Now add the auras, format "spellid effectindex spellid effectindex..."
746 char *p,*s;
747 std::vector<int> val;
748 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
749 if(p)
751 while (p[0]!=0)
753 ++p;
754 if (p[0]==' ')
756 val.push_back(atoi(s));
757 s=++p;
760 if (p!=s)
761 val.push_back(atoi(s));
763 // free char* loaded memory
764 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
766 // wrong list
767 if (val.size()%2)
769 addon->auras = NULL;
770 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
771 return;
775 // empty list
776 if(val.empty())
778 addon->auras = NULL;
779 return;
782 // replace by new structures array
783 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
785 uint32 i=0;
786 for(uint32 j = 0; j < val.size()/2; ++j)
788 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
789 cAura.spell_id = (uint32)val[2*j+0];
790 cAura.effect_idx = (uint32)val[2*j+1];
791 if ( cAura.effect_idx > 2 )
793 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);
794 continue;
796 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
797 if (!AdditionalSpellInfo)
799 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
800 continue;
803 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
805 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);
806 continue;
809 ++i;
812 // fill terminator element (after last added)
813 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
814 endAura.spell_id = 0;
815 endAura.effect_idx = 0;
818 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
820 creatureaddons.Load();
822 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
823 sLog.outString();
825 // check data correctness and convert 'auras'
826 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
828 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
829 if(!addon)
830 continue;
832 if (addon->mount)
834 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
836 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
837 const_cast<CreatureDataAddon*>(addon)->mount = 0;
841 if (!sEmotesStore.LookupEntry(addon->emote))
842 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
844 if (addon->move_flags & (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4))
846 sLog.outErrorDb("Creature (%s %u) movement flags mask defined in `%s` include forbidden flags (" I32FMT ") that can crash client, cleanup at load.", entryName, addon->guidOrEntry, creatureaddons.GetTableName(), (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4));
847 const_cast<CreatureDataAddon*>(addon)->move_flags &= ~(MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4);
850 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
854 void ObjectMgr::LoadCreatureAddons()
856 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
858 // check entry ids
859 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
860 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
861 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
862 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
864 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
866 // check entry ids
867 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
868 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
869 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
870 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
873 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
875 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
878 void ObjectMgr::LoadEquipmentTemplates()
880 sEquipmentStorage.Load();
882 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
884 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
886 if(!eqInfo)
887 continue;
889 for(uint8 j=0; j<3; j++)
891 if(!eqInfo->equipentry[j])
892 continue;
894 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
896 if(!dbcitem)
898 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
899 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
900 continue;
903 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
904 dbcitem->InventoryType != INVTYPE_SHIELD &&
905 dbcitem->InventoryType != INVTYPE_RANGED &&
906 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
907 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
908 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
909 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
910 dbcitem->InventoryType != INVTYPE_THROWN &&
911 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
913 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);
914 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
918 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
919 sLog.outString();
922 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
924 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
927 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
929 // Load creature model (display id)
930 if (data && data->displayid)
931 return data->displayid;
933 // use defaults from the template
934 uint32 display_id;
936 // DisplayID_A is used if no team is given
937 if (team == HORDE)
939 if(cinfo->DisplayID_H[0])
940 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
941 else
942 display_id = cinfo->DisplayID_H[1];
944 if(!display_id)
945 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
947 else
949 if(cinfo->DisplayID_A[0])
950 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
951 else
952 display_id = cinfo->DisplayID_A[1];
954 if(!display_id)
955 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
958 return display_id;
961 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
963 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
964 if(!minfo)
965 return NULL;
967 // If a model for another gender exists, 50% chance to use it
968 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
970 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
971 if(!minfo_tmp)
973 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
974 return minfo; // not fatal, just use the previous one
976 else
977 return minfo_tmp;
979 else
980 return minfo;
983 void ObjectMgr::LoadCreatureModelInfo()
985 sCreatureModelStorage.Load();
987 // post processing
988 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
990 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
991 if (!minfo)
992 continue;
994 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
995 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
997 if (minfo->gender > GENDER_NONE)
999 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1000 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1003 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1005 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1006 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1010 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1011 sLog.outString();
1014 void ObjectMgr::LoadCreatures()
1016 uint32 count = 0;
1017 // 0 1 2 3
1018 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1019 // 4 5 6 7 8 9 10 11
1020 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1021 // 12 13 14 15 16 17 18 19
1022 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1023 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1024 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1026 if(!result)
1028 barGoLink bar(1);
1030 bar.step();
1032 sLog.outString();
1033 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1034 return;
1037 // build single time for check creature data
1038 std::set<uint32> heroicCreatures;
1039 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1040 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1041 if(cInfo->HeroicEntry)
1042 heroicCreatures.insert(cInfo->HeroicEntry);
1044 barGoLink bar(result->GetRowCount());
1048 Field *fields = result->Fetch();
1049 bar.step();
1051 uint32 guid = fields[ 0].GetUInt32();
1052 uint32 entry = fields[ 1].GetUInt32();
1054 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1055 if(!cInfo)
1057 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1058 continue;
1061 CreatureData& data = mCreatureDataMap[guid];
1063 data.id = entry;
1064 data.mapid = fields[ 2].GetUInt32();
1065 data.displayid = fields[ 3].GetUInt32();
1066 data.equipmentId = fields[ 4].GetUInt32();
1067 data.posX = fields[ 5].GetFloat();
1068 data.posY = fields[ 6].GetFloat();
1069 data.posZ = fields[ 7].GetFloat();
1070 data.orientation = fields[ 8].GetFloat();
1071 data.spawntimesecs = fields[ 9].GetUInt32();
1072 data.spawndist = fields[10].GetFloat();
1073 data.currentwaypoint= fields[11].GetUInt32();
1074 data.curhealth = fields[12].GetUInt32();
1075 data.curmana = fields[13].GetUInt32();
1076 data.is_dead = fields[14].GetBool();
1077 data.movementType = fields[15].GetUInt8();
1078 data.spawnMask = fields[16].GetUInt8();
1079 data.phaseMask = fields[17].GetUInt16();
1080 int16 gameEvent = fields[18].GetInt16();
1081 int16 PoolId = fields[19].GetInt16();
1083 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1085 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template (entry: %u) in `creature_template`, skipped.",guid, data.id );
1086 continue;
1089 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1091 if(!GetEquipmentInfo(data.equipmentId))
1093 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);
1094 data.equipmentId = -1;
1098 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1100 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 );
1101 data.curhealth = cInfo->minhealth;
1104 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1106 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
1107 if(!map || !map->IsDungeon())
1108 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`flags_extra` including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.",guid,data.id);
1111 if(data.curmana < cInfo->minmana)
1113 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 );
1114 data.curmana = cInfo->minmana;
1117 if(data.spawndist < 0.0f)
1119 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1120 data.spawndist = 0.0f;
1122 else if(data.movementType == RANDOM_MOTION_TYPE)
1124 if(data.spawndist == 0.0f)
1126 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 );
1127 data.movementType = IDLE_MOTION_TYPE;
1130 else if(data.movementType == IDLE_MOTION_TYPE)
1132 if(data.spawndist != 0.0f)
1134 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1135 data.spawndist = 0.0f;
1139 if(data.phaseMask==0)
1141 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1142 data.phaseMask = 1;
1145 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1146 AddCreatureToGrid(guid, &data);
1148 ++count;
1150 } while (result->NextRow());
1152 delete result;
1154 sLog.outString();
1155 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1158 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1160 uint8 mask = data->spawnMask;
1161 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1163 if(mask & 1)
1165 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1166 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1168 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1169 cell_guids.creatures.insert(guid);
1174 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1176 uint8 mask = data->spawnMask;
1177 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1179 if(mask & 1)
1181 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1182 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1184 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1185 cell_guids.creatures.erase(guid);
1190 void ObjectMgr::LoadGameobjects()
1192 uint32 count = 0;
1194 // 0 1 2 3 4 5 6
1195 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1196 // 7 8 9 10 11 12 13 14 15 16 17
1197 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1198 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1199 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1201 if(!result)
1203 barGoLink bar(1);
1205 bar.step();
1207 sLog.outString();
1208 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1209 return;
1212 barGoLink bar(result->GetRowCount());
1216 Field *fields = result->Fetch();
1217 bar.step();
1219 uint32 guid = fields[ 0].GetUInt32();
1220 uint32 entry = fields[ 1].GetUInt32();
1222 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1223 if (!gInfo)
1225 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1226 continue;
1229 if(!gInfo->displayId)
1231 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) doesn't have displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1232 continue;
1235 if (gInfo->displayId && !sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1237 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1238 continue;
1241 GameObjectData& data = mGameObjectDataMap[guid];
1243 data.id = entry;
1244 data.mapid = fields[ 2].GetUInt32();
1245 data.posX = fields[ 3].GetFloat();
1246 data.posY = fields[ 4].GetFloat();
1247 data.posZ = fields[ 5].GetFloat();
1248 data.orientation = fields[ 6].GetFloat();
1249 data.rotation0 = fields[ 7].GetFloat();
1250 data.rotation1 = fields[ 8].GetFloat();
1251 data.rotation2 = fields[ 9].GetFloat();
1252 data.rotation3 = fields[10].GetFloat();
1253 data.spawntimesecs = fields[11].GetInt32();
1255 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1257 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1260 data.animprogress = fields[12].GetUInt32();
1262 uint32 go_state = fields[13].GetUInt32();
1263 if (go_state >= MAX_GO_STATE)
1265 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1266 continue;
1268 data.go_state = GOState(go_state);
1270 data.spawnMask = fields[14].GetUInt8();
1271 data.phaseMask = fields[15].GetUInt16();
1272 int16 gameEvent = fields[16].GetInt16();
1273 int16 PoolId = fields[17].GetInt16();
1275 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1277 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1278 continue;
1281 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1283 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1284 continue;
1287 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1289 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1290 continue;
1293 if(data.phaseMask == 0)
1295 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1296 data.phaseMask = 1;
1299 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1300 AddGameobjectToGrid(guid, &data);
1301 ++count;
1303 } while (result->NextRow());
1305 delete result;
1307 sLog.outString();
1308 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1311 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1313 uint8 mask = data->spawnMask;
1314 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1316 if(mask & 1)
1318 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1319 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1321 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1322 cell_guids.gameobjects.insert(guid);
1327 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1329 uint8 mask = data->spawnMask;
1330 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1332 if(mask & 1)
1334 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1335 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1337 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1338 cell_guids.gameobjects.erase(guid);
1343 void ObjectMgr::LoadCreatureRespawnTimes()
1345 // remove outdated data
1346 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1348 uint32 count = 0;
1350 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1352 if(!result)
1354 barGoLink bar(1);
1356 bar.step();
1358 sLog.outString();
1359 sLog.outString(">> Loaded 0 creature respawn time.");
1360 return;
1363 barGoLink bar(result->GetRowCount());
1367 Field *fields = result->Fetch();
1368 bar.step();
1370 uint32 loguid = fields[0].GetUInt32();
1371 uint64 respawn_time = fields[1].GetUInt64();
1372 uint32 instance = fields[2].GetUInt32();
1374 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1376 ++count;
1377 } while (result->NextRow());
1379 delete result;
1381 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1382 sLog.outString();
1385 void ObjectMgr::LoadGameobjectRespawnTimes()
1387 // remove outdated data
1388 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1390 uint32 count = 0;
1392 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1394 if(!result)
1396 barGoLink bar(1);
1398 bar.step();
1400 sLog.outString();
1401 sLog.outString(">> Loaded 0 gameobject respawn time.");
1402 return;
1405 barGoLink bar(result->GetRowCount());
1409 Field *fields = result->Fetch();
1410 bar.step();
1412 uint32 loguid = fields[0].GetUInt32();
1413 uint64 respawn_time = fields[1].GetUInt64();
1414 uint32 instance = fields[2].GetUInt32();
1416 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1418 ++count;
1419 } while (result->NextRow());
1421 delete result;
1423 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1424 sLog.outString();
1427 // name must be checked to correctness (if received) before call this function
1428 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1430 uint64 guid = 0;
1432 CharacterDatabase.escape_string(name);
1434 // Player name safe to sending to DB (checked at login) and this function using
1435 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1436 if(result)
1438 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1440 delete result;
1443 return guid;
1446 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1448 // prevent DB access for online player
1449 if(Player* player = GetPlayer(guid))
1451 name = player->GetName();
1452 return true;
1455 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1457 if(result)
1459 name = (*result)[0].GetCppString();
1460 delete result;
1461 return true;
1464 return false;
1467 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1469 // prevent DB access for online player
1470 if(Player* player = GetPlayer(guid))
1472 return Player::TeamForRace(player->getRace());
1475 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1477 if(result)
1479 uint8 race = (*result)[0].GetUInt8();
1480 delete result;
1481 return Player::TeamForRace(race);
1484 return 0;
1487 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1489 // prevent DB access for online player
1490 if(Player* player = GetPlayer(guid))
1492 return player->GetSession()->GetAccountId();
1495 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1496 if(result)
1498 uint32 acc = (*result)[0].GetUInt32();
1499 delete result;
1500 return acc;
1503 return 0;
1506 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1508 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1509 if(result)
1511 uint32 acc = (*result)[0].GetUInt32();
1512 delete result;
1513 return acc;
1516 return 0;
1519 void ObjectMgr::LoadItemLocales()
1521 mItemLocaleMap.clear(); // need for reload case
1523 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");
1525 if(!result)
1527 barGoLink bar(1);
1529 bar.step();
1531 sLog.outString();
1532 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1533 return;
1536 barGoLink bar(result->GetRowCount());
1540 Field *fields = result->Fetch();
1541 bar.step();
1543 uint32 entry = fields[0].GetUInt32();
1545 ItemLocale& data = mItemLocaleMap[entry];
1547 for(int i = 1; i < MAX_LOCALE; ++i)
1549 std::string str = fields[1+2*(i-1)].GetCppString();
1550 if(!str.empty())
1552 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1553 if(idx >= 0)
1555 if(data.Name.size() <= idx)
1556 data.Name.resize(idx+1);
1558 data.Name[idx] = str;
1562 str = fields[1+2*(i-1)+1].GetCppString();
1563 if(!str.empty())
1565 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1566 if(idx >= 0)
1568 if(data.Description.size() <= idx)
1569 data.Description.resize(idx+1);
1571 data.Description[idx] = str;
1575 } while (result->NextRow());
1577 delete result;
1579 sLog.outString();
1580 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1583 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1585 template<class D>
1586 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1588 dst = D(objmgr.GetScriptId(src));
1592 void ObjectMgr::LoadItemPrototypes()
1594 SQLItemLoader loader;
1595 loader.Load(sItemStorage);
1596 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1597 sLog.outString();
1599 // check data correctness
1600 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1602 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1603 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1604 if(!proto)
1606 /* to many errors, and possible not all items really used in game
1607 if (dbcitem)
1608 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1610 continue;
1613 if(dbcitem)
1615 if(proto->Class != dbcitem->Class)
1617 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1618 // It safe let use Class from DB
1620 /* disabled: have some strange wrong cases for Subclass values.
1621 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1622 if(proto->SubClass != dbcitem->SubClass)
1624 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);
1625 // It safe let use Subclass from DB
1629 if(proto->Unk0 != dbcitem->Unk0)
1631 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1632 // It safe let use Unk0 from DB
1635 if(proto->Material != dbcitem->Material)
1637 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1638 // It safe let use Material from DB
1641 if(proto->InventoryType != dbcitem->InventoryType)
1643 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1644 // It safe let use InventoryType from DB
1647 if(proto->DisplayInfoID != dbcitem->DisplayId)
1649 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1650 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1652 if(proto->Sheath != dbcitem->Sheath)
1654 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1655 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1658 else
1660 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1663 if(proto->Class >= MAX_ITEM_CLASS)
1665 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1666 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1669 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1671 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1672 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1675 if(proto->Quality >= MAX_ITEM_QUALITY)
1677 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1678 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1681 if(proto->BuyCount <= 0)
1683 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1684 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1687 if(proto->InventoryType >= MAX_INVTYPE)
1689 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1690 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1693 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1695 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1696 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1700 // can be used in equip slot, as page read use in inventory, or spell casting at use
1701 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1702 if(!req)
1704 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1706 if(proto->Spells[j].SpellId)
1708 req = true;
1709 break;
1714 if(req)
1716 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1717 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1719 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1720 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1724 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1726 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1727 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1730 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1731 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1733 if(proto->RequiredReputationFaction)
1735 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1737 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1738 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1741 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1742 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1744 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1745 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1747 if(proto->MaxCount < -1)
1749 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1750 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1753 if(proto->Stackable == 0)
1755 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1756 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1758 else if(proto->Stackable < -1)
1760 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1761 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1763 else if(proto->Stackable > 1000)
1765 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1766 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1769 if(proto->ContainerSlots > MAX_BAG_SIZE)
1771 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1772 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1775 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1777 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1778 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1781 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1783 // for ItemStatValue != 0
1784 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1786 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1787 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1790 switch(proto->ItemStat[j].ItemStatType)
1792 case ITEM_MOD_SPELL_HEALING_DONE:
1793 case ITEM_MOD_SPELL_DAMAGE_DONE:
1794 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1795 break;
1796 default:
1797 break;
1801 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1803 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1805 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1806 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1810 // special format
1811 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1813 // spell_1
1814 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1816 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);
1817 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1818 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1819 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1820 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1823 // spell_2 have learning spell
1824 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1826 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);
1827 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1828 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1829 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1831 else if(!proto->Spells[1].SpellId)
1833 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1834 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1835 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1837 else
1839 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1840 if(!spellInfo)
1842 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1843 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1844 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1845 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1847 // allowed only in special format
1848 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1850 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1851 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1852 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1853 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1857 // spell_3*,spell_4*,spell_5* is empty
1858 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1860 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1862 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1863 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1864 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1866 else if(proto->Spells[j].SpellId != 0)
1868 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1869 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1873 // normal spell list
1874 else
1876 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1878 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1880 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1881 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1882 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1884 // on hit can be sued only at weapon
1885 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1887 if(proto->Class != ITEM_CLASS_WEAPON)
1888 sLog.outErrorDb("Item (Entry: %u) isn't weapon (Class: %u) but has on hit spelltrigger_%d (%u), it will not triggered.",i,proto->Class,j+1,proto->Spells[j].SpellTrigger);
1891 if(proto->Spells[j].SpellId)
1893 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1894 if(!spellInfo)
1896 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1897 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1899 // allowed only in special format
1900 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1902 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1903 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1909 if(proto->Bonding >= MAX_BIND_TYPE)
1910 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1912 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1913 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1915 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1916 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1918 if(proto->Sheath >= MAX_SHEATHETYPE)
1920 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1921 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1924 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1926 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1927 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1930 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1932 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1933 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1936 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1938 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1939 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1942 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1943 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1945 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1946 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1948 if(proto->BagFamily)
1950 // check bits
1951 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1953 uint32 mask = 1 << j;
1954 if((proto->BagFamily & mask)==0)
1955 continue;
1957 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1958 if(!bf)
1960 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
1961 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1962 continue;
1965 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
1967 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
1968 if(!ctEntry)
1970 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
1971 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1977 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1978 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1980 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
1982 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1984 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1985 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1989 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1990 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1992 if(proto->FoodType >= MAX_PET_DIET)
1994 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1995 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1998 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2000 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2001 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2004 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2006 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2007 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2012 void ObjectMgr::LoadItemRequiredTarget()
2014 m_ItemRequiredTarget.clear(); // needed for reload case
2016 uint32 count = 0;
2018 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2020 if (!result)
2022 barGoLink bar(1);
2024 bar.step();
2026 sLog.outString();
2027 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2028 return;
2031 barGoLink bar(result->GetRowCount());
2035 Field *fields = result->Fetch();
2036 bar.step();
2038 uint32 uiItemId = fields[0].GetUInt32();
2039 uint32 uiType = fields[1].GetUInt32();
2040 uint32 uiTargetEntry = fields[2].GetUInt32();
2042 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2044 if (!pItemProto)
2046 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2047 continue;
2050 bool bIsItemSpellValid = false;
2052 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2054 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2056 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2057 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2059 SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2060 if (bounds.first != bounds.second)
2061 break;
2063 for (int j = 0; j < 3; ++j)
2065 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2066 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2067 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2068 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2070 bIsItemSpellValid = true;
2071 break;
2074 if (bIsItemSpellValid)
2075 break;
2080 if (!bIsItemSpellValid)
2082 sLog.outErrorDb("Table `item_required_target`: Spell used by item %u does not have implicit target TARGET_CHAIN_DAMAGE(6), TARGET_DUELVSPLAYER(25), already listed in `spell_script_target` or doesn't have item spelltrigger.",uiItemId);
2083 continue;
2086 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2088 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2089 continue;
2092 if (!uiTargetEntry)
2094 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2095 continue;
2098 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2100 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2101 continue;
2104 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2106 ++count;
2107 } while (result->NextRow());
2109 delete result;
2111 sLog.outString();
2112 sLog.outString(">> Loaded %u Item required targets", count);
2115 void ObjectMgr::LoadPetLevelInfo()
2117 // Loading levels data
2119 // 0 1 2 3 4 5 6 7 8 9
2120 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2122 uint32 count = 0;
2124 if (!result)
2126 barGoLink bar( 1 );
2128 sLog.outString();
2129 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2130 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
2131 return;
2134 barGoLink bar( result->GetRowCount() );
2138 Field* fields = result->Fetch();
2140 uint32 creature_id = fields[0].GetUInt32();
2141 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2143 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2144 continue;
2147 uint32 current_level = fields[1].GetUInt32();
2148 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2150 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2151 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2152 else
2154 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2155 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2157 continue;
2159 else if(current_level < 1)
2161 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2162 continue;
2165 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2167 if(pInfoMapEntry==NULL)
2168 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2170 // data for level 1 stored in [0] array element, ...
2171 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2173 pLevelInfo->health = fields[2].GetUInt16();
2174 pLevelInfo->mana = fields[3].GetUInt16();
2175 pLevelInfo->armor = fields[9].GetUInt16();
2177 for (int i = 0; i < MAX_STATS; i++)
2179 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2182 bar.step();
2183 ++count;
2185 while (result->NextRow());
2187 delete result;
2189 sLog.outString();
2190 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2193 // Fill gaps and check integrity
2194 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2196 PetLevelInfo* pInfo = itr->second;
2198 // fatal error if no level 1 data
2199 if(!pInfo || pInfo[0].health == 0 )
2201 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2202 exit(1);
2205 // fill level gaps
2206 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2208 if(pInfo[level].health == 0)
2210 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2211 pInfo[level] = pInfo[level-1];
2217 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2219 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2220 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2222 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2223 if(itr == petInfo.end())
2224 return NULL;
2226 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2229 void ObjectMgr::LoadPlayerInfo()
2231 // Load playercreate
2233 // 0 1 2 3 4 5 6
2234 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2236 uint32 count = 0;
2238 if (!result)
2240 barGoLink bar( 1 );
2242 sLog.outString();
2243 sLog.outString( ">> Loaded %u player create definitions", count );
2244 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2245 exit(1);
2248 barGoLink bar( result->GetRowCount() );
2252 Field* fields = result->Fetch();
2254 uint32 current_race = fields[0].GetUInt32();
2255 uint32 current_class = fields[1].GetUInt32();
2256 uint32 mapId = fields[2].GetUInt32();
2257 uint32 zoneId = fields[3].GetUInt32();
2258 float positionX = fields[4].GetFloat();
2259 float positionY = fields[5].GetFloat();
2260 float positionZ = fields[6].GetFloat();
2262 if(current_race >= MAX_RACES)
2264 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2265 continue;
2268 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2269 if(!rEntry)
2271 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2272 continue;
2275 if(current_class >= MAX_CLASSES)
2277 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2278 continue;
2281 if(!sChrClassesStore.LookupEntry(current_class))
2283 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2284 continue;
2287 // accept DB data only for valid position (and non instanceable)
2288 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2290 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2291 continue;
2294 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2296 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2297 continue;
2300 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2302 pInfo->mapId = mapId;
2303 pInfo->zoneId = zoneId;
2304 pInfo->positionX = positionX;
2305 pInfo->positionY = positionY;
2306 pInfo->positionZ = positionZ;
2308 pInfo->displayId_m = rEntry->model_m;
2309 pInfo->displayId_f = rEntry->model_f;
2311 bar.step();
2312 ++count;
2314 while (result->NextRow());
2316 delete result;
2318 sLog.outString();
2319 sLog.outString( ">> Loaded %u player create definitions", count );
2322 // Load playercreate items
2324 // 0 1 2 3
2325 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2327 uint32 count = 0;
2329 if (!result)
2331 barGoLink bar( 1 );
2333 bar.step();
2335 sLog.outString();
2336 sLog.outString( ">> Loaded %u custom player create items", count );
2338 else
2340 barGoLink bar( result->GetRowCount() );
2344 Field* fields = result->Fetch();
2346 uint32 current_race = fields[0].GetUInt32();
2347 if(current_race >= MAX_RACES)
2349 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2350 continue;
2353 uint32 current_class = fields[1].GetUInt32();
2354 if(current_class >= MAX_CLASSES)
2356 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2357 continue;
2360 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2362 uint32 item_id = fields[2].GetUInt32();
2364 if(!GetItemPrototype(item_id))
2366 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);
2367 continue;
2370 uint32 amount = fields[3].GetUInt32();
2372 if(!amount)
2374 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2375 continue;
2378 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2380 bar.step();
2381 ++count;
2383 while(result->NextRow());
2385 delete result;
2387 sLog.outString();
2388 sLog.outString( ">> Loaded %u custom player create items", count );
2392 // Load playercreate spells
2394 // 0 1 2
2395 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2397 uint32 count = 0;
2399 if (!result)
2401 barGoLink bar( 1 );
2403 sLog.outString();
2404 sLog.outString( ">> Loaded %u player create spells", count );
2405 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2407 else
2409 barGoLink bar( result->GetRowCount() );
2413 Field* fields = result->Fetch();
2415 uint32 current_race = fields[0].GetUInt32();
2416 if(current_race >= MAX_RACES)
2418 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2419 continue;
2422 uint32 current_class = fields[1].GetUInt32();
2423 if(current_class >= MAX_CLASSES)
2425 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2426 continue;
2429 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2430 pInfo->spell.push_back(fields[2].GetUInt32());
2432 bar.step();
2433 ++count;
2435 while( result->NextRow() );
2437 delete result;
2439 sLog.outString();
2440 sLog.outString( ">> Loaded %u player create spells", count );
2444 // Load playercreate actions
2446 // 0 1 2 3 4
2447 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2449 uint32 count = 0;
2451 if (!result)
2453 barGoLink bar( 1 );
2455 sLog.outString();
2456 sLog.outString( ">> Loaded %u player create actions", count );
2457 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2459 else
2461 barGoLink bar( result->GetRowCount() );
2465 Field* fields = result->Fetch();
2467 uint32 current_race = fields[0].GetUInt32();
2468 if(current_race >= MAX_RACES)
2470 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2471 continue;
2474 uint32 current_class = fields[1].GetUInt32();
2475 if(current_class >= MAX_CLASSES)
2477 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2478 continue;
2481 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2482 pInfo->action.push_back(PlayerCreateInfoAction(fields[2].GetUInt8(),fields[3].GetUInt32(),fields[4].GetUInt8()));
2484 bar.step();
2485 ++count;
2487 while( result->NextRow() );
2489 delete result;
2491 sLog.outString();
2492 sLog.outString( ">> Loaded %u player create actions", count );
2496 // Loading levels data (class only dependent)
2498 // 0 1 2 3
2499 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2501 uint32 count = 0;
2503 if (!result)
2505 barGoLink bar( 1 );
2507 sLog.outString();
2508 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2509 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2510 exit(1);
2513 barGoLink bar( result->GetRowCount() );
2517 Field* fields = result->Fetch();
2519 uint32 current_class = fields[0].GetUInt32();
2520 if(current_class >= MAX_CLASSES)
2522 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2523 continue;
2526 uint32 current_level = fields[1].GetUInt32();
2527 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2529 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2530 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2531 else
2533 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2534 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2536 continue;
2539 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2541 if(!pClassInfo->levelInfo)
2542 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2544 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2546 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2547 pClassLevelInfo->basemana = fields[3].GetUInt16();
2549 bar.step();
2550 ++count;
2552 while (result->NextRow());
2554 delete result;
2556 sLog.outString();
2557 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2560 // Fill gaps and check integrity
2561 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2563 // skip non existed classes
2564 if(!sChrClassesStore.LookupEntry(class_))
2565 continue;
2567 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2569 // fatal error if no level 1 data
2570 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2572 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2573 exit(1);
2576 // fill level gaps
2577 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2579 if(pClassInfo->levelInfo[level].basehealth == 0)
2581 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2582 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2587 // Loading levels data (class/race dependent)
2589 // 0 1 2 3 4 5 6 7
2590 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2592 uint32 count = 0;
2594 if (!result)
2596 barGoLink bar( 1 );
2598 sLog.outString();
2599 sLog.outString( ">> Loaded %u level stats definitions", count );
2600 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2601 exit(1);
2604 barGoLink bar( result->GetRowCount() );
2608 Field* fields = result->Fetch();
2610 uint32 current_race = fields[0].GetUInt32();
2611 if(current_race >= MAX_RACES)
2613 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2614 continue;
2617 uint32 current_class = fields[1].GetUInt32();
2618 if(current_class >= MAX_CLASSES)
2620 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2621 continue;
2624 uint32 current_level = fields[2].GetUInt32();
2625 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2627 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2628 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2629 else
2631 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2632 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2634 continue;
2637 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2639 if(!pInfo->levelInfo)
2640 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2642 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2644 for (int i = 0; i < MAX_STATS; i++)
2646 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2649 bar.step();
2650 ++count;
2652 while (result->NextRow());
2654 delete result;
2656 sLog.outString();
2657 sLog.outString( ">> Loaded %u level stats definitions", count );
2660 // Fill gaps and check integrity
2661 for (int race = 0; race < MAX_RACES; ++race)
2663 // skip non existed races
2664 if(!sChrRacesStore.LookupEntry(race))
2665 continue;
2667 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2669 // skip non existed classes
2670 if(!sChrClassesStore.LookupEntry(class_))
2671 continue;
2673 PlayerInfo* pInfo = &playerInfo[race][class_];
2675 // skip non loaded combinations
2676 if(!pInfo->displayId_m || !pInfo->displayId_f)
2677 continue;
2679 // skip expansion races if not playing with expansion
2680 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2681 continue;
2683 // skip expansion classes if not playing with expansion
2684 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2685 continue;
2687 // fatal error if no level 1 data
2688 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2690 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2691 exit(1);
2694 // fill level gaps
2695 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2697 if(pInfo->levelInfo[level].stats[0] == 0)
2699 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2700 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2706 // Loading xp per level data
2708 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2709 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2710 mPlayerXPperLevel[level] = 0;
2712 // 0 1
2713 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2715 uint32 count = 0;
2717 if (!result)
2719 barGoLink bar( 1 );
2721 sLog.outString();
2722 sLog.outString( ">> Loaded %u xp for level definitions", count );
2723 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2724 exit(1);
2727 barGoLink bar( result->GetRowCount() );
2731 Field* fields = result->Fetch();
2733 uint32 current_level = fields[0].GetUInt32();
2734 uint32 current_xp = fields[1].GetUInt32();
2736 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2738 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2739 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2740 else
2742 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2743 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2745 continue;
2747 //PlayerXPperLevel
2748 mPlayerXPperLevel[current_level] = current_xp;
2749 bar.step();
2750 ++count;
2752 while (result->NextRow());
2754 delete result;
2756 sLog.outString();
2757 sLog.outString( ">> Loaded %u xp for level definitions", count );
2760 // fill level gaps
2761 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2763 if( mPlayerXPperLevel[level] == 0)
2765 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2766 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2771 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2773 if(level < 1 || class_ >= MAX_CLASSES)
2774 return;
2776 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2778 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2779 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2781 *info = pInfo->levelInfo[level-1];
2784 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2786 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2787 return;
2789 PlayerInfo const* pInfo = &playerInfo[race][class_];
2790 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2791 return;
2793 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2794 *info = pInfo->levelInfo[level-1];
2795 else
2796 BuildPlayerLevelInfo(race,class_,level,info);
2799 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2801 // base data (last known level)
2802 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2804 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2806 switch(_class)
2808 case CLASS_WARRIOR:
2809 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2810 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2811 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2812 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2813 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2814 break;
2815 case CLASS_PALADIN:
2816 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2817 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2818 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2819 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2820 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2821 break;
2822 case CLASS_HUNTER:
2823 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2824 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2825 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2826 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2827 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2828 break;
2829 case CLASS_ROGUE:
2830 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2831 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2832 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2833 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2834 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2835 break;
2836 case CLASS_PRIEST:
2837 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2838 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2839 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2840 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2841 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2842 break;
2843 case CLASS_SHAMAN:
2844 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2845 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2846 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2847 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2848 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2849 break;
2850 case CLASS_MAGE:
2851 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2852 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2853 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2854 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2855 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2856 break;
2857 case CLASS_WARLOCK:
2858 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2859 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2860 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2861 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2862 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2863 break;
2864 case CLASS_DRUID:
2865 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2866 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2867 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2868 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2869 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2874 void ObjectMgr::LoadGuilds()
2876 Guild *newGuild;
2877 uint32 count = 0;
2879 // 0 1 2 3 4 5 6
2880 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
2881 // 7 8 9 10 11 12
2882 "BackgroundColor,info,motd,createdate,BankMoney,COUNT(guild_bank_tab.guildid) "
2883 "FROM guild LEFT JOIN guild_bank_tab ON guild.guildid = guild_bank_tab.guildid GROUP BY guild.guildid ORDER BY guildid ASC");
2885 if( !result )
2888 barGoLink bar( 1 );
2890 bar.step();
2892 sLog.outString();
2893 sLog.outString( ">> Loaded %u guild definitions", count );
2894 return;
2897 // load guild ranks
2898 // 0 1 2 3 4
2899 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
2901 // load guild members
2902 // 0 1 2 3 4 5 6
2903 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
2904 // 7 8 9 10 11 12
2905 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
2906 // 13 14 15 16 17 18
2907 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
2908 // 19 20 21 22 23
2909 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
2910 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
2912 // load guild bank tab rights
2913 // 0 1 2 3 4
2914 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
2916 barGoLink bar( result->GetRowCount() );
2920 //Field *fields = result->Fetch();
2922 bar.step();
2923 ++count;
2925 newGuild = new Guild;
2926 if (!newGuild->LoadGuildFromDB(result) ||
2927 !newGuild->LoadRanksFromDB(guildRanksResult) ||
2928 !newGuild->LoadMembersFromDB(guildMembersResult) ||
2929 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
2930 !newGuild->CheckGuildStructure()
2933 newGuild->Disband();
2934 delete newGuild;
2935 continue;
2937 AddGuild(newGuild);
2939 }while( result->NextRow() );
2941 delete result;
2942 delete guildRanksResult;
2943 delete guildMembersResult;
2944 delete guildBankTabRightsResult;
2946 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
2947 //you can comment these lines if you don't plan to change CONFIG_GUILD_EVENT_LOG_COUNT and CONFIG_GUILD_BANK_EVENT_LOG_COUNT
2948 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_EVENT_LOG_COUNT));
2949 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));
2951 sLog.outString();
2952 sLog.outString( ">> Loaded %u guild definitions", count );
2955 void ObjectMgr::LoadArenaTeams()
2957 uint32 count = 0;
2959 // 0 1 2 3 4 5
2960 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
2961 // 6 7 8 9 10 11 12 13 14
2962 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
2963 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
2965 if( !result )
2968 barGoLink bar( 1 );
2970 bar.step();
2972 sLog.outString();
2973 sLog.outString( ">> Loaded %u arenateam definitions", count );
2974 return;
2977 // load arena_team members
2978 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
2979 // 0 1 2 3 4 5 6 7 8
2980 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
2981 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
2983 barGoLink bar( result->GetRowCount() );
2987 Field *fields = result->Fetch();
2989 bar.step();
2990 ++count;
2992 ArenaTeam *newArenaTeam = new ArenaTeam;
2993 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
2994 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
2996 newArenaTeam->Disband(NULL);
2997 delete newArenaTeam;
2998 continue;
3000 AddArenaTeam(newArenaTeam);
3001 }while( result->NextRow() );
3003 delete result;
3004 delete arenaTeamMembersResult;
3006 sLog.outString();
3007 sLog.outString( ">> Loaded %u arenateam definitions", count );
3010 void ObjectMgr::LoadGroups()
3012 // -- loading groups --
3013 Group *group = NULL;
3014 uint64 leaderGuid = 0;
3015 uint32 count = 0;
3016 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3017 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid FROM groups");
3019 if( !result )
3021 barGoLink bar( 1 );
3023 bar.step();
3025 sLog.outString();
3026 sLog.outString( ">> Loaded %u group definitions", count );
3027 return;
3030 barGoLink bar( result->GetRowCount() );
3034 bar.step();
3035 Field *fields = result->Fetch();
3036 ++count;
3037 leaderGuid = MAKE_NEW_GUID(fields[16].GetUInt32(),0,HIGHGUID_PLAYER);
3039 group = new Group;
3040 if(!group->LoadGroupFromDB(leaderGuid, result, false))
3042 group->Disband();
3043 delete group;
3044 continue;
3046 AddGroup(group);
3047 }while( result->NextRow() );
3049 delete result;
3051 sLog.outString();
3052 sLog.outString( ">> Loaded %u group definitions", count );
3054 // -- loading members --
3055 count = 0;
3056 group = NULL;
3057 leaderGuid = 0;
3058 // 0 1 2 3
3059 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
3060 if(!result)
3062 barGoLink bar2( 1 );
3063 bar2.step();
3065 else
3067 barGoLink bar2( result->GetRowCount() );
3070 bar2.step();
3071 Field *fields = result->Fetch();
3072 count++;
3073 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
3074 if(!group || group->GetLeaderGUID() != leaderGuid)
3076 group = GetGroupByLeader(leaderGuid);
3077 if(!group)
3079 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
3080 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3081 continue;
3085 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
3087 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
3088 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3090 }while( result->NextRow() );
3091 delete result;
3094 // clean groups
3095 // TODO: maybe delete from the DB before loading in this case
3096 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
3098 if((*itr)->GetMembersCount() < 2)
3100 (*itr)->Disband();
3101 delete *itr;
3102 mGroupSet.erase(itr++);
3104 else
3105 ++itr;
3108 // -- loading instances --
3109 count = 0;
3110 group = NULL;
3111 leaderGuid = 0;
3112 result = CharacterDatabase.Query(
3113 // 0 1 2 3 4 5
3114 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
3115 // 6
3116 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
3117 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
3120 if(!result)
3122 barGoLink bar2( 1 );
3123 bar2.step();
3125 else
3127 barGoLink bar2( result->GetRowCount() );
3130 bar2.step();
3131 Field *fields = result->Fetch();
3132 count++;
3133 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3134 if(!group || group->GetLeaderGUID() != leaderGuid)
3136 group = GetGroupByLeader(leaderGuid);
3137 if(!group)
3139 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
3140 continue;
3144 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
3145 if(!mapEntry || !mapEntry->IsDungeon())
3147 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
3148 continue;
3151 uint32 diff = fields[4].GetUInt8();
3152 if(diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3154 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff);
3155 diff = 0; // default for both difficaly types
3158 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3159 group->BindToInstance(save, fields[3].GetBool(), true);
3160 }while( result->NextRow() );
3161 delete result;
3164 sLog.outString();
3165 sLog.outString( ">> Loaded %u group-instance binds total", count );
3167 sLog.outString();
3168 sLog.outString( ">> Loaded %u group members total", count );
3171 void ObjectMgr::LoadQuests()
3173 // For reload case
3174 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3175 delete itr->second;
3176 mQuestTemplates.clear();
3178 mExclusiveQuestGroups.clear();
3180 // 0 1 2 3 4 5 6 7 8
3181 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3182 // 9 10 11 12 13 14 15 16
3183 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3184 // 17 18 19 20 21 22 23 24 25 26 27 28
3185 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
3186 // 29 30 31 32 33 34 35 36 37 38
3187 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3188 // 39 40 41 42 43 44 45 46
3189 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
3190 // 47 48 49 50 51 52 53 54
3191 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3192 // 55 56 57 58 59 60 61 62
3193 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3194 // 63 64 65 66
3195 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3196 // 67 68 69 70 71 72
3197 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3198 // 73 74 75 76 77 78
3199 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3200 // 79 80 81 82 83 84 85 86
3201 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3202 // 87 88 89 90 91 92 93 94 95 96
3203 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3204 // 97 98 99 100 101 102 103 104 105 106 107
3205 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3206 // 108 109 110 111 112 113 114 115
3207 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3208 // 116 117 118 119 120 121
3209 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3210 // 122 123 124 125
3211 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3212 // 126 127
3213 "StartScript, CompleteScript"
3214 " FROM quest_template");
3215 if(result == NULL)
3217 barGoLink bar( 1 );
3218 bar.step();
3220 sLog.outString();
3221 sLog.outString( ">> Loaded 0 quests definitions" );
3222 sLog.outErrorDb("`quest_template` table is empty!");
3223 return;
3226 // create multimap previous quest for each existed quest
3227 // some quests can have many previous maps set by NextQuestId in previous quest
3228 // for example set of race quests can lead to single not race specific quest
3229 barGoLink bar( result->GetRowCount() );
3232 bar.step();
3233 Field *fields = result->Fetch();
3235 Quest * newQuest = new Quest(fields);
3236 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3237 } while( result->NextRow() );
3239 delete result;
3241 // Post processing
3242 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3244 Quest * qinfo = iter->second;
3246 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3248 if( qinfo->GetQuestMethod() >= 3 )
3250 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3253 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3255 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3256 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
3257 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3260 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3262 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3264 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3265 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3269 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3271 // at auto-reward can be rewarded only RewChoiceItemId[0]
3272 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3274 if(uint32 id = qinfo->RewChoiceItemId[j])
3276 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3277 qinfo->GetQuestId(),j+1,id,j+1);
3278 // no changes, quest ignore this data
3283 // client quest log visual (area case)
3284 if( qinfo->ZoneOrSort > 0 )
3286 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3288 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3289 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3290 // no changes, quest not dependent from this value but can have problems at client
3293 // client quest log visual (sort case)
3294 if( qinfo->ZoneOrSort < 0 )
3296 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3297 if( !qSort )
3299 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3300 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3301 // 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)
3303 //check SkillOrClass value (class case).
3304 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3306 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3307 if(qinfo->SkillOrClass < 0)
3309 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3310 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3313 //check for proper SkillOrClass value (skill case)
3314 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3316 // skill is positive value in SkillOrClass
3317 if(qinfo->SkillOrClass != skill_id )
3319 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3320 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3321 //override, and force proper value here?
3326 // SkillOrClass (class case)
3327 if( qinfo->SkillOrClass < 0 )
3329 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3331 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3332 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3335 // SkillOrClass (skill case)
3336 if( qinfo->SkillOrClass > 0 )
3338 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3340 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3341 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3345 if( qinfo->RequiredSkillValue )
3347 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3349 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3350 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3351 // no changes, quest can't be done for this requirement
3354 if( qinfo->SkillOrClass <= 0 )
3356 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3357 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3358 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3361 // else Skill quests can have 0 skill level, this is ok
3363 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3365 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3366 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3367 // no changes, quest can't be done for this requirement
3370 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3372 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3373 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3374 // no changes, quest can't be done for this requirement
3377 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3379 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3380 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3381 // no changes, quest can't be done for this requirement
3384 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3386 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3387 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3388 // no changes, quest can't be done for this requirement
3391 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3393 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3394 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3395 // no changes, quest can't be done for this requirement
3398 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3400 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3401 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3402 // warning
3405 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3407 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3408 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3409 // warning
3412 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3414 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3415 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3416 // warning
3419 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3421 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3422 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3423 qinfo->CharTitleId = 0;
3424 // quest can't reward this title
3427 if(qinfo->SrcItemId)
3429 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3431 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3432 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3433 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3435 else if(qinfo->SrcItemCount==0)
3437 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3438 qinfo->GetQuestId(),qinfo->SrcItemId);
3439 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3442 else if(qinfo->SrcItemCount>0)
3444 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3445 qinfo->GetQuestId(),qinfo->SrcItemCount);
3446 qinfo->SrcItemCount=0; // no quest work changes in fact
3449 if(qinfo->SrcSpell)
3451 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3452 if(!spellInfo)
3454 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3455 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3456 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3458 else if(!SpellMgr::IsSpellValid(spellInfo))
3460 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3461 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3462 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3466 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3468 uint32 id = qinfo->ReqItemId[j];
3469 if(id)
3471 if(qinfo->ReqItemCount[j]==0)
3473 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3474 qinfo->GetQuestId(),j+1,id,j+1);
3475 // no changes, quest can't be done for this requirement
3478 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3480 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3482 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3483 qinfo->GetQuestId(),j+1,id,id);
3484 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3487 else if(qinfo->ReqItemCount[j]>0)
3489 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3490 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3491 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3495 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3497 uint32 id = qinfo->ReqSourceId[j];
3498 if(id)
3500 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3502 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3503 qinfo->GetQuestId(),j+1,id,id);
3504 // no changes, quest can't be done for this requirement
3507 else
3509 if(qinfo->ReqSourceCount[j]>0)
3511 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3512 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3513 // no changes, quest ignore this data
3518 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3520 uint32 id = qinfo->ReqSpell[j];
3521 if(id)
3523 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3524 if(!spellInfo)
3526 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3527 qinfo->GetQuestId(),j+1,id,id);
3528 continue;
3531 if(!qinfo->ReqCreatureOrGOId[j])
3533 bool found = false;
3534 for(int k = 0; k < 3; ++k)
3536 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3537 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3539 found = true;
3540 break;
3544 if(found)
3546 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3548 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);
3550 // this will prevent quest completing without objective
3551 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3554 else
3556 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.",
3557 qinfo->GetQuestId(),j+1,id,j+1,id);
3558 // no changes, quest can't be done for this requirement
3564 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3566 int32 id = qinfo->ReqCreatureOrGOId[j];
3567 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3569 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3570 qinfo->GetQuestId(),j+1,id,uint32(-id));
3571 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3574 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3576 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3577 qinfo->GetQuestId(),j+1,id,uint32(id));
3578 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3581 if(id)
3583 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3585 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3587 if(!qinfo->ReqCreatureOrGOCount[j])
3589 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3590 qinfo->GetQuestId(),j+1,id,j+1);
3591 // no changes, quest can be incorrectly done, but we already report this
3594 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3596 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3597 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3598 // no changes, quest ignore this data
3602 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3604 uint32 id = qinfo->RewChoiceItemId[j];
3605 if(id)
3607 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3609 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3610 qinfo->GetQuestId(),j+1,id,id);
3611 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3614 if(!qinfo->RewChoiceItemCount[j])
3616 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3617 qinfo->GetQuestId(),j+1,id,j+1);
3618 // no changes, quest can't be done
3621 else if(qinfo->RewChoiceItemCount[j]>0)
3623 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3624 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3625 // no changes, quest ignore this data
3629 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3631 uint32 id = qinfo->RewItemId[j];
3632 if(id)
3634 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3636 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3637 qinfo->GetQuestId(),j+1,id,id);
3638 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3641 if(!qinfo->RewItemCount[j])
3643 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3644 qinfo->GetQuestId(),j+1,id,j+1);
3645 // no changes
3648 else if(qinfo->RewItemCount[j]>0)
3650 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3651 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3652 // no changes, quest ignore this data
3656 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3658 if(qinfo->RewRepFaction[j])
3660 if(!qinfo->RewRepValue[j])
3662 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3663 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3664 // no changes
3667 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3669 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.",
3670 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3671 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3674 else if(qinfo->RewRepValue[j]!=0)
3676 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3677 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3678 // no changes, quest ignore this data
3682 if(qinfo->RewSpell)
3684 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3686 if(!spellInfo)
3688 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3689 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3690 qinfo->RewSpell = 0; // no spell reward will display for this quest
3692 else if(!SpellMgr::IsSpellValid(spellInfo))
3694 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3695 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3696 qinfo->RewSpell = 0; // no spell reward will display for this quest
3698 else if(GetTalentSpellCost(qinfo->RewSpell))
3700 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3701 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3702 qinfo->RewSpell = 0; // no spell reward will display for this quest
3706 if(qinfo->RewSpellCast)
3708 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3710 if(!spellInfo)
3712 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3713 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3714 qinfo->RewSpellCast = 0; // no spell will be casted on player
3716 else if(!SpellMgr::IsSpellValid(spellInfo))
3718 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3719 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3720 qinfo->RewSpellCast = 0; // no spell will be casted on player
3722 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3724 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3725 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3726 qinfo->RewSpellCast = 0; // no spell will be casted on player
3730 if(qinfo->RewMailTemplateId)
3732 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3734 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3735 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3736 qinfo->RewMailTemplateId = 0; // no mail will send to player
3737 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3741 if(qinfo->NextQuestInChain)
3743 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3744 if(qNextItr == mQuestTemplates.end())
3746 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3747 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3748 qinfo->NextQuestInChain = 0;
3750 else
3751 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3754 // fill additional data stores
3755 if(qinfo->PrevQuestId)
3757 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3759 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3761 else
3763 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3767 if(qinfo->NextQuestId)
3769 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3770 if (qNextItr == mQuestTemplates.end())
3772 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3774 else
3776 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3777 qNextItr->second->prevQuests.push_back(signedQuestId);
3781 if(qinfo->ExclusiveGroup)
3782 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3783 if(qinfo->LimitTime)
3784 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3787 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3788 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3790 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3791 if(!spellInfo)
3792 continue;
3794 for(int j = 0; j < 3; ++j)
3796 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3797 continue;
3799 uint32 quest_id = spellInfo->EffectMiscValue[j];
3801 Quest const* quest = GetQuestTemplate(quest_id);
3803 // some quest referenced in spells not exist (outdated spells)
3804 if(!quest)
3805 continue;
3807 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3809 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);
3811 // this will prevent quest completing without objective
3812 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3817 sLog.outString();
3818 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3821 void ObjectMgr::LoadQuestLocales()
3823 mQuestLocaleMap.clear(); // need for reload case
3825 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3826 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3827 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3828 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3829 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3830 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3831 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3832 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3833 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3834 " FROM locales_quest"
3837 if(!result)
3839 barGoLink bar(1);
3841 bar.step();
3843 sLog.outString();
3844 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3845 return;
3848 barGoLink bar(result->GetRowCount());
3852 Field *fields = result->Fetch();
3853 bar.step();
3855 uint32 entry = fields[0].GetUInt32();
3857 QuestLocale& data = mQuestLocaleMap[entry];
3859 for(int i = 1; i < MAX_LOCALE; ++i)
3861 std::string str = fields[1+10*(i-1)].GetCppString();
3862 if(!str.empty())
3864 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3865 if(idx >= 0)
3867 if(data.Title.size() <= idx)
3868 data.Title.resize(idx+1);
3870 data.Title[idx] = str;
3873 str = fields[1+10*(i-1)+1].GetCppString();
3874 if(!str.empty())
3876 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3877 if(idx >= 0)
3879 if(data.Details.size() <= idx)
3880 data.Details.resize(idx+1);
3882 data.Details[idx] = str;
3885 str = fields[1+10*(i-1)+2].GetCppString();
3886 if(!str.empty())
3888 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3889 if(idx >= 0)
3891 if(data.Objectives.size() <= idx)
3892 data.Objectives.resize(idx+1);
3894 data.Objectives[idx] = str;
3897 str = fields[1+10*(i-1)+3].GetCppString();
3898 if(!str.empty())
3900 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3901 if(idx >= 0)
3903 if(data.OfferRewardText.size() <= idx)
3904 data.OfferRewardText.resize(idx+1);
3906 data.OfferRewardText[idx] = str;
3909 str = fields[1+10*(i-1)+4].GetCppString();
3910 if(!str.empty())
3912 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3913 if(idx >= 0)
3915 if(data.RequestItemsText.size() <= idx)
3916 data.RequestItemsText.resize(idx+1);
3918 data.RequestItemsText[idx] = str;
3921 str = fields[1+10*(i-1)+5].GetCppString();
3922 if(!str.empty())
3924 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3925 if(idx >= 0)
3927 if(data.EndText.size() <= idx)
3928 data.EndText.resize(idx+1);
3930 data.EndText[idx] = str;
3933 for(int k = 0; k < 4; ++k)
3935 str = fields[1+10*(i-1)+6+k].GetCppString();
3936 if(!str.empty())
3938 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3939 if(idx >= 0)
3941 if(data.ObjectiveText[k].size() <= idx)
3942 data.ObjectiveText[k].resize(idx+1);
3944 data.ObjectiveText[k][idx] = str;
3949 } while (result->NextRow());
3951 delete result;
3953 sLog.outString();
3954 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3957 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3959 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3960 return;
3962 sLog.outString( "%s :", tablename);
3964 scripts.clear(); // need for reload support
3966 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3968 uint32 count = 0;
3970 if( !result )
3972 barGoLink bar( 1 );
3973 bar.step();
3975 sLog.outString();
3976 sLog.outString( ">> Loaded %u script definitions", count );
3977 return;
3980 barGoLink bar( result->GetRowCount() );
3984 bar.step();
3986 Field *fields = result->Fetch();
3987 ScriptInfo tmp;
3988 tmp.id = fields[0].GetUInt32();
3989 tmp.delay = fields[1].GetUInt32();
3990 tmp.command = fields[2].GetUInt32();
3991 tmp.datalong = fields[3].GetUInt32();
3992 tmp.datalong2 = fields[4].GetUInt32();
3993 tmp.dataint = fields[5].GetInt32();
3994 tmp.x = fields[6].GetFloat();
3995 tmp.y = fields[7].GetFloat();
3996 tmp.z = fields[8].GetFloat();
3997 tmp.o = fields[9].GetFloat();
3999 // generic command args check
4000 switch(tmp.command)
4002 case SCRIPT_COMMAND_TALK:
4004 if(tmp.datalong > 3)
4006 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4007 continue;
4009 if(tmp.dataint==0)
4011 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4012 continue;
4014 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4016 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);
4017 continue;
4020 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4021 break;
4024 case SCRIPT_COMMAND_EMOTE:
4026 if(!sEmotesStore.LookupEntry(tmp.datalong))
4028 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4029 continue;
4031 break;
4034 case SCRIPT_COMMAND_TELEPORT_TO:
4036 if(!sMapStore.LookupEntry(tmp.datalong))
4038 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4039 continue;
4042 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4044 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);
4045 continue;
4047 break;
4050 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4052 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4054 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);
4055 continue;
4058 if(!GetCreatureTemplate(tmp.datalong))
4060 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4061 continue;
4063 break;
4066 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4068 GameObjectData const* data = GetGOData(tmp.datalong);
4069 if(!data)
4071 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4072 continue;
4075 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4076 if(!info)
4078 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);
4079 continue;
4082 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4083 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4084 info->type==GAMEOBJECT_TYPE_DOOR ||
4085 info->type==GAMEOBJECT_TYPE_BUTTON ||
4086 info->type==GAMEOBJECT_TYPE_TRAP )
4088 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4089 continue;
4091 break;
4093 case SCRIPT_COMMAND_OPEN_DOOR:
4094 case SCRIPT_COMMAND_CLOSE_DOOR:
4096 GameObjectData const* data = GetGOData(tmp.datalong);
4097 if(!data)
4099 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);
4100 continue;
4103 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4104 if(!info)
4106 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);
4107 continue;
4110 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4112 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);
4113 continue;
4116 break;
4118 case SCRIPT_COMMAND_QUEST_EXPLORED:
4120 Quest const* quest = GetQuestTemplate(tmp.datalong);
4121 if(!quest)
4123 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);
4124 continue;
4127 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4129 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);
4131 // this will prevent quest completing without objective
4132 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4134 // continue; - quest objective requirement set and command can be allowed
4137 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4139 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",
4140 tablename,tmp.datalong2,tmp.id);
4141 continue;
4144 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4146 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",
4147 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4148 continue;
4151 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4153 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",
4154 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4155 continue;
4158 break;
4161 case SCRIPT_COMMAND_REMOVE_AURA:
4163 if(!sSpellStore.LookupEntry(tmp.datalong))
4165 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4166 tablename,tmp.datalong,tmp.id);
4167 continue;
4169 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4171 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4172 tablename,tmp.datalong2,tmp.id);
4173 continue;
4175 break;
4177 case SCRIPT_COMMAND_CAST_SPELL:
4179 if(!sSpellStore.LookupEntry(tmp.datalong))
4181 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4182 tablename,tmp.datalong,tmp.id);
4183 continue;
4185 if(tmp.datalong2 & ~0x3) // 2 bits
4187 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4188 tablename,tmp.datalong2,tmp.id);
4189 continue;
4191 break;
4195 if (scripts.find(tmp.id) == scripts.end())
4197 ScriptMap emptyMap;
4198 scripts[tmp.id] = emptyMap;
4200 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4202 ++count;
4203 } while( result->NextRow() );
4205 delete result;
4207 sLog.outString();
4208 sLog.outString( ">> Loaded %u script definitions", count );
4211 void ObjectMgr::LoadGameObjectScripts()
4213 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4215 // check ids
4216 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4218 if(!GetGOData(itr->first))
4219 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4223 void ObjectMgr::LoadQuestEndScripts()
4225 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4227 // check ids
4228 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4230 if(!GetQuestTemplate(itr->first))
4231 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4235 void ObjectMgr::LoadQuestStartScripts()
4237 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4239 // check ids
4240 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4242 if(!GetQuestTemplate(itr->first))
4243 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4247 void ObjectMgr::LoadSpellScripts()
4249 LoadScripts(sSpellScripts, "spell_scripts");
4251 // check ids
4252 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4254 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4256 if(!spellInfo)
4258 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4259 continue;
4262 //check for correct spellEffect
4263 bool found = false;
4264 for(int i=0; i<3; ++i)
4266 // skip empty effects
4267 if( !spellInfo->Effect[i] )
4268 continue;
4270 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4272 found = true;
4273 break;
4277 if(!found)
4278 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4282 void ObjectMgr::LoadEventScripts()
4284 LoadScripts(sEventScripts, "event_scripts");
4286 std::set<uint32> evt_scripts;
4287 // Load all possible script entries from gameobjects
4288 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4290 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4291 if (goInfo)
4293 switch(goInfo->type)
4295 case GAMEOBJECT_TYPE_GOOBER:
4296 if (goInfo->goober.eventId)
4297 evt_scripts.insert(goInfo->goober.eventId);
4298 break;
4299 case GAMEOBJECT_TYPE_CHEST:
4300 if (goInfo->chest.eventId)
4301 evt_scripts.insert(goInfo->chest.eventId);
4302 break;
4303 case GAMEOBJECT_TYPE_CAMERA:
4304 if (goInfo->camera.eventID)
4305 evt_scripts.insert(goInfo->camera.eventID);
4306 default:
4307 break;
4311 // Load all possible script entries from spells
4312 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4314 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4315 if (spell)
4317 for(int j=0; j<3; ++j)
4319 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4321 if (spell->EffectMiscValue[j])
4322 evt_scripts.insert(spell->EffectMiscValue[j]);
4327 // Then check if all scripts are in above list of possible script entries
4328 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4330 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4331 if (itr2 == evt_scripts.end())
4332 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect %u",
4333 itr->first, SPELL_EFFECT_SEND_EVENT);
4337 void ObjectMgr::LoadItemTexts()
4339 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4341 uint32 count = 0;
4343 if( !result )
4345 barGoLink bar( 1 );
4346 bar.step();
4348 sLog.outString();
4349 sLog.outString( ">> Loaded %u item pages", count );
4350 return;
4353 barGoLink bar( result->GetRowCount() );
4355 Field* fields;
4358 bar.step();
4360 fields = result->Fetch();
4362 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4364 ++count;
4366 } while ( result->NextRow() );
4368 delete result;
4370 sLog.outString();
4371 sLog.outString( ">> Loaded %u item texts", count );
4374 void ObjectMgr::LoadPageTexts()
4376 sPageTextStore.Free(); // for reload case
4378 sPageTextStore.Load();
4379 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4380 sLog.outString();
4382 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4384 // check data correctness
4385 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4386 if(!page)
4387 continue;
4389 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4391 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4392 continue;
4395 // detect circular reference
4396 std::set<uint32> checkedPages;
4397 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4399 if(!pageItr->Next_Page)
4400 break;
4401 checkedPages.insert(pageItr->Page_ID);
4402 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4404 std::ostringstream ss;
4405 ss<< "The text page(s) ";
4406 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4407 ss << *itr << " ";
4408 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4409 << pageItr->Page_ID <<" to 0";
4410 sLog.outErrorDb(ss.str().c_str());
4411 const_cast<PageText*>(pageItr)->Next_Page = 0;
4412 break;
4418 void ObjectMgr::LoadPageTextLocales()
4420 mPageTextLocaleMap.clear(); // need for reload case
4422 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");
4424 if(!result)
4426 barGoLink bar(1);
4428 bar.step();
4430 sLog.outString();
4431 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4432 return;
4435 barGoLink bar(result->GetRowCount());
4439 Field *fields = result->Fetch();
4440 bar.step();
4442 uint32 entry = fields[0].GetUInt32();
4444 PageTextLocale& data = mPageTextLocaleMap[entry];
4446 for(int i = 1; i < MAX_LOCALE; ++i)
4448 std::string str = fields[i].GetCppString();
4449 if(str.empty())
4450 continue;
4452 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4453 if(idx >= 0)
4455 if(data.Text.size() <= idx)
4456 data.Text.resize(idx+1);
4458 data.Text[idx] = str;
4462 } while (result->NextRow());
4464 delete result;
4466 sLog.outString();
4467 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4470 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4472 template<class D>
4473 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4475 dst = D(objmgr.GetScriptId(src));
4479 void ObjectMgr::LoadInstanceTemplate()
4481 SQLInstanceLoader loader;
4482 loader.Load(sInstanceTemplate);
4484 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4486 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4487 if(!temp)
4488 continue;
4490 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4491 if(!entry)
4493 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4494 continue;
4497 //FIXME: now exist heroic instance, normal/heroic raid instances
4498 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4499 // entry->resetTimeRaid store reset time for normal raid only
4500 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4501 // but at some point wee need implement reset time dependent from raid instance mode
4502 if(temp->reset_delay == 0)
4504 MapDifficulty const* mapDiffNorm = GetMapDifficultyData(temp->map,DUNGEON_DIFFICULTY_NORMAL);
4505 MapDifficulty const* mapDiffHeroic = GetMapDifficultyData(temp->map,DUNGEON_DIFFICULTY_HEROIC);
4507 // no reset time
4508 if ((!mapDiffNorm || mapDiffNorm->resetTime == 0) &&
4509 (!mapDiffHeroic || mapDiffHeroic->resetTime == 0))
4510 continue;
4512 // use defaults from the DBC
4513 if(mapDiffHeroic && mapDiffHeroic->resetTime) // for both raid and non raids, read above
4515 temp->reset_delay = mapDiffHeroic->resetTime / DAY;
4517 else if (mapDiffNorm && mapDiffNorm->resetTime && entry->map_type == MAP_RAID)
4518 // for normal raid only
4520 temp->reset_delay = mapDiffNorm->resetTime / DAY;
4524 // the reset_delay must be at least one day
4525 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4528 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4529 sLog.outString();
4532 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4534 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4535 if(itr != mGossipText.end())
4536 return &itr->second;
4537 return NULL;
4540 void ObjectMgr::LoadGossipText()
4542 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4544 int count = 0;
4545 if( !result )
4547 barGoLink bar( 1 );
4548 bar.step();
4550 sLog.outString();
4551 sLog.outString( ">> Loaded %u npc texts", count );
4552 return;
4555 int cic;
4557 barGoLink bar( result->GetRowCount() );
4561 ++count;
4562 cic = 0;
4564 Field *fields = result->Fetch();
4566 bar.step();
4568 uint32 Text_ID = fields[cic++].GetUInt32();
4569 if(!Text_ID)
4571 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4572 continue;
4575 GossipText& gText = mGossipText[Text_ID];
4577 for (int i=0; i< 8; i++)
4579 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4580 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4582 gText.Options[i].Language = fields[cic++].GetUInt32();
4583 gText.Options[i].Probability = fields[cic++].GetFloat();
4585 for(int j=0; j < 3; ++j)
4587 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4588 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4591 } while( result->NextRow() );
4593 sLog.outString();
4594 sLog.outString( ">> Loaded %u npc texts", count );
4595 delete result;
4598 void ObjectMgr::LoadNpcTextLocales()
4600 mNpcTextLocaleMap.clear(); // need for reload case
4602 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4603 "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,"
4604 "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,"
4605 "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,"
4606 "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,"
4607 "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,"
4608 "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,"
4609 "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, "
4610 "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 "
4611 " FROM locales_npc_text");
4613 if(!result)
4615 barGoLink bar(1);
4617 bar.step();
4619 sLog.outString();
4620 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4621 return;
4624 barGoLink bar(result->GetRowCount());
4628 Field *fields = result->Fetch();
4629 bar.step();
4631 uint32 entry = fields[0].GetUInt32();
4633 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4635 for(int i=1; i<MAX_LOCALE; ++i)
4637 for(int j=0; j<8; ++j)
4639 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4640 if(!str0.empty())
4642 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4643 if(idx >= 0)
4645 if(data.Text_0[j].size() <= idx)
4646 data.Text_0[j].resize(idx+1);
4648 data.Text_0[j][idx] = str0;
4651 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4652 if(!str1.empty())
4654 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4655 if(idx >= 0)
4657 if(data.Text_1[j].size() <= idx)
4658 data.Text_1[j].resize(idx+1);
4660 data.Text_1[j][idx] = str1;
4665 } while (result->NextRow());
4667 delete result;
4669 sLog.outString();
4670 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4673 //not very fast function but it is called only once a day, or on starting-up
4674 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4676 time_t basetime = time(NULL);
4677 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4678 //delete all old mails without item and without body immediately, if starting server
4679 if (!serverUp)
4680 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4681 // 0 1 2 3 4 5 6 7 8 9
4682 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime);
4683 if ( !result )
4685 barGoLink bar(1);
4686 bar.step();
4687 sLog.outString();
4688 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4689 return; // any mails need to be returned or deleted
4692 //std::ostringstream delitems, delmails; //will be here for optimization
4693 //bool deletemail = false, deleteitem = false;
4694 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4695 //delmails << "DELETE FROM mail WHERE id IN ( "
4697 barGoLink bar( result->GetRowCount() );
4698 uint32 count = 0;
4699 Field *fields;
4703 bar.step();
4705 fields = result->Fetch();
4706 Mail *m = new Mail;
4707 m->messageID = fields[0].GetUInt32();
4708 m->messageType = fields[1].GetUInt8();
4709 m->sender = fields[2].GetUInt32();
4710 m->receiver = fields[3].GetUInt32();
4711 m->itemTextId = fields[4].GetUInt32();
4712 bool has_items = fields[5].GetBool();
4713 m->expire_time = (time_t)fields[6].GetUInt64();
4714 m->deliver_time = 0;
4715 m->COD = fields[7].GetUInt32();
4716 m->checked = fields[8].GetUInt32();
4717 m->mailTemplateId = fields[9].GetInt16();
4719 Player *pl = 0;
4720 if (serverUp)
4721 pl = GetPlayer((uint64)m->receiver);
4722 if (pl && pl->m_mailsLoaded)
4723 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4724 //his in mailbox and he has already listed his mails )
4725 delete m;
4726 continue;
4728 //delete or return mail:
4729 if (has_items)
4731 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4732 if(resultItems)
4736 Field *fields2 = resultItems->Fetch();
4738 uint32 item_guid_low = fields2[0].GetUInt32();
4739 uint32 item_template = fields2[1].GetUInt32();
4741 m->AddItem(item_guid_low, item_template);
4743 while (resultItems->NextRow());
4745 delete resultItems;
4747 //if it is mail from AH, it shouldn't be returned, but deleted
4748 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4750 // mail open and then not returned
4751 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4752 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4754 else
4756 //mail will be returned:
4757 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4758 delete m;
4759 continue;
4763 if (m->itemTextId)
4764 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4766 //deletemail = true;
4767 //delmails << m->messageID << ", ";
4768 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4769 delete m;
4770 ++count;
4771 } while (result->NextRow());
4772 delete result;
4774 sLog.outString();
4775 sLog.outString( ">> Loaded %u mails", count );
4778 void ObjectMgr::LoadQuestAreaTriggers()
4780 mQuestAreaTriggerMap.clear(); // need for reload case
4782 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4784 uint32 count = 0;
4786 if( !result )
4788 barGoLink bar( 1 );
4789 bar.step();
4791 sLog.outString();
4792 sLog.outString( ">> Loaded %u quest trigger points", count );
4793 return;
4796 barGoLink bar( result->GetRowCount() );
4800 ++count;
4801 bar.step();
4803 Field *fields = result->Fetch();
4805 uint32 trigger_ID = fields[0].GetUInt32();
4806 uint32 quest_ID = fields[1].GetUInt32();
4808 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4809 if(!atEntry)
4811 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4812 continue;
4815 Quest const* quest = GetQuestTemplate(quest_ID);
4817 if(!quest)
4819 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4820 continue;
4823 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4825 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);
4827 // this will prevent quest completing without objective
4828 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4830 // continue; - quest modified to required objective and trigger can be allowed.
4833 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4835 } while( result->NextRow() );
4837 delete result;
4839 sLog.outString();
4840 sLog.outString( ">> Loaded %u quest trigger points", count );
4843 void ObjectMgr::LoadTavernAreaTriggers()
4845 mTavernAreaTriggerSet.clear(); // need for reload case
4847 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4849 uint32 count = 0;
4851 if( !result )
4853 barGoLink bar( 1 );
4854 bar.step();
4856 sLog.outString();
4857 sLog.outString( ">> Loaded %u tavern triggers", count );
4858 return;
4861 barGoLink bar( result->GetRowCount() );
4865 ++count;
4866 bar.step();
4868 Field *fields = result->Fetch();
4870 uint32 Trigger_ID = fields[0].GetUInt32();
4872 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4873 if(!atEntry)
4875 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4876 continue;
4879 mTavernAreaTriggerSet.insert(Trigger_ID);
4880 } while( result->NextRow() );
4882 delete result;
4884 sLog.outString();
4885 sLog.outString( ">> Loaded %u tavern triggers", count );
4888 void ObjectMgr::LoadAreaTriggerScripts()
4890 mAreaTriggerScripts.clear(); // need for reload case
4891 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4893 uint32 count = 0;
4895 if( !result )
4897 barGoLink bar( 1 );
4898 bar.step();
4900 sLog.outString();
4901 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4902 return;
4905 barGoLink bar( result->GetRowCount() );
4909 ++count;
4910 bar.step();
4912 Field *fields = result->Fetch();
4914 uint32 Trigger_ID = fields[0].GetUInt32();
4915 const char *scriptName = fields[1].GetString();
4917 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4918 if(!atEntry)
4920 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4921 continue;
4923 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4924 } while( result->NextRow() );
4926 delete result;
4928 sLog.outString();
4929 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4932 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4934 bool found = false;
4935 float dist;
4936 uint32 id = 0;
4938 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4940 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4941 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4942 continue;
4944 uint8 field = (uint8)((i - 1) / 32);
4945 uint32 submask = 1<<((i-1)%32);
4947 // skip not taxi network nodes
4948 if((sTaxiNodesMask[field] & submask)==0)
4949 continue;
4951 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4952 if(found)
4954 if(dist2 < dist)
4956 dist = dist2;
4957 id = i;
4960 else
4962 found = true;
4963 dist = dist2;
4964 id = i;
4968 return id;
4971 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4973 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4974 if(src_i==sTaxiPathSetBySource.end())
4976 path = 0;
4977 cost = 0;
4978 return;
4981 TaxiPathSetForSource& pathSet = src_i->second;
4983 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4984 if(dest_i==pathSet.end())
4986 path = 0;
4987 cost = 0;
4988 return;
4991 cost = dest_i->second.price;
4992 path = dest_i->second.ID;
4995 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
4997 uint16 mount_entry = 0;
4999 // select mount creature id
5000 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5001 if(node)
5003 if (team == ALLIANCE)
5005 mount_entry = node->MountCreatureID[1];
5006 if(!mount_entry && allowed_alt_team)
5007 mount_entry = node->MountCreatureID[0];
5009 else if (team == HORDE)
5011 mount_entry = node->MountCreatureID[0];
5013 if(!mount_entry && allowed_alt_team)
5014 mount_entry = node->MountCreatureID[1];
5018 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5019 if (!mount_info)
5020 return 0;
5022 uint16 mount_id = objmgr.ChooseDisplayId(team,mount_info);
5023 if (!mount_id)
5024 return 0;
5026 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(mount_id);
5027 if (minfo)
5028 mount_id = minfo->modelid;
5030 return mount_id;
5033 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5035 if(path >= sTaxiPathNodesByPath.size())
5036 return;
5038 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5040 pathnodes.Resize(nodeList.size());
5041 mapIds.resize(nodeList.size());
5043 for(size_t i = 0; i < nodeList.size(); ++i)
5045 pathnodes[ i ].x = nodeList[i].x;
5046 pathnodes[ i ].y = nodeList[i].y;
5047 pathnodes[ i ].z = nodeList[i].z;
5049 mapIds[i] = nodeList[i].mapid;
5053 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5055 if(path >= sTaxiPathNodesByPath.size())
5056 return;
5058 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5060 pathnodes.Resize(nodeList.size());
5062 for(size_t i = 0; i < nodeList.size(); ++i)
5064 pathnodes[ i ].mapid = nodeList[i].mapid;
5065 pathnodes[ i ].x = nodeList[i].x;
5066 pathnodes[ i ].y = nodeList[i].y;
5067 pathnodes[ i ].z = nodeList[i].z;
5068 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5069 pathnodes[ i ].delay = nodeList[i].delay;
5073 void ObjectMgr::LoadGraveyardZones()
5075 mGraveYardMap.clear(); // need for reload case
5077 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5079 uint32 count = 0;
5081 if( !result )
5083 barGoLink bar( 1 );
5084 bar.step();
5086 sLog.outString();
5087 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5088 return;
5091 barGoLink bar( result->GetRowCount() );
5095 ++count;
5096 bar.step();
5098 Field *fields = result->Fetch();
5100 uint32 safeLocId = fields[0].GetUInt32();
5101 uint32 zoneId = fields[1].GetUInt32();
5102 uint32 team = fields[2].GetUInt32();
5104 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5105 if(!entry)
5107 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5108 continue;
5111 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5112 if(!areaEntry)
5114 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5115 continue;
5118 if(areaEntry->zone != 0)
5120 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5121 continue;
5124 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5126 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5127 continue;
5130 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5131 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5132 } while( result->NextRow() );
5134 delete result;
5136 sLog.outString();
5137 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5140 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5142 // search for zone associated closest graveyard
5143 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
5145 // Simulate std. algorithm:
5146 // found some graveyard associated to (ghost_zone,ghost_map)
5148 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5149 // then check faction
5150 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5151 // then check faction
5152 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5153 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5154 if(graveLow==graveUp)
5156 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5157 return NULL;
5160 // at corpse map
5161 bool foundNear = false;
5162 float distNear;
5163 WorldSafeLocsEntry const* entryNear = NULL;
5165 // at entrance map for corpse map
5166 bool foundEntr = false;
5167 float distEntr;
5168 WorldSafeLocsEntry const* entryEntr = NULL;
5170 // some where other
5171 WorldSafeLocsEntry const* entryFar = NULL;
5173 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5175 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5177 GraveYardData const& data = itr->second;
5179 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5180 if(!entry)
5182 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5183 continue;
5186 // skip enemy faction graveyard
5187 // team == 0 case can be at call from .neargrave
5188 if(data.team != 0 && team != 0 && data.team != team)
5189 continue;
5191 // find now nearest graveyard at other map
5192 if(MapId != entry->map_id)
5194 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5195 if (!mapEntry ||
5196 mapEntry->entrance_map < 0 ||
5197 mapEntry->entrance_map != entry->map_id ||
5198 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5200 // not have any corrdinates for check distance anyway
5201 entryFar = entry;
5202 continue;
5205 // at entrance map calculate distance (2D);
5206 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5207 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5208 if(foundEntr)
5210 if(dist2 < distEntr)
5212 distEntr = dist2;
5213 entryEntr = entry;
5216 else
5218 foundEntr = true;
5219 distEntr = dist2;
5220 entryEntr = entry;
5223 // find now nearest graveyard at same map
5224 else
5226 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5227 if(foundNear)
5229 if(dist2 < distNear)
5231 distNear = dist2;
5232 entryNear = entry;
5235 else
5237 foundNear = true;
5238 distNear = dist2;
5239 entryNear = entry;
5244 if(entryNear)
5245 return entryNear;
5247 if(entryEntr)
5248 return entryEntr;
5250 return entryFar;
5253 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5255 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5256 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5258 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5260 if(itr->second.safeLocId==id)
5261 return &itr->second;
5264 return NULL;
5267 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5269 if(FindGraveYardData(id,zoneId))
5270 return false;
5272 // add link to loaded data
5273 GraveYardData data;
5274 data.safeLocId = id;
5275 data.team = team;
5277 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5279 // add link to DB
5280 if(inDB)
5282 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5283 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5286 return true;
5289 void ObjectMgr::LoadAreaTriggerTeleports()
5291 mAreaTriggers.clear(); // need for reload case
5293 uint32 count = 0;
5295 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5296 QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_quest_done_heroic, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
5297 if( !result )
5300 barGoLink bar( 1 );
5302 bar.step();
5304 sLog.outString();
5305 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5306 return;
5309 barGoLink bar( result->GetRowCount() );
5313 Field *fields = result->Fetch();
5315 bar.step();
5317 ++count;
5319 uint32 Trigger_ID = fields[0].GetUInt32();
5321 AreaTrigger at;
5323 at.requiredLevel = fields[1].GetUInt8();
5324 at.requiredItem = fields[2].GetUInt32();
5325 at.requiredItem2 = fields[3].GetUInt32();
5326 at.heroicKey = fields[4].GetUInt32();
5327 at.heroicKey2 = fields[5].GetUInt32();
5328 at.requiredQuest = fields[6].GetUInt32();
5329 at.requiredQuestHeroic = fields[7].GetUInt32();
5330 at.requiredFailedText = fields[8].GetCppString();
5331 at.target_mapId = fields[9].GetUInt32();
5332 at.target_X = fields[10].GetFloat();
5333 at.target_Y = fields[11].GetFloat();
5334 at.target_Z = fields[12].GetFloat();
5335 at.target_Orientation = fields[13].GetFloat();
5337 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5338 if(!atEntry)
5340 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5341 continue;
5344 if(at.requiredItem)
5346 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5347 if(!pProto)
5349 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5350 at.requiredItem = 0;
5353 if(at.requiredItem2)
5355 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5356 if(!pProto)
5358 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5359 at.requiredItem2 = 0;
5363 if(at.heroicKey)
5365 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5366 if(!pProto)
5368 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5369 at.heroicKey = 0;
5373 if(at.heroicKey2)
5375 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5376 if(!pProto)
5378 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5379 at.heroicKey2 = 0;
5383 if(at.requiredQuest)
5385 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5386 if(qReqItr == mQuestTemplates.end())
5388 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5389 at.requiredQuest = 0;
5393 if(at.requiredQuestHeroic)
5395 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5396 if(qReqItr == mQuestTemplates.end())
5398 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5399 at.requiredQuestHeroic = 0;
5403 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5404 if(!mapEntry)
5406 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5407 continue;
5410 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5412 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5413 continue;
5416 mAreaTriggers[Trigger_ID] = at;
5418 } while( result->NextRow() );
5420 delete result;
5422 sLog.outString();
5423 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5427 * Searches for the areatrigger which teleports players out of the given map
5429 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5431 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5432 if(!mapEntry) return NULL;
5433 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5435 if(itr->second.target_mapId == mapEntry->entrance_map)
5437 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5438 if(atEntry && atEntry->mapid == Map)
5439 return &itr->second;
5442 return NULL;
5446 * Searches for the areatrigger which teleports players to the given map
5448 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5450 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5452 if(itr->second.target_mapId == Map)
5454 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5455 if(atEntry)
5456 return &itr->second;
5459 return NULL;
5462 void ObjectMgr::SetHighestGuids()
5464 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5465 if( result )
5467 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5468 delete result;
5471 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5472 if( result )
5474 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5475 delete result;
5478 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5479 if( result )
5481 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5482 delete result;
5485 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5486 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5487 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5488 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5489 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5491 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5492 if( result )
5494 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5495 delete result;
5498 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5499 if( result )
5501 m_auctionid = (*result)[0].GetUInt32()+1;
5502 delete result;
5505 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5506 if( result )
5508 m_mailid = (*result)[0].GetUInt32()+1;
5509 delete result;
5512 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5513 if( result )
5515 m_ItemTextId = (*result)[0].GetUInt32()+1;
5516 delete result;
5519 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5520 if( result )
5522 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5523 delete result;
5526 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5527 if (result)
5529 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5530 delete result;
5533 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5534 if (result)
5536 m_equipmentSetGuid = (*result)[0].GetUInt64()+1;
5537 delete result;
5540 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5541 if (result)
5543 m_guildId = (*result)[0].GetUInt32()+1;
5544 delete result;
5548 uint32 ObjectMgr::GenerateArenaTeamId()
5550 if(m_arenaTeamId>=0xFFFFFFFE)
5552 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5553 World::StopNow(ERROR_EXIT_CODE);
5555 return m_arenaTeamId++;
5558 uint32 ObjectMgr::GenerateAuctionID()
5560 if(m_auctionid>=0xFFFFFFFE)
5562 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5563 World::StopNow(ERROR_EXIT_CODE);
5565 return m_auctionid++;
5568 uint64 ObjectMgr::GenerateEquipmentSetGuid()
5570 if(m_equipmentSetGuid>=0xFFFFFFFFFFFFFFFEll)
5572 sLog.outError("EquipmentSet guid overflow!! Can't continue, shutting down server. ");
5573 World::StopNow(ERROR_EXIT_CODE);
5575 return m_equipmentSetGuid++;
5578 uint32 ObjectMgr::GenerateGuildId()
5580 if(m_guildId>=0xFFFFFFFE)
5582 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5583 World::StopNow(ERROR_EXIT_CODE);
5585 return m_guildId++;
5588 uint32 ObjectMgr::GenerateMailID()
5590 if(m_mailid>=0xFFFFFFFE)
5592 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5593 World::StopNow(ERROR_EXIT_CODE);
5595 return m_mailid++;
5598 uint32 ObjectMgr::GenerateItemTextID()
5600 if(m_ItemTextId>=0xFFFFFFFE)
5602 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5603 World::StopNow(ERROR_EXIT_CODE);
5605 return m_ItemTextId++;
5608 uint32 ObjectMgr::CreateItemText(std::string text)
5610 uint32 newItemTextId = GenerateItemTextID();
5611 //insert new itempage to container
5612 mItemTexts[ newItemTextId ] = text;
5613 //save new itempage
5614 CharacterDatabase.escape_string(text);
5615 //any Delete query needed, itemTextId is maximum of all ids
5616 std::ostringstream query;
5617 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5618 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5619 return newItemTextId;
5622 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5624 switch(guidhigh)
5626 case HIGHGUID_ITEM:
5627 if(m_hiItemGuid>=0xFFFFFFFE)
5629 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5630 World::StopNow(ERROR_EXIT_CODE);
5632 return m_hiItemGuid++;
5633 case HIGHGUID_UNIT:
5634 if(m_hiCreatureGuid>=0x00FFFFFE)
5636 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5637 World::StopNow(ERROR_EXIT_CODE);
5639 return m_hiCreatureGuid++;
5640 case HIGHGUID_PET:
5641 if(m_hiPetGuid>=0x00FFFFFE)
5643 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5644 World::StopNow(ERROR_EXIT_CODE);
5646 return m_hiPetGuid++;
5647 case HIGHGUID_VEHICLE:
5648 if(m_hiVehicleGuid>=0x00FFFFFF)
5650 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5651 World::StopNow(ERROR_EXIT_CODE);
5653 return m_hiVehicleGuid++;
5654 case HIGHGUID_PLAYER:
5655 if(m_hiCharGuid>=0xFFFFFFFE)
5657 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5658 World::StopNow(ERROR_EXIT_CODE);
5660 return m_hiCharGuid++;
5661 case HIGHGUID_GAMEOBJECT:
5662 if(m_hiGoGuid>=0x00FFFFFE)
5664 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5665 World::StopNow(ERROR_EXIT_CODE);
5667 return m_hiGoGuid++;
5668 case HIGHGUID_CORPSE:
5669 if(m_hiCorpseGuid>=0xFFFFFFFE)
5671 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5672 World::StopNow(ERROR_EXIT_CODE);
5674 return m_hiCorpseGuid++;
5675 case HIGHGUID_DYNAMICOBJECT:
5676 if(m_hiDoGuid>=0xFFFFFFFE)
5678 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5679 World::StopNow(ERROR_EXIT_CODE);
5681 return m_hiDoGuid++;
5682 default:
5683 ASSERT(0);
5686 ASSERT(0);
5687 return 0;
5690 void ObjectMgr::LoadGameObjectLocales()
5692 mGameObjectLocaleMap.clear(); // need for reload case
5694 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5695 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5696 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5697 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5699 if(!result)
5701 barGoLink bar(1);
5703 bar.step();
5705 sLog.outString();
5706 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5707 return;
5710 barGoLink bar(result->GetRowCount());
5714 Field *fields = result->Fetch();
5715 bar.step();
5717 uint32 entry = fields[0].GetUInt32();
5719 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5721 for(int i = 1; i < MAX_LOCALE; ++i)
5723 std::string str = fields[i].GetCppString();
5724 if(!str.empty())
5726 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5727 if(idx >= 0)
5729 if(data.Name.size() <= idx)
5730 data.Name.resize(idx+1);
5732 data.Name[idx] = str;
5737 for(int i = 1; i < MAX_LOCALE; ++i)
5739 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5740 if(!str.empty())
5742 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5743 if(idx >= 0)
5745 if(data.CastBarCaption.size() <= idx)
5746 data.CastBarCaption.resize(idx+1);
5748 data.CastBarCaption[idx] = str;
5753 } while (result->NextRow());
5755 delete result;
5757 sLog.outString();
5758 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5761 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5763 template<class D>
5764 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5766 dst = D(objmgr.GetScriptId(src));
5770 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5772 if (sLockStore.LookupEntry(dataN))
5773 return;
5775 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5776 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5779 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5781 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5783 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5784 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5785 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5787 /* disable check for while (too many error reports baout not existed in trap templates
5788 else
5789 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5790 goInfo->id,goInfo->type,N,dataN,dataN);
5794 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5796 if (sSpellStore.LookupEntry(dataN))
5797 return;
5799 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5800 goInfo->id,goInfo->type,N,dataN,dataN);
5803 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5805 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5806 return;
5808 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5809 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5811 // prevent client and server unexpected work
5812 const_cast<uint32&>(dataN) = 0;
5815 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5817 // 0/1 correct values
5818 if (dataN <= 1)
5819 return;
5821 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5822 goInfo->id,goInfo->type,N,dataN);
5825 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5827 // 0/1 correct values
5828 if (dataN <= 1)
5829 return;
5831 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5832 goInfo->id,goInfo->type,N,dataN);
5835 void ObjectMgr::LoadGameobjectInfo()
5837 SQLGameObjectLoader loader;
5838 loader.Load(sGOStorage);
5840 // some checks
5841 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5843 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5844 if (!goInfo)
5845 continue;
5847 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5849 switch(goInfo->type)
5851 case GAMEOBJECT_TYPE_DOOR: //0
5853 if (goInfo->door.lockId)
5854 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5855 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5856 break;
5858 case GAMEOBJECT_TYPE_BUTTON: //1
5860 if (goInfo->button.lockId)
5861 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5862 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5863 break;
5865 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5867 if (goInfo->questgiver.lockId)
5868 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5869 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5870 break;
5872 case GAMEOBJECT_TYPE_CHEST: //3
5874 if (goInfo->chest.lockId)
5875 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5877 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
5879 if (goInfo->chest.linkedTrapId) // linked trap
5880 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5881 break;
5883 case GAMEOBJECT_TYPE_TRAP: //6
5885 if (goInfo->trap.lockId)
5886 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5887 /* disable check for while, too many not existed spells
5888 if (goInfo->trap.spellId) // spell
5889 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5891 break;
5893 case GAMEOBJECT_TYPE_CHAIR: //7
5894 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5895 break;
5896 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5898 if (goInfo->spellFocus.focusId)
5900 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5901 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5902 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5905 if (goInfo->spellFocus.linkedTrapId) // linked trap
5906 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5907 break;
5909 case GAMEOBJECT_TYPE_GOOBER: //10
5911 if (goInfo->goober.lockId)
5912 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5914 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
5916 if (goInfo->goober.pageId) // pageId
5918 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5919 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5920 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5922 /* disable check for while, too many not existed spells
5923 if (goInfo->goober.spellId) // spell
5924 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5926 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5927 if (goInfo->goober.linkedTrapId) // linked trap
5928 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5929 break;
5931 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5933 if (goInfo->areadamage.lockId)
5934 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5935 break;
5937 case GAMEOBJECT_TYPE_CAMERA: //13
5939 if (goInfo->camera.lockId)
5940 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5941 break;
5943 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5945 if (goInfo->moTransport.taxiPathId)
5947 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5948 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5949 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5951 break;
5953 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5955 /* disable check for while, too many not existed spells
5956 // always must have spell
5957 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5959 break;
5961 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5963 // always must have spell
5964 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5965 break;
5967 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5969 if (goInfo->flagstand.lockId)
5970 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5971 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5972 break;
5974 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5976 if (goInfo->fishinghole.lockId)
5977 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5978 break;
5980 case GAMEOBJECT_TYPE_FLAGDROP: //26
5982 if (goInfo->flagdrop.lockId)
5983 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5984 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5985 break;
5987 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5988 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5989 break;
5993 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5994 sLog.outString();
5997 void ObjectMgr::LoadExplorationBaseXP()
5999 uint32 count = 0;
6000 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6002 if( !result )
6004 barGoLink bar( 1 );
6006 bar.step();
6008 sLog.outString();
6009 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6010 return;
6013 barGoLink bar( result->GetRowCount() );
6017 bar.step();
6019 Field *fields = result->Fetch();
6020 uint32 level = fields[0].GetUInt32();
6021 uint32 basexp = fields[1].GetUInt32();
6022 mBaseXPTable[level] = basexp;
6023 ++count;
6025 while (result->NextRow());
6027 delete result;
6029 sLog.outString();
6030 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6033 uint32 ObjectMgr::GetBaseXP(uint32 level)
6035 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
6038 uint32 ObjectMgr::GetXPForLevel(uint32 level)
6040 if (level < mPlayerXPperLevel.size())
6041 return mPlayerXPperLevel[level];
6042 return 0;
6045 void ObjectMgr::LoadPetNames()
6047 uint32 count = 0;
6048 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6050 if( !result )
6052 barGoLink bar( 1 );
6054 bar.step();
6056 sLog.outString();
6057 sLog.outString( ">> Loaded %u pet name parts", count );
6058 return;
6061 barGoLink bar( result->GetRowCount() );
6065 bar.step();
6067 Field *fields = result->Fetch();
6068 std::string word = fields[0].GetString();
6069 uint32 entry = fields[1].GetUInt32();
6070 bool half = fields[2].GetBool();
6071 if(half)
6072 PetHalfName1[entry].push_back(word);
6073 else
6074 PetHalfName0[entry].push_back(word);
6075 ++count;
6077 while (result->NextRow());
6078 delete result;
6080 sLog.outString();
6081 sLog.outString( ">> Loaded %u pet name parts", count );
6084 void ObjectMgr::LoadPetNumber()
6086 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6087 if(result)
6089 Field *fields = result->Fetch();
6090 m_hiPetNumber = fields[0].GetUInt32()+1;
6091 delete result;
6094 barGoLink bar( 1 );
6095 bar.step();
6097 sLog.outString();
6098 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
6101 std::string ObjectMgr::GeneratePetName(uint32 entry)
6103 std::vector<std::string> & list0 = PetHalfName0[entry];
6104 std::vector<std::string> & list1 = PetHalfName1[entry];
6106 if(list0.empty() || list1.empty())
6108 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6109 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6110 if(!petname)
6111 petname = cinfo->Name;
6112 return std::string(petname);
6115 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6118 uint32 ObjectMgr::GeneratePetNumber()
6120 return ++m_hiPetNumber;
6123 void ObjectMgr::LoadCorpses()
6125 uint32 count = 0;
6126 // 0 1 2 3 4 5 6 7 8 10
6127 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");
6129 if( !result )
6131 barGoLink bar( 1 );
6133 bar.step();
6135 sLog.outString();
6136 sLog.outString( ">> Loaded %u corpses", count );
6137 return;
6140 barGoLink bar( result->GetRowCount() );
6144 bar.step();
6146 Field *fields = result->Fetch();
6148 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6150 Corpse *corpse = new Corpse;
6151 if(!corpse->LoadFromDB(guid,fields))
6153 delete corpse;
6154 continue;
6157 ObjectAccessor::Instance().AddCorpse(corpse);
6159 ++count;
6161 while (result->NextRow());
6162 delete result;
6164 sLog.outString();
6165 sLog.outString( ">> Loaded %u corpses", count );
6168 void ObjectMgr::LoadReputationOnKill()
6170 uint32 count = 0;
6172 // 0 1 2
6173 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6174 // 3 4 5 6 7 8 9
6175 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6176 "FROM creature_onkill_reputation");
6178 if(!result)
6180 barGoLink bar(1);
6182 bar.step();
6184 sLog.outString();
6185 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6186 return;
6189 barGoLink bar(result->GetRowCount());
6193 Field *fields = result->Fetch();
6194 bar.step();
6196 uint32 creature_id = fields[0].GetUInt32();
6198 ReputationOnKillEntry repOnKill;
6199 repOnKill.repfaction1 = fields[1].GetUInt32();
6200 repOnKill.repfaction2 = fields[2].GetUInt32();
6201 repOnKill.is_teamaward1 = fields[3].GetBool();
6202 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6203 repOnKill.repvalue1 = fields[5].GetInt32();
6204 repOnKill.is_teamaward2 = fields[6].GetBool();
6205 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6206 repOnKill.repvalue2 = fields[8].GetInt32();
6207 repOnKill.team_dependent = fields[9].GetUInt8();
6209 if(!GetCreatureTemplate(creature_id))
6211 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6212 continue;
6215 if(repOnKill.repfaction1)
6217 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6218 if(!factionEntry1)
6220 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6221 continue;
6225 if(repOnKill.repfaction2)
6227 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6228 if(!factionEntry2)
6230 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6231 continue;
6235 mRepOnKill[creature_id] = repOnKill;
6237 ++count;
6238 } while (result->NextRow());
6240 delete result;
6242 sLog.outString();
6243 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6246 void ObjectMgr::LoadPointsOfInterest()
6248 uint32 count = 0;
6250 // 0 1 2 3 4 5
6251 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6253 if(!result)
6255 barGoLink bar(1);
6257 bar.step();
6259 sLog.outString();
6260 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6261 return;
6264 barGoLink bar(result->GetRowCount());
6268 Field *fields = result->Fetch();
6269 bar.step();
6271 uint32 point_id = fields[0].GetUInt32();
6273 PointOfInterest POI;
6274 POI.x = fields[1].GetFloat();
6275 POI.y = fields[2].GetFloat();
6276 POI.icon = fields[3].GetUInt32();
6277 POI.flags = fields[4].GetUInt32();
6278 POI.data = fields[5].GetUInt32();
6279 POI.icon_name = fields[6].GetCppString();
6281 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6283 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6284 continue;
6287 mPointsOfInterest[point_id] = POI;
6289 ++count;
6290 } while (result->NextRow());
6292 delete result;
6294 sLog.outString();
6295 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6298 void ObjectMgr::LoadNPCSpellClickSpells()
6300 uint32 count = 0;
6302 mSpellClickInfoMap.clear();
6303 // 0 1 2 3 4 5
6304 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6306 if(!result)
6308 barGoLink bar(1);
6310 bar.step();
6312 sLog.outString();
6313 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6314 return;
6317 barGoLink bar(result->GetRowCount());
6321 Field *fields = result->Fetch();
6322 bar.step();
6324 uint32 npc_entry = fields[0].GetUInt32();
6325 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6326 if (!cInfo)
6328 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6329 continue;
6332 uint32 spellid = fields[1].GetUInt32();
6333 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6334 if (!spellinfo)
6336 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6337 continue;
6340 uint32 quest_start = fields[2].GetUInt32();
6342 // quest might be 0 to enable spellclick independent of any quest
6343 if (quest_start)
6345 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6347 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6348 continue;
6353 bool quest_start_active = fields[3].GetBool();
6355 uint32 quest_end = fields[4].GetUInt32();
6356 // quest might be 0 to enable spellclick active infinity after start quest
6357 if (quest_end)
6359 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6361 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6362 continue;
6367 uint8 castFlags = fields[5].GetUInt8();
6368 SpellClickInfo info;
6369 info.spellId = spellid;
6370 info.questStart = quest_start;
6371 info.questStartCanActive = quest_start_active;
6372 info.questEnd = quest_end;
6373 info.castFlags = castFlags;
6374 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6376 // mark creature template as spell clickable
6377 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6379 ++count;
6380 } while (result->NextRow());
6382 delete result;
6384 sLog.outString();
6385 sLog.outString(">> Loaded %u spellclick definitions", count);
6388 void ObjectMgr::LoadWeatherZoneChances()
6390 uint32 count = 0;
6392 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6393 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");
6395 if(!result)
6397 barGoLink bar(1);
6399 bar.step();
6401 sLog.outString();
6402 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6403 return;
6406 barGoLink bar(result->GetRowCount());
6410 Field *fields = result->Fetch();
6411 bar.step();
6413 uint32 zone_id = fields[0].GetUInt32();
6415 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6417 for(int season = 0; season < WEATHER_SEASONS; ++season)
6419 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6420 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6421 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6423 if(wzc.data[season].rainChance > 100)
6425 wzc.data[season].rainChance = 25;
6426 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6429 if(wzc.data[season].snowChance > 100)
6431 wzc.data[season].snowChance = 25;
6432 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6435 if(wzc.data[season].stormChance > 100)
6437 wzc.data[season].stormChance = 25;
6438 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6442 ++count;
6443 } while (result->NextRow());
6445 delete result;
6447 sLog.outString();
6448 sLog.outString(">> Loaded %u weather definitions", count);
6451 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6453 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6454 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6455 if(t)
6456 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6459 void ObjectMgr::DeleteCreatureData(uint32 guid)
6461 // remove mapid*cellid -> guid_set map
6462 CreatureData const* data = GetCreatureData(guid);
6463 if(data)
6464 RemoveCreatureFromGrid(guid, data);
6466 mCreatureDataMap.erase(guid);
6469 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6471 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6472 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6473 if(t)
6474 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6477 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6479 RespawnTimes::iterator next;
6481 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6483 next = itr;
6484 ++next;
6486 if(GUID_HIPART(itr->first)==instance)
6487 mGORespawnTimes.erase(itr);
6490 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6492 next = itr;
6493 ++next;
6495 if(GUID_HIPART(itr->first)==instance)
6496 mCreatureRespawnTimes.erase(itr);
6499 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6500 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6503 void ObjectMgr::DeleteGOData(uint32 guid)
6505 // remove mapid*cellid -> guid_set map
6506 GameObjectData const* data = GetGOData(guid);
6507 if(data)
6508 RemoveGameobjectFromGrid(guid, data);
6510 mGameObjectDataMap.erase(guid);
6513 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6515 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6516 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6517 cell_guids.corpses[player_guid] = instance;
6520 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6522 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6523 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6524 cell_guids.corpses.erase(player_guid);
6527 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6529 map.clear(); // need for reload case
6531 uint32 count = 0;
6533 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6535 if(!result)
6537 barGoLink bar(1);
6539 bar.step();
6541 sLog.outString();
6542 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6543 return;
6546 barGoLink bar(result->GetRowCount());
6550 Field *fields = result->Fetch();
6551 bar.step();
6553 uint32 id = fields[0].GetUInt32();
6554 uint32 quest = fields[1].GetUInt32();
6556 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6558 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6559 continue;
6562 map.insert(QuestRelations::value_type(id,quest));
6564 ++count;
6565 } while (result->NextRow());
6567 delete result;
6569 sLog.outString();
6570 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6573 void ObjectMgr::LoadGameobjectQuestRelations()
6575 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6577 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6579 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6580 if(!goInfo)
6581 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6582 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6583 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6587 void ObjectMgr::LoadGameobjectInvolvedRelations()
6589 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6591 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6593 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6594 if(!goInfo)
6595 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6596 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6597 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6601 void ObjectMgr::LoadCreatureQuestRelations()
6603 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6605 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6607 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6608 if(!cInfo)
6609 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6610 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6611 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);
6615 void ObjectMgr::LoadCreatureInvolvedRelations()
6617 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6619 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6621 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6622 if(!cInfo)
6623 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6624 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6625 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);
6629 void ObjectMgr::LoadReservedPlayersNames()
6631 m_ReservedNames.clear(); // need for reload case
6633 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6635 uint32 count = 0;
6637 if( !result )
6639 barGoLink bar( 1 );
6640 bar.step();
6642 sLog.outString();
6643 sLog.outString( ">> Loaded %u reserved player names", count );
6644 return;
6647 barGoLink bar( result->GetRowCount() );
6649 Field* fields;
6652 bar.step();
6653 fields = result->Fetch();
6654 std::string name= fields[0].GetCppString();
6656 std::wstring wstr;
6657 if(!Utf8toWStr (name,wstr))
6659 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6660 continue;
6663 wstrToLower(wstr);
6665 m_ReservedNames.insert(wstr);
6666 ++count;
6667 } while ( result->NextRow() );
6669 delete result;
6671 sLog.outString();
6672 sLog.outString( ">> Loaded %u reserved player names", count );
6675 bool ObjectMgr::IsReservedName( const std::string& name ) const
6677 std::wstring wstr;
6678 if(!Utf8toWStr (name,wstr))
6679 return false;
6681 wstrToLower(wstr);
6683 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6686 enum LanguageType
6688 LT_BASIC_LATIN = 0x0000,
6689 LT_EXTENDEN_LATIN = 0x0001,
6690 LT_CYRILLIC = 0x0002,
6691 LT_EAST_ASIA = 0x0004,
6692 LT_ANY = 0xFFFF
6695 static LanguageType GetRealmLanguageType(bool create)
6697 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6699 case REALM_ZONE_UNKNOWN: // any language
6700 case REALM_ZONE_DEVELOPMENT:
6701 case REALM_ZONE_TEST_SERVER:
6702 case REALM_ZONE_QA_SERVER:
6703 return LT_ANY;
6704 case REALM_ZONE_UNITED_STATES: // extended-Latin
6705 case REALM_ZONE_OCEANIC:
6706 case REALM_ZONE_LATIN_AMERICA:
6707 case REALM_ZONE_ENGLISH:
6708 case REALM_ZONE_GERMAN:
6709 case REALM_ZONE_FRENCH:
6710 case REALM_ZONE_SPANISH:
6711 return LT_EXTENDEN_LATIN;
6712 case REALM_ZONE_KOREA: // East-Asian
6713 case REALM_ZONE_TAIWAN:
6714 case REALM_ZONE_CHINA:
6715 return LT_EAST_ASIA;
6716 case REALM_ZONE_RUSSIAN: // Cyrillic
6717 return LT_CYRILLIC;
6718 default:
6719 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6723 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6725 if(strictMask==0) // any language, ignore realm
6727 if(isExtendedLatinString(wstr,numericOrSpace))
6728 return true;
6729 if(isCyrillicString(wstr,numericOrSpace))
6730 return true;
6731 if(isEastAsianString(wstr,numericOrSpace))
6732 return true;
6733 return false;
6736 if(strictMask & 0x2) // realm zone specific
6738 LanguageType lt = GetRealmLanguageType(create);
6739 if(lt & LT_EXTENDEN_LATIN)
6740 if(isExtendedLatinString(wstr,numericOrSpace))
6741 return true;
6742 if(lt & LT_CYRILLIC)
6743 if(isCyrillicString(wstr,numericOrSpace))
6744 return true;
6745 if(lt & LT_EAST_ASIA)
6746 if(isEastAsianString(wstr,numericOrSpace))
6747 return true;
6750 if(strictMask & 0x1) // basic Latin
6752 if(isBasicLatinString(wstr,numericOrSpace))
6753 return true;
6756 return false;
6759 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6761 std::wstring wname;
6762 if(!Utf8toWStr(name,wname))
6763 return CHAR_NAME_INVALID_CHARACTER;
6765 if(wname.size() > MAX_PLAYER_NAME)
6766 return CHAR_NAME_TOO_LONG;
6768 uint32 minName = sWorld.getConfig(CONFIG_MIN_PLAYER_NAME);
6769 if(wname.size() < minName)
6770 return CHAR_NAME_TOO_SHORT;
6772 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6773 if(!isValidString(wname,strictMask,false,create))
6774 return CHAR_NAME_MIXED_LANGUAGES;
6776 return CHAR_NAME_SUCCESS;
6779 bool ObjectMgr::IsValidCharterName( const std::string& name )
6781 std::wstring wname;
6782 if(!Utf8toWStr(name,wname))
6783 return false;
6785 if(wname.size() > MAX_CHARTER_NAME)
6786 return false;
6788 uint32 minName = sWorld.getConfig(CONFIG_MIN_CHARTER_NAME);
6789 if(wname.size() < minName)
6790 return false;
6792 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6794 return isValidString(wname,strictMask,true);
6797 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
6799 std::wstring wname;
6800 if(!Utf8toWStr(name,wname))
6801 return PET_NAME_INVALID;
6803 if(wname.size() > MAX_PET_NAME)
6804 return PET_NAME_TOO_LONG;
6806 uint32 minName = sWorld.getConfig(CONFIG_MIN_PET_NAME);
6807 if(wname.size() < minName)
6808 return PET_NAME_TOO_SHORT;
6810 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6811 if(!isValidString(wname,strictMask,false))
6812 return PET_NAME_MIXED_LANGUAGES;
6814 return PET_NAME_SUCCESS;
6817 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6819 if(loc==LOCALE_enUS)
6820 return -1;
6822 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6823 if(m_LocalForIndex[i]==loc)
6824 return i;
6826 return -1;
6829 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6831 if (i<0 || i>=m_LocalForIndex.size())
6832 return LOCALE_enUS;
6834 return m_LocalForIndex[i];
6837 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6839 if(loc==LOCALE_enUS)
6840 return -1;
6842 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6843 if(m_LocalForIndex[i]==loc)
6844 return i;
6846 m_LocalForIndex.push_back(loc);
6847 return m_LocalForIndex.size()-1;
6850 void ObjectMgr::LoadGameObjectForQuests()
6852 mGameObjectForQuestSet.clear(); // need for reload case
6854 if( !sGOStorage.MaxEntry )
6856 barGoLink bar( 1 );
6857 bar.step();
6858 sLog.outString();
6859 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6860 return;
6863 barGoLink bar( sGOStorage.MaxEntry - 1 );
6864 uint32 count = 0;
6866 // collect GO entries for GO that must activated
6867 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6869 bar.step();
6870 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6871 if(!goInfo)
6872 continue;
6874 switch(goInfo->type)
6876 // scan GO chest with loot including quest items
6877 case GAMEOBJECT_TYPE_CHEST:
6879 uint32 loot_id = goInfo->GetLootId();
6881 // find quest loot for GO
6882 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6884 mGameObjectForQuestSet.insert(go_entry);
6885 ++count;
6887 break;
6889 case GAMEOBJECT_TYPE_GOOBER:
6891 if(goInfo->goober.questId) //quests objects
6893 mGameObjectForQuestSet.insert(go_entry);
6894 count++;
6896 break;
6898 default:
6899 break;
6903 sLog.outString();
6904 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6907 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6909 int32 start_value = min_value;
6910 int32 end_value = max_value;
6911 // some string can have negative indexes range
6912 if (start_value < 0)
6914 if (end_value >= start_value)
6916 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6917 return false;
6920 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
6921 std::swap(start_value,end_value);
6922 ++start_value;
6923 ++end_value;
6925 else
6927 if (start_value >= end_value)
6929 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6930 return false;
6934 // cleanup affected map part for reloading case
6935 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6937 if (itr->first >= start_value && itr->first < end_value)
6938 mMangosStringLocaleMap.erase(itr++);
6939 else
6940 ++itr;
6943 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);
6945 if (!result)
6947 barGoLink bar(1);
6949 bar.step();
6951 sLog.outString();
6952 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6953 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6954 else
6955 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6956 return false;
6959 uint32 count = 0;
6961 barGoLink bar(result->GetRowCount());
6965 Field *fields = result->Fetch();
6966 bar.step();
6968 int32 entry = fields[0].GetInt32();
6970 if (entry==0)
6972 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6973 continue;
6975 else if (entry < start_value || entry >= end_value)
6977 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
6978 continue;
6981 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6983 if (data.Content.size() > 0)
6985 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6986 continue;
6989 data.Content.resize(1);
6990 ++count;
6992 // 0 -> default, idx in to idx+1
6993 data.Content[0] = fields[1].GetCppString();
6995 for(int i = 1; i < MAX_LOCALE; ++i)
6997 std::string str = fields[i+1].GetCppString();
6998 if (!str.empty())
7000 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7001 if (idx >= 0)
7003 // 0 -> default, idx in to idx+1
7004 if (data.Content.size() <= idx+1)
7005 data.Content.resize(idx+2);
7007 data.Content[idx+1] = str;
7011 } while (result->NextRow());
7013 delete result;
7015 sLog.outString();
7016 if (min_value == MIN_MANGOS_STRING_ID)
7017 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7018 else
7019 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7021 return true;
7024 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7026 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7027 // Content[0] always exist if exist MangosStringLocale
7028 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7030 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7031 return msl->Content[locale_idx+1].c_str();
7032 else
7033 return msl->Content[0].c_str();
7036 if(entry > 0)
7037 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7038 else
7039 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7040 return "<error>";
7043 void ObjectMgr::LoadFishingBaseSkillLevel()
7045 mFishingBaseForArea.clear(); // for reload case
7047 uint32 count = 0;
7048 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7050 if( !result )
7052 barGoLink bar( 1 );
7054 bar.step();
7056 sLog.outString();
7057 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7058 return;
7061 barGoLink bar( result->GetRowCount() );
7065 bar.step();
7067 Field *fields = result->Fetch();
7068 uint32 entry = fields[0].GetUInt32();
7069 int32 skill = fields[1].GetInt32();
7071 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7072 if(!fArea)
7074 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7075 continue;
7078 mFishingBaseForArea[entry] = skill;
7079 ++count;
7081 while (result->NextRow());
7083 delete result;
7085 sLog.outString();
7086 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7089 // Searches for the same condition already in Conditions store
7090 // Returns Id if found, else adds it to Conditions and returns Id
7091 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7093 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7094 for (uint16 i=0; i < mConditions.size(); ++i)
7096 if (lc == mConditions[i])
7097 return i;
7100 mConditions.push_back(lc);
7102 if(mConditions.size() > 0xFFFF)
7104 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7105 return 0;
7108 return mConditions.size() - 1;
7111 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7113 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7115 std::wstring wname;
7116 if(!Utf8toWStr(names.name[i],wname))
7117 return false;
7119 if(mainpart!=GetMainPartOfName(wname,i+1))
7120 return false;
7122 return true;
7125 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7127 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7128 if(i!= mAreaTriggerScripts.end())
7129 return i->second;
7130 return 0;
7133 // Checks if player meets the condition
7134 bool PlayerCondition::Meets(Player const * player) const
7136 if( !player )
7137 return false; // player not present, return false
7139 switch (condition)
7141 case CONDITION_NONE:
7142 return true; // empty condition, always met
7143 case CONDITION_AURA:
7144 return player->HasAura(value1, value2);
7145 case CONDITION_ITEM:
7146 return player->HasItemCount(value1, value2);
7147 case CONDITION_ITEM_EQUIPPED:
7148 return player->HasItemOrGemWithIdEquipped(value1,1);
7149 case CONDITION_ZONEID:
7150 return player->GetZoneId() == value1;
7151 case CONDITION_REPUTATION_RANK:
7153 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7154 return faction && player->GetReputationMgr().GetRank(faction) >= int32(value2);
7156 case CONDITION_TEAM:
7157 return player->GetTeam() == value1;
7158 case CONDITION_SKILL:
7159 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7160 case CONDITION_QUESTREWARDED:
7161 return player->GetQuestRewardStatus(value1);
7162 case CONDITION_QUESTTAKEN:
7164 QuestStatus status = player->GetQuestStatus(value1);
7165 return (status == QUEST_STATUS_INCOMPLETE);
7167 case CONDITION_AD_COMMISSION_AURA:
7169 Unit::AuraMap const& auras = player->GetAuras();
7170 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7171 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7172 return true;
7173 return false;
7175 case CONDITION_NO_AURA:
7176 return !player->HasAura(value1, value2);
7177 case CONDITION_ACTIVE_EVENT:
7178 return gameeventmgr.IsActiveEvent(value1);
7179 default:
7180 return false;
7184 // Verification of condition values validity
7185 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7187 if( condition >= MAX_CONDITION) // Wrong condition type
7189 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7190 return false;
7193 switch (condition)
7195 case CONDITION_AURA:
7197 if(!sSpellStore.LookupEntry(value1))
7199 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7200 return false;
7202 if(value2 > 2)
7204 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7205 return false;
7207 break;
7209 case CONDITION_ITEM:
7211 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
7212 if(!proto)
7214 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7215 return false;
7217 break;
7219 case CONDITION_ITEM_EQUIPPED:
7221 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
7222 if(!proto)
7224 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7225 return false;
7227 break;
7229 case CONDITION_ZONEID:
7231 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7232 if(!areaEntry)
7234 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7235 return false;
7237 if(areaEntry->zone != 0)
7239 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7240 return false;
7242 break;
7244 case CONDITION_REPUTATION_RANK:
7246 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7247 if(!factionEntry)
7249 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7250 return false;
7252 break;
7254 case CONDITION_TEAM:
7256 if (value1 != ALLIANCE && value1 != HORDE)
7258 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7259 return false;
7261 break;
7263 case CONDITION_SKILL:
7265 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7266 if (!pSkill)
7268 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7269 return false;
7271 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7273 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7274 return false;
7276 break;
7278 case CONDITION_QUESTREWARDED:
7279 case CONDITION_QUESTTAKEN:
7281 Quest const *Quest = objmgr.GetQuestTemplate(value1);
7282 if (!Quest)
7284 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7285 return false;
7287 if(value2)
7288 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7289 break;
7291 case CONDITION_AD_COMMISSION_AURA:
7293 if(value1)
7294 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7295 if(value2)
7296 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7297 break;
7299 case CONDITION_NO_AURA:
7301 if(!sSpellStore.LookupEntry(value1))
7303 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7304 return false;
7306 if(value2 > 2)
7308 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7309 return false;
7311 break;
7313 case CONDITION_ACTIVE_EVENT:
7315 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
7316 if(value1 >=events.size() || !events[value1].isValid())
7318 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7319 return false;
7321 break;
7323 case CONDITION_NONE:
7324 break;
7326 return true;
7329 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7331 switch(pSkill->categoryId)
7333 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7334 case SKILL_CATEGORY_WEAPON:
7335 if(pSkill->id!=SKILL_FIST_WEAPONS)
7336 return SKILL_RANGE_LEVEL;
7337 else
7338 return SKILL_RANGE_MONO;
7339 case SKILL_CATEGORY_ARMOR:
7340 case SKILL_CATEGORY_CLASS:
7341 if(pSkill->id != SKILL_LOCKPICKING)
7342 return SKILL_RANGE_MONO;
7343 else
7344 return SKILL_RANGE_LEVEL;
7345 case SKILL_CATEGORY_SECONDARY:
7346 case SKILL_CATEGORY_PROFESSION:
7347 // not set skills for professions and racial abilities
7348 if(IsProfessionSkill(pSkill->id))
7349 return SKILL_RANGE_RANK;
7350 else if(racial)
7351 return SKILL_RANGE_NONE;
7352 else
7353 return SKILL_RANGE_MONO;
7354 default:
7355 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7356 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7357 return SKILL_RANGE_NONE;
7361 void ObjectMgr::LoadGameTele()
7363 m_GameTeleMap.clear(); // for reload case
7365 uint32 count = 0;
7366 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7368 if( !result )
7370 barGoLink bar( 1 );
7372 bar.step();
7374 sLog.outString();
7375 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7376 return;
7379 barGoLink bar( result->GetRowCount() );
7383 bar.step();
7385 Field *fields = result->Fetch();
7387 uint32 id = fields[0].GetUInt32();
7389 GameTele gt;
7391 gt.position_x = fields[1].GetFloat();
7392 gt.position_y = fields[2].GetFloat();
7393 gt.position_z = fields[3].GetFloat();
7394 gt.orientation = fields[4].GetFloat();
7395 gt.mapId = fields[5].GetUInt32();
7396 gt.name = fields[6].GetCppString();
7398 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7400 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7401 continue;
7404 if(!Utf8toWStr(gt.name,gt.wnameLow))
7406 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7407 continue;
7410 wstrToLower( gt.wnameLow );
7412 m_GameTeleMap[id] = gt;
7414 ++count;
7416 while (result->NextRow());
7417 delete result;
7419 sLog.outString();
7420 sLog.outString( ">> Loaded %u GameTeleports", count );
7423 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7425 // explicit name case
7426 std::wstring wname;
7427 if(!Utf8toWStr(name,wname))
7428 return false;
7430 // converting string that we try to find to lower case
7431 wstrToLower( wname );
7433 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7434 const GameTele* alt = NULL;
7435 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7436 if(itr->second.wnameLow == wname)
7437 return &itr->second;
7438 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7439 alt = &itr->second;
7441 return alt;
7444 bool ObjectMgr::AddGameTele(GameTele& tele)
7446 // find max id
7447 uint32 new_id = 0;
7448 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7449 if(itr->first > new_id)
7450 new_id = itr->first;
7452 // use next
7453 ++new_id;
7455 if(!Utf8toWStr(tele.name,tele.wnameLow))
7456 return false;
7458 wstrToLower( tele.wnameLow );
7460 m_GameTeleMap[new_id] = tele;
7462 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')",
7463 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7466 bool ObjectMgr::DeleteGameTele(const std::string& name)
7468 // explicit name case
7469 std::wstring wname;
7470 if(!Utf8toWStr(name,wname))
7471 return false;
7473 // converting string that we try to find to lower case
7474 wstrToLower( wname );
7476 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7478 if(itr->second.wnameLow == wname)
7480 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7481 m_GameTeleMap.erase(itr);
7482 return true;
7486 return false;
7489 void ObjectMgr::LoadTrainerSpell()
7491 // For reload case
7492 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7493 itr->second.Clear();
7494 m_mCacheTrainerSpellMap.clear();
7496 std::set<uint32> skip_trainers;
7498 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7500 if( !result )
7502 barGoLink bar( 1 );
7504 bar.step();
7506 sLog.outString();
7507 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7508 return;
7511 barGoLink bar( result->GetRowCount() );
7513 std::set<uint32> talentIds;
7515 uint32 count = 0;
7518 bar.step();
7520 Field* fields = result->Fetch();
7522 uint32 entry = fields[0].GetUInt32();
7523 uint32 spell = fields[1].GetUInt32();
7525 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7527 if(!cInfo)
7529 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7530 continue;
7533 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7535 if(skip_trainers.count(entry) == 0)
7537 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7538 skip_trainers.insert(entry);
7540 continue;
7543 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7544 if(!spellinfo)
7546 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7547 continue;
7550 if(!SpellMgr::IsSpellValid(spellinfo))
7552 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7553 continue;
7556 if(GetTalentSpellCost(spell))
7558 if(talentIds.count(spell)==0)
7560 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7561 talentIds.insert(spell);
7563 continue;
7566 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7568 TrainerSpell& trainerSpell = data.spellList[spell];
7569 trainerSpell.spell = spell;
7570 trainerSpell.spellCost = fields[2].GetUInt32();
7571 trainerSpell.reqSkill = fields[3].GetUInt32();
7572 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7573 trainerSpell.reqLevel = fields[5].GetUInt32();
7575 if(!trainerSpell.reqLevel)
7576 trainerSpell.reqLevel = spellinfo->spellLevel;
7578 // calculate learned spell for profession case when stored cast-spell
7579 trainerSpell.learnedSpell = spell;
7580 for(int i = 0; i <3; ++i)
7582 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7583 continue;
7584 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7586 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7587 break;
7591 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7592 data.trainerType = 2;
7594 ++count;
7596 } while (result->NextRow());
7597 delete result;
7599 sLog.outString();
7600 sLog.outString( ">> Loaded %d Trainers", count );
7603 void ObjectMgr::LoadVendors()
7605 // For reload case
7606 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7607 itr->second.Clear();
7608 m_mCacheVendorItemMap.clear();
7610 std::set<uint32> skip_vendors;
7612 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7613 if( !result )
7615 barGoLink bar( 1 );
7617 bar.step();
7619 sLog.outString();
7620 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7621 return;
7624 barGoLink bar( result->GetRowCount() );
7626 uint32 count = 0;
7629 bar.step();
7630 Field* fields = result->Fetch();
7632 uint32 entry = fields[0].GetUInt32();
7633 uint32 item_id = fields[1].GetUInt32();
7634 uint32 maxcount = fields[2].GetUInt32();
7635 uint32 incrtime = fields[3].GetUInt32();
7636 uint32 ExtendedCost = fields[4].GetUInt32();
7638 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7639 continue;
7641 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7643 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7644 ++count;
7646 } while (result->NextRow());
7647 delete result;
7649 sLog.outString();
7650 sLog.outString( ">> Loaded %d Vendors ", count );
7653 void ObjectMgr::LoadNpcTextId()
7656 m_mCacheNpcTextIdMap.clear();
7658 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7659 if( !result )
7661 barGoLink bar( 1 );
7663 bar.step();
7665 sLog.outString();
7666 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7667 return;
7670 barGoLink bar( result->GetRowCount() );
7672 uint32 count = 0;
7673 uint32 guid,textid;
7676 bar.step();
7678 Field* fields = result->Fetch();
7680 guid = fields[0].GetUInt32();
7681 textid = fields[1].GetUInt32();
7683 if (!GetCreatureData(guid))
7685 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7686 continue;
7688 if (!GetGossipText(textid))
7690 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7691 continue;
7694 m_mCacheNpcTextIdMap[guid] = textid ;
7695 ++count;
7697 } while (result->NextRow());
7698 delete result;
7700 sLog.outString();
7701 sLog.outString( ">> Loaded %d NpcTextId ", count );
7704 void ObjectMgr::LoadNpcOptions()
7706 m_mCacheNpcOptionList.clear(); // For reload case
7708 QueryResult *result = WorldDatabase.Query(
7709 // 0 1 2 3 4 5 6 7 8
7710 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7711 "FROM npc_option");
7713 if( !result )
7715 barGoLink bar( 1 );
7717 bar.step();
7719 sLog.outString();
7720 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7721 return;
7724 barGoLink bar( result->GetRowCount() );
7726 uint32 count = 0;
7730 bar.step();
7732 Field* fields = result->Fetch();
7734 GossipOption go;
7735 go.Id = fields[0].GetUInt32();
7736 go.GossipId = fields[1].GetUInt32();
7737 go.NpcFlag = fields[2].GetUInt32();
7738 go.Icon = fields[3].GetUInt32();
7739 go.Action = fields[4].GetUInt32();
7740 go.BoxMoney = fields[5].GetUInt32();
7741 go.Coded = fields[6].GetUInt8()!=0;
7742 go.OptionText = fields[7].GetCppString();
7743 go.BoxText = fields[8].GetCppString();
7745 m_mCacheNpcOptionList.push_back(go);
7747 ++count;
7749 } while (result->NextRow());
7750 delete result;
7752 sLog.outString();
7753 sLog.outString( ">> Loaded %d npc_option entries", count );
7756 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7758 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7759 vList.AddItem(item,maxcount,incrtime,extendedcost);
7761 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7764 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7766 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7767 if(iter == m_mCacheVendorItemMap.end())
7768 return false;
7770 if(!iter->second.FindItem(item))
7771 return false;
7773 iter->second.RemoveItem(item);
7774 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7775 return true;
7778 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7780 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7781 if(!cInfo)
7783 if(pl)
7784 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7785 else
7786 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7787 return false;
7790 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7792 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7794 if(pl)
7795 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7796 else
7797 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7799 if(skip_vendors)
7800 skip_vendors->insert(vendor_entry);
7802 return false;
7805 if(!GetItemPrototype(item_id))
7807 if(pl)
7808 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7809 else
7810 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7811 return false;
7814 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7816 if(pl)
7817 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7818 else
7819 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7820 return false;
7823 if(maxcount > 0 && incrtime == 0)
7825 if(pl)
7826 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7827 else
7828 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7829 return false;
7831 else if(maxcount==0 && incrtime > 0)
7833 if(pl)
7834 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7835 else
7836 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7837 return false;
7840 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7841 if(!vItems)
7842 return true; // later checks for non-empty lists
7844 if(vItems->FindItem(item_id))
7846 if(pl)
7847 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7848 else
7849 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7850 return false;
7853 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7855 if(pl)
7856 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7857 else
7858 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7859 return false;
7862 return true;
7865 void ObjectMgr::LoadScriptNames()
7867 m_scriptNames.push_back("");
7868 QueryResult *result = WorldDatabase.Query(
7869 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7870 "UNION "
7871 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7872 "UNION "
7873 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7874 "UNION "
7875 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7876 "UNION "
7877 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7879 if( !result )
7881 barGoLink bar( 1 );
7882 bar.step();
7883 sLog.outString();
7884 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7885 return;
7888 barGoLink bar( result->GetRowCount() );
7889 uint32 count = 0;
7893 bar.step();
7894 m_scriptNames.push_back((*result)[0].GetString());
7895 ++count;
7896 } while (result->NextRow());
7897 delete result;
7899 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7900 sLog.outString();
7901 sLog.outString( ">> Loaded %d Script Names", count );
7904 uint32 ObjectMgr::GetScriptId(const char *name)
7906 // use binary search to find the script name in the sorted vector
7907 // assume "" is the first element
7908 if(!name) return 0;
7909 ScriptNameMap::const_iterator itr =
7910 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7911 if(itr == m_scriptNames.end() || *itr != name) return 0;
7912 return itr - m_scriptNames.begin();
7915 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7917 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7919 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7921 switch(itrM->second.command)
7923 case SCRIPT_COMMAND_TALK:
7925 if(!GetMangosStringLocale (itrM->second.dataint))
7926 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7928 if(ids.count(itrM->second.dataint))
7929 ids.erase(itrM->second.dataint);
7936 void ObjectMgr::LoadDbScriptStrings()
7938 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7940 std::set<int32> ids;
7942 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7943 if(GetMangosStringLocale(i))
7944 ids.insert(i);
7946 CheckScripts(sQuestEndScripts,ids);
7947 CheckScripts(sQuestStartScripts,ids);
7948 CheckScripts(sSpellScripts,ids);
7949 CheckScripts(sGameObjectScripts,ids);
7950 CheckScripts(sEventScripts,ids);
7952 WaypointMgr.CheckTextsExistance(ids);
7954 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7955 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7958 // Functions for scripting access
7959 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7961 return objmgr.GetAreaTriggerScriptId(trigger_id);
7964 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7966 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
7967 // start/end reversed for negative values
7968 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
7970 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
7971 return false;
7974 return objmgr.LoadMangosStrings(db,table,start_value,end_value);
7977 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7979 return objmgr.GetScriptId(name);
7982 ObjectMgr::ScriptNameMap & GetScriptNames()
7984 return objmgr.GetScriptNames();
7987 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7989 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7992 Quest const* GetQuestTemplateStore(uint32 entry)
7994 return objmgr.GetQuestTemplate(entry);