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

Revision 6, 105.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Added ACE for Linux and Windows (Thanks Derex for Linux part and partial Windows part)
* Updated to 6721 and 676
* Fixed TrinityScript? logo
* Version updated to 0.2.6721.676

Original author: Neo2003
Date: 2008-10-04 06:17:19-05:00

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