root/trunk/src/game/World.cpp @ 34

Revision 34, 108.7 kB (checked in by yumileroy, 17 years ago)

[svn] * Removing useless data accidentally committed.
* Applying ImpConfig? patch.
* Note: QUEUE_FOR_GM currently disabled as it's not compatible with the ACE patch. Anyone care to rewrite it?
* Note2: This is untested - I may have done some mistakes here and there. Will try to compile now.

Original author: XTZGZoReX
Date: 2008-10-10 13:37:21-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
19/** \file
20    \ingroup world
21*/
22
23#include "Common.h"
24//#include "WorldSocket.h"
25#include "Database/DatabaseEnv.h"
26#include "Config/ConfigEnv.h"
27#include "SystemConfig.h"
28#include "Log.h"
29#include "Opcodes.h"
30#include "WorldSession.h"
31#include "WorldPacket.h"
32#include "Weather.h"
33#include "Player.h"
34#include "SkillExtraItems.h"
35#include "SkillDiscovery.h"
36#include "World.h"
37#include "ObjectMgr.h"
38#include "SpellMgr.h"
39#include "Chat.h"
40#include "Database/DBCStores.h"
41#include "LootMgr.h"
42#include "ItemEnchantmentMgr.h"
43#include "MapManager.h"
44#include "ScriptCalls.h"
45#include "CreatureAIRegistry.h"
46#include "Policies/SingletonImp.h"
47#include "BattleGroundMgr.h"
48#include "TemporarySummon.h"
49#include "WaypointMovementGenerator.h"
50#include "VMapFactory.h"
51#include "GlobalEvents.h"
52#include "GameEvent.h"
53#include "Database/DatabaseImpl.h"
54#include "GridNotifiersImpl.h"
55#include "CellImpl.h"
56#include "InstanceSaveMgr.h"
57#include "WaypointManager.h"
58#include "Util.h"
59
60INSTANTIATE_SINGLETON_1( World );
61
62volatile bool World::m_stopEvent = false;
63volatile uint32 World::m_worldLoopCounter = 0;
64
65float World::m_PlayerStartGold = 0; // starting gold
66float World::m_MaxVisibleDistanceForCreature  = DEFAULT_VISIBILITY_DISTANCE;
67float World::m_MaxVisibleDistanceForPlayer    = DEFAULT_VISIBILITY_DISTANCE;
68float World::m_MaxVisibleDistanceForObject    = DEFAULT_VISIBILITY_DISTANCE;
69float World::m_MaxVisibleDistanceInFlight     = DEFAULT_VISIBILITY_DISTANCE;
70float World::m_VisibleUnitGreyDistance        = 0;
71float World::m_VisibleObjectGreyDistance      = 0;
72
73// ServerMessages.dbc
74enum ServerMessageType
75{
76    SERVER_MSG_SHUTDOWN_TIME      = 1,
77    SERVER_MSG_RESTART_TIME       = 2,
78    SERVER_MSG_STRING             = 3,
79    SERVER_MSG_SHUTDOWN_CANCELLED = 4,
80    SERVER_MSG_RESTART_CANCELLED  = 5
81};
82
83struct ScriptAction
84{
85    uint64 sourceGUID;
86    uint64 targetGUID;
87    uint64 ownerGUID;                                       // owner of source if source is item
88    ScriptInfo const* script;                               // pointer to static script data
89};
90
91/// World constructor
92World::World()
93{
94    m_playerLimit = 0;
95    m_allowMovement = true;
96    m_ShutdownMask = 0;
97    m_ShutdownTimer = 0;
98    m_gameTime=time(NULL);
99    m_startTime=m_gameTime;
100    m_maxActiveSessionCount = 0;
101    m_maxQueuedSessionCount = 0;
102    m_resultQueue = NULL;
103    m_NextDailyQuestReset = 0;
104
105    m_defaultDbcLocale = LOCALE_enUS;
106    m_availableDbcLocaleMask = 0;
107}
108
109/// World destructor
110World::~World()
111{
112    ///- Empty the kicked session set
113    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
114        delete *itr;
115
116    m_kicked_sessions.clear();
117
118    ///- Empty the WeatherMap
119    for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
120        delete itr->second;
121
122    m_weathers.clear();
123
124    VMAP::VMapFactory::clear();
125
126    if(m_resultQueue) delete m_resultQueue;
127   
128    //TODO free addSessQueue
129}
130
131/// Find a player in a specified zone
132Player* World::FindPlayerInZone(uint32 zone)
133{
134    ///- circle through active sessions and return the first player found in the zone
135    SessionMap::iterator itr;
136    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
137    {
138        if(!itr->second)
139            continue;
140        Player *player = itr->second->GetPlayer();
141        if(!player)
142            continue;
143        if( player->IsInWorld() && player->GetZoneId() == zone )
144        {
145            // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
146            return player;
147        }
148    }
149    return NULL;
150}
151
152/// Find a session by its id
153WorldSession* World::FindSession(uint32 id) const
154{
155    SessionMap::const_iterator itr = m_sessions.find(id);
156
157    if(itr != m_sessions.end())
158        return itr->second;                                 // also can return NULL for kicked session
159    else
160        return NULL;
161}
162
163/// Remove a given session
164bool World::RemoveSession(uint32 id)
165{
166    ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
167    SessionMap::iterator itr = m_sessions.find(id);
168
169    if(itr != m_sessions.end() && itr->second)
170    {
171        if (itr->second->PlayerLoading())
172            return false;
173        itr->second->KickPlayer();
174    }
175
176    return true;
177}
178
179void World::AddSession(WorldSession* s)
180{
181  addSessQueue.add(s);
182}
183
184void
185World::AddSession_ (WorldSession* s)
186{
187  ASSERT (s);
188
189  //NOTE - Still there is race condition in WorldSession* being used in the Sockets
190
191  ///- kick already loaded player with same account (if any) and remove session
192  ///- if player is in loading and want to load again, return
193  if (!RemoveSession (s->GetAccountId ()))
194    {
195      s->KickPlayer ();
196      m_kicked_sessions.insert (s);
197      return;
198    }
199
200  WorldSession* old = m_sessions[s->GetAccountId ()];
201  m_sessions[s->GetAccountId ()] = s;
202
203  // if session already exist, prepare to it deleting at next world update
204  // NOTE - KickPlayer() should be called on "old" in RemoveSession()
205  if (old)
206    m_kicked_sessions.insert (old);
207
208  uint32 Sessions = GetActiveAndQueuedSessionCount ();
209  uint32 pLimit = GetPlayerAmountLimit ();
210  uint32 QueueSize = GetQueueSize (); //number of players in the queue
211  bool inQueue = false;
212  //so we don't count the user trying to
213  //login as a session and queue the socket that we are using
214  --Sessions;
215
216  if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
217    {
218      AddQueuedPlayer (s);
219      UpdateMaxSessionCounters ();
220      sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
221      return;
222    }
223 
224  WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
225  packet << uint8 (AUTH_OK);
226  packet << uint32 (0); // unknown random value...
227  packet << uint8 (0);
228  packet << uint32 (0);
229  packet << uint8 (s->IsTBC () ? 1 : 0); // 0 - normal, 1 - TBC, must be set in database manually for each account
230  s->SendPacket (&packet);
231
232  UpdateMaxSessionCounters ();
233
234  // Updates the population
235  if (pLimit > 0)
236    {
237      float popu = GetActiveSessionCount (); //updated number of users on the server
238      popu /= pLimit;
239      popu *= 2;
240      loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
241      sLog.outDetail ("Server Population (%f).", popu);
242    }
243}
244
245int32 World::GetQueuePos(WorldSession* sess)
246{
247    uint32 position = 1;
248
249    for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
250        if((*iter) == sess)
251            return position;
252
253    return 0;
254}
255
256void World::AddQueuedPlayer(WorldSession* sess)
257{
258    m_QueuedPlayer.push_back (sess);
259   
260    // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
261    WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
262    packet << uint8 (AUTH_WAIT_QUEUE);
263    packet << uint32 (0); // unknown random value...
264    packet << uint8 (0);
265    packet << uint32 (0);
266    packet << uint8 (sess->IsTBC () ? 1 : 0); // 0 - normal, 1 - TBC, must be set in database manually for each account
267    packet << uint32(GetQueuePos (sess));
268    sess->SendPacket (&packet);
269   
270    //sess->SendAuthWaitQue (GetQueuePos (sess));
271}
272
273void World::RemoveQueuedPlayer(WorldSession* sess)
274{
275    // sessions count including queued to remove (if removed_session set)
276    uint32 sessions = GetActiveSessionCount();
277
278    uint32 position = 1;
279    Queue::iterator iter = m_QueuedPlayer.begin();
280
281    // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
282    bool decrease_session = true;
283
284    // search to remove and count skipped positions
285    for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
286    {
287        if(*iter==sess)
288        {
289            Queue::iterator iter2 = iter;
290            ++iter;
291            m_QueuedPlayer.erase(iter2);
292            decrease_session = false;                       // removing queued session
293            break;
294        }
295    }
296
297    // iter point to next socked after removed or end()
298    // position store position of removed socket and then new position next socket after removed
299
300    // decrease for case session queued for removing
301    if(decrease_session && sessions)
302        --sessions;
303
304    // accept first in queue
305    if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
306    {
307        WorldSession * socket = m_QueuedPlayer.front();
308        socket->SendAuthWaitQue(0);
309        m_QueuedPlayer.pop_front();
310
311        // update iter to point first queued socket or end() if queue is empty now
312        iter = m_QueuedPlayer.begin();
313        position = 1;
314    }
315
316    // update position from iter to end()
317    // iter point to first not updated socket, position store new position
318    for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
319        (*iter)->SendAuthWaitQue(position);
320}
321
322/// Find a Weather object by the given zoneid
323Weather* World::FindWeather(uint32 id) const
324{
325    WeatherMap::const_iterator itr = m_weathers.find(id);
326
327    if(itr != m_weathers.end())
328        return itr->second;
329    else
330        return 0;
331}
332
333/// Remove a Weather object for the given zoneid
334void World::RemoveWeather(uint32 id)
335{
336    // not called at the moment. Kept for completeness
337    WeatherMap::iterator itr = m_weathers.find(id);
338
339    if(itr != m_weathers.end())
340    {
341        delete itr->second;
342        m_weathers.erase(itr);
343    }
344}
345
346/// Add a Weather object to the list
347Weather* World::AddWeather(uint32 zone_id)
348{
349    WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
350
351    // zone not have weather, ignore
352    if(!weatherChances)
353        return NULL;
354
355    Weather* w = new Weather(zone_id,weatherChances);
356    m_weathers[w->GetZone()] = w;
357    w->ReGenerate();
358    w->UpdateWeather();
359    return w;
360}
361
362/// Initialize config values
363void World::LoadConfigSettings(bool reload)
364{
365    if(reload)
366    {
367        if(!sConfig.Reload())
368        {
369            sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
370            return;
371        }
372        //TODO Check if config is outdated
373    }
374
375    ///- Read the player limit and the Message of the day from the config file
376    SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
377    SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
378
379    ///- Read all rates from the config file
380    rate_values[RATE_HEALTH]      = sConfig.GetFloatDefault("Rate.Health", 1);
381    if(rate_values[RATE_HEALTH] < 0)
382    {
383        sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
384        rate_values[RATE_HEALTH] = 1;
385    }
386    rate_values[RATE_POWER_MANA]  = sConfig.GetFloatDefault("Rate.Mana", 1);
387    if(rate_values[RATE_POWER_MANA] < 0)
388    {
389        sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
390        rate_values[RATE_POWER_MANA] = 1;
391    }
392    rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
393    rate_values[RATE_POWER_RAGE_LOSS]   = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
394    if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
395    {
396        sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
397        rate_values[RATE_POWER_RAGE_LOSS] = 1;
398    }
399    rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
400    rate_values[RATE_LOYALTY]     = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
401    rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
402    rate_values[RATE_DROP_ITEM_POOR]       = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
403    rate_values[RATE_DROP_ITEM_NORMAL]     = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
404    rate_values[RATE_DROP_ITEM_UNCOMMON]   = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
405    rate_values[RATE_DROP_ITEM_RARE]       = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
406    rate_values[RATE_DROP_ITEM_EPIC]       = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
407    rate_values[RATE_DROP_ITEM_LEGENDARY]  = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
408    rate_values[RATE_DROP_ITEM_ARTIFACT]   = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
409    rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
410    rate_values[RATE_DROP_MONEY]  = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
411    rate_values[RATE_XP_KILL]     = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
412    rate_values[RATE_XP_QUEST]    = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
413    rate_values[RATE_XP_EXPLORE]  = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
414    rate_values[RATE_XP_PAST_70]  = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
415    rate_values[RATE_REPUTATION_GAIN]  = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
416    rate_values[RATE_CREATURE_NORMAL_DAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
417    rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
418    rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
419    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
420    rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
421    rate_values[RATE_CREATURE_NORMAL_HP]          = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
422    rate_values[RATE_CREATURE_ELITE_ELITE_HP]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
423    rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
424    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
425    rate_values[RATE_CREATURE_ELITE_RARE_HP]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
426    rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
427    rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
428    rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
429    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
430    rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
431    rate_values[RATE_CREATURE_AGGRO]  = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
432    rate_values[RATE_REST_INGAME]                    = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
433    rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
434    rate_values[RATE_REST_OFFLINE_IN_WILDERNESS]     = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
435    rate_values[RATE_DAMAGE_FALL]  = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
436    rate_values[RATE_AUCTION_TIME]  = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
437    rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
438    rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
439    rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
440    rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
441    rate_values[RATE_MINING_NEXT]   = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
442    rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
443    rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
444    if(rate_values[RATE_TALENT] < 0.0f)
445    {
446        sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
447        rate_values[RATE_TALENT] = 1.0f;
448    }
449    rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
450
451    rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
452    if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
453    {
454        sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
455        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
456    }
457    else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
458    {
459        sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
460        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
461    }
462
463    rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
464    if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
465    {
466        sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
467        rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
468    }
469    rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
470    if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
471    {
472        sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
473        rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
474    }
475    rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
476    if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
477    {
478        sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
479        rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
480    }
481    rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
482    if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
483    {
484        sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
485        rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
486    }
487
488    ///- Read other configuration items from the config file
489
490    m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
491    if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
492    {
493        sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
494        m_configs[CONFIG_COMPRESSION] = 1;
495    }
496    m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
497    m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
498    m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
499
500    m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
501    if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
502    {
503        sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
504        m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
505    }
506    if(reload)
507        MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
508
509    m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
510    if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
511    {
512        sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
513        m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
514    }
515    if(reload)
516        MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
517
518    m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
519
520    if(reload)
521    {
522        uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
523        if(val!=m_configs[CONFIG_PORT_WORLD])
524            sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
525    }
526    else
527        m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
528
529    if(reload)
530    {
531        uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
532        if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
533            sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
534    }
535    else
536        m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
537
538
539    m_configs[CONFIG_TCP_NO_DELAY] = sConfig.GetBoolDefault("TcpNoDelay", false);
540    m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
541    /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
542    m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
543    m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
544
545    if(reload)
546    {
547        uint32 val = sConfig.GetIntDefault("GameType", 0);
548        if(val!=m_configs[CONFIG_GAME_TYPE])
549            sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
550    }
551    else
552        m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
553
554    if(reload)
555    {
556        uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
557        if(val!=m_configs[CONFIG_REALM_ZONE])
558            sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
559    }
560    else
561        m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
562
563    m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
564    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
565    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
566    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
567    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
568    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
569    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
570    m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
571    m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
572    m_configs[CONFIG_STRICT_PLAYER_NAMES]  = sConfig.GetIntDefault("StrictPlayerNames",  0);
573    m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
574    m_configs[CONFIG_STRICT_PET_NAMES]     = sConfig.GetIntDefault("StrictPetNames",     0);
575
576    m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
577
578    m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
579    if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
580    {
581        sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
582        m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
583    }
584
585    // must be after CONFIG_CHARACTERS_PER_REALM
586    m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
587    if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
588    {
589        sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
590        m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
591    }
592
593    m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
594    if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
595    {
596        sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
597        m_configs[CONFIG_SKIP_CINEMATICS] = 0;
598    }
599
600
601    if(reload)
602    {
603        uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
604        if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
605            sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
606    }
607    else
608        m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
609    if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
610    {
611        sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
612        m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
613    }
614
615    m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
616    if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
617    {
618        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]);
619        m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
620    }
621    else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
622    {
623        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]);
624        m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
625    }
626    m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
627    m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
628
629    m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
630    m_configs[CONFIG_INSTANCE_IGNORE_RAID]  = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
631
632    m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER]              = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
633
634    m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
635    m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR]  = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
636    m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
637
638    m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
639    m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
640    if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
641    {
642        sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
643        m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
644    }
645
646    m_configs[CONFIG_GM_LOGIN_STATE]       = sConfig.GetIntDefault("GM.LoginState",2);
647    m_configs[CONFIG_GM_ACCEPT_TICKETS]    = sConfig.GetIntDefault("GM.AcceptTickets",2);
648    m_configs[CONFIG_GM_CHAT]              = sConfig.GetIntDefault("GM.Chat",2);
649    m_configs[CONFIG_GM_WISPERING_TO]      = sConfig.GetIntDefault("GM.WhisperingTo",2);
650
651    m_configs[CONFIG_GM_IN_GM_LIST]        = sConfig.GetBoolDefault("GM.InGMList",false);
652    m_configs[CONFIG_GM_IN_WHO_LIST]       = sConfig.GetBoolDefault("GM.InWhoList",false);
653    m_configs[CONFIG_GM_LOG_TRADE]         = sConfig.GetBoolDefault("GM.LogTrade", false);
654
655    m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
656
657    m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
658
659    m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
660    if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
661    {
662        sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
663        m_configs[CONFIG_UPTIME_UPDATE] = 10;
664    }
665    if(reload)
666    {
667        m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
668        m_timers[WUPDATE_UPTIME].Reset();
669    }
670
671    m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
672    m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
673    m_configs[CONFIG_SKILL_CHANCE_GREEN]  = sConfig.GetIntDefault("SkillChance.Green",25);
674    m_configs[CONFIG_SKILL_CHANCE_GREY]   = sConfig.GetIntDefault("SkillChance.Grey",0);
675
676    m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS]  = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
677    m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS]   = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
678
679    m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
680
681    m_configs[CONFIG_SKILL_GAIN_CRAFTING]  = sConfig.GetIntDefault("SkillGain.Crafting", 1);
682    if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
683    {
684        sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
685        m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
686    }
687
688    m_configs[CONFIG_SKILL_GAIN_DEFENSE]  = sConfig.GetIntDefault("SkillGain.Defense", 1);
689    if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
690    {
691        sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
692        m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
693    }
694
695    m_configs[CONFIG_SKILL_GAIN_GATHERING]  = sConfig.GetIntDefault("SkillGain.Gathering", 1);
696    if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
697    {
698        sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
699        m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
700    }
701
702    m_configs[CONFIG_SKILL_GAIN_WEAPON]  = sConfig.GetIntDefault("SkillGain.Weapon", 1);
703    if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
704    {
705        sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
706        m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
707    }
708
709    m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
710    if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
711    {
712        sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
713        m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
714    }
715
716    m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
717    m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
718
719    if(reload)
720    {
721        uint32 val = sConfig.GetIntDefault("Expansion",1);
722        if(val!=m_configs[CONFIG_EXPANSION])
723            sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
724    }
725    else
726        m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
727
728    m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
729    m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
730    m_configs[CONFIG_CHATFLOOD_MUTE_TIME]     = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
731
732    m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
733
734    m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
735
736    m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
737
738    // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
739    m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
740    if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
741        m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
742    m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
743    if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
744        m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
745
746    m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
747    m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
748
749    m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
750    m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
751
752    m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
753    m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
754    m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
755    m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
756    m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
757
758    m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
759    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
760    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
761
762    m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
763
764    // always use declined names in the russian client
765    m_configs[CONFIG_DECLINED_NAMES_USED] = 
766        (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
767
768    m_configs[CONFIG_LISTEN_RANGE_SAY]       = sConfig.GetIntDefault("ListenRange.Say", 25);
769    m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
770    m_configs[CONFIG_LISTEN_RANGE_YELL]      = sConfig.GetIntDefault("ListenRange.Yell", 300);
771
772        m_PlayerStartGold = sConfig.GetFloatDefault("PlayerStart.Gold", 0);
773        if(m_PlayerStartGold < 0)
774                m_PlayerStartGold = 0;
775
776        if(m_PlayerStartGold > MAX_MONEY_AMOUNT)
777                m_PlayerStartGold = MAX_MONEY_AMOUNT;
778
779        m_configs[CONFIG_PLAYER_START_HONOR] = sConfig.GetIntDefault("PlayerStart.HonorPoints", 0);
780        if(m_configs[CONFIG_PLAYER_START_HONOR] < 0)
781                m_configs[CONFIG_PLAYER_START_HONOR] = 0;
782
783        m_configs[CONFIG_PLAYER_START_ARENAPTS] = sConfig.GetIntDefault("PlayerStart.ArenaPoints", 0);
784        if(m_configs[CONFIG_PLAYER_START_ARENAPTS] < 0)
785                m_configs[CONFIG_PLAYER_START_ARENAPTS] = 0;
786
787        m_configs[CONFIG_GM_START_LEVEL] = sConfig.GetIntDefault("GamemasterStartLevel", 70);
788        if(m_configs[CONFIG_GM_START_LEVEL] < 1)
789                m_configs[CONFIG_GM_START_LEVEL] = 1;
790
791        m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetBoolDefault("PlayerInstantLogout", false);
792        m_configs[CONFIG_BG_START_MUSIC] = sConfig.GetBoolDefault("MusicInBattleground", false);
793        m_configs[CONFIG_START_ALL_SPELLS] = sConfig.GetBoolDefault("PlayerStart.AllSpells", false);
794        // Leaving GM queue option out for now, it's not 100% functional with the ACE patch
795        //m_configs[CONFIG_QUEUE_FOR_GM] = sConfig.GetBoolDefault("EnableQueueForGMs", false);
796        m_configs[CONFIG_HONOR_AFTER_DUEL] = sConfig.GetIntDefault("HonorPointsAfterDuel", 0);
797        if(m_configs[CONFIG_HONOR_AFTER_DUEL] < 0)
798                m_configs[CONFIG_HONOR_AFTER_DUEL]= 0;
799        m_configs[CONFIG_KICK_FROM_GMISLAND] = sConfig.GetBoolDefault("AntiCheat.GMIsland", false);
800        m_configs[CONFIG_START_ALL_EXPLORED] = sConfig.GetBoolDefault("PlayerStart.MapsExplored", false);
801        m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetBoolDefault("DisableWaterBreath", false);
802        m_configs[CONFIG_DISABLE_RES_SICKNESS] = sConfig.GetBoolDefault("DisableResurrectSickness", false);
803        m_configs[CONFIG_START_ALL_REP] = sConfig.GetBoolDefault("PlayerStart.AllReputation", false);
804        m_configs[CONFIG_ALWAYS_MAXSKILL] = sConfig.GetBoolDefault("AlwaysMaxWeaponSkill", false);
805        m_configs[CONFIG_START_ALL_TAXI] = sConfig.GetBoolDefault("PlayerStart.AllFlightPaths", false);
806        m_configs[CONFIG_PVP_TOKEN_ENABLE] = sConfig.GetBoolDefault("PvPToken.Enable", false);
807        m_configs[CONFIG_PVP_TOKEN_MAP_TYPE] = sConfig.GetIntDefault("PvPToken.MapAllowType", 4);
808        m_configs[CONFIG_PVP_TOKEN_ID] = sConfig.GetIntDefault("PvPToken.ItemID", 29434);
809        m_configs[CONFIG_PVP_TOKEN_COUNT] = sConfig.GetIntDefault("PvPToken.ItemCount", 1);
810        if(m_configs[CONFIG_PVP_TOKEN_COUNT] < 1)
811                m_configs[CONFIG_PVP_TOKEN_COUNT] = 1;
812        m_configs[CONFIG_NO_RESET_TALENT_COST] = sConfig.GetBoolDefault("NoResetTalentsCost", false);
813
814    m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
815    m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
816    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
817    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
818
819    m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
820
821    m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
822    if(m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
823    {
824        sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
825        m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
826    }
827    m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
828    if(m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
829    {
830        sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
831        m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
832    }
833
834    m_MaxVisibleDistanceForCreature      = sConfig.GetFloatDefault("Visibility.Distance.Creature",     DEFAULT_VISIBILITY_DISTANCE);
835    if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
836    {
837        sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
838        m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
839    }
840    else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
841    {
842        sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
843        m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
844    }
845    m_MaxVisibleDistanceForPlayer        = sConfig.GetFloatDefault("Visibility.Distance.Player",       DEFAULT_VISIBILITY_DISTANCE);
846    if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
847    {
848        sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
849        m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
850    }
851    else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
852    {
853        sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
854        m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
855    }
856    m_MaxVisibleDistanceForObject    = sConfig.GetFloatDefault("Visibility.Distance.Gameobject",   DEFAULT_VISIBILITY_DISTANCE);
857    if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
858    {
859        sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
860        m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
861    }
862    else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
863    {
864        sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
865        m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
866    }
867    m_MaxVisibleDistanceInFlight    = sConfig.GetFloatDefault("Visibility.Distance.InFlight",      DEFAULT_VISIBILITY_DISTANCE);
868    if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
869    {
870        sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
871        m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
872    }
873
874    ///- Read the "Data" directory from the config file
875    std::string dataPath = sConfig.GetStringDefault("DataDir","./");
876    if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
877        dataPath.append("/");
878
879    if(reload)
880    {
881        if(dataPath!=m_dataPath)
882            sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
883    }
884    else
885    {
886        m_dataPath = dataPath;
887        sLog.outString("Using DataDir %s",m_dataPath.c_str());
888    }
889
890    bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
891    bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
892    std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
893    std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
894    VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
895    VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
896    VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
897    VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
898    sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
899    sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
900    sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
901}
902
903/// Initialize the World
904void World::SetInitialWorldSettings()
905{
906    ///- Initialize the random number generator
907    srand((unsigned int)time(NULL));
908
909    ///- Initialize config settings
910    LoadConfigSettings();
911
912    ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
913    objmgr.SetHighestGuids();
914
915    ///- Check the existence of the map files for all races' startup areas.
916    if(   !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
917        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
918        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
919        ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
920        ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
921        ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
922        ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
923        ||m_configs[CONFIG_EXPANSION] && (
924        !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
925    {
926        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());
927        exit(1);
928    }
929
930    ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
931    sLog.outString( "" );
932    sLog.outString( "Loading MaNGOS strings..." );
933    if (!objmgr.LoadMangosStrings())
934        exit(1);                                            // Error message displayed in function already
935
936    ///- Update the realm entry in the database with the realm type from the config file
937    //No SQL injection as values are treated as integers
938
939    // not send custom type REALM_FFA_PVP to realm list
940    uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
941    uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
942    loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
943
944    ///- Remove the bones after a restart
945    CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
946
947    ///- Load the DBC files
948    sLog.outString("Initialize data stores...");
949    LoadDBCStores(m_dataPath);
950    DetectDBCLang();
951
952    sLog.outString( "Loading InstanceTemplate" );
953    objmgr.LoadInstanceTemplate();
954
955    sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
956    spellmgr.LoadSkillLineAbilityMap();
957
958    ///- Clean up and pack instances
959    sLog.outString( "Cleaning up instances..." );
960    sInstanceSaveManager.CleanupInstances();                              // must be called before `creature_respawn`/`gameobject_respawn` tables
961
962    sLog.outString( "Packing instances..." );
963    sInstanceSaveManager.PackInstances();
964
965    sLog.outString( "Loading Localization strings..." );
966    objmgr.LoadCreatureLocales();
967    objmgr.LoadGameObjectLocales();
968    objmgr.LoadItemLocales();
969    objmgr.LoadQuestLocales();
970    objmgr.LoadNpcTextLocales();
971    objmgr.LoadPageTextLocales();
972    objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale());        // Get once for all the locale index of DBC language (console/broadcasts)
973
974    sLog.outString( "Loading Page Texts..." );
975    objmgr.LoadPageTexts();
976
977    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
978    objmgr.LoadGameobjectInfo();
979
980    sLog.outString( "Loading Spell Chain Data..." );
981    spellmgr.LoadSpellChains();
982
983    sLog.outString( "Loading Spell Elixir types..." );
984    spellmgr.LoadSpellElixirs();
985
986    sLog.outString( "Loading Spell Learn Skills..." );
987    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
988
989    sLog.outString( "Loading Spell Learn Spells..." );
990    spellmgr.LoadSpellLearnSpells();
991
992    sLog.outString( "Loading Spell Proc Event conditions..." );
993    spellmgr.LoadSpellProcEvents();
994
995    sLog.outString( "Loading Aggro Spells Definitions...");
996    spellmgr.LoadSpellThreats();
997
998    sLog.outString( "Loading NPC Texts..." );
999    objmgr.LoadGossipText();
1000
1001    sLog.outString( "Loading Item Random Enchantments Table..." );
1002    LoadRandomEnchantmentsTable();
1003
1004    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1005    objmgr.LoadItemPrototypes();
1006
1007    sLog.outString( "Loading Item Texts..." );
1008    objmgr.LoadItemTexts();
1009
1010    sLog.outString( "Loading Creature Model Based Info Data..." );
1011    objmgr.LoadCreatureModelInfo();
1012
1013    sLog.outString( "Loading Equipment templates...");
1014    objmgr.LoadEquipmentTemplates();
1015
1016    sLog.outString( "Loading Creature templates..." );
1017    objmgr.LoadCreatureTemplates();
1018
1019    sLog.outString( "Loading SpellsScriptTarget...");
1020    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
1021
1022    sLog.outString( "Loading Creature Reputation OnKill Data..." );
1023    objmgr.LoadReputationOnKill();
1024
1025    sLog.outString( "Loading Pet Create Spells..." );
1026    objmgr.LoadPetCreateSpells();
1027
1028    sLog.outString( "Loading Creature Data..." );
1029    objmgr.LoadCreatures();
1030
1031    sLog.outString( "Loading Creature Addon Data..." );
1032    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
1033
1034    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
1035    objmgr.LoadCreatureRespawnTimes();
1036
1037    sLog.outString( "Loading Gameobject Data..." );
1038    objmgr.LoadGameobjects();
1039
1040    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1041    objmgr.LoadGameobjectRespawnTimes();
1042
1043    sLog.outString( "Loading Game Event Data...");
1044    gameeventmgr.LoadFromDB();
1045
1046    sLog.outString( "Loading Weather Data..." );
1047    objmgr.LoadWeatherZoneChances();
1048
1049    sLog.outString( "Loading Quests..." );
1050    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
1051
1052    sLog.outString( "Loading Quests Relations..." );
1053    objmgr.LoadQuestRelations();                            // must be after quest load
1054
1055    sLog.outString( "Loading AreaTrigger definitions..." );
1056    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
1057
1058    sLog.outString( "Loading Quest Area Triggers..." );
1059    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
1060
1061    sLog.outString( "Loading Tavern Area Triggers..." );
1062    objmgr.LoadTavernAreaTriggers();
1063   
1064    sLog.outString( "Loading AreaTrigger script names..." );
1065    objmgr.LoadAreaTriggerScripts();
1066
1067
1068    sLog.outString( "Loading Graveyard-zone links...");
1069    objmgr.LoadGraveyardZones();
1070
1071    sLog.outString( "Loading Spell target coordinates..." );
1072    spellmgr.LoadSpellTargetPositions();
1073
1074    sLog.outString( "Loading SpellAffect definitions..." );
1075    spellmgr.LoadSpellAffects();
1076
1077    sLog.outString( "Loading spell pet auras..." );
1078    spellmgr.LoadSpellPetAuras();
1079
1080    sLog.outString( "Loading player Create Info & Level Stats..." );
1081    objmgr.LoadPlayerInfo();
1082
1083    sLog.outString( "Loading Exploration BaseXP Data..." );
1084    objmgr.LoadExplorationBaseXP();
1085
1086    sLog.outString( "Loading Pet Name Parts..." );
1087    objmgr.LoadPetNames();
1088
1089    sLog.outString( "Loading the max pet number..." );
1090    objmgr.LoadPetNumber();
1091
1092    sLog.outString( "Loading pet level stats..." );
1093    objmgr.LoadPetLevelInfo();
1094
1095    sLog.outString( "Loading Player Corpses..." );
1096    objmgr.LoadCorpses();
1097
1098    sLog.outString( "Loading Loot Tables..." );
1099    LoadLootTables();
1100
1101    sLog.outString( "Loading Skill Discovery Table..." );
1102    LoadSkillDiscoveryTable();
1103
1104    sLog.outString( "Loading Skill Extra Item Table..." );
1105    LoadSkillExtraItemTable();
1106
1107    sLog.outString( "Loading Skill Fishing base level requirements..." );
1108    objmgr.LoadFishingBaseSkillLevel();
1109
1110    ///- Load dynamic data tables from the database
1111    sLog.outString( "Loading Auctions..." );
1112    objmgr.LoadAuctionItems();
1113    objmgr.LoadAuctions();
1114
1115    sLog.outString( "Loading Guilds..." );
1116    objmgr.LoadGuilds();
1117
1118    sLog.outString( "Loading ArenaTeams..." );
1119    objmgr.LoadArenaTeams();
1120
1121    sLog.outString( "Loading Groups..." );
1122    objmgr.LoadGroups();
1123
1124    sLog.outString( "Loading ReservedNames..." );
1125    objmgr.LoadReservedPlayersNames();
1126
1127    sLog.outString( "Loading GameObject for quests..." );
1128    objmgr.LoadGameObjectForQuests();
1129
1130    sLog.outString( "Loading BattleMasters..." );
1131    objmgr.LoadBattleMastersEntry();
1132
1133    sLog.outString( "Loading GameTeleports..." );
1134    objmgr.LoadGameTele();
1135
1136    sLog.outString( "Loading Npc Text Id..." );
1137    objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
1138
1139    sLog.outString( "Loading vendors..." );
1140    objmgr.LoadVendors();                                   // must be after load CreatureTemplate and ItemTemplate
1141
1142    sLog.outString( "Loading trainers..." );
1143    objmgr.LoadTrainerSpell();                              // must be after load CreatureTemplate
1144
1145    sLog.outString( "Loading Waypoints..." );
1146    WaypointMgr.Load();
1147
1148    ///- Handle outdated emails (delete/return)
1149    sLog.outString( "Returning old mails..." );
1150    objmgr.ReturnOrDeleteOldMails(false);
1151
1152    ///- Load and initialize scripts
1153    sLog.outString( "Loading Scripts..." );
1154    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1155    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1156    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1157    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1158    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1159
1160    sLog.outString( "Initializing Scripts..." );
1161    if(!LoadScriptingModule())
1162        exit(1);
1163
1164    ///- Initialize game time and timers
1165    sLog.outString( "DEBUG:: Initialize game time and timers" );
1166    m_gameTime = time(NULL);
1167    m_startTime=m_gameTime;
1168
1169    tm local;
1170    time_t curr;
1171    time(&curr);
1172    local=*(localtime(&curr));                              // dereference and assign
1173    char isoDate[128];
1174    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1175        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1176
1177    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1178
1179    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1180    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1181    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1182    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1183    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1184                                                            //Update "uptime" table based on configuration entry in minutes.
1185    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1186
1187    //to set mailtimer to return mails every day between 4 and 5 am
1188    //mailtimer is increased when updating auctions
1189    //one second is 1000 -(tested on win system)
1190    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1191                                                            //1440
1192    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1193    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1194
1195    ///- Initilize static helper structures
1196    AIRegistry::Initialize();
1197    WaypointMovementGenerator<Creature>::Initialize();
1198    Player::InitVisibleBits();
1199
1200    ///- Initialize MapManager
1201    sLog.outString( "Starting Map System" );
1202    MapManager::Instance().Initialize();
1203
1204    ///- Initialize Battlegrounds
1205    sLog.outString( "Starting BattleGround System" );
1206    sBattleGroundMgr.CreateInitialBattleGrounds();
1207    sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1208
1209    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1210    sLog.outString( "Loading Transports..." );
1211    MapManager::Instance().LoadTransports();
1212
1213    sLog.outString("Deleting expired bans..." );
1214    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1215
1216    sLog.outString("Calculate next daily quest reset time..." );
1217    InitDailyQuestResetTime();
1218
1219    sLog.outString("Starting Game Event system..." );
1220    uint32 nextGameEvent = gameeventmgr.Initialize();
1221    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1222
1223    sLog.outString( "WORLD: World initialized" );
1224}
1225void World::DetectDBCLang()
1226{
1227    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1228
1229    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1230    {
1231        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1232        m_lang_confid = LOCALE_enUS;
1233    }
1234
1235    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1236
1237    std::string availableLocalsStr;
1238
1239    int default_locale = MAX_LOCALE;
1240    for (int i = MAX_LOCALE-1; i >= 0; --i)
1241    {
1242        if ( strlen(race->name[i]) > 0)                     // check by race names
1243        {
1244            default_locale = i;
1245            m_availableDbcLocaleMask |= (1 << i);
1246            availableLocalsStr += localeNames[i];
1247            availableLocalsStr += " ";
1248        }
1249    }
1250
1251    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1252        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1253    {
1254        default_locale = m_lang_confid;
1255    }
1256
1257    if(default_locale >= MAX_LOCALE)
1258    {
1259        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1260        exit(1);
1261    }
1262
1263    m_defaultDbcLocale = LocaleConstant(default_locale);
1264
1265    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1266}
1267
1268/// Update the World !
1269void World::Update(time_t diff)
1270{
1271    ///- Update the different timers
1272    for(int i = 0; i < WUPDATE_COUNT; i++)
1273        if(m_timers[i].GetCurrent()>=0)
1274            m_timers[i].Update(diff);
1275    else m_timers[i].SetCurrent(0);
1276
1277    ///- Update the game time and check for shutdown time
1278    _UpdateGameTime();
1279
1280    /// Handle daily quests reset time
1281    if(m_gameTime > m_NextDailyQuestReset)
1282    {
1283        ResetDailyQuests();
1284        m_NextDailyQuestReset += DAY;
1285    }
1286
1287    /// <ul><li> Handle auctions when the timer has passed
1288    if (m_timers[WUPDATE_AUCTIONS].Passed())
1289    {
1290        m_timers[WUPDATE_AUCTIONS].Reset();
1291
1292        ///- Update mails (return old mails with item, or delete them)
1293        //(tested... works on win)
1294        if (++mail_timer > mail_timer_expires)
1295        {
1296            mail_timer = 0;
1297            objmgr.ReturnOrDeleteOldMails(true);
1298        }
1299
1300        AuctionHouseObject* AuctionMap;
1301        for (int i = 0; i < 3; i++)
1302        {
1303            switch (i)
1304            {
1305                case 0:
1306                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1307                    break;
1308                case 1:
1309                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1310                    break;
1311                case 2:
1312                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1313                    break;
1314            }
1315
1316            ///- Handle expired auctions
1317            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1318            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1319            {
1320                next = itr;
1321                ++next;
1322                if (m_gameTime > (itr->second->time))
1323                {
1324                    ///- Either cancel the auction if there was no bidder
1325                    if (itr->second->bidder == 0)
1326                    {
1327                        objmgr.SendAuctionExpiredMail( itr->second );
1328                    }
1329                    ///- Or perform the transaction
1330                    else
1331                    {
1332                        //we should send an "item sold" message if the seller is online
1333                        //we send the item to the winner
1334                        //we send the money to the seller
1335                        objmgr.SendAuctionSuccessfulMail( itr->second );
1336                        objmgr.SendAuctionWonMail( itr->second );
1337                    }
1338
1339                    ///- In any case clear the auction
1340                    //No SQL injection (Id is integer)
1341                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1342                    objmgr.RemoveAItem(itr->second->item_guidlow);
1343                    delete itr->second;
1344                    AuctionMap->RemoveAuction(itr->first);
1345                }
1346            }
1347        }
1348    }
1349
1350    /// <li> Handle session updates when the timer has passed
1351    if (m_timers[WUPDATE_SESSIONS].Passed())
1352    {
1353        m_timers[WUPDATE_SESSIONS].Reset();
1354
1355        UpdateSessions(diff);
1356    }
1357
1358    /// <li> Handle weather updates when the timer has passed
1359    if (m_timers[WUPDATE_WEATHERS].Passed())
1360    {
1361        m_timers[WUPDATE_WEATHERS].Reset();
1362
1363        ///- Send an update signal to Weather objects
1364        WeatherMap::iterator itr, next;
1365        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1366        {
1367            next = itr;
1368            ++next;
1369
1370            ///- and remove Weather objects for zones with no player
1371                                                            //As interval > WorldTick
1372            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1373            {
1374                delete itr->second;
1375                m_weathers.erase(itr);
1376            }
1377        }
1378    }
1379    /// <li> Update uptime table
1380    if (m_timers[WUPDATE_UPTIME].Passed())
1381    {
1382        uint32 tmpDiff = (m_gameTime - m_startTime);
1383        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1384
1385        m_timers[WUPDATE_UPTIME].Reset();
1386        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1387    }
1388
1389    /// <li> Handle all other objects
1390    if (m_timers[WUPDATE_OBJECTS].Passed())
1391    {
1392        m_timers[WUPDATE_OBJECTS].Reset();
1393        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1394        MapManager::Instance().Update(diff);                // As interval = 0
1395
1396        ///- Process necessary scripts
1397        if (!m_scriptSchedule.empty())
1398            ScriptsProcess();
1399
1400        sBattleGroundMgr.Update(diff);
1401    }
1402
1403    // execute callbacks from sql queries that were queued recently
1404    UpdateResultQueue();
1405
1406    ///- Erase corpses once every 20 minutes
1407    if (m_timers[WUPDATE_CORPSES].Passed())
1408    {
1409        m_timers[WUPDATE_CORPSES].Reset();
1410
1411        CorpsesErase();
1412    }
1413
1414    ///- Process Game events when necessary
1415    if (m_timers[WUPDATE_EVENTS].Passed())
1416    {
1417        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1418        uint32 nextGameEvent = gameeventmgr.Update();
1419        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1420        m_timers[WUPDATE_EVENTS].Reset();
1421    }
1422
1423    /// </ul>
1424    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1425    MapManager::Instance().DoDelayedMovesAndRemoves();
1426
1427    // update the instance reset times
1428    sInstanceSaveManager.Update();
1429
1430    // And last, but not least handle the issued cli commands
1431    ProcessCliCommands();
1432}
1433
1434/// Put scripts in the execution queue
1435void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1436{
1437    ///- Find the script map
1438    ScriptMapMap::const_iterator s = scripts.find(id);
1439    if (s == scripts.end())
1440        return;
1441
1442    // prepare static data
1443    uint64 sourceGUID = source->GetGUID();
1444    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1445    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1446
1447    ///- Schedule script execution for all scripts in the script map
1448    ScriptMap const *s2 = &(s->second);
1449    bool immedScript = false;
1450    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1451    {
1452        ScriptAction sa;
1453        sa.sourceGUID = sourceGUID;
1454        sa.targetGUID = targetGUID;
1455        sa.ownerGUID  = ownerGUID;
1456
1457        sa.script = &iter->second;
1458        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1459        if (iter->first == 0)
1460            immedScript = true;
1461    }
1462    ///- If one of the effects should be immediate, launch the script execution
1463    if (immedScript)
1464        ScriptsProcess();
1465}
1466
1467void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1468{
1469    // NOTE: script record _must_ exist until command executed
1470
1471    // prepare static data
1472    uint64 sourceGUID = source->GetGUID();
1473    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1474    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1475
1476    ScriptAction sa;
1477    sa.sourceGUID = sourceGUID;
1478    sa.targetGUID = targetGUID;
1479    sa.ownerGUID  = ownerGUID;
1480
1481    sa.script = &script;
1482    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1483
1484    ///- If effects should be immediate, launch the script execution
1485    if(delay == 0)
1486        ScriptsProcess();
1487}
1488
1489/// Process queued scripts
1490void World::ScriptsProcess()
1491{
1492    if (m_scriptSchedule.empty())
1493        return;
1494
1495    ///- Process overdue queued scripts
1496    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1497                                                            // ok as multimap is a *sorted* associative container
1498    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1499    {
1500        ScriptAction const& step = iter->second;
1501
1502        Object* source = NULL;
1503
1504        if(step.sourceGUID)
1505        {
1506            switch(GUID_HIPART(step.sourceGUID))
1507            {
1508                case HIGHGUID_ITEM:
1509                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1510                    {
1511                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1512                        if(player)
1513                            source = player->GetItemByGuid(step.sourceGUID);
1514                        break;
1515                    }
1516                case HIGHGUID_UNIT:
1517                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1518                    break;
1519                case HIGHGUID_PET:
1520                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1521                    break;
1522                case HIGHGUID_PLAYER:
1523                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1524                    break;
1525                case HIGHGUID_GAMEOBJECT:
1526                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1527                    break;
1528                case HIGHGUID_CORPSE:
1529                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1530                    break;
1531                default:
1532                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1533                    break;
1534            }
1535        }
1536
1537        Object* target = NULL;
1538
1539        if(step.targetGUID)
1540        {
1541            switch(GUID_HIPART(step.targetGUID))
1542            {
1543                case HIGHGUID_UNIT:
1544                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1545                    break;
1546                case HIGHGUID_PET:
1547                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1548                    break;
1549                case HIGHGUID_PLAYER:                       // empty GUID case also
1550                    target = HashMapHolder<Player>::Find(step.targetGUID);
1551                    break;
1552                case HIGHGUID_GAMEOBJECT:
1553                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1554                    break;
1555                case HIGHGUID_CORPSE:
1556                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1557                    break;
1558                default:
1559                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1560                    break;
1561            }
1562        }
1563
1564        switch (step.script->command)
1565        {
1566            case SCRIPT_COMMAND_TALK:
1567            {
1568                if(!source)
1569                {
1570                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1571                    break;
1572                }
1573
1574                if(source->GetTypeId()!=TYPEID_UNIT)
1575                {
1576                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1577                    break;
1578                }
1579                if(step.script->datalong > 3)
1580                {
1581                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1582                    break;
1583                }
1584
1585                uint64 unit_target = target ? target->GetGUID() : 0;
1586
1587                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1588                switch(step.script->datalong)
1589                {
1590                    case 0:                                 // Say
1591                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1592                        break;
1593                    case 1:                                 // Whisper
1594                        if(!unit_target)
1595                        {
1596                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1597                            break;
1598                        }
1599                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1600                        break;
1601                    case 2:                                 // Yell
1602                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1603                        break;
1604                    case 3:                                 // Emote text
1605                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1606                        break;
1607                    default:
1608                        break;                              // must be already checked at load
1609                }
1610                break;
1611            }
1612
1613            case SCRIPT_COMMAND_EMOTE:
1614                if(!source)
1615                {
1616                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1617                    break;
1618                }
1619
1620                if(source->GetTypeId()!=TYPEID_UNIT)
1621                {
1622                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1623                    break;
1624                }
1625
1626                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1627                break;
1628            case SCRIPT_COMMAND_FIELD_SET:
1629                if(!source)
1630                {
1631                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1632                    break;
1633                }
1634                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1635                {
1636                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1637                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1638                    break;
1639                }
1640
1641                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1642                break;
1643            case SCRIPT_COMMAND_MOVE_TO:
1644                if(!source)
1645                {
1646                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1647                    break;
1648                }
1649
1650                if(source->GetTypeId()!=TYPEID_UNIT)
1651                {
1652                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1653                    break;
1654                }
1655                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1656                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1657                break;
1658            case SCRIPT_COMMAND_FLAG_SET:
1659                if(!source)
1660                {
1661                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1662                    break;
1663                }
1664                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1665                {
1666                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1667                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1668                    break;
1669                }
1670
1671                source->SetFlag(step.script->datalong, step.script->datalong2);
1672                break;
1673            case SCRIPT_COMMAND_FLAG_REMOVE:
1674                if(!source)
1675                {
1676                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1677                    break;
1678                }
1679                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1680                {
1681                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1682                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1683                    break;
1684                }
1685
1686                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1687                break;
1688
1689            case SCRIPT_COMMAND_TELEPORT_TO:
1690            {
1691                // accept player in any one from target/source arg
1692                if (!target && !source)
1693                {
1694                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1695                    break;
1696                }
1697
1698                                                            // must be only Player
1699                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1700                {
1701                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1702                    break;
1703                }
1704
1705                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1706
1707                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1708                break;
1709            }
1710
1711            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1712            {
1713                if(!step.script->datalong)                  // creature not specified
1714                {
1715                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1716                    break;
1717                }
1718
1719                if(!source)
1720                {
1721                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1722                    break;
1723                }
1724
1725                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1726
1727                if(!summoner)
1728                {
1729                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1730                    break;
1731                }
1732
1733                float x = step.script->x;
1734                float y = step.script->y;
1735                float z = step.script->z;
1736                float o = step.script->o;
1737
1738                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1739                if (!pCreature)
1740                {
1741                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1742                    break;
1743                }
1744
1745                break;
1746            }
1747
1748            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1749            {
1750                if(!step.script->datalong)                  // gameobject not specified
1751                {
1752                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1753                    break;
1754                }
1755
1756                if(!source)
1757                {
1758                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1759                    break;
1760                }
1761
1762                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1763
1764                if(!summoner)
1765                {
1766                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1767                    break;
1768                }
1769
1770                GameObject *go = NULL;
1771                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1772
1773                CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1774                Cell cell(p);
1775                cell.data.Part.reserved = ALL_DISTRICT;
1776
1777                MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1778                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1779
1780                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1781                CellLock<GridReadGuard> cell_lock(cell, p);
1782                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1783
1784                if ( !go )
1785                {
1786                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1787                    break;
1788                }
1789
1790                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1791                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1792                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1793                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1794                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1795                {
1796                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1797                    break;
1798                }
1799
1800                if( go->isSpawned() )
1801                    break;                                  //gameobject already spawned
1802
1803                go->SetLootState(GO_READY);
1804                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1805
1806                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1807                break;
1808            }
1809            case SCRIPT_COMMAND_OPEN_DOOR:
1810            {
1811                if(!step.script->datalong)                  // door not specified
1812                {
1813                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1814                    break;
1815                }
1816
1817                if(!source)
1818                {
1819                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1820                    break;
1821                }
1822
1823                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1824                {
1825                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1826                    break;
1827                }
1828
1829                Unit* caster = (Unit*)source;
1830
1831                GameObject *door = NULL;
1832                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1833
1834                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1835                Cell cell(p);
1836                cell.data.Part.reserved = ALL_DISTRICT;
1837
1838                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1839                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1840
1841                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1842                CellLock<GridReadGuard> cell_lock(cell, p);
1843                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1844
1845                if ( !door )
1846                {
1847                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1848                    break;
1849                }
1850                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1851                {
1852                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1853                    break;
1854                }
1855
1856                if( !door->GetGoState() )
1857                    break;                                  //door already  open
1858
1859                door->UseDoorOrButton(time_to_close);
1860
1861                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1862                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1863                break;
1864            }
1865            case SCRIPT_COMMAND_CLOSE_DOOR:
1866            {
1867                if(!step.script->datalong)                  // guid for door not specified
1868                {
1869                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1870                    break;
1871                }
1872
1873                if(!source)
1874                {
1875                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1876                    break;
1877                }
1878
1879                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1880                {
1881                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1882                    break;
1883                }
1884
1885                Unit* caster = (Unit*)source;
1886
1887                GameObject *door = NULL;
1888                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1889
1890                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1891                Cell cell(p);
1892                cell.data.Part.reserved = ALL_DISTRICT;
1893
1894                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1895                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1896
1897                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1898                CellLock<GridReadGuard> cell_lock(cell, p);
1899                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1900
1901                if ( !door )
1902                {
1903                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1904                    break;
1905                }
1906                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1907                {
1908                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1909                    break;
1910                }
1911
1912                if( door->GetGoState() )
1913                    break;                                  //door already closed
1914
1915                door->UseDoorOrButton(time_to_open);
1916
1917                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1918                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1919
1920                break;
1921            }
1922            case SCRIPT_COMMAND_QUEST_EXPLORED:
1923            {
1924                if(!source)
1925                {
1926                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1927                    break;
1928                }
1929
1930                if(!target)
1931                {
1932                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1933                    break;
1934                }
1935
1936                // when script called for item spell casting then target == (unit or GO) and source is player
1937                WorldObject* worldObject;
1938                Player* player;
1939
1940                if(target->GetTypeId()==TYPEID_PLAYER)
1941                {
1942                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1943                    {
1944                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1945                        break;
1946                    }
1947
1948                    worldObject = (WorldObject*)source;
1949                    player = (Player*)target;
1950                }
1951                else
1952                {
1953                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1954                    {
1955                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1956                        break;
1957                    }
1958
1959                    if(source->GetTypeId()!=TYPEID_PLAYER)
1960                    {
1961                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1962                        break;
1963                    }
1964
1965                    worldObject = (WorldObject*)target;
1966                    player = (Player*)source;
1967                }
1968
1969                // quest id and flags checked at script loading
1970                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1971                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1972                    player->AreaExploredOrEventHappens(step.script->datalong);
1973                else
1974                    player->FailQuest(step.script->datalong);
1975
1976                break;
1977            }
1978
1979            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1980            {
1981                if(!source)
1982                {
1983                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1984                    break;
1985                }
1986
1987                if(!source->isType(TYPEMASK_UNIT))
1988                {
1989                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1990                    break;
1991                }
1992
1993                if(!target)
1994                {
1995                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1996                    break;
1997                }
1998
1999                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2000                {
2001                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2002                    break;
2003                }
2004
2005                Unit* caster = (Unit*)source;
2006
2007                GameObject *go = (GameObject*)target;
2008
2009                go->Use(caster);
2010                break;
2011            }
2012
2013            case SCRIPT_COMMAND_REMOVE_AURA:
2014            {
2015                Object* cmdTarget = step.script->datalong2 ? source : target;
2016
2017                if(!cmdTarget)
2018                {
2019                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2020                    break;
2021                }
2022
2023                if(!cmdTarget->isType(TYPEMASK_UNIT))
2024                {
2025                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2026                    break;
2027                }
2028
2029                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2030                break;
2031            }
2032
2033            case SCRIPT_COMMAND_CAST_SPELL:
2034            {
2035                if(!source)
2036                {
2037                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2038                    break;
2039                }
2040
2041                if(!source->isType(TYPEMASK_UNIT))
2042                {
2043                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2044                    break;
2045                }
2046
2047                Object* cmdTarget = step.script->datalong2 ? source : target;
2048
2049                if(!cmdTarget)
2050                {
2051                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2052                    break;
2053                }
2054
2055                if(!cmdTarget->isType(TYPEMASK_UNIT))
2056                {
2057                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2058                    break;
2059                }
2060
2061                Unit* spellTarget = (Unit*)cmdTarget;
2062
2063                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2064                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2065
2066                break;
2067            }
2068
2069            default:
2070                sLog.outError("Unknown script command %u called.",step.script->command);
2071                break;
2072        }
2073
2074        m_scriptSchedule.erase(iter);
2075
2076        iter = m_scriptSchedule.begin();
2077    }
2078    return;
2079}
2080
2081/// Send a packet to all players (except self if mentioned)
2082void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2083{
2084    SessionMap::iterator itr;
2085    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2086    {
2087        if (itr->second &&
2088            itr->second->GetPlayer() &&
2089            itr->second->GetPlayer()->IsInWorld() &&
2090            itr->second != self &&
2091            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2092        {
2093            itr->second->SendPacket(packet);
2094        }
2095    }
2096}
2097
2098/// Send a System Message to all players (except self if mentioned)
2099void World::SendWorldText(int32 string_id, ...)
2100{
2101    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
2102
2103    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2104    {
2105        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2106            continue;
2107
2108        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2109        uint32 cache_idx = loc_idx+1;
2110
2111        std::vector<WorldPacket*>* data_list;
2112
2113        // create if not cached yet
2114        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2115        {
2116            if(data_cache.size() < cache_idx+1)
2117                data_cache.resize(cache_idx+1);
2118
2119            data_list = &data_cache[cache_idx];
2120
2121            char const* text = objmgr.GetMangosString(string_id,loc_idx);
2122
2123            char buf[1000];
2124
2125            va_list argptr;
2126            va_start( argptr, string_id );
2127            vsnprintf( buf,1000, text, argptr );
2128            va_end( argptr );
2129
2130            char* pos = &buf[0];
2131
2132            while(char* line = ChatHandler::LineFromMessage(pos))
2133            {
2134                WorldPacket* data = new WorldPacket();
2135                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2136                data_list->push_back(data);
2137            }
2138        }
2139        else
2140            data_list = &data_cache[cache_idx];
2141
2142        for(int i = 0; i < data_list->size(); ++i)
2143            itr->second->SendPacket((*data_list)[i]);
2144    }
2145
2146    // free memory
2147    for(int i = 0; i < data_cache.size(); ++i)
2148        for(int j = 0; j < data_cache[i].size(); ++j)
2149            delete data_cache[i][j];
2150}
2151
2152/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2153void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2154{
2155    SessionMap::iterator itr;
2156    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2157    {
2158        if (itr->second &&
2159            itr->second->GetPlayer() &&
2160            itr->second->GetPlayer()->IsInWorld() &&
2161            itr->second->GetPlayer()->GetZoneId() == zone &&
2162            itr->second != self &&
2163            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2164        {
2165            itr->second->SendPacket(packet);
2166        }
2167    }
2168}
2169
2170/// Send a System Message to all players in the zone (except self if mentioned)
2171void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2172{
2173    WorldPacket data;
2174    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2175    SendZoneMessage(zone, &data, self,team);
2176}
2177
2178/// Kick (and save) all players
2179void World::KickAll()
2180{
2181    // session not removed at kick and will removed in next update tick
2182    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2183        itr->second->KickPlayer();
2184}
2185
2186/// Kick (and save) all players with security level less `sec`
2187void World::KickAllLess(AccountTypes sec)
2188{
2189    // session not removed at kick and will removed in next update tick
2190    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2191        if(itr->second->GetSecurity() < sec)
2192            itr->second->KickPlayer();
2193}
2194
2195/// Kick all queued players
2196void World::KickAllQueued()
2197{
2198    // session not removed at kick and will removed in next update tick
2199  //TODO here
2200//    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2201//        if(WorldSession* session = (*itr)->GetSession())
2202//            session->KickPlayer();
2203
2204    m_QueuedPlayer.empty();
2205}
2206
2207/// Kick (and save) the designated player
2208bool World::KickPlayer(std::string playerName)
2209{
2210    SessionMap::iterator itr;
2211
2212    // session not removed at kick and will removed in next update tick
2213    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2214    {
2215        if(!itr->second)
2216            continue;
2217        Player *player = itr->second->GetPlayer();
2218        if(!player)
2219            continue;
2220        if( player->IsInWorld() )
2221        {
2222            if (playerName == player->GetName())
2223            {
2224                itr->second->KickPlayer();
2225                return true;
2226            }
2227        }
2228    }
2229    return false;
2230}
2231
2232/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2233uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2234{
2235    loginDatabase.escape_string(nameOrIP);
2236    loginDatabase.escape_string(reason);
2237    std::string safe_author=author;
2238    loginDatabase.escape_string(safe_author);
2239
2240    if(type != "ip" && !normalizePlayerName(nameOrIP))
2241        return BAN_NOTFOUND;                                // Nobody to ban
2242
2243    uint32 duration_secs = TimeStringToSecs(duration);
2244    QueryResult *resultAccounts = NULL;                     //used for kicking
2245
2246    ///- Update the database with ban information
2247
2248    if(type=="ip")
2249    {
2250        //No SQL injection as strings are escaped
2251        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2252        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());
2253    }
2254    else if(type=="account")
2255    {
2256        //No SQL injection as string is escaped
2257        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2258    }
2259    else if(type=="character")
2260    {
2261        //No SQL injection as string is escaped
2262        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2263    }
2264    else
2265        return BAN_SYNTAX_ERROR;                            //Syntax problem
2266
2267    if(!resultAccounts)
2268        if(type=="ip")
2269            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2270    else
2271        return BAN_NOTFOUND;                                // Nobody to ban
2272
2273    ///- Disconnect all affected players (for IP it can be several)
2274    do
2275    {
2276        Field* fieldsAccount = resultAccounts->Fetch();
2277        uint32 account = fieldsAccount->GetUInt32();
2278
2279        if(type != "ip")
2280            //No SQL injection as strings are escaped
2281            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2282                account,duration_secs,safe_author.c_str(),reason.c_str());
2283
2284        WorldSession* sess = FindSession(account);
2285        if( sess )
2286            if(std::string(sess->GetPlayerName()) != author)
2287                sess->KickPlayer();
2288    }
2289    while( resultAccounts->NextRow() );
2290
2291    delete resultAccounts;
2292    return BAN_SUCCESS;
2293}
2294
2295/// Remove a ban from an account or IP address
2296bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2297{
2298    if(type == "ip")
2299    {
2300        loginDatabase.escape_string(nameOrIP);
2301        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2302    }
2303    else
2304    {
2305        uint32 account=0;
2306        if(type == "account")
2307        {
2308            //NO SQL injection as name is escaped
2309            loginDatabase.escape_string(nameOrIP);
2310            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2311            if(!resultAccounts)
2312                return false;
2313            Field* fieldsAccount = resultAccounts->Fetch();
2314            account = fieldsAccount->GetUInt32();
2315
2316            delete resultAccounts;
2317        }
2318        else if(type == "character")
2319        {
2320            if(!normalizePlayerName(nameOrIP))
2321                return false;
2322
2323            //NO SQL injection as name is escaped
2324            loginDatabase.escape_string(nameOrIP);
2325            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2326            if(!resultAccounts)
2327                return false;
2328            Field* fieldsAccount = resultAccounts->Fetch();
2329            account = fieldsAccount->GetUInt32();
2330
2331            delete resultAccounts;
2332        }
2333        if(!account)
2334            return false;
2335        //NO SQL injection as account is uint32
2336        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2337    }
2338    return true;
2339}
2340
2341/// Update the game time
2342void World::_UpdateGameTime()
2343{
2344    ///- update the time
2345    time_t thisTime = time(NULL);
2346    uint32 elapsed = uint32(thisTime - m_gameTime);
2347    m_gameTime = thisTime;
2348
2349    ///- if there is a shutdown timer
2350    if(m_ShutdownTimer > 0 && elapsed > 0)
2351    {
2352        ///- ... and it is overdue, stop the world (set m_stopEvent)
2353        if( m_ShutdownTimer <= elapsed )
2354        {
2355            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2356                m_stopEvent = true;
2357            else
2358                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2359        }
2360        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2361        else
2362        {
2363            m_ShutdownTimer -= elapsed;
2364
2365            ShutdownMsg();
2366        }
2367    }
2368}
2369
2370/// Shutdown the server
2371void World::ShutdownServ(uint32 time, uint32 options)
2372{
2373    m_ShutdownMask = options;
2374
2375    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2376    if(time==0)
2377    {
2378        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2379            m_stopEvent = true;
2380        else
2381            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2382    }
2383    ///- Else set the shutdown timer and warn users
2384    else
2385    {
2386        m_ShutdownTimer = time;
2387        ShutdownMsg(true);
2388    }
2389}
2390
2391/// Display a shutdown message to the user(s)
2392void World::ShutdownMsg(bool show, Player* player)
2393{
2394    // not show messages for idle shutdown mode
2395    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2396        return;
2397
2398    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2399    if ( show ||
2400        (m_ShutdownTimer < 10) ||
2401                                                            // < 30 sec; every 5 sec
2402        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2403                                                            // < 5 min ; every 1 min
2404        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2405                                                            // < 30 min ; every 5 min
2406        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2407                                                            // < 12 h ; every 1 h
2408        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2409                                                            // > 12 h ; every 12 h
2410        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2411    {
2412        std::string str = secsToTimeString(m_ShutdownTimer);
2413
2414        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2415
2416        SendServerMessage(msgid,str.c_str(),player);
2417        DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2418    }
2419}
2420
2421/// Cancel a planned server shutdown
2422void World::ShutdownCancel()
2423{
2424    if(!m_ShutdownTimer)
2425        return;
2426
2427    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2428
2429    m_ShutdownMask = 0;
2430    m_ShutdownTimer = 0;
2431    SendServerMessage(msgid);
2432
2433    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2434}
2435
2436/// Send a server message to the user(s)
2437void World::SendServerMessage(uint32 type, const char *text, Player* player)
2438{
2439    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2440    data << uint32(type);
2441    if(type <= SERVER_MSG_STRING)
2442        data << text;
2443
2444    if(player)
2445        player->GetSession()->SendPacket(&data);
2446    else
2447        SendGlobalMessage( &data );
2448}
2449
2450void World::UpdateSessions( time_t diff )
2451{
2452    while(!addSessQueue.empty())
2453    {
2454      WorldSession* sess = addSessQueue.next ();
2455      AddSession_ (sess);
2456    }
2457       
2458    ///- Delete kicked sessions at add new session
2459    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2460        delete *itr;
2461    m_kicked_sessions.clear();
2462
2463    ///- Then send an update signal to remaining ones
2464    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2465    {
2466        next = itr;
2467        ++next;
2468
2469        if(!itr->second)
2470            continue;
2471
2472        ///- and remove not active sessions from the list
2473        if(!itr->second->Update(diff))                      // As interval = 0
2474        {
2475            delete itr->second;
2476            m_sessions.erase(itr);
2477        }
2478    }
2479}
2480
2481// This handles the issued and queued CLI commands
2482void World::ProcessCliCommands()
2483{
2484    if (cliCmdQueue.empty()) return;
2485
2486    CliCommandHolder *command;
2487    pPrintf p_zprintf;
2488    while (!cliCmdQueue.empty())
2489    {
2490        sLog.outDebug("CLI command under processing...");
2491        command = cliCmdQueue.next();
2492        command->Execute();
2493        p_zprintf=command->GetOutputMethod();
2494        delete command;
2495    }
2496    // print the console message here so it looks right
2497    p_zprintf("mangos>");
2498}
2499
2500void World::InitResultQueue()
2501{
2502    m_resultQueue = new SqlResultQueue;
2503    CharacterDatabase.SetResultQueue(m_resultQueue);
2504}
2505
2506void World::UpdateResultQueue()
2507{
2508    m_resultQueue->Update();
2509}
2510
2511void World::UpdateRealmCharCount(uint32 accountId)
2512{
2513    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2514        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2515}
2516
2517void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2518{
2519    if (resultCharCount)
2520    {
2521        Field *fields = resultCharCount->Fetch();
2522        uint32 charCount = fields[0].GetUInt32();
2523        delete resultCharCount;
2524        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2525        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2526    }
2527}
2528
2529void World::InitDailyQuestResetTime()
2530{
2531    time_t mostRecentQuestTime;
2532
2533    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2534    if(result)
2535    {
2536        Field *fields = result->Fetch();
2537
2538        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2539        delete result;
2540    }
2541    else
2542        mostRecentQuestTime = 0;
2543
2544    // client built-in time for reset is 6:00 AM
2545    // FIX ME: client not show day start time
2546    time_t curTime = time(NULL);
2547    tm localTm = *localtime(&curTime);
2548    localTm.tm_hour = 6;
2549    localTm.tm_min  = 0;
2550    localTm.tm_sec  = 0;
2551
2552    // current day reset time
2553    time_t curDayResetTime = mktime(&localTm);
2554
2555    // last reset time before current moment
2556    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2557
2558    // need reset (if we have quest time before last reset time (not processed by some reason)
2559    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2560        m_NextDailyQuestReset = mostRecentQuestTime;
2561    else
2562    {
2563        // plan next reset time
2564        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2565    }
2566}
2567
2568void World::ResetDailyQuests()
2569{
2570    sLog.outDetail("Daily quests reset for all characters.");
2571    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2572    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2573        if(itr->second->GetPlayer())
2574            itr->second->GetPlayer()->ResetDailyQuestStatus();
2575}
2576
2577void World::SetPlayerLimit( int32 limit, bool needUpdate )
2578{
2579    if(limit < -SEC_ADMINISTRATOR)
2580        limit = -SEC_ADMINISTRATOR;
2581
2582    // lock update need
2583    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2584
2585    m_playerLimit = limit;
2586
2587    if(db_update_need)
2588        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2589}
2590
2591void World::UpdateMaxSessionCounters()
2592{
2593    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2594    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2595}
Note: See TracBrowser for help on using the browser.