[7770] Prevent access to possible deleted aura's spell proto in Aura::HandleModStealth.
[AHbot.git] / src / game / World.cpp
blob3542d68acfdbd734de3a6788abcb36ad2a464d48
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 /** \file
20 \ingroup world
23 #include "Common.h"
24 #include "Database/DatabaseEnv.h"
25 #include "Config/ConfigEnv.h"
26 #include "SystemConfig.h"
27 #include "Log.h"
28 #include "Opcodes.h"
29 #include "WorldSession.h"
30 #include "WorldPacket.h"
31 #include "Weather.h"
32 #include "Player.h"
33 #include "Vehicle.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
41 #include "CreatureEventAIMgr.h"
42 #include "SpellMgr.h"
43 #include "Chat.h"
44 #include "DBCStores.h"
45 #include "LootMgr.h"
46 #include "ItemEnchantmentMgr.h"
47 #include "MapManager.h"
48 #include "ScriptCalls.h"
49 #include "CreatureAIRegistry.h"
50 #include "Policies/SingletonImp.h"
51 #include "BattleGroundMgr.h"
52 #include "TemporarySummon.h"
53 #include "WaypointMovementGenerator.h"
54 #include "VMapFactory.h"
55 #include "GlobalEvents.h"
56 #include "GameEventMgr.h"
57 #include "PoolHandler.h"
58 #include "Database/DatabaseImpl.h"
59 #include "GridNotifiersImpl.h"
60 #include "CellImpl.h"
61 #include "InstanceSaveMgr.h"
62 #include "WaypointManager.h"
63 #include "GMTicketMgr.h"
64 #include "Util.h"
66 INSTANTIATE_SINGLETON_1( World );
68 volatile bool World::m_stopEvent = false;
69 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
70 volatile uint32 World::m_worldLoopCounter = 0;
72 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
74 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
75 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
76 float World::m_VisibleUnitGreyDistance = 0;
77 float World::m_VisibleObjectGreyDistance = 0;
79 struct ScriptAction
81 uint64 sourceGUID;
82 uint64 targetGUID;
83 uint64 ownerGUID; // owner of source if source is item
84 ScriptInfo const* script; // pointer to static script data
87 /// World constructor
88 World::World()
90 m_playerLimit = 0;
91 m_allowMovement = true;
92 m_ShutdownMask = 0;
93 m_ShutdownTimer = 0;
94 m_gameTime=time(NULL);
95 m_startTime=m_gameTime;
96 m_maxActiveSessionCount = 0;
97 m_maxQueuedSessionCount = 0;
98 m_resultQueue = NULL;
99 m_NextDailyQuestReset = 0;
101 m_defaultDbcLocale = LOCALE_enUS;
102 m_availableDbcLocaleMask = 0;
105 /// World destructor
106 World::~World()
108 ///- Empty the kicked session set
109 while (!m_sessions.empty())
111 // not remove from queue, prevent loading new sessions
112 delete m_sessions.begin()->second;
113 m_sessions.erase(m_sessions.begin());
116 ///- Empty the WeatherMap
117 for (WeatherMap::const_iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
118 delete itr->second;
120 m_weathers.clear();
122 while (!cliCmdQueue.empty())
123 delete cliCmdQueue.next();
125 VMAP::VMapFactory::clear();
127 if(m_resultQueue) delete m_resultQueue;
129 //TODO free addSessQueue
132 /// Find a player in a specified zone
133 Player* World::FindPlayerInZone(uint32 zone)
135 ///- circle through active sessions and return the first player found in the zone
136 SessionMap::const_iterator itr;
137 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
139 if(!itr->second)
140 continue;
141 Player *player = itr->second->GetPlayer();
142 if(!player)
143 continue;
144 if( player->IsInWorld() && player->GetZoneId() == zone )
146 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
147 return player;
150 return NULL;
153 /// Find a session by its id
154 WorldSession* World::FindSession(uint32 id) const
156 SessionMap::const_iterator itr = m_sessions.find(id);
158 if(itr != m_sessions.end())
159 return itr->second; // also can return NULL for kicked session
160 else
161 return NULL;
164 /// Remove a given session
165 bool World::RemoveSession(uint32 id)
167 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
168 SessionMap::const_iterator itr = m_sessions.find(id);
170 if(itr != m_sessions.end() && itr->second)
172 if (itr->second->PlayerLoading())
173 return false;
174 itr->second->KickPlayer();
177 return true;
180 void World::AddSession(WorldSession* s)
182 addSessQueue.add(s);
185 void
186 World::AddSession_ (WorldSession* s)
188 ASSERT (s);
190 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
192 ///- kick already loaded player with same account (if any) and remove session
193 ///- if player is in loading and want to load again, return
194 if (!RemoveSession (s->GetAccountId ()))
196 s->KickPlayer ();
197 delete s; // session not added yet in session list, so not listed in queue
198 return;
201 // decrease session counts only at not reconnection case
202 bool decrease_session = true;
204 // if session already exist, prepare to it deleting at next world update
205 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
207 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
209 if(old != m_sessions.end())
211 // prevent decrease sessions count if session queued
212 if(RemoveQueuedPlayer(old->second))
213 decrease_session = false;
214 // not remove replaced session form queue if listed
215 delete old->second;
219 m_sessions[s->GetAccountId ()] = s;
221 uint32 Sessions = GetActiveAndQueuedSessionCount ();
222 uint32 pLimit = GetPlayerAmountLimit ();
223 uint32 QueueSize = GetQueueSize (); //number of players in the queue
225 //so we don't count the user trying to
226 //login as a session and queue the socket that we are using
227 if(decrease_session)
228 --Sessions;
230 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
232 AddQueuedPlayer (s);
233 UpdateMaxSessionCounters ();
234 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
235 return;
238 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
239 packet << uint8 (AUTH_OK);
240 packet << uint32 (0); // BillingTimeRemaining
241 packet << uint8 (0); // BillingPlanFlags
242 packet << uint32 (0); // BillingTimeRested
243 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
244 s->SendPacket (&packet);
246 s->SendAddonsInfo();
247 UpdateMaxSessionCounters ();
249 // Updates the population
250 if (pLimit > 0)
252 float popu = GetActiveSessionCount (); //updated number of users on the server
253 popu /= pLimit;
254 popu *= 2;
255 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
256 sLog.outDetail ("Server Population (%f).", popu);
260 int32 World::GetQueuePos(WorldSession* sess)
262 uint32 position = 1;
264 for(Queue::const_iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
265 if((*iter) == sess)
266 return position;
268 return 0;
271 void World::AddQueuedPlayer(WorldSession* sess)
273 sess->SetInQueue(true);
274 m_QueuedPlayer.push_back (sess);
276 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
277 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
278 packet << uint8 (AUTH_WAIT_QUEUE);
279 packet << uint32 (0); // BillingTimeRemaining
280 packet << uint8 (0); // BillingPlanFlags
281 packet << uint32 (0); // BillingTimeRested
282 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
283 packet << uint32(GetQueuePos (sess));
284 sess->SendPacket (&packet);
286 //sess->SendAuthWaitQue (GetQueuePos (sess));
289 bool World::RemoveQueuedPlayer(WorldSession* sess)
291 // sessions count including queued to remove (if removed_session set)
292 uint32 sessions = GetActiveSessionCount();
294 uint32 position = 1;
295 Queue::iterator iter = m_QueuedPlayer.begin();
297 // search to remove and count skipped positions
298 bool found = false;
300 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
302 if(*iter==sess)
304 sess->SetInQueue(false);
305 iter = m_QueuedPlayer.erase(iter);
306 found = true; // removing queued session
307 break;
311 // iter point to next socked after removed or end()
312 // position store position of removed socket and then new position next socket after removed
314 // if session not queued then we need decrease sessions count
315 if(!found && sessions)
316 --sessions;
318 // accept first in queue
319 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
321 WorldSession* pop_sess = m_QueuedPlayer.front();
322 pop_sess->SetInQueue(false);
323 pop_sess->SendAuthWaitQue(0);
324 m_QueuedPlayer.pop_front();
326 // update iter to point first queued socket or end() if queue is empty now
327 iter = m_QueuedPlayer.begin();
328 position = 1;
331 // update position from iter to end()
332 // iter point to first not updated socket, position store new position
333 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
334 (*iter)->SendAuthWaitQue(position);
336 return found;
339 /// Find a Weather object by the given zoneid
340 Weather* World::FindWeather(uint32 id) const
342 WeatherMap::const_iterator itr = m_weathers.find(id);
344 if(itr != m_weathers.end())
345 return itr->second;
346 else
347 return 0;
350 /// Remove a Weather object for the given zoneid
351 void World::RemoveWeather(uint32 id)
353 // not called at the moment. Kept for completeness
354 WeatherMap::iterator itr = m_weathers.find(id);
356 if(itr != m_weathers.end())
358 delete itr->second;
359 m_weathers.erase(itr);
363 /// Add a Weather object to the list
364 Weather* World::AddWeather(uint32 zone_id)
366 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
368 // zone not have weather, ignore
369 if(!weatherChances)
370 return NULL;
372 Weather* w = new Weather(zone_id,weatherChances);
373 m_weathers[w->GetZone()] = w;
374 w->ReGenerate();
375 w->UpdateWeather();
376 return w;
379 /// Initialize config values
380 void World::LoadConfigSettings(bool reload)
382 if(reload)
384 if(!sConfig.Reload())
386 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
387 return;
391 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
392 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
393 if(!confVersion)
395 sLog.outError("*****************************************************************************");
396 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
397 sLog.outError(" Your configuration file may be out of date!");
398 sLog.outError("*****************************************************************************");
399 clock_t pause = 3000 + clock();
400 while (pause > clock())
401 ; // empty body
403 else
405 if (confVersion < _MANGOSDCONFVERSION)
407 sLog.outError("*****************************************************************************");
408 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
409 sLog.outError(" Please check for updates, as your current default values may cause");
410 sLog.outError(" unexpected behavior.");
411 sLog.outError("*****************************************************************************");
412 clock_t pause = 3000 + clock();
413 while (pause > clock())
414 ; // empty body
418 ///- Read the player limit and the Message of the day from the config file
419 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
420 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
422 ///- Read all rates from the config file
423 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
424 if(rate_values[RATE_HEALTH] < 0)
426 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
427 rate_values[RATE_HEALTH] = 1;
429 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
430 if(rate_values[RATE_POWER_MANA] < 0)
432 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
433 rate_values[RATE_POWER_MANA] = 1;
435 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
436 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
437 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
439 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
440 rate_values[RATE_POWER_RAGE_LOSS] = 1;
442 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
443 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
444 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
446 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
447 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
449 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
450 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
451 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
452 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
453 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
454 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
455 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
456 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
457 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
458 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
459 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
460 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
461 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
462 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
463 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
464 rate_values[RATE_REPUTATION_LOWLEVEL_KILL] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f);
465 rate_values[RATE_REPUTATION_LOWLEVEL_QUEST] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f);
466 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
467 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
468 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
469 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
471 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
476 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
477 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
478 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
481 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
482 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
483 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
484 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
485 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
486 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
487 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
488 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
489 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
490 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
491 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
492 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
493 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
494 if(rate_values[RATE_TALENT] < 0.0f)
496 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
497 rate_values[RATE_TALENT] = 1.0f;
499 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
501 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
502 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
504 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
505 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
507 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
509 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
510 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
511 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
514 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
515 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
517 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
518 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
520 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
521 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
523 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
524 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
526 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
527 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
529 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
530 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
532 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
533 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
535 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
536 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
539 ///- Read other configuration items from the config file
541 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
542 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
544 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
545 m_configs[CONFIG_COMPRESSION] = 1;
547 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
548 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
549 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
551 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
552 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
554 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
555 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
557 if(reload)
558 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
560 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
561 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
563 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
564 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
566 if(reload)
567 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
569 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
571 if(reload)
573 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
574 if(val!=m_configs[CONFIG_PORT_WORLD])
575 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
577 else
578 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
580 if(reload)
582 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
583 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
584 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
586 else
587 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
589 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
590 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
591 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
592 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
594 if(reload)
596 uint32 val = sConfig.GetIntDefault("GameType", 0);
597 if(val!=m_configs[CONFIG_GAME_TYPE])
598 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
600 else
601 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
603 if(reload)
605 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
606 if(val!=m_configs[CONFIG_REALM_ZONE])
607 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
609 else
610 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
612 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
613 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
614 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
615 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
617 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
621 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
622 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
623 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
625 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
627 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
628 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
630 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
631 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
634 // must be after CONFIG_CHARACTERS_PER_REALM
635 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
636 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
638 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
639 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
642 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
643 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
645 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
646 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
649 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
651 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
652 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
654 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
655 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
658 if(reload)
660 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 80);
661 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
662 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
664 else
665 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 80);
667 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
669 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
670 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
673 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
674 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
676 sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 1.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
677 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
679 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
681 sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
682 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
685 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
686 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
688 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
689 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
690 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
692 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
694 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
695 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
696 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
699 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
700 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
702 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
703 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
705 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
707 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
708 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
709 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
712 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
713 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
715 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
716 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
719 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
720 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
722 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
723 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
724 m_configs[CONFIG_START_HONOR_POINTS] = 0;
726 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
728 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
729 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
730 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
733 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
734 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
736 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
737 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
740 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
741 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
743 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
744 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
745 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
747 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
749 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
750 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
751 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
754 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
756 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
757 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
759 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
760 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
761 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
763 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
764 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
765 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
767 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
768 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
771 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
772 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
773 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
774 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
775 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
777 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList", false);
778 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList", false);
779 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
781 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
782 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
784 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
785 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
786 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
788 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
790 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
791 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
793 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
794 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
796 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
798 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
800 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
801 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
803 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
804 m_configs[CONFIG_UPTIME_UPDATE] = 10;
806 if(reload)
808 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
809 m_timers[WUPDATE_UPTIME].Reset();
812 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
813 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
814 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
815 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
817 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
818 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
820 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
821 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
823 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
824 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
826 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
827 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
830 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
831 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
833 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
834 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
837 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
838 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
840 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
841 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
844 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
845 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
847 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
848 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
851 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
852 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
854 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
855 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
858 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
859 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
861 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
863 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
865 if(reload)
867 uint32 val = sConfig.GetIntDefault("Expansion",1);
868 if(val!=m_configs[CONFIG_EXPANSION])
869 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
871 else
872 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
874 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
875 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
876 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
878 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
880 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
881 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
883 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
885 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
886 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
887 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
888 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
889 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
890 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
891 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
893 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
895 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
896 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
898 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
899 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
901 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
902 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
903 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
904 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
905 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
907 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
908 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
909 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
910 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
911 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
913 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
915 // always use declined names in the russian client
916 m_configs[CONFIG_DECLINED_NAMES_USED] =
917 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
919 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
920 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
921 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
923 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
924 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
925 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
926 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
927 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
928 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
929 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
930 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
931 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
932 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
933 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
934 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
935 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
937 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
939 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
941 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
942 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
944 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
945 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
947 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
948 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
950 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
951 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
954 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
955 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
957 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
958 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
960 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
962 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
963 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
965 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
966 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
968 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
969 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
971 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
973 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
974 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
976 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
977 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
979 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
980 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
982 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
984 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
985 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
987 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
988 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
990 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
991 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
994 ///- Read the "Data" directory from the config file
995 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
996 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
997 dataPath.append("/");
999 if(reload)
1001 if(dataPath!=m_dataPath)
1002 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1004 else
1006 m_dataPath = dataPath;
1007 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1010 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1011 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1012 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1013 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1014 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1015 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1016 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1017 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1018 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1019 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1020 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1023 /// Initialize the World
1024 void World::SetInitialWorldSettings()
1026 ///- Initialize the random number generator
1027 srand((unsigned int)time(NULL));
1029 ///- Initialize config settings
1030 LoadConfigSettings();
1032 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1033 objmgr.SetHighestGuids();
1035 ///- Check the existence of the map files for all races' startup areas.
1036 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1037 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1038 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1039 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1040 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1041 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1042 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1043 ||m_configs[CONFIG_EXPANSION] && (
1044 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1046 sLog.outError("Correct *.map files not found in path '%smaps' or *.vmap/*vmdir files in '%svmaps'. Please place *.map/*.vmap/*.vmdir files in appropriate directories or correct the DataDir value in the mangosd.conf file.",m_dataPath.c_str(),m_dataPath.c_str());
1047 exit(1);
1050 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1051 sLog.outString();
1052 sLog.outString("Loading MaNGOS strings...");
1053 if (!objmgr.LoadMangosStrings())
1054 exit(1); // Error message displayed in function already
1056 ///- Update the realm entry in the database with the realm type from the config file
1057 //No SQL injection as values are treated as integers
1059 // not send custom type REALM_FFA_PVP to realm list
1060 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1061 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1062 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1064 ///- Remove the bones after a restart
1065 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1067 ///- Load the DBC files
1068 sLog.outString("Initialize data stores...");
1069 LoadDBCStores(m_dataPath);
1070 DetectDBCLang();
1072 sLog.outString( "Loading Script Names...");
1073 objmgr.LoadScriptNames();
1075 sLog.outString( "Loading InstanceTemplate..." );
1076 objmgr.LoadInstanceTemplate();
1078 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1079 spellmgr.LoadSkillLineAbilityMap();
1081 ///- Clean up and pack instances
1082 sLog.outString( "Cleaning up instances..." );
1083 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1085 sLog.outString( "Packing instances..." );
1086 sInstanceSaveManager.PackInstances();
1088 sLog.outString();
1089 sLog.outString( "Loading Localization strings..." );
1090 objmgr.LoadCreatureLocales();
1091 objmgr.LoadGameObjectLocales();
1092 objmgr.LoadItemLocales();
1093 objmgr.LoadQuestLocales();
1094 objmgr.LoadNpcTextLocales();
1095 objmgr.LoadPageTextLocales();
1096 objmgr.LoadNpcOptionLocales();
1097 objmgr.LoadPointOfInterestLocales();
1098 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1099 sLog.outString( ">>> Localization strings loaded" );
1100 sLog.outString();
1102 sLog.outString( "Loading Page Texts..." );
1103 objmgr.LoadPageTexts();
1105 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1106 objmgr.LoadGameobjectInfo();
1108 sLog.outString( "Loading Spell Chain Data..." );
1109 spellmgr.LoadSpellChains();
1111 sLog.outString( "Loading Spell Elixir types..." );
1112 spellmgr.LoadSpellElixirs();
1114 sLog.outString( "Loading Spell Learn Skills..." );
1115 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1117 sLog.outString( "Loading Spell Learn Spells..." );
1118 spellmgr.LoadSpellLearnSpells();
1120 sLog.outString( "Loading Spell Proc Event conditions..." );
1121 spellmgr.LoadSpellProcEvents();
1123 sLog.outString( "Loading Spell Bonus Data..." );
1124 spellmgr.LoadSpellBonusess();
1126 sLog.outString( "Loading Aggro Spells Definitions...");
1127 spellmgr.LoadSpellThreats();
1129 sLog.outString( "Loading NPC Texts..." );
1130 objmgr.LoadGossipText();
1132 sLog.outString( "Loading Item Random Enchantments Table..." );
1133 LoadRandomEnchantmentsTable();
1135 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1136 objmgr.LoadItemPrototypes();
1138 sLog.outString( "Loading Item Texts..." );
1139 objmgr.LoadItemTexts();
1141 sLog.outString( "Loading Creature Model Based Info Data..." );
1142 objmgr.LoadCreatureModelInfo();
1144 sLog.outString( "Loading Equipment templates...");
1145 objmgr.LoadEquipmentTemplates();
1147 sLog.outString( "Loading Creature templates..." );
1148 objmgr.LoadCreatureTemplates();
1150 sLog.outString( "Loading SpellsScriptTarget...");
1151 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1153 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1154 objmgr.LoadReputationOnKill();
1156 sLog.outString( "Loading Points Of Interest Data..." );
1157 objmgr.LoadPointsOfInterest();
1159 sLog.outString( "Loading Pet Create Spells..." );
1160 objmgr.LoadPetCreateSpells();
1162 sLog.outString( "Loading Creature Data..." );
1163 objmgr.LoadCreatures();
1165 sLog.outString( "Loading Creature Addon Data..." );
1166 sLog.outString();
1167 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1168 sLog.outString( ">>> Creature Addon Data loaded" );
1169 sLog.outString();
1171 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1172 objmgr.LoadCreatureRespawnTimes();
1174 sLog.outString( "Loading Gameobject Data..." );
1175 objmgr.LoadGameobjects();
1177 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1178 objmgr.LoadGameobjectRespawnTimes();
1180 sLog.outString( "Loading Objects Pooling Data...");
1181 poolhandler.LoadFromDB();
1183 sLog.outString( "Loading Game Event Data...");
1184 sLog.outString();
1185 gameeventmgr.LoadFromDB();
1186 sLog.outString( ">>> Game Event Data loaded" );
1187 sLog.outString();
1189 sLog.outString( "Loading Weather Data..." );
1190 objmgr.LoadWeatherZoneChances();
1192 sLog.outString( "Loading Quests..." );
1193 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1195 sLog.outString( "Loading Quests Relations..." );
1196 sLog.outString();
1197 objmgr.LoadQuestRelations(); // must be after quest load
1198 sLog.outString( ">>> Quests Relations loaded" );
1199 sLog.outString();
1201 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1202 spellmgr.LoadSpellAreas();
1204 sLog.outString( "Loading AreaTrigger definitions..." );
1205 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1207 sLog.outString( "Loading Quest Area Triggers..." );
1208 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1210 sLog.outString( "Loading Tavern Area Triggers..." );
1211 objmgr.LoadTavernAreaTriggers();
1213 sLog.outString( "Loading AreaTrigger script names..." );
1214 objmgr.LoadAreaTriggerScripts();
1216 sLog.outString( "Loading Graveyard-zone links...");
1217 objmgr.LoadGraveyardZones();
1219 sLog.outString( "Loading Spell target coordinates..." );
1220 spellmgr.LoadSpellTargetPositions();
1222 sLog.outString( "Loading SpellAffect definitions..." );
1223 spellmgr.LoadSpellAffects();
1225 sLog.outString( "Loading spell pet auras..." );
1226 spellmgr.LoadSpellPetAuras();
1228 sLog.outString( "Loading pet levelup spells..." );
1229 spellmgr.LoadPetLevelupSpellMap();
1231 sLog.outString( "Loading Player Create Info & Level Stats..." );
1232 sLog.outString();
1233 objmgr.LoadPlayerInfo();
1234 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1235 sLog.outString();
1237 sLog.outString( "Loading Exploration BaseXP Data..." );
1238 objmgr.LoadExplorationBaseXP();
1240 sLog.outString( "Loading Pet Name Parts..." );
1241 objmgr.LoadPetNames();
1243 sLog.outString( "Loading the max pet number..." );
1244 objmgr.LoadPetNumber();
1246 sLog.outString( "Loading pet level stats..." );
1247 objmgr.LoadPetLevelInfo();
1249 sLog.outString( "Loading Player Corpses..." );
1250 objmgr.LoadCorpses();
1252 sLog.outString( "Loading Loot Tables..." );
1253 sLog.outString();
1254 LoadLootTables();
1255 sLog.outString( ">>> Loot Tables loaded" );
1256 sLog.outString();
1258 sLog.outString( "Loading Skill Discovery Table..." );
1259 LoadSkillDiscoveryTable();
1261 sLog.outString( "Loading Skill Extra Item Table..." );
1262 LoadSkillExtraItemTable();
1264 sLog.outString( "Loading Skill Fishing base level requirements..." );
1265 objmgr.LoadFishingBaseSkillLevel();
1267 sLog.outString( "Loading Achievements..." );
1268 sLog.outString();
1269 achievementmgr.LoadAchievementReferenceList();
1270 achievementmgr.LoadAchievementCriteriaList();
1271 achievementmgr.LoadAchievementCriteriaData();
1272 achievementmgr.LoadRewards();
1273 achievementmgr.LoadRewardLocales();
1274 achievementmgr.LoadCompletedAchievements();
1275 sLog.outString( ">>> Achievements loaded" );
1276 sLog.outString();
1278 ///- Load dynamic data tables from the database
1279 sLog.outString( "Loading Auctions..." );
1280 sLog.outString();
1281 auctionmgr.LoadAuctionItems();
1282 auctionmgr.LoadAuctions();
1283 sLog.outString( ">>> Auctions loaded" );
1284 sLog.outString();
1286 sLog.outString( "Loading Guilds..." );
1287 objmgr.LoadGuilds();
1289 sLog.outString( "Loading ArenaTeams..." );
1290 objmgr.LoadArenaTeams();
1292 sLog.outString( "Loading Groups..." );
1293 objmgr.LoadGroups();
1295 sLog.outString( "Loading ReservedNames..." );
1296 objmgr.LoadReservedPlayersNames();
1298 sLog.outString( "Loading GameObjects for quests..." );
1299 objmgr.LoadGameObjectForQuests();
1301 sLog.outString( "Loading BattleMasters..." );
1302 sBattleGroundMgr.LoadBattleMastersEntry();
1304 sLog.outString( "Loading GameTeleports..." );
1305 objmgr.LoadGameTele();
1307 sLog.outString( "Loading Npc Text Id..." );
1308 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1310 sLog.outString( "Loading Npc Options..." );
1311 objmgr.LoadNpcOptions();
1313 sLog.outString( "Loading Vendors..." );
1314 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1316 sLog.outString( "Loading Trainers..." );
1317 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1319 sLog.outString( "Loading Waypoints..." );
1320 sLog.outString();
1321 WaypointMgr.Load();
1323 sLog.outString( "Loading GM tickets...");
1324 ticketmgr.LoadGMTickets();
1326 ///- Handle outdated emails (delete/return)
1327 sLog.outString( "Returning old mails..." );
1328 objmgr.ReturnOrDeleteOldMails(false);
1330 ///- Load and initialize scripts
1331 sLog.outString( "Loading Scripts..." );
1332 sLog.outString();
1333 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1334 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1335 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1336 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1337 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1338 sLog.outString( ">>> Scripts loaded" );
1339 sLog.outString();
1341 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1342 objmgr.LoadDbScriptStrings();
1344 sLog.outString( "Loading CreatureEventAI Texts...");
1345 CreatureEAI_Mgr.LoadCreatureEventAI_Texts();
1347 sLog.outString( "Loading CreatureEventAI Summons...");
1348 CreatureEAI_Mgr.LoadCreatureEventAI_Summons();
1350 sLog.outString( "Loading CreatureEventAI Scripts...");
1351 CreatureEAI_Mgr.LoadCreatureEventAI_Scripts();
1353 sLog.outString( "Initializing Scripts..." );
1354 if(!LoadScriptingModule())
1355 exit(1);
1357 ///- Initialize game time and timers
1358 sLog.outString( "DEBUG:: Initialize game time and timers" );
1359 m_gameTime = time(NULL);
1360 m_startTime=m_gameTime;
1362 tm local;
1363 time_t curr;
1364 time(&curr);
1365 local=*(localtime(&curr)); // dereference and assign
1366 char isoDate[128];
1367 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1368 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1370 loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " I64FMTD ", '%s', 0)",
1371 realmID, uint64(m_startTime), isoDate);
1373 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1374 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1375 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1376 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1377 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1378 //Update "uptime" table based on configuration entry in minutes.
1379 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1380 //erase corpses every 20 minutes
1382 //to set mailtimer to return mails every day between 4 and 5 am
1383 //mailtimer is increased when updating auctions
1384 //one second is 1000 -(tested on win system)
1385 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1386 //1440
1387 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1388 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1390 ///- Initilize static helper structures
1391 AIRegistry::Initialize();
1392 WaypointMovementGenerator<Creature>::Initialize();
1393 Player::InitVisibleBits();
1395 ///- Initialize MapManager
1396 sLog.outString( "Starting Map System" );
1397 MapManager::Instance().Initialize();
1399 ///- Initialize Battlegrounds
1400 sLog.outString( "Starting BattleGround System" );
1401 sBattleGroundMgr.CreateInitialBattleGrounds();
1402 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1404 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1405 sLog.outString( "Loading Transports..." );
1406 MapManager::Instance().LoadTransports();
1408 sLog.outString("Deleting expired bans..." );
1409 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1411 sLog.outString("Calculate next daily quest reset time..." );
1412 InitDailyQuestResetTime();
1414 sLog.outString("Starting objects Pooling system..." );
1415 poolhandler.Initialize();
1417 sLog.outString("Starting Game Event system..." );
1418 uint32 nextGameEvent = gameeventmgr.Initialize();
1419 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1421 sLog.outString( "WORLD: World initialized" );
1424 void World::DetectDBCLang()
1426 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1428 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1430 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1431 m_lang_confid = LOCALE_enUS;
1434 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1436 std::string availableLocalsStr;
1438 int default_locale = MAX_LOCALE;
1439 for (int i = MAX_LOCALE-1; i >= 0; --i)
1441 if ( strlen(race->name[i]) > 0) // check by race names
1443 default_locale = i;
1444 m_availableDbcLocaleMask |= (1 << i);
1445 availableLocalsStr += localeNames[i];
1446 availableLocalsStr += " ";
1450 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1451 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1453 default_locale = m_lang_confid;
1456 if(default_locale >= MAX_LOCALE)
1458 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1459 exit(1);
1462 m_defaultDbcLocale = LocaleConstant(default_locale);
1464 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1465 sLog.outString();
1468 /// Update the World !
1469 void World::Update(uint32 diff)
1471 ///- Update the different timers
1472 for(int i = 0; i < WUPDATE_COUNT; ++i)
1473 if(m_timers[i].GetCurrent()>=0)
1474 m_timers[i].Update(diff);
1475 else m_timers[i].SetCurrent(0);
1477 ///- Update the game time and check for shutdown time
1478 _UpdateGameTime();
1480 /// Handle daily quests reset time
1481 if(m_gameTime > m_NextDailyQuestReset)
1483 ResetDailyQuests();
1484 m_NextDailyQuestReset += DAY;
1487 /// <ul><li> Handle auctions when the timer has passed
1488 if (m_timers[WUPDATE_AUCTIONS].Passed())
1490 m_timers[WUPDATE_AUCTIONS].Reset();
1492 ///- Update mails (return old mails with item, or delete them)
1493 //(tested... works on win)
1494 if (++mail_timer > mail_timer_expires)
1496 mail_timer = 0;
1497 objmgr.ReturnOrDeleteOldMails(true);
1500 ///- Handle expired auctions
1501 auctionmgr.Update();
1504 /// <li> Handle session updates when the timer has passed
1505 if (m_timers[WUPDATE_SESSIONS].Passed())
1507 m_timers[WUPDATE_SESSIONS].Reset();
1509 UpdateSessions(diff);
1512 /// <li> Handle weather updates when the timer has passed
1513 if (m_timers[WUPDATE_WEATHERS].Passed())
1515 m_timers[WUPDATE_WEATHERS].Reset();
1517 ///- Send an update signal to Weather objects
1518 WeatherMap::iterator itr, next;
1519 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1521 next = itr;
1522 ++next;
1524 ///- and remove Weather objects for zones with no player
1525 //As interval > WorldTick
1526 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1528 delete itr->second;
1529 m_weathers.erase(itr);
1533 /// <li> Update uptime table
1534 if (m_timers[WUPDATE_UPTIME].Passed())
1536 uint32 tmpDiff = (m_gameTime - m_startTime);
1537 uint32 maxClientsNum = GetMaxActiveSessionCount();
1539 m_timers[WUPDATE_UPTIME].Reset();
1540 loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " I64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
1543 /// <li> Handle all other objects
1544 if (m_timers[WUPDATE_OBJECTS].Passed())
1546 m_timers[WUPDATE_OBJECTS].Reset();
1547 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1548 MapManager::Instance().Update(diff); // As interval = 0
1550 ///- Process necessary scripts
1551 if (!m_scriptSchedule.empty())
1552 ScriptsProcess();
1554 sBattleGroundMgr.Update(diff);
1557 // execute callbacks from sql queries that were queued recently
1558 UpdateResultQueue();
1560 ///- Erase corpses once every 20 minutes
1561 if (m_timers[WUPDATE_CORPSES].Passed())
1563 m_timers[WUPDATE_CORPSES].Reset();
1565 CorpsesErase();
1568 ///- Process Game events when necessary
1569 if (m_timers[WUPDATE_EVENTS].Passed())
1571 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1572 uint32 nextGameEvent = gameeventmgr.Update();
1573 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1574 m_timers[WUPDATE_EVENTS].Reset();
1577 /// </ul>
1578 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1579 MapManager::Instance().DoDelayedMovesAndRemoves();
1581 // update the instance reset times
1582 sInstanceSaveManager.Update();
1584 // And last, but not least handle the issued cli commands
1585 ProcessCliCommands();
1588 /// Put scripts in the execution queue
1589 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1591 ///- Find the script map
1592 ScriptMapMap::const_iterator s = scripts.find(id);
1593 if (s == scripts.end())
1594 return;
1596 // prepare static data
1597 uint64 sourceGUID = source->GetGUID();
1598 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1599 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1601 ///- Schedule script execution for all scripts in the script map
1602 ScriptMap const *s2 = &(s->second);
1603 bool immedScript = false;
1604 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1606 ScriptAction sa;
1607 sa.sourceGUID = sourceGUID;
1608 sa.targetGUID = targetGUID;
1609 sa.ownerGUID = ownerGUID;
1611 sa.script = &iter->second;
1612 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1613 if (iter->first == 0)
1614 immedScript = true;
1616 ///- If one of the effects should be immediate, launch the script execution
1617 if (immedScript)
1618 ScriptsProcess();
1621 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1623 // NOTE: script record _must_ exist until command executed
1625 // prepare static data
1626 uint64 sourceGUID = source->GetGUID();
1627 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1628 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1630 ScriptAction sa;
1631 sa.sourceGUID = sourceGUID;
1632 sa.targetGUID = targetGUID;
1633 sa.ownerGUID = ownerGUID;
1635 sa.script = &script;
1636 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1638 ///- If effects should be immediate, launch the script execution
1639 if(delay == 0)
1640 ScriptsProcess();
1643 /// Process queued scripts
1644 void World::ScriptsProcess()
1646 if (m_scriptSchedule.empty())
1647 return;
1649 ///- Process overdue queued scripts
1650 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1651 // ok as multimap is a *sorted* associative container
1652 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1654 ScriptAction const& step = iter->second;
1656 Object* source = NULL;
1658 if(step.sourceGUID)
1660 switch(GUID_HIPART(step.sourceGUID))
1662 case HIGHGUID_ITEM:
1663 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1665 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1666 if(player)
1667 source = player->GetItemByGuid(step.sourceGUID);
1668 break;
1670 case HIGHGUID_UNIT:
1671 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1672 break;
1673 case HIGHGUID_PET:
1674 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1675 break;
1676 case HIGHGUID_VEHICLE:
1677 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
1678 break;
1679 case HIGHGUID_PLAYER:
1680 source = HashMapHolder<Player>::Find(step.sourceGUID);
1681 break;
1682 case HIGHGUID_GAMEOBJECT:
1683 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1684 break;
1685 case HIGHGUID_CORPSE:
1686 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1687 break;
1688 default:
1689 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1690 break;
1694 if(source && !source->IsInWorld()) source = NULL;
1696 Object* target = NULL;
1698 if(step.targetGUID)
1700 switch(GUID_HIPART(step.targetGUID))
1702 case HIGHGUID_UNIT:
1703 target = HashMapHolder<Creature>::Find(step.targetGUID);
1704 break;
1705 case HIGHGUID_PET:
1706 target = HashMapHolder<Pet>::Find(step.targetGUID);
1707 break;
1708 case HIGHGUID_VEHICLE:
1709 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
1710 break;
1711 case HIGHGUID_PLAYER: // empty GUID case also
1712 target = HashMapHolder<Player>::Find(step.targetGUID);
1713 break;
1714 case HIGHGUID_GAMEOBJECT:
1715 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1716 break;
1717 case HIGHGUID_CORPSE:
1718 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1719 break;
1720 default:
1721 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1722 break;
1726 if(target && !target->IsInWorld()) target = NULL;
1728 switch (step.script->command)
1730 case SCRIPT_COMMAND_TALK:
1732 if(!source)
1734 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1735 break;
1738 if(source->GetTypeId()!=TYPEID_UNIT)
1740 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1741 break;
1744 uint64 unit_target = target ? target->GetGUID() : 0;
1746 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1747 switch(step.script->datalong)
1749 case 0: // Say
1750 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1751 break;
1752 case 1: // Whisper
1753 if(!unit_target)
1755 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1756 break;
1758 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1759 break;
1760 case 2: // Yell
1761 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1762 break;
1763 case 3: // Emote text
1764 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1765 break;
1766 default:
1767 break; // must be already checked at load
1769 break;
1772 case SCRIPT_COMMAND_EMOTE:
1773 if(!source)
1775 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1776 break;
1779 if(source->GetTypeId()!=TYPEID_UNIT)
1781 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1782 break;
1785 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1786 break;
1787 case SCRIPT_COMMAND_FIELD_SET:
1788 if(!source)
1790 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1791 break;
1793 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1795 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1796 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1797 break;
1800 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1801 break;
1802 case SCRIPT_COMMAND_MOVE_TO:
1803 if(!source)
1805 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1806 break;
1809 if(source->GetTypeId()!=TYPEID_UNIT)
1811 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1812 break;
1814 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
1815 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1816 break;
1817 case SCRIPT_COMMAND_FLAG_SET:
1818 if(!source)
1820 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1821 break;
1823 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1825 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1826 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1827 break;
1830 source->SetFlag(step.script->datalong, step.script->datalong2);
1831 break;
1832 case SCRIPT_COMMAND_FLAG_REMOVE:
1833 if(!source)
1835 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1836 break;
1838 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1840 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1841 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1842 break;
1845 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1846 break;
1848 case SCRIPT_COMMAND_TELEPORT_TO:
1850 // accept player in any one from target/source arg
1851 if (!target && !source)
1853 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1854 break;
1857 // must be only Player
1858 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1860 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1861 break;
1864 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1866 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1867 break;
1870 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1872 if(!step.script->datalong) // creature not specified
1874 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1875 break;
1878 if(!source)
1880 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1881 break;
1884 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1886 if(!summoner)
1888 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1889 break;
1892 float x = step.script->x;
1893 float y = step.script->y;
1894 float z = step.script->z;
1895 float o = step.script->o;
1897 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1898 if (!pCreature)
1900 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1901 break;
1904 break;
1907 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1909 if(!step.script->datalong) // gameobject not specified
1911 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1912 break;
1915 if(!source)
1917 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1918 break;
1921 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1923 if(!summoner)
1925 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1926 break;
1929 GameObject *go = NULL;
1930 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1932 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1933 Cell cell(p);
1934 cell.data.Part.reserved = ALL_DISTRICT;
1936 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1937 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
1939 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1940 CellLock<GridReadGuard> cell_lock(cell, p);
1941 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1943 if ( !go )
1945 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1946 break;
1949 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1950 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1951 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1952 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1954 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1955 break;
1958 if( go->isSpawned() )
1959 break; //gameobject already spawned
1961 go->SetLootState(GO_READY);
1962 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1964 go->GetMap()->Add(go);
1965 break;
1967 case SCRIPT_COMMAND_OPEN_DOOR:
1969 if(!step.script->datalong) // door not specified
1971 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1972 break;
1975 if(!source)
1977 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1978 break;
1981 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1983 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1984 break;
1987 Unit* caster = (Unit*)source;
1989 GameObject *door = NULL;
1990 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1992 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1993 Cell cell(p);
1994 cell.data.Part.reserved = ALL_DISTRICT;
1996 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1997 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
1999 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2000 CellLock<GridReadGuard> cell_lock(cell, p);
2001 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2003 if (!door)
2005 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2006 break;
2008 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
2010 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2011 break;
2014 if (door->GetGoState() != GO_STATE_READY)
2015 break; //door already open
2017 door->UseDoorOrButton(time_to_close);
2019 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2020 ((GameObject*)target)->UseDoorOrButton(time_to_close);
2021 break;
2023 case SCRIPT_COMMAND_CLOSE_DOOR:
2025 if(!step.script->datalong) // guid for door not specified
2027 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2028 break;
2031 if(!source)
2033 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2034 break;
2037 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2039 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2040 break;
2043 Unit* caster = (Unit*)source;
2045 GameObject *door = NULL;
2046 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2048 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2049 Cell cell(p);
2050 cell.data.Part.reserved = ALL_DISTRICT;
2052 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2053 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2055 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2056 CellLock<GridReadGuard> cell_lock(cell, p);
2057 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2059 if ( !door )
2061 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2062 break;
2064 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2066 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2067 break;
2070 if( door->GetGoState() == GO_STATE_READY )
2071 break; //door already closed
2073 door->UseDoorOrButton(time_to_open);
2075 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2076 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2078 break;
2080 case SCRIPT_COMMAND_QUEST_EXPLORED:
2082 if(!source)
2084 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2085 break;
2088 if(!target)
2090 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2091 break;
2094 // when script called for item spell casting then target == (unit or GO) and source is player
2095 WorldObject* worldObject;
2096 Player* player;
2098 if(target->GetTypeId()==TYPEID_PLAYER)
2100 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2102 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2103 break;
2106 worldObject = (WorldObject*)source;
2107 player = (Player*)target;
2109 else
2111 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2113 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2114 break;
2117 if(source->GetTypeId()!=TYPEID_PLAYER)
2119 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2120 break;
2123 worldObject = (WorldObject*)target;
2124 player = (Player*)source;
2127 // quest id and flags checked at script loading
2128 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2129 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2130 player->AreaExploredOrEventHappens(step.script->datalong);
2131 else
2132 player->FailQuest(step.script->datalong);
2134 break;
2137 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2139 if(!source)
2141 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2142 break;
2145 if(!source->isType(TYPEMASK_UNIT))
2147 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2148 break;
2151 if(!target)
2153 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2154 break;
2157 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2159 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2160 break;
2163 Unit* caster = (Unit*)source;
2165 GameObject *go = (GameObject*)target;
2167 go->Use(caster);
2168 break;
2171 case SCRIPT_COMMAND_REMOVE_AURA:
2173 Object* cmdTarget = step.script->datalong2 ? source : target;
2175 if(!cmdTarget)
2177 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2178 break;
2181 if(!cmdTarget->isType(TYPEMASK_UNIT))
2183 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2184 break;
2187 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2188 break;
2191 case SCRIPT_COMMAND_CAST_SPELL:
2193 if(!source)
2195 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2196 break;
2199 if(!source->isType(TYPEMASK_UNIT))
2201 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2202 break;
2205 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
2207 if(!cmdTarget)
2209 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
2210 break;
2213 if(!cmdTarget->isType(TYPEMASK_UNIT))
2215 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
2216 break;
2219 Unit* spellTarget = (Unit*)cmdTarget;
2221 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
2223 if(!cmdSource)
2225 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
2226 break;
2229 if(!cmdSource->isType(TYPEMASK_UNIT))
2231 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
2232 break;
2235 Unit* spellSource = (Unit*)cmdSource;
2237 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2238 spellSource->CastSpell(spellTarget,step.script->datalong,false);
2240 break;
2243 case SCRIPT_COMMAND_PLAY_SOUND:
2245 if(!source)
2247 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
2248 break;
2251 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
2252 if(!pSource)
2254 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
2255 break;
2258 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2259 Player* pTarget = NULL;
2260 if(step.script->datalong2 & 1)
2262 if(!target)
2264 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
2265 break;
2268 if(target->GetTypeId()!=TYPEID_PLAYER)
2270 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
2271 break;
2274 pTarget = (Player*)target;
2277 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2278 if(step.script->datalong2 & 2)
2279 pSource->PlayDistanceSound(step.script->datalong,pTarget);
2280 else
2281 pSource->PlayDirectSound(step.script->datalong,pTarget);
2282 break;
2284 default:
2285 sLog.outError("Unknown script command %u called.",step.script->command);
2286 break;
2289 m_scriptSchedule.erase(iter);
2291 iter = m_scriptSchedule.begin();
2293 return;
2296 /// Send a packet to all players (except self if mentioned)
2297 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2299 SessionMap::const_iterator itr;
2300 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2302 if (itr->second &&
2303 itr->second->GetPlayer() &&
2304 itr->second->GetPlayer()->IsInWorld() &&
2305 itr->second != self &&
2306 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2308 itr->second->SendPacket(packet);
2313 namespace MaNGOS
2315 class WorldWorldTextBuilder
2317 public:
2318 typedef std::vector<WorldPacket*> WorldPacketList;
2319 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
2320 void operator()(WorldPacketList& data_list, int32 loc_idx)
2322 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
2324 if(i_args)
2326 // we need copy va_list before use or original va_list will corrupted
2327 va_list ap;
2328 va_copy(ap,*i_args);
2330 char str [2048];
2331 vsnprintf(str,2048,text, ap );
2332 va_end(ap);
2334 do_helper(data_list,&str[0]);
2336 else
2337 do_helper(data_list,(char*)text);
2339 private:
2340 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
2341 void do_helper(WorldPacketList& data_list, char* text)
2343 char* pos = text;
2345 while(char* line = lineFromMessage(pos))
2347 WorldPacket* data = new WorldPacket();
2349 uint32 lineLength = (line ? strlen(line) : 0) + 1;
2351 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
2352 *data << uint8(CHAT_MSG_SYSTEM);
2353 *data << uint32(LANG_UNIVERSAL);
2354 *data << uint64(0);
2355 *data << uint32(0); // can be chat msg group or something
2356 *data << uint64(0);
2357 *data << uint32(lineLength);
2358 *data << line;
2359 *data << uint8(0);
2361 data_list.push_back(data);
2365 int32 i_textId;
2366 va_list* i_args;
2368 } // namespace MaNGOS
2370 /// Send a System Message to all players (except self if mentioned)
2371 void World::SendWorldText(int32 string_id, ...)
2373 va_list ap;
2374 va_start(ap, string_id);
2376 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
2377 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
2378 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2380 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2381 continue;
2383 wt_do(itr->second->GetPlayer());
2386 va_end(ap);
2389 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2390 void World::SendGlobalText(const char* text, WorldSession *self)
2392 WorldPacket data;
2394 // need copy to prevent corruption by strtok call in LineFromMessage original string
2395 char* buf = strdup(text);
2396 char* pos = buf;
2398 while(char* line = ChatHandler::LineFromMessage(pos))
2400 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2401 SendGlobalMessage(&data, self);
2404 free(buf);
2407 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2408 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2410 SessionMap::const_iterator itr;
2411 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2413 if (itr->second &&
2414 itr->second->GetPlayer() &&
2415 itr->second->GetPlayer()->IsInWorld() &&
2416 itr->second->GetPlayer()->GetZoneId() == zone &&
2417 itr->second != self &&
2418 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2420 itr->second->SendPacket(packet);
2425 /// Send a System Message to all players in the zone (except self if mentioned)
2426 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2428 WorldPacket data;
2429 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2430 SendZoneMessage(zone, &data, self,team);
2433 /// Kick (and save) all players
2434 void World::KickAll()
2436 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2438 // session not removed at kick and will removed in next update tick
2439 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2440 itr->second->KickPlayer();
2443 /// Kick (and save) all players with security level less `sec`
2444 void World::KickAllLess(AccountTypes sec)
2446 // session not removed at kick and will removed in next update tick
2447 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2448 if(itr->second->GetSecurity() < sec)
2449 itr->second->KickPlayer();
2452 /// Kick (and save) the designated player
2453 bool World::KickPlayer(const std::string& playerName)
2455 SessionMap::const_iterator itr;
2457 // session not removed at kick and will removed in next update tick
2458 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2460 if(!itr->second)
2461 continue;
2462 Player *player = itr->second->GetPlayer();
2463 if(!player)
2464 continue;
2465 if( player->IsInWorld() )
2467 if (playerName == player->GetName())
2469 itr->second->KickPlayer();
2470 return true;
2474 return false;
2477 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2478 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2480 loginDatabase.escape_string(nameOrIP);
2481 loginDatabase.escape_string(reason);
2482 std::string safe_author=author;
2483 loginDatabase.escape_string(safe_author);
2485 uint32 duration_secs = TimeStringToSecs(duration);
2486 QueryResult *resultAccounts = NULL; //used for kicking
2488 ///- Update the database with ban information
2489 switch(mode)
2491 case BAN_IP:
2492 //No SQL injection as strings are escaped
2493 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2494 loginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+%u,'%s','%s')",nameOrIP.c_str(),duration_secs,safe_author.c_str(),reason.c_str());
2495 break;
2496 case BAN_ACCOUNT:
2497 //No SQL injection as string is escaped
2498 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2499 break;
2500 case BAN_CHARACTER:
2501 //No SQL injection as string is escaped
2502 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2503 break;
2504 default:
2505 return BAN_SYNTAX_ERROR;
2508 if(!resultAccounts)
2510 if(mode==BAN_IP)
2511 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2512 else
2513 return BAN_NOTFOUND; // Nobody to ban
2516 ///- Disconnect all affected players (for IP it can be several)
2519 Field* fieldsAccount = resultAccounts->Fetch();
2520 uint32 account = fieldsAccount->GetUInt32();
2522 if(mode!=BAN_IP)
2524 //No SQL injection as strings are escaped
2525 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2526 account,duration_secs,safe_author.c_str(),reason.c_str());
2529 if (WorldSession* sess = FindSession(account))
2530 if(std::string(sess->GetPlayerName()) != author)
2531 sess->KickPlayer();
2533 while( resultAccounts->NextRow() );
2535 delete resultAccounts;
2536 return BAN_SUCCESS;
2539 /// Remove a ban from an account or IP address
2540 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2542 if (mode == BAN_IP)
2544 loginDatabase.escape_string(nameOrIP);
2545 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2547 else
2549 uint32 account = 0;
2550 if (mode == BAN_ACCOUNT)
2551 account = accmgr.GetId (nameOrIP);
2552 else if (mode == BAN_CHARACTER)
2553 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2555 if (!account)
2556 return false;
2558 //NO SQL injection as account is uint32
2559 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2561 return true;
2564 /// Update the game time
2565 void World::_UpdateGameTime()
2567 ///- update the time
2568 time_t thisTime = time(NULL);
2569 uint32 elapsed = uint32(thisTime - m_gameTime);
2570 m_gameTime = thisTime;
2572 ///- if there is a shutdown timer
2573 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2575 ///- ... and it is overdue, stop the world (set m_stopEvent)
2576 if( m_ShutdownTimer <= elapsed )
2578 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2579 m_stopEvent = true; // exist code already set
2580 else
2581 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2583 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2584 else
2586 m_ShutdownTimer -= elapsed;
2588 ShutdownMsg();
2593 /// Shutdown the server
2594 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2596 // ignore if server shutdown at next tick
2597 if(m_stopEvent)
2598 return;
2600 m_ShutdownMask = options;
2601 m_ExitCode = exitcode;
2603 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2604 if(time==0)
2606 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2607 m_stopEvent = true; // exist code already set
2608 else
2609 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2611 ///- Else set the shutdown timer and warn users
2612 else
2614 m_ShutdownTimer = time;
2615 ShutdownMsg(true);
2619 /// Display a shutdown message to the user(s)
2620 void World::ShutdownMsg(bool show, Player* player)
2622 // not show messages for idle shutdown mode
2623 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2624 return;
2626 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2627 if ( show ||
2628 (m_ShutdownTimer < 10) ||
2629 // < 30 sec; every 5 sec
2630 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2631 // < 5 min ; every 1 min
2632 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2633 // < 30 min ; every 5 min
2634 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2635 // < 12 h ; every 1 h
2636 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2637 // > 12 h ; every 12 h
2638 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2640 std::string str = secsToTimeString(m_ShutdownTimer);
2642 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2644 SendServerMessage(msgid,str.c_str(),player);
2645 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2649 /// Cancel a planned server shutdown
2650 void World::ShutdownCancel()
2652 // nothing cancel or too later
2653 if(!m_ShutdownTimer || m_stopEvent)
2654 return;
2656 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2658 m_ShutdownMask = 0;
2659 m_ShutdownTimer = 0;
2660 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2661 SendServerMessage(msgid);
2663 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2666 /// Send a server message to the user(s)
2667 void World::SendServerMessage(ServerMessageType type, const char *text, Player* player)
2669 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2670 data << uint32(type);
2671 if(type <= SERVER_MSG_STRING)
2672 data << text;
2674 if(player)
2675 player->GetSession()->SendPacket(&data);
2676 else
2677 SendGlobalMessage( &data );
2680 void World::UpdateSessions( uint32 diff )
2682 ///- Add new sessions
2683 while(!addSessQueue.empty())
2685 WorldSession* sess = addSessQueue.next ();
2686 AddSession_ (sess);
2689 ///- Then send an update signal to remaining ones
2690 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2692 next = itr;
2693 ++next;
2695 if(!itr->second)
2696 continue;
2698 ///- and remove not active sessions from the list
2699 if(!itr->second->Update(diff)) // As interval = 0
2701 RemoveQueuedPlayer (itr->second);
2702 delete itr->second;
2703 m_sessions.erase(itr);
2708 // This handles the issued and queued CLI commands
2709 void World::ProcessCliCommands()
2711 if (cliCmdQueue.empty())
2712 return;
2714 CliCommandHolder::Print* zprint;
2716 while (!cliCmdQueue.empty())
2718 sLog.outDebug("CLI command under processing...");
2719 CliCommandHolder *command = cliCmdQueue.next();
2721 zprint = command->m_print;
2723 CliHandler(zprint).ParseCommands(command->m_command);
2725 delete command;
2728 // print the console message here so it looks right
2729 zprint("mangos>");
2732 void World::InitResultQueue()
2734 m_resultQueue = new SqlResultQueue;
2735 CharacterDatabase.SetResultQueue(m_resultQueue);
2738 void World::UpdateResultQueue()
2740 m_resultQueue->Update();
2743 void World::UpdateRealmCharCount(uint32 accountId)
2745 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2746 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2749 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2751 if (resultCharCount)
2753 Field *fields = resultCharCount->Fetch();
2754 uint32 charCount = fields[0].GetUInt32();
2755 delete resultCharCount;
2756 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2757 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2761 void World::InitDailyQuestResetTime()
2763 time_t mostRecentQuestTime;
2765 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2766 if(result)
2768 Field *fields = result->Fetch();
2770 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2771 delete result;
2773 else
2774 mostRecentQuestTime = 0;
2776 // client built-in time for reset is 6:00 AM
2777 // FIX ME: client not show day start time
2778 time_t curTime = time(NULL);
2779 tm localTm = *localtime(&curTime);
2780 localTm.tm_hour = 6;
2781 localTm.tm_min = 0;
2782 localTm.tm_sec = 0;
2784 // current day reset time
2785 time_t curDayResetTime = mktime(&localTm);
2787 // last reset time before current moment
2788 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2790 // need reset (if we have quest time before last reset time (not processed by some reason)
2791 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2792 m_NextDailyQuestReset = mostRecentQuestTime;
2793 else
2795 // plan next reset time
2796 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2800 void World::ResetDailyQuests()
2802 sLog.outDetail("Daily quests reset for all characters.");
2803 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2804 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2805 if(itr->second->GetPlayer())
2806 itr->second->GetPlayer()->ResetDailyQuestStatus();
2809 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2811 if(limit < -SEC_ADMINISTRATOR)
2812 limit = -SEC_ADMINISTRATOR;
2814 // lock update need
2815 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2817 m_playerLimit = limit;
2819 if(db_update_need)
2820 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2823 void World::UpdateMaxSessionCounters()
2825 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2826 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2829 void World::LoadDBVersion()
2831 QueryResult* result = WorldDatabase.Query("SELECT version, creature_ai_version FROM db_version LIMIT 1");
2832 if(result)
2834 Field* fields = result->Fetch();
2836 m_DBVersion = fields[0].GetCppString();
2837 m_CreatureEventAIVersion = fields[1].GetCppString();
2838 delete result;
2841 if(m_DBVersion.empty())
2842 m_DBVersion = "Unknown world database.";
2844 if(m_CreatureEventAIVersion.empty())
2845 m_CreatureEventAIVersion = "Unknown creature EventAI.";