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

Revision 83, 107.0 kB (checked in by yumileroy, 17 years ago)

[svn] * Compile fixes from previous revs.

Original author: KingPin?
Date: 2008-10-20 14:11:58-05:00

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