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

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

[svn] * Improve some arena team related DB access
* Cache GM tickets on server startup.
* Remove unused src/game/HateMatrix.h and references.
* Better check client inventory pos data received in some client packets to
skip invalid cases

Original author: KingPin?
Date: 2008-11-10 09:04:23-06:00

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