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

Revision 88, 107.2 kB (checked in by yumileroy, 17 years ago)

[svn] * Added some player info cache to the core. Thanx to Rognar for patch, visaglis for testing and bugging me to add it.

Original author: KingPin?
Date: 2008-10-21 12:43:24-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 Player info in cache..." );
992    objmgr.LoadPlayerInfoInCache();
993
994    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
995    objmgr.LoadGameobjectInfo();
996
997    sLog.outString( "Loading Spell Chain Data..." );
998    spellmgr.LoadSpellChains();
999
1000    sLog.outString( "Loading Spell Elixir types..." );
1001    spellmgr.LoadSpellElixirs();
1002
1003    sLog.outString( "Loading Spell Learn Skills..." );
1004    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
1005
1006    sLog.outString( "Loading Spell Learn Spells..." );
1007    spellmgr.LoadSpellLearnSpells();
1008
1009    sLog.outString( "Loading Spell Proc Event conditions..." );
1010    spellmgr.LoadSpellProcEvents();
1011
1012    sLog.outString( "Loading Aggro Spells Definitions...");
1013    spellmgr.LoadSpellThreats();
1014
1015    sLog.outString( "Loading NPC Texts..." );
1016    objmgr.LoadGossipText();
1017
1018    sLog.outString( "Loading Item Random Enchantments Table..." );
1019    LoadRandomEnchantmentsTable();
1020
1021    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1022    objmgr.LoadItemPrototypes();
1023
1024    sLog.outString( "Loading Item Texts..." );
1025    objmgr.LoadItemTexts();
1026
1027    sLog.outString( "Loading Creature Model Based Info Data..." );
1028    objmgr.LoadCreatureModelInfo();
1029
1030    sLog.outString( "Loading Equipment templates...");
1031    objmgr.LoadEquipmentTemplates();
1032
1033    sLog.outString( "Loading Creature templates..." );
1034    objmgr.LoadCreatureTemplates();
1035
1036    sLog.outString( "Loading SpellsScriptTarget...");
1037    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
1038
1039    sLog.outString( "Loading Creature Reputation OnKill Data..." );
1040    objmgr.LoadReputationOnKill();
1041
1042    sLog.outString( "Loading Pet Create Spells..." );
1043    objmgr.LoadPetCreateSpells();
1044
1045    sLog.outString( "Loading Creature Data..." );
1046    objmgr.LoadCreatures();
1047
1048    sLog.outString( "Loading Creature Addon Data..." );
1049    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
1050
1051    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
1052    objmgr.LoadCreatureRespawnTimes();
1053
1054    sLog.outString( "Loading Gameobject Data..." );
1055    objmgr.LoadGameobjects();
1056
1057    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1058    objmgr.LoadGameobjectRespawnTimes();
1059
1060    sLog.outString( "Loading Game Event Data...");
1061    gameeventmgr.LoadFromDB();
1062
1063    sLog.outString( "Loading Weather Data..." );
1064    objmgr.LoadWeatherZoneChances();
1065
1066    sLog.outString( "Loading Quests..." );
1067    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
1068
1069    sLog.outString( "Loading Quests Relations..." );
1070    objmgr.LoadQuestRelations();                            // must be after quest load
1071
1072    sLog.outString( "Loading AreaTrigger definitions..." );
1073    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
1074
1075    sLog.outString( "Loading Quest Area Triggers..." );
1076    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
1077
1078    sLog.outString( "Loading Tavern Area Triggers..." );
1079    objmgr.LoadTavernAreaTriggers();
1080   
1081    sLog.outString( "Loading AreaTrigger script names..." );
1082    objmgr.LoadAreaTriggerScripts();
1083
1084
1085    sLog.outString( "Loading Graveyard-zone links...");
1086    objmgr.LoadGraveyardZones();
1087
1088    sLog.outString( "Loading Spell target coordinates..." );
1089    spellmgr.LoadSpellTargetPositions();
1090
1091    sLog.outString( "Loading SpellAffect definitions..." );
1092    spellmgr.LoadSpellAffects();
1093
1094    sLog.outString( "Loading spell pet auras..." );
1095    spellmgr.LoadSpellPetAuras();
1096
1097    sLog.outString( "Loading player Create Info & Level Stats..." );
1098    objmgr.LoadPlayerInfo();
1099
1100    sLog.outString( "Loading Exploration BaseXP Data..." );
1101    objmgr.LoadExplorationBaseXP();
1102
1103    sLog.outString( "Loading Pet Name Parts..." );
1104    objmgr.LoadPetNames();
1105
1106    sLog.outString( "Loading the max pet number..." );
1107    objmgr.LoadPetNumber();
1108
1109    sLog.outString( "Loading pet level stats..." );
1110    objmgr.LoadPetLevelInfo();
1111
1112    sLog.outString( "Loading Player Corpses..." );
1113    objmgr.LoadCorpses();
1114
1115    sLog.outString( "Loading Disabled Spells..." );
1116    objmgr.LoadSpellDisabledEntrys();
1117
1118    sLog.outString( "Loading Loot Tables..." );
1119    LoadLootTables();
1120
1121    sLog.outString( "Loading Skill Discovery Table..." );
1122    LoadSkillDiscoveryTable();
1123
1124    sLog.outString( "Loading Skill Extra Item Table..." );
1125    LoadSkillExtraItemTable();
1126
1127    sLog.outString( "Loading Skill Fishing base level requirements..." );
1128    objmgr.LoadFishingBaseSkillLevel();
1129
1130    ///- Load dynamic data tables from the database
1131    sLog.outString( "Loading Auctions..." );
1132    objmgr.LoadAuctionItems();
1133    objmgr.LoadAuctions();
1134
1135    sLog.outString( "Loading Guilds..." );
1136    objmgr.LoadGuilds();
1137
1138    sLog.outString( "Loading ArenaTeams..." );
1139    objmgr.LoadArenaTeams();
1140
1141    sLog.outString( "Loading Groups..." );
1142    objmgr.LoadGroups();
1143
1144    sLog.outString( "Loading ReservedNames..." );
1145    objmgr.LoadReservedPlayersNames();
1146
1147    sLog.outString( "Loading GameObject for quests..." );
1148    objmgr.LoadGameObjectForQuests();
1149
1150    sLog.outString( "Loading BattleMasters..." );
1151    objmgr.LoadBattleMastersEntry();
1152
1153    sLog.outString( "Loading GameTeleports..." );
1154    objmgr.LoadGameTele();
1155
1156    sLog.outString( "Loading Npc Text Id..." );
1157    objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
1158
1159    sLog.outString( "Loading vendors..." );
1160    objmgr.LoadVendors();                                   // must be after load CreatureTemplate and ItemTemplate
1161
1162    sLog.outString( "Loading trainers..." );
1163    objmgr.LoadTrainerSpell();                              // must be after load CreatureTemplate
1164
1165    sLog.outString( "Loading Waypoints..." );
1166    WaypointMgr.Load();
1167
1168    ///- Handle outdated emails (delete/return)
1169    sLog.outString( "Returning old mails..." );
1170    objmgr.ReturnOrDeleteOldMails(false);
1171
1172    ///- Load and initialize scripts
1173    sLog.outString( "Loading Scripts..." );
1174    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1175    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1176    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1177    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1178    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1179
1180    sLog.outString( "Initializing Scripts..." );
1181    if(!LoadScriptingModule())
1182        exit(1);
1183
1184    ///- Initialize game time and timers
1185    sLog.outString( "DEBUG:: Initialize game time and timers" );
1186    m_gameTime = time(NULL);
1187    m_startTime=m_gameTime;
1188
1189    tm local;
1190    time_t curr;
1191    time(&curr);
1192    local=*(localtime(&curr));                              // dereference and assign
1193    char isoDate[128];
1194    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1195        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1196
1197    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1198
1199    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1200    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1201    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1202    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1203    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1204                                                            //Update "uptime" table based on configuration entry in minutes.
1205    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1206
1207    //to set mailtimer to return mails every day between 4 and 5 am
1208    //mailtimer is increased when updating auctions
1209    //one second is 1000 -(tested on win system)
1210    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1211                                                            //1440
1212    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1213    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1214
1215    ///- Initilize static helper structures
1216    AIRegistry::Initialize();
1217    WaypointMovementGenerator<Creature>::Initialize();
1218    Player::InitVisibleBits();
1219
1220    ///- Initialize MapManager
1221    sLog.outString( "Starting Map System" );
1222    MapManager::Instance().Initialize();
1223
1224    ///- Initialize Battlegrounds
1225    sLog.outString( "Starting BattleGround System" );
1226    sBattleGroundMgr.CreateInitialBattleGrounds();
1227    sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1228
1229    ///- Initialize outdoor pvp
1230    sLog.outString( "Starting Outdoor PvP System" );
1231    sOutdoorPvPMgr.InitOutdoorPvP();
1232
1233    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1234    sLog.outString( "Loading Transports..." );
1235    MapManager::Instance().LoadTransports();
1236
1237    sLog.outString("Deleting expired bans..." );
1238    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1239
1240    sLog.outString("Calculate next daily quest reset time..." );
1241    InitDailyQuestResetTime();
1242
1243    sLog.outString("Starting Game Event system..." );
1244    uint32 nextGameEvent = gameeventmgr.Initialize();
1245    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1246
1247    sLog.outString( "WORLD: World initialized" );
1248}
1249void World::DetectDBCLang()
1250{
1251    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1252
1253    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1254    {
1255        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1256        m_lang_confid = LOCALE_enUS;
1257    }
1258
1259    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1260
1261    std::string availableLocalsStr;
1262
1263    int default_locale = MAX_LOCALE;
1264    for (int i = MAX_LOCALE-1; i >= 0; --i)
1265    {
1266        if ( strlen(race->name[i]) > 0)                     // check by race names
1267        {
1268            default_locale = i;
1269            m_availableDbcLocaleMask |= (1 << i);
1270            availableLocalsStr += localeNames[i];
1271            availableLocalsStr += " ";
1272        }
1273    }
1274
1275    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1276        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1277    {
1278        default_locale = m_lang_confid;
1279    }
1280
1281    if(default_locale >= MAX_LOCALE)
1282    {
1283        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1284        exit(1);
1285    }
1286
1287    m_defaultDbcLocale = LocaleConstant(default_locale);
1288
1289    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1290}
1291
1292/// Update the World !
1293void World::Update(time_t diff)
1294{
1295    ///- Update the different timers
1296    for(int i = 0; i < WUPDATE_COUNT; i++)
1297        if(m_timers[i].GetCurrent()>=0)
1298            m_timers[i].Update(diff);
1299    else m_timers[i].SetCurrent(0);
1300
1301    ///- Update the game time and check for shutdown time
1302    _UpdateGameTime();
1303
1304    /// Handle daily quests reset time
1305    if(m_gameTime > m_NextDailyQuestReset)
1306    {
1307        ResetDailyQuests();
1308        m_NextDailyQuestReset += DAY;
1309    }
1310
1311    /// <ul><li> Handle auctions when the timer has passed
1312    if (m_timers[WUPDATE_AUCTIONS].Passed())
1313    {
1314        m_timers[WUPDATE_AUCTIONS].Reset();
1315
1316        ///- Update mails (return old mails with item, or delete them)
1317        //(tested... works on win)
1318        if (++mail_timer > mail_timer_expires)
1319        {
1320            mail_timer = 0;
1321            objmgr.ReturnOrDeleteOldMails(true);
1322        }
1323
1324        AuctionHouseObject* AuctionMap;
1325        for (int i = 0; i < 3; i++)
1326        {
1327            switch (i)
1328            {
1329                case 0:
1330                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1331                    break;
1332                case 1:
1333                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1334                    break;
1335                case 2:
1336                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1337                    break;
1338            }
1339
1340            ///- Handle expired auctions
1341            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1342            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1343            {
1344                next = itr;
1345                ++next;
1346                if (m_gameTime > (itr->second->time))
1347                {
1348                    ///- Either cancel the auction if there was no bidder
1349                    if (itr->second->bidder == 0)
1350                    {
1351                        objmgr.SendAuctionExpiredMail( itr->second );
1352                    }
1353                    ///- Or perform the transaction
1354                    else
1355                    {
1356                        //we should send an "item sold" message if the seller is online
1357                        //we send the item to the winner
1358                        //we send the money to the seller
1359                        objmgr.SendAuctionSuccessfulMail( itr->second );
1360                        objmgr.SendAuctionWonMail( itr->second );
1361                    }
1362
1363                    ///- In any case clear the auction
1364                    //No SQL injection (Id is integer)
1365                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1366                    objmgr.RemoveAItem(itr->second->item_guidlow);
1367                    delete itr->second;
1368                    AuctionMap->RemoveAuction(itr->first);
1369                }
1370            }
1371        }
1372    }
1373
1374    /// <li> Handle session updates when the timer has passed
1375    if (m_timers[WUPDATE_SESSIONS].Passed())
1376    {
1377        m_timers[WUPDATE_SESSIONS].Reset();
1378
1379        UpdateSessions(diff);
1380    }
1381
1382    /// <li> Handle weather updates when the timer has passed
1383    if (m_timers[WUPDATE_WEATHERS].Passed())
1384    {
1385        m_timers[WUPDATE_WEATHERS].Reset();
1386
1387        ///- Send an update signal to Weather objects
1388        WeatherMap::iterator itr, next;
1389        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1390        {
1391            next = itr;
1392            ++next;
1393
1394            ///- and remove Weather objects for zones with no player
1395                                                            //As interval > WorldTick
1396            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1397            {
1398                delete itr->second;
1399                m_weathers.erase(itr);
1400            }
1401        }
1402    }
1403    /// <li> Update uptime table
1404    if (m_timers[WUPDATE_UPTIME].Passed())
1405    {
1406        uint32 tmpDiff = (m_gameTime - m_startTime);
1407        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1408
1409        m_timers[WUPDATE_UPTIME].Reset();
1410        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1411    }
1412
1413    /// <li> Handle all other objects
1414    if (m_timers[WUPDATE_OBJECTS].Passed())
1415    {
1416        m_timers[WUPDATE_OBJECTS].Reset();
1417        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1418        MapManager::Instance().Update(diff);                // As interval = 0
1419
1420        ///- Process necessary scripts
1421        if (!m_scriptSchedule.empty())
1422            ScriptsProcess();
1423
1424        sBattleGroundMgr.Update(diff);
1425
1426        sOutdoorPvPMgr.Update(diff);
1427    }
1428
1429    // execute callbacks from sql queries that were queued recently
1430    UpdateResultQueue();
1431
1432    ///- Erase corpses once every 20 minutes
1433    if (m_timers[WUPDATE_CORPSES].Passed())
1434    {
1435        m_timers[WUPDATE_CORPSES].Reset();
1436
1437        CorpsesErase();
1438    }
1439
1440    ///- Process Game events when necessary
1441    if (m_timers[WUPDATE_EVENTS].Passed())
1442    {
1443        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1444        uint32 nextGameEvent = gameeventmgr.Update();
1445        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1446        m_timers[WUPDATE_EVENTS].Reset();
1447    }
1448
1449    MapManager::Instance().DoDelayedMovesAndRemoves(); ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1450
1451    // update the instance reset times
1452    sInstanceSaveManager.Update();
1453
1454    // And last, but not least handle the issued cli commands
1455    ProcessCliCommands();
1456}
1457
1458void World::ForceGameEventUpdate()
1459{
1460    m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1461    uint32 nextGameEvent = gameeventmgr.Update();
1462    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1463    m_timers[WUPDATE_EVENTS].Reset();
1464}
1465
1466/// Put scripts in the execution queue
1467void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1468{
1469    ///- Find the script map
1470    ScriptMapMap::const_iterator s = scripts.find(id);
1471    if (s == scripts.end())
1472        return;
1473
1474    // prepare static data
1475    uint64 sourceGUID = source->GetGUID();
1476    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1477    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1478
1479    ///- Schedule script execution for all scripts in the script map
1480    ScriptMap const *s2 = &(s->second);
1481    bool immedScript = false;
1482    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1483    {
1484        ScriptAction sa;
1485        sa.sourceGUID = sourceGUID;
1486        sa.targetGUID = targetGUID;
1487        sa.ownerGUID  = ownerGUID;
1488
1489        sa.script = &iter->second;
1490        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1491        if (iter->first == 0)
1492            immedScript = true;
1493    }
1494    ///- If one of the effects should be immediate, launch the script execution
1495    if (immedScript)
1496        ScriptsProcess();
1497}
1498
1499void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1500{
1501    // NOTE: script record _must_ exist until command executed
1502
1503    // prepare static data
1504    uint64 sourceGUID = source->GetGUID();
1505    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1506    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1507
1508    ScriptAction sa;
1509    sa.sourceGUID = sourceGUID;
1510    sa.targetGUID = targetGUID;
1511    sa.ownerGUID  = ownerGUID;
1512
1513    sa.script = &script;
1514    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1515
1516    ///- If effects should be immediate, launch the script execution
1517    if(delay == 0)
1518        ScriptsProcess();
1519}
1520
1521/// Process queued scripts
1522void World::ScriptsProcess()
1523{
1524    if (m_scriptSchedule.empty())
1525        return;
1526
1527    ///- Process overdue queued scripts
1528    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1529                                                            // ok as multimap is a *sorted* associative container
1530    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1531    {
1532        ScriptAction const& step = iter->second;
1533
1534        Object* source = NULL;
1535
1536        if(step.sourceGUID)
1537        {
1538            switch(GUID_HIPART(step.sourceGUID))
1539            {
1540                case HIGHGUID_ITEM:
1541                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1542                    {
1543                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1544                        if(player)
1545                            source = player->GetItemByGuid(step.sourceGUID);
1546                        break;
1547                    }
1548                case HIGHGUID_UNIT:
1549                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1550                    break;
1551                case HIGHGUID_PET:
1552                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1553                    break;
1554                case HIGHGUID_PLAYER:
1555                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1556                    break;
1557                case HIGHGUID_GAMEOBJECT:
1558                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1559                    break;
1560                case HIGHGUID_CORPSE:
1561                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1562                    break;
1563                default:
1564                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1565                    break;
1566            }
1567        }
1568
1569        Object* target = NULL;
1570
1571        if(step.targetGUID)
1572        {
1573            switch(GUID_HIPART(step.targetGUID))
1574            {
1575                case HIGHGUID_UNIT:
1576                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1577                    break;
1578                case HIGHGUID_PET:
1579                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1580                    break;
1581                case HIGHGUID_PLAYER:                       // empty GUID case also
1582                    target = HashMapHolder<Player>::Find(step.targetGUID);
1583                    break;
1584                case HIGHGUID_GAMEOBJECT:
1585                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1586                    break;
1587                case HIGHGUID_CORPSE:
1588                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1589                    break;
1590                default:
1591                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1592                    break;
1593            }
1594        }
1595
1596        switch (step.script->command)
1597        {
1598            case SCRIPT_COMMAND_TALK:
1599            {
1600                if(!source)
1601                {
1602                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1603                    break;
1604                }
1605
1606                if(source->GetTypeId()!=TYPEID_UNIT)
1607                {
1608                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1609                    break;
1610                }
1611                if(step.script->datalong > 3)
1612                {
1613                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1614                    break;
1615                }
1616
1617                uint64 unit_target = target ? target->GetGUID() : 0;
1618
1619                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1620                switch(step.script->datalong)
1621                {
1622                    case 0:                                 // Say
1623                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1624                        break;
1625                    case 1:                                 // Whisper
1626                        if(!unit_target)
1627                        {
1628                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1629                            break;
1630                        }
1631                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1632                        break;
1633                    case 2:                                 // Yell
1634                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1635                        break;
1636                    case 3:                                 // Emote text
1637                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1638                        break;
1639                    default:
1640                        break;                              // must be already checked at load
1641                }
1642                break;
1643            }
1644
1645            case SCRIPT_COMMAND_EMOTE:
1646                if(!source)
1647                {
1648                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1649                    break;
1650                }
1651
1652                if(source->GetTypeId()!=TYPEID_UNIT)
1653                {
1654                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1655                    break;
1656                }
1657
1658                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1659                break;
1660            case SCRIPT_COMMAND_FIELD_SET:
1661                if(!source)
1662                {
1663                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1664                    break;
1665                }
1666                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1667                {
1668                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1669                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1670                    break;
1671                }
1672
1673                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1674                break;
1675            case SCRIPT_COMMAND_MOVE_TO:
1676                if(!source)
1677                {
1678                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1679                    break;
1680                }
1681
1682                if(source->GetTypeId()!=TYPEID_UNIT)
1683                {
1684                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1685                    break;
1686                }
1687                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1688                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1689                break;
1690            case SCRIPT_COMMAND_FLAG_SET:
1691                if(!source)
1692                {
1693                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1694                    break;
1695                }
1696                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1697                {
1698                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1699                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1700                    break;
1701                }
1702
1703                source->SetFlag(step.script->datalong, step.script->datalong2);
1704                break;
1705            case SCRIPT_COMMAND_FLAG_REMOVE:
1706                if(!source)
1707                {
1708                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1709                    break;
1710                }
1711                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1712                {
1713                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1714                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1715                    break;
1716                }
1717
1718                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1719                break;
1720
1721            case SCRIPT_COMMAND_TELEPORT_TO:
1722            {
1723                // accept player in any one from target/source arg
1724                if (!target && !source)
1725                {
1726                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1727                    break;
1728                }
1729
1730                                                            // must be only Player
1731                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1732                {
1733                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1734                    break;
1735                }
1736
1737                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1738
1739                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1740                break;
1741            }
1742
1743            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1744            {
1745                if(!step.script->datalong)                  // creature not specified
1746                {
1747                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1748                    break;
1749                }
1750
1751                if(!source)
1752                {
1753                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1754                    break;
1755                }
1756
1757                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1758
1759                if(!summoner)
1760                {
1761                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1762                    break;
1763                }
1764
1765                float x = step.script->x;
1766                float y = step.script->y;
1767                float z = step.script->z;
1768                float o = step.script->o;
1769
1770                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1771                if (!pCreature)
1772                {
1773                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1774                    break;
1775                }
1776
1777                break;
1778            }
1779
1780            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1781            {
1782                if(!step.script->datalong)                  // gameobject not specified
1783                {
1784                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1785                    break;
1786                }
1787
1788                if(!source)
1789                {
1790                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1791                    break;
1792                }
1793
1794                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1795
1796                if(!summoner)
1797                {
1798                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1799                    break;
1800                }
1801
1802                GameObject *go = NULL;
1803                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1804
1805                CellPair p(Trinity::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1806                Cell cell(p);
1807                cell.data.Part.reserved = ALL_DISTRICT;
1808
1809                Trinity::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1810                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(go,go_check);
1811
1812                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1813                CellLock<GridReadGuard> cell_lock(cell, p);
1814                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1815
1816                if ( !go )
1817                {
1818                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1819                    break;
1820                }
1821
1822                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1823                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1824                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1825                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1826                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1827                {
1828                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1829                    break;
1830                }
1831
1832                if( go->isSpawned() )
1833                    break;                                  //gameobject already spawned
1834
1835                go->SetLootState(GO_READY);
1836                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1837
1838                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1839                break;
1840            }
1841            case SCRIPT_COMMAND_OPEN_DOOR:
1842            {
1843                if(!step.script->datalong)                  // door not specified
1844                {
1845                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1846                    break;
1847                }
1848
1849                if(!source)
1850                {
1851                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1852                    break;
1853                }
1854
1855                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1856                {
1857                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1858                    break;
1859                }
1860
1861                Unit* caster = (Unit*)source;
1862
1863                GameObject *door = NULL;
1864                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1865
1866                CellPair p(Trinity::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1867                Cell cell(p);
1868                cell.data.Part.reserved = ALL_DISTRICT;
1869
1870                Trinity::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1871                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(door,go_check);
1872
1873                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1874                CellLock<GridReadGuard> cell_lock(cell, p);
1875                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1876
1877                if ( !door )
1878                {
1879                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1880                    break;
1881                }
1882                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1883                {
1884                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1885                    break;
1886                }
1887
1888                if( !door->GetGoState() )
1889                    break;                                  //door already  open
1890
1891                door->UseDoorOrButton(time_to_close);
1892
1893                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1894                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1895                break;
1896            }
1897            case SCRIPT_COMMAND_CLOSE_DOOR:
1898            {
1899                if(!step.script->datalong)                  // guid for door not specified
1900                {
1901                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1902                    break;
1903                }
1904
1905                if(!source)
1906                {
1907                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1908                    break;
1909                }
1910
1911                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1912                {
1913                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1914                    break;
1915                }
1916
1917                Unit* caster = (Unit*)source;
1918
1919                GameObject *door = NULL;
1920                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1921
1922                CellPair p(Trinity::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1923                Cell cell(p);
1924                cell.data.Part.reserved = ALL_DISTRICT;
1925
1926                Trinity::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1927                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(door,go_check);
1928
1929                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1930                CellLock<GridReadGuard> cell_lock(cell, p);
1931                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1932
1933                if ( !door )
1934                {
1935                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1936                    break;
1937                }
1938                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1939                {
1940                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1941                    break;
1942                }
1943
1944                if( door->GetGoState() )
1945                    break;                                  //door already closed
1946
1947                door->UseDoorOrButton(time_to_open);
1948
1949                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1950                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1951
1952                break;
1953            }
1954            case SCRIPT_COMMAND_QUEST_EXPLORED:
1955            {
1956                if(!source)
1957                {
1958                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1959                    break;
1960                }
1961
1962                if(!target)
1963                {
1964                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1965                    break;
1966                }
1967
1968                // when script called for item spell casting then target == (unit or GO) and source is player
1969                WorldObject* worldObject;
1970                Player* player;
1971
1972                if(target->GetTypeId()==TYPEID_PLAYER)
1973                {
1974                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1975                    {
1976                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1977                        break;
1978                    }
1979
1980                    worldObject = (WorldObject*)source;
1981                    player = (Player*)target;
1982                }
1983                else
1984                {
1985                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1986                    {
1987                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1988                        break;
1989                    }
1990
1991                    if(source->GetTypeId()!=TYPEID_PLAYER)
1992                    {
1993                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1994                        break;
1995                    }
1996
1997                    worldObject = (WorldObject*)target;
1998                    player = (Player*)source;
1999                }
2000
2001                // quest id and flags checked at script loading
2002                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2003                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2004                    player->AreaExploredOrEventHappens(step.script->datalong);
2005                else
2006                    player->FailQuest(step.script->datalong);
2007
2008                break;
2009            }
2010
2011            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2012            {
2013                if(!source)
2014                {
2015                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2016                    break;
2017                }
2018
2019                if(!source->isType(TYPEMASK_UNIT))
2020                {
2021                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2022                    break;
2023                }
2024
2025                if(!target)
2026                {
2027                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2028                    break;
2029                }
2030
2031                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2032                {
2033                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2034                    break;
2035                }
2036
2037                Unit* caster = (Unit*)source;
2038
2039                GameObject *go = (GameObject*)target;
2040
2041                go->Use(caster);
2042                break;
2043            }
2044
2045            case SCRIPT_COMMAND_REMOVE_AURA:
2046            {
2047                Object* cmdTarget = step.script->datalong2 ? source : target;
2048
2049                if(!cmdTarget)
2050                {
2051                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2052                    break;
2053                }
2054
2055                if(!cmdTarget->isType(TYPEMASK_UNIT))
2056                {
2057                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2058                    break;
2059                }
2060
2061                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2062                break;
2063            }
2064
2065            case SCRIPT_COMMAND_CAST_SPELL:
2066            {
2067                if(!source)
2068                {
2069                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2070                    break;
2071                }
2072
2073                if(!source->isType(TYPEMASK_UNIT))
2074                {
2075                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2076                    break;
2077                }
2078
2079                Object* cmdTarget = step.script->datalong2 ? source : target;
2080
2081                if(!cmdTarget)
2082                {
2083                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2084                    break;
2085                }
2086
2087                if(!cmdTarget->isType(TYPEMASK_UNIT))
2088                {
2089                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2090                    break;
2091                }
2092
2093                Unit* spellTarget = (Unit*)cmdTarget;
2094
2095                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2096                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2097
2098                break;
2099            }
2100
2101            default:
2102                sLog.outError("Unknown script command %u called.",step.script->command);
2103                break;
2104        }
2105
2106        m_scriptSchedule.erase(iter);
2107
2108        iter = m_scriptSchedule.begin();
2109    }
2110    return;
2111}
2112
2113/// Send a packet to all players (except self if mentioned)
2114void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2115{
2116    SessionMap::iterator itr;
2117    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2118    {
2119        if (itr->second &&
2120            itr->second->GetPlayer() &&
2121            itr->second->GetPlayer()->IsInWorld() &&
2122            itr->second != self &&
2123            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2124        {
2125            itr->second->SendPacket(packet);
2126        }
2127    }
2128}
2129
2130/// Send a System Message to all players (except self if mentioned)
2131void World::SendWorldText(int32 string_id, ...)
2132{
2133    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
2134
2135    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2136    {
2137        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2138            continue;
2139
2140        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2141        uint32 cache_idx = loc_idx+1;
2142
2143        std::vector<WorldPacket*>* data_list;
2144
2145        // create if not cached yet
2146        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2147        {
2148            if(data_cache.size() < cache_idx+1)
2149                data_cache.resize(cache_idx+1);
2150
2151            data_list = &data_cache[cache_idx];
2152
2153            char const* text = objmgr.GetTrinityString(string_id,loc_idx);
2154
2155            char buf[1000];
2156
2157            va_list argptr;
2158            va_start( argptr, string_id );
2159            vsnprintf( buf,1000, text, argptr );
2160            va_end( argptr );
2161
2162            char* pos = &buf[0];
2163
2164            while(char* line = ChatHandler::LineFromMessage(pos))
2165            {
2166                WorldPacket* data = new WorldPacket();
2167                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2168                data_list->push_back(data);
2169            }
2170        }
2171        else
2172            data_list = &data_cache[cache_idx];
2173
2174        for(int i = 0; i < data_list->size(); ++i)
2175            itr->second->SendPacket((*data_list)[i]);
2176    }
2177
2178    // free memory
2179    for(int i = 0; i < data_cache.size(); ++i)
2180        for(int j = 0; j < data_cache[i].size(); ++j)
2181            delete data_cache[i][j];
2182}
2183
2184/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2185void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2186{
2187    SessionMap::iterator itr;
2188    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2189    {
2190        if (itr->second &&
2191            itr->second->GetPlayer() &&
2192            itr->second->GetPlayer()->IsInWorld() &&
2193            itr->second->GetPlayer()->GetZoneId() == zone &&
2194            itr->second != self &&
2195            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2196        {
2197            itr->second->SendPacket(packet);
2198        }
2199    }
2200}
2201
2202/// Send a System Message to all players in the zone (except self if mentioned)
2203void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2204{
2205    WorldPacket data;
2206    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2207    SendZoneMessage(zone, &data, self,team);
2208}
2209
2210/// Kick (and save) all players
2211void World::KickAll()
2212{
2213    // session not removed at kick and will removed in next update tick
2214    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2215        itr->second->KickPlayer();
2216}
2217
2218/// Kick (and save) all players with security level less `sec`
2219void World::KickAllLess(AccountTypes sec)
2220{
2221    // session not removed at kick and will removed in next update tick
2222    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2223        if(itr->second->GetSecurity() < sec)
2224            itr->second->KickPlayer();
2225}
2226
2227/// Kick all queued players
2228void World::KickAllQueued()
2229{
2230    // session not removed at kick and will removed in next update tick
2231  //TODO here
2232//    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2233//        if(WorldSession* session = (*itr)->GetSession())
2234//            session->KickPlayer();
2235
2236    m_QueuedPlayer.empty();
2237}
2238
2239/// Kick (and save) the designated player
2240bool World::KickPlayer(std::string playerName)
2241{
2242    SessionMap::iterator itr;
2243
2244    // session not removed at kick and will removed in next update tick
2245    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2246    {
2247        if(!itr->second)
2248            continue;
2249        Player *player = itr->second->GetPlayer();
2250        if(!player)
2251            continue;
2252        if( player->IsInWorld() )
2253        {
2254            if (playerName == player->GetName())
2255            {
2256                itr->second->KickPlayer();
2257                return true;
2258            }
2259        }
2260    }
2261    return false;
2262}
2263
2264/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2265uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2266{
2267    loginDatabase.escape_string(nameOrIP);
2268    loginDatabase.escape_string(reason);
2269    std::string safe_author=author;
2270    loginDatabase.escape_string(safe_author);
2271
2272    if(type != "ip" && !normalizePlayerName(nameOrIP))
2273        return BAN_NOTFOUND;                                // Nobody to ban
2274
2275    uint32 duration_secs = TimeStringToSecs(duration);
2276    QueryResult *resultAccounts = NULL;                     //used for kicking
2277
2278    ///- Update the database with ban information
2279
2280    if(type=="ip")
2281    {
2282        //No SQL injection as strings are escaped
2283        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2284        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());
2285    }
2286    else if(type=="account")
2287    {
2288        //No SQL injection as string is escaped
2289        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2290    }
2291    else if(type=="character")
2292    {
2293        //No SQL injection as string is escaped
2294        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2295    }
2296    else
2297        return BAN_SYNTAX_ERROR;                            //Syntax problem
2298
2299    if(!resultAccounts)
2300        if(type=="ip")
2301            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2302    else
2303        return BAN_NOTFOUND;                                // Nobody to ban
2304
2305    ///- Disconnect all affected players (for IP it can be several)
2306    do
2307    {
2308        Field* fieldsAccount = resultAccounts->Fetch();
2309        uint32 account = fieldsAccount->GetUInt32();
2310
2311        if(type != "ip")
2312            //No SQL injection as strings are escaped
2313            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2314                account,duration_secs,safe_author.c_str(),reason.c_str());
2315
2316        WorldSession* sess = FindSession(account);
2317        if( sess )
2318            if(std::string(sess->GetPlayerName()) != author)
2319                sess->KickPlayer();
2320    }
2321    while( resultAccounts->NextRow() );
2322
2323    delete resultAccounts;
2324    return BAN_SUCCESS;
2325}
2326
2327/// Remove a ban from an account or IP address
2328bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2329{
2330    if(type == "ip")
2331    {
2332        loginDatabase.escape_string(nameOrIP);
2333        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2334    }
2335    else
2336    {
2337        uint32 account=0;
2338        if(type == "account")
2339        {
2340            //NO SQL injection as name is escaped
2341            loginDatabase.escape_string(nameOrIP);
2342            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2343            if(!resultAccounts)
2344                return false;
2345            Field* fieldsAccount = resultAccounts->Fetch();
2346            account = fieldsAccount->GetUInt32();
2347
2348            delete resultAccounts;
2349        }
2350        else if(type == "character")
2351        {
2352            if(!normalizePlayerName(nameOrIP))
2353                return false;
2354
2355            //NO SQL injection as name is escaped
2356            loginDatabase.escape_string(nameOrIP);
2357            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2358            if(!resultAccounts)
2359                return false;
2360            Field* fieldsAccount = resultAccounts->Fetch();
2361            account = fieldsAccount->GetUInt32();
2362
2363            delete resultAccounts;
2364        }
2365        if(!account)
2366            return false;
2367        //NO SQL injection as account is uint32
2368        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2369    }
2370    return true;
2371}
2372
2373/// Update the game time
2374void World::_UpdateGameTime()
2375{
2376    ///- update the time
2377    time_t thisTime = time(NULL);
2378    uint32 elapsed = uint32(thisTime - m_gameTime);
2379    m_gameTime = thisTime;
2380
2381    ///- if there is a shutdown timer
2382    if(m_ShutdownTimer > 0 && elapsed > 0)
2383    {
2384        ///- ... and it is overdue, stop the world (set m_stopEvent)
2385        if( m_ShutdownTimer <= elapsed )
2386        {
2387            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2388                m_stopEvent = true;
2389            else
2390                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2391        }
2392        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2393        else
2394        {
2395            m_ShutdownTimer -= elapsed;
2396
2397            ShutdownMsg();
2398        }
2399    }
2400}
2401
2402/// Shutdown the server
2403void World::ShutdownServ(uint32 time, uint32 options)
2404{
2405    m_ShutdownMask = options;
2406
2407    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2408    if(time==0)
2409    {
2410        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2411            m_stopEvent = true;
2412        else
2413            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2414    }
2415    ///- Else set the shutdown timer and warn users
2416    else
2417    {
2418        m_ShutdownTimer = time;
2419        ShutdownMsg(true);
2420    }
2421}
2422
2423/// Display a shutdown message to the user(s)
2424void World::ShutdownMsg(bool show, Player* player)
2425{
2426    // not show messages for idle shutdown mode
2427    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2428        return;
2429
2430    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2431    if ( show ||
2432        (m_ShutdownTimer < 10) ||
2433                                                            // < 30 sec; every 5 sec
2434        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2435                                                            // < 5 min ; every 1 min
2436        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2437                                                            // < 30 min ; every 5 min
2438        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2439                                                            // < 12 h ; every 1 h
2440        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2441                                                            // > 12 h ; every 12 h
2442        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2443    {
2444        std::string str = secsToTimeString(m_ShutdownTimer);
2445
2446        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2447
2448        SendServerMessage(msgid,str.c_str(),player);
2449        outstring_log("Server will %s in %s", (m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shutdown"), str.c_str());
2450    }
2451}
2452
2453/// Cancel a planned server shutdown
2454void World::ShutdownCancel()
2455{
2456    if(!m_ShutdownTimer)
2457        return;
2458
2459    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2460
2461    m_ShutdownMask = 0;
2462    m_ShutdownTimer = 0;
2463    SendServerMessage(msgid);
2464
2465    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2466}
2467
2468/// Send a server message to the user(s)
2469void World::SendServerMessage(uint32 type, const char *text, Player* player)
2470{
2471    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2472    data << uint32(type);
2473    if(type <= SERVER_MSG_STRING)
2474        data << text;
2475
2476    if(player)
2477        player->GetSession()->SendPacket(&data);
2478    else
2479        SendGlobalMessage( &data );
2480}
2481
2482void World::UpdateSessions( time_t diff )
2483{
2484    while(!addSessQueue.empty())
2485    {
2486      WorldSession* sess = addSessQueue.next ();
2487      AddSession_ (sess);
2488    }
2489       
2490    ///- Delete kicked sessions at add new session
2491    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2492        delete *itr;
2493    m_kicked_sessions.clear();
2494
2495    ///- Then send an update signal to remaining ones
2496    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2497    {
2498        next = itr;
2499        ++next;
2500
2501        if(!itr->second)
2502            continue;
2503
2504        ///- and remove not active sessions from the list
2505        if(!itr->second->Update(diff))                      // As interval = 0
2506        {
2507            delete itr->second;
2508            m_sessions.erase(itr);
2509        }
2510    }
2511}
2512
2513// This handles the issued and queued CLI commands
2514void World::ProcessCliCommands()
2515{
2516    if (cliCmdQueue.empty()) return;
2517
2518    CliCommandHolder *command;
2519    pPrintf p_zprintf;
2520    while (!cliCmdQueue.empty())
2521    {
2522        sLog.outDebug("CLI command under processing...");
2523        command = cliCmdQueue.next();
2524        command->Execute();
2525        p_zprintf=command->GetOutputMethod();
2526        delete command;
2527    }
2528    // print the console message here so it looks right
2529    p_zprintf("TC> ");
2530}
2531
2532void World::InitResultQueue()
2533{
2534    m_resultQueue = new SqlResultQueue;
2535    CharacterDatabase.SetResultQueue(m_resultQueue);
2536}
2537
2538void World::UpdateResultQueue()
2539{
2540    m_resultQueue->Update();
2541}
2542
2543void World::UpdateRealmCharCount(uint32 accountId)
2544{
2545    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2546        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2547}
2548
2549void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2550{
2551    if (resultCharCount)
2552    {
2553        Field *fields = resultCharCount->Fetch();
2554        uint32 charCount = fields[0].GetUInt32();
2555        delete resultCharCount;
2556        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2557        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2558    }
2559}
2560
2561void World::InitDailyQuestResetTime()
2562{
2563    time_t mostRecentQuestTime;
2564
2565    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2566    if(result)
2567    {
2568        Field *fields = result->Fetch();
2569
2570        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2571        delete result;
2572    }
2573    else
2574        mostRecentQuestTime = 0;
2575
2576    // client built-in time for reset is 6:00 AM
2577    // FIX ME: client not show day start time
2578    time_t curTime = time(NULL);
2579    tm localTm = *localtime(&curTime);
2580    localTm.tm_hour = 6;
2581    localTm.tm_min  = 0;
2582    localTm.tm_sec  = 0;
2583
2584    // current day reset time
2585    time_t curDayResetTime = mktime(&localTm);
2586
2587    // last reset time before current moment
2588    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2589
2590    // need reset (if we have quest time before last reset time (not processed by some reason)
2591    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2592        m_NextDailyQuestReset = mostRecentQuestTime;
2593    else
2594    {
2595        // plan next reset time
2596        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2597    }
2598}
2599
2600void World::ResetDailyQuests()
2601{
2602    sLog.outDetail("Daily quests reset for all characters.");
2603    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2604    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2605        if(itr->second->GetPlayer())
2606            itr->second->GetPlayer()->ResetDailyQuestStatus();
2607}
2608
2609void World::SetPlayerLimit( int32 limit, bool needUpdate )
2610{
2611    if(limit < -SEC_ADMINISTRATOR)
2612        limit = -SEC_ADMINISTRATOR;
2613
2614    // lock update need
2615    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2616
2617    m_playerLimit = limit;
2618
2619    if(db_update_need)
2620        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2621}
2622
2623void World::UpdateMaxSessionCounters()
2624{
2625    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2626    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2627}
Note: See TracBrowser for help on using the browser.