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

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

[svn] *** Source: MaNGOS ***
* Implement localization of creature/gameobject name that say/yell. Author: evilstar (rewrited by: Vladimir)
* Fix auth login queue. Author: Derex
* Allowed switching INVTYPE_HOLDABLE items during combat, used correct spells for triggering global cooldown at weapon switch. Author: mobel/simak
* Fixed some format arg type/value pairs. Other warnings. Author: Vladimir
* [238_world.sql] Allow have team dependent graveyards at entrance map for instances. Author: Vladimir

NOTE:
Entrance map graveyards selected by same way as local (by distance from entrance) Until DB support will work in old way base at current DB data.

Original author: visagalis
Date: 2008-11-14 17:03:03-06:00

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