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

Revision 41, 107.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Random changes/fixes...
* Some fixes to MangChat?, more coming.
* Cleaning up scripting part and preparing to merge it into the core.

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