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

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

[svn] Implement a new table (spell_disabled) to allow disabling some spells for players and / or creatures. To disable a spell for a players and pets, set 20 in the disable_mask, to disable for creatures, set 21. The comment field is optional. Original patch provided by Craker.

Original author: w12x
Date: 2008-10-21 03:58:38-05:00

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