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

Revision 19, 105.9 kB (checked in by yumileroy, 17 years ago)

[svn] * Removed ObjectPosSelector? and DetectPosCollision?. See http://www.trinitycore.org/forum/project.php?issueid=3
* Need win32 build fix ;)

Original author: derex_tri
Date: 2008-10-06 07:39:04-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
633    m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
634    m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR]  = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
635    m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
636
637    m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
638    m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
639    if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
640    {
641        sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
642        m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
643    }
644
645    m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetBoolDefault("GM.WhisperingTo",false);
646    m_configs[CONFIG_GM_IN_GM_LIST]  = sConfig.GetBoolDefault("GM.InGMList",false);
647    m_configs[CONFIG_GM_IN_WHO_LIST]  = sConfig.GetBoolDefault("GM.InWhoList",false);
648    m_configs[CONFIG_GM_LOGIN_STATE]  = sConfig.GetIntDefault("GM.LoginState",2);
649    m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
650
651    m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
652
653    m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
654
655    m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
656    if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
657    {
658        sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
659        m_configs[CONFIG_UPTIME_UPDATE] = 10;
660    }
661    if(reload)
662    {
663        m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
664        m_timers[WUPDATE_UPTIME].Reset();
665    }
666
667    m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
668    m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
669    m_configs[CONFIG_SKILL_CHANCE_GREEN]  = sConfig.GetIntDefault("SkillChance.Green",25);
670    m_configs[CONFIG_SKILL_CHANCE_GREY]   = sConfig.GetIntDefault("SkillChance.Grey",0);
671
672    m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS]  = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
673    m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS]   = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
674
675    m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
676
677    m_configs[CONFIG_SKILL_GAIN_CRAFTING]  = sConfig.GetIntDefault("SkillGain.Crafting", 1);
678    if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
679    {
680        sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
681        m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
682    }
683
684    m_configs[CONFIG_SKILL_GAIN_DEFENSE]  = sConfig.GetIntDefault("SkillGain.Defense", 1);
685    if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
686    {
687        sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
688        m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
689    }
690
691    m_configs[CONFIG_SKILL_GAIN_GATHERING]  = sConfig.GetIntDefault("SkillGain.Gathering", 1);
692    if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
693    {
694        sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
695        m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
696    }
697
698    m_configs[CONFIG_SKILL_GAIN_WEAPON]  = sConfig.GetIntDefault("SkillGain.Weapon", 1);
699    if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
700    {
701        sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
702        m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
703    }
704
705    m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
706    if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
707    {
708        sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
709        m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
710    }
711
712    m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
713    m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
714
715    if(reload)
716    {
717        uint32 val = sConfig.GetIntDefault("Expansion",1);
718        if(val!=m_configs[CONFIG_EXPANSION])
719            sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
720    }
721    else
722        m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
723
724    m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
725    m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
726    m_configs[CONFIG_CHATFLOOD_MUTE_TIME]     = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
727
728    m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
729
730    m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
731
732    m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
733
734    // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
735    m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
736    if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
737        m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
738    m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
739    if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
740        m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
741
742    m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
743    m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
744
745    m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
746    m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
747
748    m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
749    m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
750    m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
751    m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
752    m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
753
754    m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
755    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
756    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
757
758    m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
759
760    // always use declined names in the russian client
761    m_configs[CONFIG_DECLINED_NAMES_USED] = 
762        (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
763
764    m_configs[CONFIG_LISTEN_RANGE_SAY]       = sConfig.GetIntDefault("ListenRange.Say", 25);
765    m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
766    m_configs[CONFIG_LISTEN_RANGE_YELL]      = sConfig.GetIntDefault("ListenRange.Yell", 300);
767
768
769    m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
770    m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
771    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
772    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
773
774    m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
775
776    m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
777    if(m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
778    {
779        sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
780        m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
781    }
782    m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
783    if(m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
784    {
785        sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
786        m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
787    }
788
789    m_MaxVisibleDistanceForCreature      = sConfig.GetFloatDefault("Visibility.Distance.Creature",     DEFAULT_VISIBILITY_DISTANCE);
790    if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
791    {
792        sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
793        m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
794    }
795    else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
796    {
797        sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
798        m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
799    }
800    m_MaxVisibleDistanceForPlayer        = sConfig.GetFloatDefault("Visibility.Distance.Player",       DEFAULT_VISIBILITY_DISTANCE);
801    if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
802    {
803        sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
804        m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
805    }
806    else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
807    {
808        sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
809        m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
810    }
811    m_MaxVisibleDistanceForObject    = sConfig.GetFloatDefault("Visibility.Distance.Gameobject",   DEFAULT_VISIBILITY_DISTANCE);
812    if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
813    {
814        sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
815        m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
816    }
817    else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
818    {
819        sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
820        m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
821    }
822    m_MaxVisibleDistanceInFlight    = sConfig.GetFloatDefault("Visibility.Distance.InFlight",      DEFAULT_VISIBILITY_DISTANCE);
823    if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
824    {
825        sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
826        m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
827    }
828
829    ///- Read the "Data" directory from the config file
830    std::string dataPath = sConfig.GetStringDefault("DataDir","./");
831    if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
832        dataPath.append("/");
833
834    if(reload)
835    {
836        if(dataPath!=m_dataPath)
837            sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
838    }
839    else
840    {
841        m_dataPath = dataPath;
842        sLog.outString("Using DataDir %s",m_dataPath.c_str());
843    }
844
845    bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
846    bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
847    std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
848    std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
849    VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
850    VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
851    VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
852    VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
853    sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
854    sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
855    sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
856}
857
858/// Initialize the World
859void World::SetInitialWorldSettings()
860{
861    ///- Initialize the random number generator
862    srand((unsigned int)time(NULL));
863
864    ///- Initialize config settings
865    LoadConfigSettings();
866
867    ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
868    objmgr.SetHighestGuids();
869
870    ///- Check the existence of the map files for all races' startup areas.
871    if(   !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
872        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
873        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
874        ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
875        ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
876        ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
877        ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
878        ||m_configs[CONFIG_EXPANSION] && (
879        !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
880    {
881        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());
882        exit(1);
883    }
884
885    ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
886    sLog.outString( "" );
887    sLog.outString( "Loading MaNGOS strings..." );
888    if (!objmgr.LoadMangosStrings())
889        exit(1);                                            // Error message displayed in function already
890
891    ///- Update the realm entry in the database with the realm type from the config file
892    //No SQL injection as values are treated as integers
893
894    // not send custom type REALM_FFA_PVP to realm list
895    uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
896    uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
897    loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
898
899    ///- Remove the bones after a restart
900    CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
901
902    ///- Load the DBC files
903    sLog.outString("Initialize data stores...");
904    LoadDBCStores(m_dataPath);
905    DetectDBCLang();
906
907    sLog.outString( "Loading InstanceTemplate" );
908    objmgr.LoadInstanceTemplate();
909
910    sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
911    spellmgr.LoadSkillLineAbilityMap();
912
913    ///- Clean up and pack instances
914    sLog.outString( "Cleaning up instances..." );
915    sInstanceSaveManager.CleanupInstances();                              // must be called before `creature_respawn`/`gameobject_respawn` tables
916
917    sLog.outString( "Packing instances..." );
918    sInstanceSaveManager.PackInstances();
919
920    sLog.outString( "Loading Localization strings..." );
921    objmgr.LoadCreatureLocales();
922    objmgr.LoadGameObjectLocales();
923    objmgr.LoadItemLocales();
924    objmgr.LoadQuestLocales();
925    objmgr.LoadNpcTextLocales();
926    objmgr.LoadPageTextLocales();
927    objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale());        // Get once for all the locale index of DBC language (console/broadcasts)
928
929    sLog.outString( "Loading Page Texts..." );
930    objmgr.LoadPageTexts();
931
932    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
933    objmgr.LoadGameobjectInfo();
934
935    sLog.outString( "Loading Spell Chain Data..." );
936    spellmgr.LoadSpellChains();
937
938    sLog.outString( "Loading Spell Elixir types..." );
939    spellmgr.LoadSpellElixirs();
940
941    sLog.outString( "Loading Spell Learn Skills..." );
942    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
943
944    sLog.outString( "Loading Spell Learn Spells..." );
945    spellmgr.LoadSpellLearnSpells();
946
947    sLog.outString( "Loading Spell Proc Event conditions..." );
948    spellmgr.LoadSpellProcEvents();
949
950    sLog.outString( "Loading Aggro Spells Definitions...");
951    spellmgr.LoadSpellThreats();
952
953    sLog.outString( "Loading NPC Texts..." );
954    objmgr.LoadGossipText();
955
956    sLog.outString( "Loading Item Random Enchantments Table..." );
957    LoadRandomEnchantmentsTable();
958
959    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
960    objmgr.LoadItemPrototypes();
961
962    sLog.outString( "Loading Item Texts..." );
963    objmgr.LoadItemTexts();
964
965    sLog.outString( "Loading Creature Model Based Info Data..." );
966    objmgr.LoadCreatureModelInfo();
967
968    sLog.outString( "Loading Equipment templates...");
969    objmgr.LoadEquipmentTemplates();
970
971    sLog.outString( "Loading Creature templates..." );
972    objmgr.LoadCreatureTemplates();
973
974    sLog.outString( "Loading SpellsScriptTarget...");
975    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
976
977    sLog.outString( "Loading Creature Reputation OnKill Data..." );
978    objmgr.LoadReputationOnKill();
979
980    sLog.outString( "Loading Pet Create Spells..." );
981    objmgr.LoadPetCreateSpells();
982
983    sLog.outString( "Loading Creature Data..." );
984    objmgr.LoadCreatures();
985
986    sLog.outString( "Loading Creature Addon Data..." );
987    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
988
989    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
990    objmgr.LoadCreatureRespawnTimes();
991
992    sLog.outString( "Loading Gameobject Data..." );
993    objmgr.LoadGameobjects();
994
995    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
996    objmgr.LoadGameobjectRespawnTimes();
997
998    sLog.outString( "Loading Game Event Data...");
999    gameeventmgr.LoadFromDB();
1000
1001    sLog.outString( "Loading Weather Data..." );
1002    objmgr.LoadWeatherZoneChances();
1003
1004    sLog.outString( "Loading Quests..." );
1005    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
1006
1007    sLog.outString( "Loading Quests Relations..." );
1008    objmgr.LoadQuestRelations();                            // must be after quest load
1009
1010    sLog.outString( "Loading AreaTrigger definitions..." );
1011    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
1012
1013    sLog.outString( "Loading Quest Area Triggers..." );
1014    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
1015
1016    sLog.outString( "Loading Tavern Area Triggers..." );
1017    objmgr.LoadTavernAreaTriggers();
1018   
1019    sLog.outString( "Loading AreaTrigger script names..." );
1020    objmgr.LoadAreaTriggerScripts();
1021
1022
1023    sLog.outString( "Loading Graveyard-zone links...");
1024    objmgr.LoadGraveyardZones();
1025
1026    sLog.outString( "Loading Spell target coordinates..." );
1027    spellmgr.LoadSpellTargetPositions();
1028
1029    sLog.outString( "Loading SpellAffect definitions..." );
1030    spellmgr.LoadSpellAffects();
1031
1032    sLog.outString( "Loading spell pet auras..." );
1033    spellmgr.LoadSpellPetAuras();
1034
1035    sLog.outString( "Loading player Create Info & Level Stats..." );
1036    objmgr.LoadPlayerInfo();
1037
1038    sLog.outString( "Loading Exploration BaseXP Data..." );
1039    objmgr.LoadExplorationBaseXP();
1040
1041    sLog.outString( "Loading Pet Name Parts..." );
1042    objmgr.LoadPetNames();
1043
1044    sLog.outString( "Loading the max pet number..." );
1045    objmgr.LoadPetNumber();
1046
1047    sLog.outString( "Loading pet level stats..." );
1048    objmgr.LoadPetLevelInfo();
1049
1050    sLog.outString( "Loading Player Corpses..." );
1051    objmgr.LoadCorpses();
1052
1053    sLog.outString( "Loading Loot Tables..." );
1054    LoadLootTables();
1055
1056    sLog.outString( "Loading Skill Discovery Table..." );
1057    LoadSkillDiscoveryTable();
1058
1059    sLog.outString( "Loading Skill Extra Item Table..." );
1060    LoadSkillExtraItemTable();
1061
1062    sLog.outString( "Loading Skill Fishing base level requirements..." );
1063    objmgr.LoadFishingBaseSkillLevel();
1064
1065    ///- Load dynamic data tables from the database
1066    sLog.outString( "Loading Auctions..." );
1067    objmgr.LoadAuctionItems();
1068    objmgr.LoadAuctions();
1069
1070    sLog.outString( "Loading Guilds..." );
1071    objmgr.LoadGuilds();
1072
1073    sLog.outString( "Loading ArenaTeams..." );
1074    objmgr.LoadArenaTeams();
1075
1076    sLog.outString( "Loading Groups..." );
1077    objmgr.LoadGroups();
1078
1079    sLog.outString( "Loading ReservedNames..." );
1080    objmgr.LoadReservedPlayersNames();
1081
1082    sLog.outString( "Loading GameObject for quests..." );
1083    objmgr.LoadGameObjectForQuests();
1084
1085    sLog.outString( "Loading BattleMasters..." );
1086    objmgr.LoadBattleMastersEntry();
1087
1088    sLog.outString( "Loading GameTeleports..." );
1089    objmgr.LoadGameTele();
1090
1091    sLog.outString( "Loading Npc Text Id..." );
1092    objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
1093
1094    sLog.outString( "Loading vendors..." );
1095    objmgr.LoadVendors();                                   // must be after load CreatureTemplate and ItemTemplate
1096
1097    sLog.outString( "Loading trainers..." );
1098    objmgr.LoadTrainerSpell();                              // must be after load CreatureTemplate
1099
1100    sLog.outString( "Loading Waypoints..." );
1101    WaypointMgr.Load();
1102
1103    ///- Handle outdated emails (delete/return)
1104    sLog.outString( "Returning old mails..." );
1105    objmgr.ReturnOrDeleteOldMails(false);
1106
1107    ///- Load and initialize scripts
1108    sLog.outString( "Loading Scripts..." );
1109    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1110    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1111    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1112    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1113    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1114
1115    sLog.outString( "Initializing Scripts..." );
1116    if(!LoadScriptingModule())
1117        exit(1);
1118
1119    ///- Initialize game time and timers
1120    sLog.outString( "DEBUG:: Initialize game time and timers" );
1121    m_gameTime = time(NULL);
1122    m_startTime=m_gameTime;
1123
1124    tm local;
1125    time_t curr;
1126    time(&curr);
1127    local=*(localtime(&curr));                              // dereference and assign
1128    char isoDate[128];
1129    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1130        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1131
1132    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1133
1134    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1135    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1136    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1137    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1138    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1139                                                            //Update "uptime" table based on configuration entry in minutes.
1140    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1141
1142    //to set mailtimer to return mails every day between 4 and 5 am
1143    //mailtimer is increased when updating auctions
1144    //one second is 1000 -(tested on win system)
1145    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1146                                                            //1440
1147    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1148    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1149
1150    ///- Initilize static helper structures
1151    AIRegistry::Initialize();
1152    WaypointMovementGenerator<Creature>::Initialize();
1153    Player::InitVisibleBits();
1154
1155    ///- Initialize MapManager
1156    sLog.outString( "Starting Map System" );
1157    MapManager::Instance().Initialize();
1158
1159    ///- Initialize Battlegrounds
1160    sLog.outString( "Starting BattleGround System" );
1161    sBattleGroundMgr.CreateInitialBattleGrounds();
1162    sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1163
1164    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1165    sLog.outString( "Loading Transports..." );
1166    MapManager::Instance().LoadTransports();
1167
1168    sLog.outString("Deleting expired bans..." );
1169    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1170
1171    sLog.outString("Calculate next daily quest reset time..." );
1172    InitDailyQuestResetTime();
1173
1174    sLog.outString("Starting Game Event system..." );
1175    uint32 nextGameEvent = gameeventmgr.Initialize();
1176    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1177
1178    sLog.outString( "WORLD: World initialized" );
1179}
1180void World::DetectDBCLang()
1181{
1182    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1183
1184    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1185    {
1186        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1187        m_lang_confid = LOCALE_enUS;
1188    }
1189
1190    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1191
1192    std::string availableLocalsStr;
1193
1194    int default_locale = MAX_LOCALE;
1195    for (int i = MAX_LOCALE-1; i >= 0; --i)
1196    {
1197        if ( strlen(race->name[i]) > 0)                     // check by race names
1198        {
1199            default_locale = i;
1200            m_availableDbcLocaleMask |= (1 << i);
1201            availableLocalsStr += localeNames[i];
1202            availableLocalsStr += " ";
1203        }
1204    }
1205
1206    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1207        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1208    {
1209        default_locale = m_lang_confid;
1210    }
1211
1212    if(default_locale >= MAX_LOCALE)
1213    {
1214        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1215        exit(1);
1216    }
1217
1218    m_defaultDbcLocale = LocaleConstant(default_locale);
1219
1220    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1221}
1222
1223/// Update the World !
1224void World::Update(time_t diff)
1225{
1226    ///- Update the different timers
1227    for(int i = 0; i < WUPDATE_COUNT; i++)
1228        if(m_timers[i].GetCurrent()>=0)
1229            m_timers[i].Update(diff);
1230    else m_timers[i].SetCurrent(0);
1231
1232    ///- Update the game time and check for shutdown time
1233    _UpdateGameTime();
1234
1235    /// Handle daily quests reset time
1236    if(m_gameTime > m_NextDailyQuestReset)
1237    {
1238        ResetDailyQuests();
1239        m_NextDailyQuestReset += DAY;
1240    }
1241
1242    /// <ul><li> Handle auctions when the timer has passed
1243    if (m_timers[WUPDATE_AUCTIONS].Passed())
1244    {
1245        m_timers[WUPDATE_AUCTIONS].Reset();
1246
1247        ///- Update mails (return old mails with item, or delete them)
1248        //(tested... works on win)
1249        if (++mail_timer > mail_timer_expires)
1250        {
1251            mail_timer = 0;
1252            objmgr.ReturnOrDeleteOldMails(true);
1253        }
1254
1255        AuctionHouseObject* AuctionMap;
1256        for (int i = 0; i < 3; i++)
1257        {
1258            switch (i)
1259            {
1260                case 0:
1261                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1262                    break;
1263                case 1:
1264                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1265                    break;
1266                case 2:
1267                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1268                    break;
1269            }
1270
1271            ///- Handle expired auctions
1272            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1273            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1274            {
1275                next = itr;
1276                ++next;
1277                if (m_gameTime > (itr->second->time))
1278                {
1279                    ///- Either cancel the auction if there was no bidder
1280                    if (itr->second->bidder == 0)
1281                    {
1282                        objmgr.SendAuctionExpiredMail( itr->second );
1283                    }
1284                    ///- Or perform the transaction
1285                    else
1286                    {
1287                        //we should send an "item sold" message if the seller is online
1288                        //we send the item to the winner
1289                        //we send the money to the seller
1290                        objmgr.SendAuctionSuccessfulMail( itr->second );
1291                        objmgr.SendAuctionWonMail( itr->second );
1292                    }
1293
1294                    ///- In any case clear the auction
1295                    //No SQL injection (Id is integer)
1296                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1297                    objmgr.RemoveAItem(itr->second->item_guidlow);
1298                    delete itr->second;
1299                    AuctionMap->RemoveAuction(itr->first);
1300                }
1301            }
1302        }
1303    }
1304
1305    /// <li> Handle session updates when the timer has passed
1306    if (m_timers[WUPDATE_SESSIONS].Passed())
1307    {
1308        m_timers[WUPDATE_SESSIONS].Reset();
1309
1310        UpdateSessions(diff);
1311    }
1312
1313    /// <li> Handle weather updates when the timer has passed
1314    if (m_timers[WUPDATE_WEATHERS].Passed())
1315    {
1316        m_timers[WUPDATE_WEATHERS].Reset();
1317
1318        ///- Send an update signal to Weather objects
1319        WeatherMap::iterator itr, next;
1320        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1321        {
1322            next = itr;
1323            ++next;
1324
1325            ///- and remove Weather objects for zones with no player
1326                                                            //As interval > WorldTick
1327            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1328            {
1329                delete itr->second;
1330                m_weathers.erase(itr);
1331            }
1332        }
1333    }
1334    /// <li> Update uptime table
1335    if (m_timers[WUPDATE_UPTIME].Passed())
1336    {
1337        uint32 tmpDiff = (m_gameTime - m_startTime);
1338        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1339
1340        m_timers[WUPDATE_UPTIME].Reset();
1341        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1342    }
1343
1344    /// <li> Handle all other objects
1345    if (m_timers[WUPDATE_OBJECTS].Passed())
1346    {
1347        m_timers[WUPDATE_OBJECTS].Reset();
1348        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1349        MapManager::Instance().Update(diff);                // As interval = 0
1350
1351        ///- Process necessary scripts
1352        if (!m_scriptSchedule.empty())
1353            ScriptsProcess();
1354
1355        sBattleGroundMgr.Update(diff);
1356    }
1357
1358    // execute callbacks from sql queries that were queued recently
1359    UpdateResultQueue();
1360
1361    ///- Erase corpses once every 20 minutes
1362    if (m_timers[WUPDATE_CORPSES].Passed())
1363    {
1364        m_timers[WUPDATE_CORPSES].Reset();
1365
1366        CorpsesErase();
1367    }
1368
1369    ///- Process Game events when necessary
1370    if (m_timers[WUPDATE_EVENTS].Passed())
1371    {
1372        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1373        uint32 nextGameEvent = gameeventmgr.Update();
1374        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1375        m_timers[WUPDATE_EVENTS].Reset();
1376    }
1377
1378    /// </ul>
1379    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1380    MapManager::Instance().DoDelayedMovesAndRemoves();
1381
1382    // update the instance reset times
1383    sInstanceSaveManager.Update();
1384
1385    // And last, but not least handle the issued cli commands
1386    ProcessCliCommands();
1387}
1388
1389/// Put scripts in the execution queue
1390void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1391{
1392    ///- Find the script map
1393    ScriptMapMap::const_iterator s = scripts.find(id);
1394    if (s == scripts.end())
1395        return;
1396
1397    // prepare static data
1398    uint64 sourceGUID = source->GetGUID();
1399    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1400    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1401
1402    ///- Schedule script execution for all scripts in the script map
1403    ScriptMap const *s2 = &(s->second);
1404    bool immedScript = false;
1405    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1406    {
1407        ScriptAction sa;
1408        sa.sourceGUID = sourceGUID;
1409        sa.targetGUID = targetGUID;
1410        sa.ownerGUID  = ownerGUID;
1411
1412        sa.script = &iter->second;
1413        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1414        if (iter->first == 0)
1415            immedScript = true;
1416    }
1417    ///- If one of the effects should be immediate, launch the script execution
1418    if (immedScript)
1419        ScriptsProcess();
1420}
1421
1422void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1423{
1424    // NOTE: script record _must_ exist until command executed
1425
1426    // prepare static data
1427    uint64 sourceGUID = source->GetGUID();
1428    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1429    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1430
1431    ScriptAction sa;
1432    sa.sourceGUID = sourceGUID;
1433    sa.targetGUID = targetGUID;
1434    sa.ownerGUID  = ownerGUID;
1435
1436    sa.script = &script;
1437    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1438
1439    ///- If effects should be immediate, launch the script execution
1440    if(delay == 0)
1441        ScriptsProcess();
1442}
1443
1444/// Process queued scripts
1445void World::ScriptsProcess()
1446{
1447    if (m_scriptSchedule.empty())
1448        return;
1449
1450    ///- Process overdue queued scripts
1451    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1452                                                            // ok as multimap is a *sorted* associative container
1453    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1454    {
1455        ScriptAction const& step = iter->second;
1456
1457        Object* source = NULL;
1458
1459        if(step.sourceGUID)
1460        {
1461            switch(GUID_HIPART(step.sourceGUID))
1462            {
1463                case HIGHGUID_ITEM:
1464                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1465                    {
1466                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1467                        if(player)
1468                            source = player->GetItemByGuid(step.sourceGUID);
1469                        break;
1470                    }
1471                case HIGHGUID_UNIT:
1472                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1473                    break;
1474                case HIGHGUID_PET:
1475                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1476                    break;
1477                case HIGHGUID_PLAYER:
1478                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1479                    break;
1480                case HIGHGUID_GAMEOBJECT:
1481                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1482                    break;
1483                case HIGHGUID_CORPSE:
1484                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1485                    break;
1486                default:
1487                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1488                    break;
1489            }
1490        }
1491
1492        Object* target = NULL;
1493
1494        if(step.targetGUID)
1495        {
1496            switch(GUID_HIPART(step.targetGUID))
1497            {
1498                case HIGHGUID_UNIT:
1499                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1500                    break;
1501                case HIGHGUID_PET:
1502                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1503                    break;
1504                case HIGHGUID_PLAYER:                       // empty GUID case also
1505                    target = HashMapHolder<Player>::Find(step.targetGUID);
1506                    break;
1507                case HIGHGUID_GAMEOBJECT:
1508                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1509                    break;
1510                case HIGHGUID_CORPSE:
1511                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1512                    break;
1513                default:
1514                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1515                    break;
1516            }
1517        }
1518
1519        switch (step.script->command)
1520        {
1521            case SCRIPT_COMMAND_TALK:
1522            {
1523                if(!source)
1524                {
1525                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1526                    break;
1527                }
1528
1529                if(source->GetTypeId()!=TYPEID_UNIT)
1530                {
1531                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1532                    break;
1533                }
1534                if(step.script->datalong > 3)
1535                {
1536                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1537                    break;
1538                }
1539
1540                uint64 unit_target = target ? target->GetGUID() : 0;
1541
1542                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1543                switch(step.script->datalong)
1544                {
1545                    case 0:                                 // Say
1546                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1547                        break;
1548                    case 1:                                 // Whisper
1549                        if(!unit_target)
1550                        {
1551                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1552                            break;
1553                        }
1554                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1555                        break;
1556                    case 2:                                 // Yell
1557                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1558                        break;
1559                    case 3:                                 // Emote text
1560                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1561                        break;
1562                    default:
1563                        break;                              // must be already checked at load
1564                }
1565                break;
1566            }
1567
1568            case SCRIPT_COMMAND_EMOTE:
1569                if(!source)
1570                {
1571                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1572                    break;
1573                }
1574
1575                if(source->GetTypeId()!=TYPEID_UNIT)
1576                {
1577                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1578                    break;
1579                }
1580
1581                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1582                break;
1583            case SCRIPT_COMMAND_FIELD_SET:
1584                if(!source)
1585                {
1586                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1587                    break;
1588                }
1589                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1590                {
1591                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1592                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1593                    break;
1594                }
1595
1596                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1597                break;
1598            case SCRIPT_COMMAND_MOVE_TO:
1599                if(!source)
1600                {
1601                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1602                    break;
1603                }
1604
1605                if(source->GetTypeId()!=TYPEID_UNIT)
1606                {
1607                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1608                    break;
1609                }
1610                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1611                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1612                break;
1613            case SCRIPT_COMMAND_FLAG_SET:
1614                if(!source)
1615                {
1616                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1617                    break;
1618                }
1619                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1620                {
1621                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1622                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1623                    break;
1624                }
1625
1626                source->SetFlag(step.script->datalong, step.script->datalong2);
1627                break;
1628            case SCRIPT_COMMAND_FLAG_REMOVE:
1629                if(!source)
1630                {
1631                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1632                    break;
1633                }
1634                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1635                {
1636                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1637                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1638                    break;
1639                }
1640
1641                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1642                break;
1643
1644            case SCRIPT_COMMAND_TELEPORT_TO:
1645            {
1646                // accept player in any one from target/source arg
1647                if (!target && !source)
1648                {
1649                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1650                    break;
1651                }
1652
1653                                                            // must be only Player
1654                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1655                {
1656                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1657                    break;
1658                }
1659
1660                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1661
1662                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1663                break;
1664            }
1665
1666            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1667            {
1668                if(!step.script->datalong)                  // creature not specified
1669                {
1670                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1671                    break;
1672                }
1673
1674                if(!source)
1675                {
1676                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1677                    break;
1678                }
1679
1680                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1681
1682                if(!summoner)
1683                {
1684                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1685                    break;
1686                }
1687
1688                float x = step.script->x;
1689                float y = step.script->y;
1690                float z = step.script->z;
1691                float o = step.script->o;
1692
1693                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1694                if (!pCreature)
1695                {
1696                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1697                    break;
1698                }
1699
1700                break;
1701            }
1702
1703            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1704            {
1705                if(!step.script->datalong)                  // gameobject not specified
1706                {
1707                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1708                    break;
1709                }
1710
1711                if(!source)
1712                {
1713                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1714                    break;
1715                }
1716
1717                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1718
1719                if(!summoner)
1720                {
1721                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1722                    break;
1723                }
1724
1725                GameObject *go = NULL;
1726                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1727
1728                CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1729                Cell cell(p);
1730                cell.data.Part.reserved = ALL_DISTRICT;
1731
1732                MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1733                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1734
1735                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1736                CellLock<GridReadGuard> cell_lock(cell, p);
1737                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1738
1739                if ( !go )
1740                {
1741                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1742                    break;
1743                }
1744
1745                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1746                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1747                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1748                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1749                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1750                {
1751                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1752                    break;
1753                }
1754
1755                if( go->isSpawned() )
1756                    break;                                  //gameobject already spawned
1757
1758                go->SetLootState(GO_READY);
1759                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1760
1761                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1762                break;
1763            }
1764            case SCRIPT_COMMAND_OPEN_DOOR:
1765            {
1766                if(!step.script->datalong)                  // door not specified
1767                {
1768                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1769                    break;
1770                }
1771
1772                if(!source)
1773                {
1774                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1775                    break;
1776                }
1777
1778                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1779                {
1780                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1781                    break;
1782                }
1783
1784                Unit* caster = (Unit*)source;
1785
1786                GameObject *door = NULL;
1787                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1788
1789                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1790                Cell cell(p);
1791                cell.data.Part.reserved = ALL_DISTRICT;
1792
1793                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1794                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1795
1796                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1797                CellLock<GridReadGuard> cell_lock(cell, p);
1798                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1799
1800                if ( !door )
1801                {
1802                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1803                    break;
1804                }
1805                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1806                {
1807                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1808                    break;
1809                }
1810
1811                if( !door->GetGoState() )
1812                    break;                                  //door already  open
1813
1814                door->UseDoorOrButton(time_to_close);
1815
1816                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1817                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1818                break;
1819            }
1820            case SCRIPT_COMMAND_CLOSE_DOOR:
1821            {
1822                if(!step.script->datalong)                  // guid for door not specified
1823                {
1824                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1825                    break;
1826                }
1827
1828                if(!source)
1829                {
1830                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1831                    break;
1832                }
1833
1834                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1835                {
1836                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1837                    break;
1838                }
1839
1840                Unit* caster = (Unit*)source;
1841
1842                GameObject *door = NULL;
1843                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1844
1845                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1846                Cell cell(p);
1847                cell.data.Part.reserved = ALL_DISTRICT;
1848
1849                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1850                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1851
1852                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1853                CellLock<GridReadGuard> cell_lock(cell, p);
1854                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1855
1856                if ( !door )
1857                {
1858                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1859                    break;
1860                }
1861                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1862                {
1863                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1864                    break;
1865                }
1866
1867                if( door->GetGoState() )
1868                    break;                                  //door already closed
1869
1870                door->UseDoorOrButton(time_to_open);
1871
1872                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1873                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1874
1875                break;
1876            }
1877            case SCRIPT_COMMAND_QUEST_EXPLORED:
1878            {
1879                if(!source)
1880                {
1881                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1882                    break;
1883                }
1884
1885                if(!target)
1886                {
1887                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1888                    break;
1889                }
1890
1891                // when script called for item spell casting then target == (unit or GO) and source is player
1892                WorldObject* worldObject;
1893                Player* player;
1894
1895                if(target->GetTypeId()==TYPEID_PLAYER)
1896                {
1897                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1898                    {
1899                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1900                        break;
1901                    }
1902
1903                    worldObject = (WorldObject*)source;
1904                    player = (Player*)target;
1905                }
1906                else
1907                {
1908                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1909                    {
1910                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1911                        break;
1912                    }
1913
1914                    if(source->GetTypeId()!=TYPEID_PLAYER)
1915                    {
1916                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1917                        break;
1918                    }
1919
1920                    worldObject = (WorldObject*)target;
1921                    player = (Player*)source;
1922                }
1923
1924                // quest id and flags checked at script loading
1925                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1926                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1927                    player->AreaExploredOrEventHappens(step.script->datalong);
1928                else
1929                    player->FailQuest(step.script->datalong);
1930
1931                break;
1932            }
1933
1934            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1935            {
1936                if(!source)
1937                {
1938                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1939                    break;
1940                }
1941
1942                if(!source->isType(TYPEMASK_UNIT))
1943                {
1944                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1945                    break;
1946                }
1947
1948                if(!target)
1949                {
1950                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1951                    break;
1952                }
1953
1954                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1955                {
1956                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1957                    break;
1958                }
1959
1960                Unit* caster = (Unit*)source;
1961
1962                GameObject *go = (GameObject*)target;
1963
1964                go->Use(caster);
1965                break;
1966            }
1967
1968            case SCRIPT_COMMAND_REMOVE_AURA:
1969            {
1970                Object* cmdTarget = step.script->datalong2 ? source : target;
1971
1972                if(!cmdTarget)
1973                {
1974                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
1975                    break;
1976                }
1977
1978                if(!cmdTarget->isType(TYPEMASK_UNIT))
1979                {
1980                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
1981                    break;
1982                }
1983
1984                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
1985                break;
1986            }
1987
1988            case SCRIPT_COMMAND_CAST_SPELL:
1989            {
1990                if(!source)
1991                {
1992                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
1993                    break;
1994                }
1995
1996                if(!source->isType(TYPEMASK_UNIT))
1997                {
1998                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1999                    break;
2000                }
2001
2002                Object* cmdTarget = step.script->datalong2 ? source : target;
2003
2004                if(!cmdTarget)
2005                {
2006                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2007                    break;
2008                }
2009
2010                if(!cmdTarget->isType(TYPEMASK_UNIT))
2011                {
2012                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2013                    break;
2014                }
2015
2016                Unit* spellTarget = (Unit*)cmdTarget;
2017
2018                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2019                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2020
2021                break;
2022            }
2023
2024            default:
2025                sLog.outError("Unknown script command %u called.",step.script->command);
2026                break;
2027        }
2028
2029        m_scriptSchedule.erase(iter);
2030
2031        iter = m_scriptSchedule.begin();
2032    }
2033    return;
2034}
2035
2036/// Send a packet to all players (except self if mentioned)
2037void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2038{
2039    SessionMap::iterator itr;
2040    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2041    {
2042        if (itr->second &&
2043            itr->second->GetPlayer() &&
2044            itr->second->GetPlayer()->IsInWorld() &&
2045            itr->second != self &&
2046            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2047        {
2048            itr->second->SendPacket(packet);
2049        }
2050    }
2051}
2052
2053/// Send a System Message to all players (except self if mentioned)
2054void World::SendWorldText(int32 string_id, ...)
2055{
2056    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
2057
2058    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2059    {
2060        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2061            continue;
2062
2063        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2064        uint32 cache_idx = loc_idx+1;
2065
2066        std::vector<WorldPacket*>* data_list;
2067
2068        // create if not cached yet
2069        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2070        {
2071            if(data_cache.size() < cache_idx+1)
2072                data_cache.resize(cache_idx+1);
2073
2074            data_list = &data_cache[cache_idx];
2075
2076            char const* text = objmgr.GetMangosString(string_id,loc_idx);
2077
2078            char buf[1000];
2079
2080            va_list argptr;
2081            va_start( argptr, string_id );
2082            vsnprintf( buf,1000, text, argptr );
2083            va_end( argptr );
2084
2085            char* pos = &buf[0];
2086
2087            while(char* line = ChatHandler::LineFromMessage(pos))
2088            {
2089                WorldPacket* data = new WorldPacket();
2090                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2091                data_list->push_back(data);
2092            }
2093        }
2094        else
2095            data_list = &data_cache[cache_idx];
2096
2097        for(int i = 0; i < data_list->size(); ++i)
2098            itr->second->SendPacket((*data_list)[i]);
2099    }
2100
2101    // free memory
2102    for(int i = 0; i < data_cache.size(); ++i)
2103        for(int j = 0; j < data_cache[i].size(); ++j)
2104            delete data_cache[i][j];
2105}
2106
2107/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2108void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2109{
2110    SessionMap::iterator itr;
2111    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2112    {
2113        if (itr->second &&
2114            itr->second->GetPlayer() &&
2115            itr->second->GetPlayer()->IsInWorld() &&
2116            itr->second->GetPlayer()->GetZoneId() == zone &&
2117            itr->second != self &&
2118            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2119        {
2120            itr->second->SendPacket(packet);
2121        }
2122    }
2123}
2124
2125/// Send a System Message to all players in the zone (except self if mentioned)
2126void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2127{
2128    WorldPacket data;
2129    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2130    SendZoneMessage(zone, &data, self,team);
2131}
2132
2133/// Kick (and save) all players
2134void World::KickAll()
2135{
2136    // session not removed at kick and will removed in next update tick
2137    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2138        itr->second->KickPlayer();
2139}
2140
2141/// Kick (and save) all players with security level less `sec`
2142void World::KickAllLess(AccountTypes sec)
2143{
2144    // session not removed at kick and will removed in next update tick
2145    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2146        if(itr->second->GetSecurity() < sec)
2147            itr->second->KickPlayer();
2148}
2149
2150/// Kick all queued players
2151void World::KickAllQueued()
2152{
2153    // session not removed at kick and will removed in next update tick
2154  //TODO here
2155//    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2156//        if(WorldSession* session = (*itr)->GetSession())
2157//            session->KickPlayer();
2158
2159    m_QueuedPlayer.empty();
2160}
2161
2162/// Kick (and save) the designated player
2163bool World::KickPlayer(std::string playerName)
2164{
2165    SessionMap::iterator itr;
2166
2167    // session not removed at kick and will removed in next update tick
2168    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2169    {
2170        if(!itr->second)
2171            continue;
2172        Player *player = itr->second->GetPlayer();
2173        if(!player)
2174            continue;
2175        if( player->IsInWorld() )
2176        {
2177            if (playerName == player->GetName())
2178            {
2179                itr->second->KickPlayer();
2180                return true;
2181            }
2182        }
2183    }
2184    return false;
2185}
2186
2187/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2188uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2189{
2190    loginDatabase.escape_string(nameOrIP);
2191    loginDatabase.escape_string(reason);
2192    std::string safe_author=author;
2193    loginDatabase.escape_string(safe_author);
2194
2195    if(type != "ip" && !normalizePlayerName(nameOrIP))
2196        return BAN_NOTFOUND;                                // Nobody to ban
2197
2198    uint32 duration_secs = TimeStringToSecs(duration);
2199    QueryResult *resultAccounts = NULL;                     //used for kicking
2200
2201    ///- Update the database with ban information
2202
2203    if(type=="ip")
2204    {
2205        //No SQL injection as strings are escaped
2206        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2207        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());
2208    }
2209    else if(type=="account")
2210    {
2211        //No SQL injection as string is escaped
2212        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2213    }
2214    else if(type=="character")
2215    {
2216        //No SQL injection as string is escaped
2217        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2218    }
2219    else
2220        return BAN_SYNTAX_ERROR;                            //Syntax problem
2221
2222    if(!resultAccounts)
2223        if(type=="ip")
2224            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2225    else
2226        return BAN_NOTFOUND;                                // Nobody to ban
2227
2228    ///- Disconnect all affected players (for IP it can be several)
2229    do
2230    {
2231        Field* fieldsAccount = resultAccounts->Fetch();
2232        uint32 account = fieldsAccount->GetUInt32();
2233
2234        if(type != "ip")
2235            //No SQL injection as strings are escaped
2236            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2237                account,duration_secs,safe_author.c_str(),reason.c_str());
2238
2239        WorldSession* sess = FindSession(account);
2240        if( sess )
2241            if(std::string(sess->GetPlayerName()) != author)
2242                sess->KickPlayer();
2243    }
2244    while( resultAccounts->NextRow() );
2245
2246    delete resultAccounts;
2247    return BAN_SUCCESS;
2248}
2249
2250/// Remove a ban from an account or IP address
2251bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2252{
2253    if(type == "ip")
2254    {
2255        loginDatabase.escape_string(nameOrIP);
2256        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2257    }
2258    else
2259    {
2260        uint32 account=0;
2261        if(type == "account")
2262        {
2263            //NO SQL injection as name is escaped
2264            loginDatabase.escape_string(nameOrIP);
2265            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2266            if(!resultAccounts)
2267                return false;
2268            Field* fieldsAccount = resultAccounts->Fetch();
2269            account = fieldsAccount->GetUInt32();
2270
2271            delete resultAccounts;
2272        }
2273        else if(type == "character")
2274        {
2275            if(!normalizePlayerName(nameOrIP))
2276                return false;
2277
2278            //NO SQL injection as name is escaped
2279            loginDatabase.escape_string(nameOrIP);
2280            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2281            if(!resultAccounts)
2282                return false;
2283            Field* fieldsAccount = resultAccounts->Fetch();
2284            account = fieldsAccount->GetUInt32();
2285
2286            delete resultAccounts;
2287        }
2288        if(!account)
2289            return false;
2290        //NO SQL injection as account is uint32
2291        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2292    }
2293    return true;
2294}
2295
2296/// Update the game time
2297void World::_UpdateGameTime()
2298{
2299    ///- update the time
2300    time_t thisTime = time(NULL);
2301    uint32 elapsed = uint32(thisTime - m_gameTime);
2302    m_gameTime = thisTime;
2303
2304    ///- if there is a shutdown timer
2305    if(m_ShutdownTimer > 0 && elapsed > 0)
2306    {
2307        ///- ... and it is overdue, stop the world (set m_stopEvent)
2308        if( m_ShutdownTimer <= elapsed )
2309        {
2310            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2311                m_stopEvent = true;
2312            else
2313                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2314        }
2315        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2316        else
2317        {
2318            m_ShutdownTimer -= elapsed;
2319
2320            ShutdownMsg();
2321        }
2322    }
2323}
2324
2325/// Shutdown the server
2326void World::ShutdownServ(uint32 time, uint32 options)
2327{
2328    m_ShutdownMask = options;
2329
2330    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2331    if(time==0)
2332    {
2333        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2334            m_stopEvent = true;
2335        else
2336            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2337    }
2338    ///- Else set the shutdown timer and warn users
2339    else
2340    {
2341        m_ShutdownTimer = time;
2342        ShutdownMsg(true);
2343    }
2344}
2345
2346/// Display a shutdown message to the user(s)
2347void World::ShutdownMsg(bool show, Player* player)
2348{
2349    // not show messages for idle shutdown mode
2350    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2351        return;
2352
2353    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2354    if ( show ||
2355        (m_ShutdownTimer < 10) ||
2356                                                            // < 30 sec; every 5 sec
2357        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2358                                                            // < 5 min ; every 1 min
2359        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2360                                                            // < 30 min ; every 5 min
2361        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2362                                                            // < 12 h ; every 1 h
2363        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2364                                                            // > 12 h ; every 12 h
2365        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2366    {
2367        std::string str = secsToTimeString(m_ShutdownTimer);
2368
2369        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2370
2371        SendServerMessage(msgid,str.c_str(),player);
2372        DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2373    }
2374}
2375
2376/// Cancel a planned server shutdown
2377void World::ShutdownCancel()
2378{
2379    if(!m_ShutdownTimer)
2380        return;
2381
2382    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2383
2384    m_ShutdownMask = 0;
2385    m_ShutdownTimer = 0;
2386    SendServerMessage(msgid);
2387
2388    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2389}
2390
2391/// Send a server message to the user(s)
2392void World::SendServerMessage(uint32 type, const char *text, Player* player)
2393{
2394    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2395    data << uint32(type);
2396    if(type <= SERVER_MSG_STRING)
2397        data << text;
2398
2399    if(player)
2400        player->GetSession()->SendPacket(&data);
2401    else
2402        SendGlobalMessage( &data );
2403}
2404
2405void World::UpdateSessions( time_t diff )
2406{
2407    while(!addSessQueue.empty())
2408    {
2409      WorldSession* sess = addSessQueue.next ();
2410      AddSession_ (sess);
2411    }
2412       
2413    ///- Delete kicked sessions at add new session
2414    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2415        delete *itr;
2416    m_kicked_sessions.clear();
2417
2418    ///- Then send an update signal to remaining ones
2419    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2420    {
2421        next = itr;
2422        ++next;
2423
2424        if(!itr->second)
2425            continue;
2426
2427        ///- and remove not active sessions from the list
2428        if(!itr->second->Update(diff))                      // As interval = 0
2429        {
2430            delete itr->second;
2431            m_sessions.erase(itr);
2432        }
2433    }
2434}
2435
2436// This handles the issued and queued CLI commands
2437void World::ProcessCliCommands()
2438{
2439    if (cliCmdQueue.empty()) return;
2440
2441    CliCommandHolder *command;
2442    pPrintf p_zprintf;
2443    while (!cliCmdQueue.empty())
2444    {
2445        sLog.outDebug("CLI command under processing...");
2446        command = cliCmdQueue.next();
2447        command->Execute();
2448        p_zprintf=command->GetOutputMethod();
2449        delete command;
2450    }
2451    // print the console message here so it looks right
2452    p_zprintf("mangos>");
2453}
2454
2455void World::InitResultQueue()
2456{
2457    m_resultQueue = new SqlResultQueue;
2458    CharacterDatabase.SetResultQueue(m_resultQueue);
2459}
2460
2461void World::UpdateResultQueue()
2462{
2463    m_resultQueue->Update();
2464}
2465
2466void World::UpdateRealmCharCount(uint32 accountId)
2467{
2468    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2469        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2470}
2471
2472void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2473{
2474    if (resultCharCount)
2475    {
2476        Field *fields = resultCharCount->Fetch();
2477        uint32 charCount = fields[0].GetUInt32();
2478        delete resultCharCount;
2479        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2480        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2481    }
2482}
2483
2484void World::InitDailyQuestResetTime()
2485{
2486    time_t mostRecentQuestTime;
2487
2488    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2489    if(result)
2490    {
2491        Field *fields = result->Fetch();
2492
2493        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2494        delete result;
2495    }
2496    else
2497        mostRecentQuestTime = 0;
2498
2499    // client built-in time for reset is 6:00 AM
2500    // FIX ME: client not show day start time
2501    time_t curTime = time(NULL);
2502    tm localTm = *localtime(&curTime);
2503    localTm.tm_hour = 6;
2504    localTm.tm_min  = 0;
2505    localTm.tm_sec  = 0;
2506
2507    // current day reset time
2508    time_t curDayResetTime = mktime(&localTm);
2509
2510    // last reset time before current moment
2511    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2512
2513    // need reset (if we have quest time before last reset time (not processed by some reason)
2514    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2515        m_NextDailyQuestReset = mostRecentQuestTime;
2516    else
2517    {
2518        // plan next reset time
2519        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2520    }
2521}
2522
2523void World::ResetDailyQuests()
2524{
2525    sLog.outDetail("Daily quests reset for all characters.");
2526    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2527    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2528        if(itr->second->GetPlayer())
2529            itr->second->GetPlayer()->ResetDailyQuestStatus();
2530}
2531
2532void World::SetPlayerLimit( int32 limit, bool needUpdate )
2533{
2534    if(limit < -SEC_ADMINISTRATOR)
2535        limit = -SEC_ADMINISTRATOR;
2536
2537    // lock update need
2538    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2539
2540    m_playerLimit = limit;
2541
2542    if(db_update_need)
2543        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2544}
2545
2546void World::UpdateMaxSessionCounters()
2547{
2548    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2549    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2550}
Note: See TracBrowser for help on using the browser.