[6858] Prevent cheating with ignore waiting in login queue.
[getmangos.git] / src / game / World.cpp
blobba5f0aee400b7dbbd41199a9719e380038bfee83
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 //#include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
28 #include "Log.h"
29 #include "Opcodes.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
32 #include "Weather.h"
33 #include "Player.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "ObjectMgr.h"
39 #include "SpellMgr.h"
40 #include "Chat.h"
41 #include "Database/DBCStores.h"
42 #include "LootMgr.h"
43 #include "ItemEnchantmentMgr.h"
44 #include "MapManager.h"
45 #include "ScriptCalls.h"
46 #include "CreatureAIRegistry.h"
47 #include "Policies/SingletonImp.h"
48 #include "BattleGroundMgr.h"
49 #include "TemporarySummon.h"
50 #include "WaypointMovementGenerator.h"
51 #include "VMapFactory.h"
52 #include "GlobalEvents.h"
53 #include "GameEvent.h"
54 #include "Database/DatabaseImpl.h"
55 #include "GridNotifiersImpl.h"
56 #include "CellImpl.h"
57 #include "InstanceSaveMgr.h"
58 #include "WaypointManager.h"
59 #include "GMTicketMgr.h"
60 #include "Util.h"
62 INSTANTIATE_SINGLETON_1( World );
64 volatile bool World::m_stopEvent = false;
65 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
66 volatile uint32 World::m_worldLoopCounter = 0;
68 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
71 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_VisibleUnitGreyDistance = 0;
73 float World::m_VisibleObjectGreyDistance = 0;
75 // ServerMessages.dbc
76 enum ServerMessageType
78 SERVER_MSG_SHUTDOWN_TIME = 1,
79 SERVER_MSG_RESTART_TIME = 2,
80 SERVER_MSG_STRING = 3,
81 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
82 SERVER_MSG_RESTART_CANCELLED = 5
85 struct ScriptAction
87 uint64 sourceGUID;
88 uint64 targetGUID;
89 uint64 ownerGUID; // owner of source if source is item
90 ScriptInfo const* script; // pointer to static script data
93 /// World constructor
94 World::World()
96 m_playerLimit = 0;
97 m_allowMovement = true;
98 m_ShutdownMask = 0;
99 m_ShutdownTimer = 0;
100 m_gameTime=time(NULL);
101 m_startTime=m_gameTime;
102 m_maxActiveSessionCount = 0;
103 m_maxQueuedSessionCount = 0;
104 m_resultQueue = NULL;
105 m_NextDailyQuestReset = 0;
107 m_defaultDbcLocale = LOCALE_enUS;
108 m_availableDbcLocaleMask = 0;
111 /// World destructor
112 World::~World()
114 ///- Empty the kicked session set
115 while (!m_sessions.empty())
117 // not remove from queue, prevent loading new sessions
118 delete m_sessions.begin()->second;
119 m_sessions.erase(m_sessions.begin());
122 ///- Empty the WeatherMap
123 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
124 delete itr->second;
126 m_weathers.clear();
128 VMAP::VMapFactory::clear();
130 if(m_resultQueue) delete m_resultQueue;
132 //TODO free addSessQueue
135 /// Find a player in a specified zone
136 Player* World::FindPlayerInZone(uint32 zone)
138 ///- circle through active sessions and return the first player found in the zone
139 SessionMap::iterator itr;
140 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
142 if(!itr->second)
143 continue;
144 Player *player = itr->second->GetPlayer();
145 if(!player)
146 continue;
147 if( player->IsInWorld() && player->GetZoneId() == zone )
149 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
150 return player;
153 return NULL;
156 /// Find a session by its id
157 WorldSession* World::FindSession(uint32 id) const
159 SessionMap::const_iterator itr = m_sessions.find(id);
161 if(itr != m_sessions.end())
162 return itr->second; // also can return NULL for kicked session
163 else
164 return NULL;
167 /// Remove a given session
168 bool World::RemoveSession(uint32 id)
170 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
171 SessionMap::iterator itr = m_sessions.find(id);
173 if(itr != m_sessions.end() && itr->second)
175 if (itr->second->PlayerLoading())
176 return false;
177 itr->second->KickPlayer();
180 return true;
183 void World::AddSession(WorldSession* s)
185 addSessQueue.add(s);
188 void
189 World::AddSession_ (WorldSession* s)
191 ASSERT (s);
193 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
195 ///- kick already loaded player with same account (if any) and remove session
196 ///- if player is in loading and want to load again, return
197 if (!RemoveSession (s->GetAccountId ()))
199 s->KickPlayer ();
200 delete s; // session not added yet in session list, so not listed in queue
201 return;
204 // decrease session counts only at not reconnection case
205 bool decrease_session = true;
207 // if session already exist, prepare to it deleting at next world update
208 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
210 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
212 if(old != m_sessions.end())
214 // prevent decrease sessions count if session queued
215 if(RemoveQueuedPlayer(old->second))
216 decrease_session = false;
217 // not remove replaced session form queue if listed
218 delete old->second;
222 m_sessions[s->GetAccountId ()] = s;
224 uint32 Sessions = GetActiveAndQueuedSessionCount ();
225 uint32 pLimit = GetPlayerAmountLimit ();
226 uint32 QueueSize = GetQueueSize (); //number of players in the queue
228 //so we don't count the user trying to
229 //login as a session and queue the socket that we are using
230 if(decrease_session)
231 --Sessions;
233 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
235 AddQueuedPlayer (s);
236 UpdateMaxSessionCounters ();
237 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
238 return;
241 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
242 packet << uint8 (AUTH_OK);
243 packet << uint32 (0); // unknown random value...
244 packet << uint8 (0);
245 packet << uint32 (0);
246 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
247 s->SendPacket (&packet);
249 UpdateMaxSessionCounters ();
251 // Updates the population
252 if (pLimit > 0)
254 float popu = GetActiveSessionCount (); //updated number of users on the server
255 popu /= pLimit;
256 popu *= 2;
257 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
258 sLog.outDetail ("Server Population (%f).", popu);
262 int32 World::GetQueuePos(WorldSession* sess)
264 uint32 position = 1;
266 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
267 if((*iter) == sess)
268 return position;
270 return 0;
273 void World::AddQueuedPlayer(WorldSession* sess)
275 sess->SetInQueue(true);
276 m_QueuedPlayer.push_back (sess);
278 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
279 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
280 packet << uint8 (AUTH_WAIT_QUEUE);
281 packet << uint32 (0); // unknown random value...
282 packet << uint8 (0);
283 packet << uint32 (0);
284 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
285 packet << uint32(GetQueuePos (sess));
286 sess->SendPacket (&packet);
288 //sess->SendAuthWaitQue (GetQueuePos (sess));
291 bool World::RemoveQueuedPlayer(WorldSession* sess)
293 // sessions count including queued to remove (if removed_session set)
294 uint32 sessions = GetActiveSessionCount();
296 uint32 position = 1;
297 Queue::iterator iter = m_QueuedPlayer.begin();
299 // search to remove and count skipped positions
300 bool found = false;
302 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
304 if(*iter==sess)
306 sess->SetInQueue(false);
307 iter = m_QueuedPlayer.erase(iter);
308 found = true; // removing queued session
309 break;
313 // iter point to next socked after removed or end()
314 // position store position of removed socket and then new position next socket after removed
316 // if session not queued then we need decrease sessions count
317 if(!found && sessions)
318 --sessions;
320 // accept first in queue
321 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
323 WorldSession* pop_sess = m_QueuedPlayer.front();
324 pop_sess->SetInQueue(false);
325 pop_sess->SendAuthWaitQue(0);
326 m_QueuedPlayer.pop_front();
328 // update iter to point first queued socket or end() if queue is empty now
329 iter = m_QueuedPlayer.begin();
330 position = 1;
333 // update position from iter to end()
334 // iter point to first not updated socket, position store new position
335 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
336 (*iter)->SendAuthWaitQue(position);
338 return found;
341 /// Find a Weather object by the given zoneid
342 Weather* World::FindWeather(uint32 id) const
344 WeatherMap::const_iterator itr = m_weathers.find(id);
346 if(itr != m_weathers.end())
347 return itr->second;
348 else
349 return 0;
352 /// Remove a Weather object for the given zoneid
353 void World::RemoveWeather(uint32 id)
355 // not called at the moment. Kept for completeness
356 WeatherMap::iterator itr = m_weathers.find(id);
358 if(itr != m_weathers.end())
360 delete itr->second;
361 m_weathers.erase(itr);
365 /// Add a Weather object to the list
366 Weather* World::AddWeather(uint32 zone_id)
368 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
370 // zone not have weather, ignore
371 if(!weatherChances)
372 return NULL;
374 Weather* w = new Weather(zone_id,weatherChances);
375 m_weathers[w->GetZone()] = w;
376 w->ReGenerate();
377 w->UpdateWeather();
378 return w;
381 /// Initialize config values
382 void World::LoadConfigSettings(bool reload)
384 if(reload)
386 if(!sConfig.Reload())
388 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
389 return;
393 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
394 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
395 if(!confVersion)
397 sLog.outError("*****************************************************************************");
398 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
399 sLog.outError(" Your configuration file may be out of date!");
400 sLog.outError("*****************************************************************************");
401 clock_t pause = 3000 + clock();
402 while (pause > clock());
404 else
406 if (confVersion < _MANGOSDCONFVERSION)
408 sLog.outError("*****************************************************************************");
409 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
410 sLog.outError(" Please check for updates, as your current default values may cause");
411 sLog.outError(" unexpected behavior.");
412 sLog.outError("*****************************************************************************");
413 clock_t pause = 3000 + clock();
414 while (pause > clock());
418 ///- Read the player limit and the Message of the day from the config file
419 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
420 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
422 ///- Read all rates from the config file
423 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
424 if(rate_values[RATE_HEALTH] < 0)
426 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
427 rate_values[RATE_HEALTH] = 1;
429 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
430 if(rate_values[RATE_POWER_MANA] < 0)
432 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
433 rate_values[RATE_POWER_MANA] = 1;
435 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
436 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
437 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
439 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
440 rate_values[RATE_POWER_RAGE_LOSS] = 1;
442 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
443 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
444 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
445 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
446 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
447 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
448 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
449 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
450 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
451 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
452 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
453 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
454 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
455 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
456 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
457 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
458 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
459 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
460 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
461 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
462 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
463 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
464 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
465 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
466 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
467 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
468 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
469 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
474 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
475 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
476 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
477 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
478 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
479 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
480 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
481 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
482 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
483 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
484 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
485 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
486 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
487 if(rate_values[RATE_TALENT] < 0.0f)
489 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
490 rate_values[RATE_TALENT] = 1.0f;
492 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
494 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
495 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
497 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
498 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
500 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
502 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
503 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
504 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
507 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
508 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
510 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
511 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
513 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
514 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
516 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
517 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
519 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
520 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
522 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
523 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
525 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
526 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
528 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
529 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
532 ///- Read other configuration items from the config file
534 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
535 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
537 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
538 m_configs[CONFIG_COMPRESSION] = 1;
540 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
541 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
542 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
544 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
545 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
547 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
548 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
550 if(reload)
551 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
553 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
554 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
556 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
557 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
559 if(reload)
560 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
562 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
564 if(reload)
566 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
567 if(val!=m_configs[CONFIG_PORT_WORLD])
568 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
570 else
571 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
573 if(reload)
575 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
576 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
577 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
579 else
580 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
582 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
583 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
584 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
585 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
587 if(reload)
589 uint32 val = sConfig.GetIntDefault("GameType", 0);
590 if(val!=m_configs[CONFIG_GAME_TYPE])
591 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
593 else
594 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
596 if(reload)
598 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
599 if(val!=m_configs[CONFIG_REALM_ZONE])
600 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
602 else
603 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
605 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
606 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
607 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
608 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
609 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
610 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
611 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
612 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
613 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
614 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
615 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
616 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
618 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
620 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
621 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
623 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
624 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
627 // must be after CONFIG_CHARACTERS_PER_REALM
628 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
629 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
631 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
632 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
635 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
636 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
638 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
639 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
642 if(reload)
644 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
645 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
646 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
648 else
649 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
650 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
652 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
653 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
656 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
657 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
659 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]);
660 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
662 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
664 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]);
665 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
667 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
668 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
670 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
671 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
673 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
674 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
675 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
677 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
678 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
679 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
681 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
682 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
683 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
685 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
686 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
689 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
690 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
691 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
692 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
694 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
695 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
696 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
698 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
700 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
702 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
703 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
705 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
706 m_configs[CONFIG_UPTIME_UPDATE] = 10;
708 if(reload)
710 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
711 m_timers[WUPDATE_UPTIME].Reset();
714 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
715 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
716 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
717 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
719 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
720 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
722 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
724 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
725 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
727 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
728 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
731 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
732 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
734 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
735 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
738 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
739 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
741 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
742 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
745 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
746 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
748 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
749 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
752 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
753 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
755 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
756 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
759 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
760 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
762 if(reload)
764 uint32 val = sConfig.GetIntDefault("Expansion",1);
765 if(val!=m_configs[CONFIG_EXPANSION])
766 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
768 else
769 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
771 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
772 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
773 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
775 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
777 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
778 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
780 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
782 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
783 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
784 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
785 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
786 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
787 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
788 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
790 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
792 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
793 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
795 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
796 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
798 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
799 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
800 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
801 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
802 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
804 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
805 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
806 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
808 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
810 // always use declined names in the russian client
811 m_configs[CONFIG_DECLINED_NAMES_USED] =
812 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
814 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
815 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
816 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
818 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
819 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
821 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
822 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
824 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
825 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
827 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
828 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
831 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
832 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
834 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
835 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
837 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
839 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
840 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
842 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
843 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
845 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
846 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
848 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
850 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
851 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
853 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
854 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
856 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
857 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
859 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
861 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
862 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
864 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
865 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
867 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
868 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
871 ///- Read the "Data" directory from the config file
872 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
873 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
874 dataPath.append("/");
876 if(reload)
878 if(dataPath!=m_dataPath)
879 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
881 else
883 m_dataPath = dataPath;
884 sLog.outString("Using DataDir %s",m_dataPath.c_str());
887 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
888 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
889 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
890 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
891 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
892 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
893 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
894 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
895 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
896 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
897 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
900 /// Initialize the World
901 void World::SetInitialWorldSettings()
903 ///- Initialize the random number generator
904 srand((unsigned int)time(NULL));
906 ///- Initialize config settings
907 LoadConfigSettings();
909 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
910 objmgr.SetHighestGuids();
912 ///- Check the existence of the map files for all races' startup areas.
913 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
914 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
915 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
916 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
917 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
918 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
919 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
920 ||m_configs[CONFIG_EXPANSION] && (
921 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
923 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 mangosd.conf file.",m_dataPath.c_str(),m_dataPath.c_str());
924 exit(1);
927 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
928 sLog.outString( "" );
929 sLog.outString( "Loading MaNGOS strings..." );
930 if (!objmgr.LoadMangosStrings())
931 exit(1); // Error message displayed in function already
933 ///- Update the realm entry in the database with the realm type from the config file
934 //No SQL injection as values are treated as integers
936 // not send custom type REALM_FFA_PVP to realm list
937 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
938 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
939 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
941 ///- Remove the bones after a restart
942 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
944 ///- Load the DBC files
945 sLog.outString("Initialize data stores...");
946 LoadDBCStores(m_dataPath);
947 DetectDBCLang();
949 sLog.outString( "Loading Script Names...");
950 objmgr.LoadScriptNames();
952 sLog.outString( "Loading InstanceTemplate" );
953 objmgr.LoadInstanceTemplate();
955 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
956 spellmgr.LoadSkillLineAbilityMap();
958 ///- Clean up and pack instances
959 sLog.outString( "Cleaning up instances..." );
960 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
962 sLog.outString( "Packing instances..." );
963 sInstanceSaveManager.PackInstances();
965 sLog.outString( "Loading Localization strings..." );
966 objmgr.LoadCreatureLocales();
967 objmgr.LoadGameObjectLocales();
968 objmgr.LoadItemLocales();
969 objmgr.LoadQuestLocales();
970 objmgr.LoadNpcTextLocales();
971 objmgr.LoadPageTextLocales();
972 objmgr.LoadNpcOptionLocales();
973 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
975 sLog.outString( "Loading Page Texts..." );
976 objmgr.LoadPageTexts();
978 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
979 objmgr.LoadGameobjectInfo();
981 sLog.outString( "Loading Spell Chain Data..." );
982 spellmgr.LoadSpellChains();
984 sLog.outString( "Loading Spell Elixir types..." );
985 spellmgr.LoadSpellElixirs();
987 sLog.outString( "Loading Spell Learn Skills..." );
988 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
990 sLog.outString( "Loading Spell Learn Spells..." );
991 spellmgr.LoadSpellLearnSpells();
993 sLog.outString( "Loading Spell Proc Event conditions..." );
994 spellmgr.LoadSpellProcEvents();
996 sLog.outString( "Loading Aggro Spells Definitions...");
997 spellmgr.LoadSpellThreats();
999 sLog.outString( "Loading NPC Texts..." );
1000 objmgr.LoadGossipText();
1002 sLog.outString( "Loading Item Random Enchantments Table..." );
1003 LoadRandomEnchantmentsTable();
1005 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1006 objmgr.LoadItemPrototypes();
1008 sLog.outString( "Loading Item Texts..." );
1009 objmgr.LoadItemTexts();
1011 sLog.outString( "Loading Creature Model Based Info Data..." );
1012 objmgr.LoadCreatureModelInfo();
1014 sLog.outString( "Loading Equipment templates...");
1015 objmgr.LoadEquipmentTemplates();
1017 sLog.outString( "Loading Creature templates..." );
1018 objmgr.LoadCreatureTemplates();
1020 sLog.outString( "Loading SpellsScriptTarget...");
1021 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1023 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1024 objmgr.LoadReputationOnKill();
1026 sLog.outString( "Loading Pet Create Spells..." );
1027 objmgr.LoadPetCreateSpells();
1029 sLog.outString( "Loading Creature Data..." );
1030 objmgr.LoadCreatures();
1032 sLog.outString( "Loading Creature Addon Data..." );
1033 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1035 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1036 objmgr.LoadCreatureRespawnTimes();
1038 sLog.outString( "Loading Gameobject Data..." );
1039 objmgr.LoadGameobjects();
1041 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1042 objmgr.LoadGameobjectRespawnTimes();
1044 sLog.outString( "Loading Game Event Data...");
1045 gameeventmgr.LoadFromDB();
1047 sLog.outString( "Loading Weather Data..." );
1048 objmgr.LoadWeatherZoneChances();
1050 sLog.outString( "Loading Quests..." );
1051 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1053 sLog.outString( "Loading Quests Relations..." );
1054 objmgr.LoadQuestRelations(); // must be after quest load
1056 sLog.outString( "Loading AreaTrigger definitions..." );
1057 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1059 sLog.outString( "Loading Quest Area Triggers..." );
1060 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1062 sLog.outString( "Loading Tavern Area Triggers..." );
1063 objmgr.LoadTavernAreaTriggers();
1065 sLog.outString( "Loading AreaTrigger script names..." );
1066 objmgr.LoadAreaTriggerScripts();
1068 sLog.outString( "Loading Graveyard-zone links...");
1069 objmgr.LoadGraveyardZones();
1071 sLog.outString( "Loading Spell target coordinates..." );
1072 spellmgr.LoadSpellTargetPositions();
1074 sLog.outString( "Loading SpellAffect definitions..." );
1075 spellmgr.LoadSpellAffects();
1077 sLog.outString( "Loading spell pet auras..." );
1078 spellmgr.LoadSpellPetAuras();
1080 sLog.outString( "Loading player Create Info & Level Stats..." );
1081 objmgr.LoadPlayerInfo();
1083 sLog.outString( "Loading Exploration BaseXP Data..." );
1084 objmgr.LoadExplorationBaseXP();
1086 sLog.outString( "Loading Pet Name Parts..." );
1087 objmgr.LoadPetNames();
1089 sLog.outString( "Loading the max pet number..." );
1090 objmgr.LoadPetNumber();
1092 sLog.outString( "Loading pet level stats..." );
1093 objmgr.LoadPetLevelInfo();
1095 sLog.outString( "Loading Player Corpses..." );
1096 objmgr.LoadCorpses();
1098 sLog.outString( "Loading Loot Tables..." );
1099 LoadLootTables();
1101 sLog.outString( "Loading Skill Discovery Table..." );
1102 LoadSkillDiscoveryTable();
1104 sLog.outString( "Loading Skill Extra Item Table..." );
1105 LoadSkillExtraItemTable();
1107 sLog.outString( "Loading Skill Fishing base level requirements..." );
1108 objmgr.LoadFishingBaseSkillLevel();
1110 ///- Load dynamic data tables from the database
1111 sLog.outString( "Loading Auctions..." );
1112 objmgr.LoadAuctionItems();
1113 objmgr.LoadAuctions();
1115 sLog.outString( "Loading Guilds..." );
1116 objmgr.LoadGuilds();
1118 sLog.outString( "Loading ArenaTeams..." );
1119 objmgr.LoadArenaTeams();
1121 sLog.outString( "Loading Groups..." );
1122 objmgr.LoadGroups();
1124 sLog.outString( "Loading ReservedNames..." );
1125 objmgr.LoadReservedPlayersNames();
1127 sLog.outString( "Loading GameObject for quests..." );
1128 objmgr.LoadGameObjectForQuests();
1130 sLog.outString( "Loading BattleMasters..." );
1131 objmgr.LoadBattleMastersEntry();
1133 sLog.outString( "Loading GameTeleports..." );
1134 objmgr.LoadGameTele();
1136 sLog.outString( "Loading Npc Text Id..." );
1137 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1139 sLog.outString( "Loading Npc Options..." );
1140 objmgr.LoadNpcOptions();
1142 sLog.outString( "Loading vendors..." );
1143 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1145 sLog.outString( "Loading trainers..." );
1146 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1148 sLog.outString( "Loading Waypoints..." );
1149 WaypointMgr.Load();
1151 sLog.outString( "Loading GM tickets...");
1152 ticketmgr.LoadGMTickets();
1154 ///- Handle outdated emails (delete/return)
1155 sLog.outString( "Returning old mails..." );
1156 objmgr.ReturnOrDeleteOldMails(false);
1158 ///- Load and initialize scripts
1159 sLog.outString( "Loading Scripts..." );
1160 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1161 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1162 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1163 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1164 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1166 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1167 objmgr.LoadDbScriptStrings();
1169 sLog.outString( "Initializing Scripts..." );
1170 if(!LoadScriptingModule())
1171 exit(1);
1173 ///- Initialize game time and timers
1174 sLog.outString( "DEBUG:: Initialize game time and timers" );
1175 m_gameTime = time(NULL);
1176 m_startTime=m_gameTime;
1178 tm local;
1179 time_t curr;
1180 time(&curr);
1181 local=*(localtime(&curr)); // dereference and assign
1182 char isoDate[128];
1183 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1184 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1186 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1187 isoDate, uint64(m_startTime));
1189 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1190 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1191 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1192 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1193 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1194 //Update "uptime" table based on configuration entry in minutes.
1195 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1197 //to set mailtimer to return mails every day between 4 and 5 am
1198 //mailtimer is increased when updating auctions
1199 //one second is 1000 -(tested on win system)
1200 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1201 //1440
1202 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1203 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1205 ///- Initilize static helper structures
1206 AIRegistry::Initialize();
1207 WaypointMovementGenerator<Creature>::Initialize();
1208 Player::InitVisibleBits();
1210 ///- Initialize MapManager
1211 sLog.outString( "Starting Map System" );
1212 MapManager::Instance().Initialize();
1214 ///- Initialize Battlegrounds
1215 sLog.outString( "Starting BattleGround System" );
1216 sBattleGroundMgr.CreateInitialBattleGrounds();
1218 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1219 sLog.outString( "Loading Transports..." );
1220 MapManager::Instance().LoadTransports();
1222 sLog.outString("Deleting expired bans..." );
1223 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1225 sLog.outString("Calculate next daily quest reset time..." );
1226 InitDailyQuestResetTime();
1228 sLog.outString("Starting Game Event system..." );
1229 uint32 nextGameEvent = gameeventmgr.Initialize();
1230 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1232 sLog.outString( "WORLD: World initialized" );
1235 void World::DetectDBCLang()
1237 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1239 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1241 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1242 m_lang_confid = LOCALE_enUS;
1245 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1247 std::string availableLocalsStr;
1249 int default_locale = MAX_LOCALE;
1250 for (int i = MAX_LOCALE-1; i >= 0; --i)
1252 if ( strlen(race->name[i]) > 0) // check by race names
1254 default_locale = i;
1255 m_availableDbcLocaleMask |= (1 << i);
1256 availableLocalsStr += localeNames[i];
1257 availableLocalsStr += " ";
1261 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1262 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1264 default_locale = m_lang_confid;
1267 if(default_locale >= MAX_LOCALE)
1269 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1270 exit(1);
1273 m_defaultDbcLocale = LocaleConstant(default_locale);
1275 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1278 /// Update the World !
1279 void World::Update(time_t diff)
1281 ///- Update the different timers
1282 for(int i = 0; i < WUPDATE_COUNT; i++)
1283 if(m_timers[i].GetCurrent()>=0)
1284 m_timers[i].Update(diff);
1285 else m_timers[i].SetCurrent(0);
1287 ///- Update the game time and check for shutdown time
1288 _UpdateGameTime();
1290 /// Handle daily quests reset time
1291 if(m_gameTime > m_NextDailyQuestReset)
1293 ResetDailyQuests();
1294 m_NextDailyQuestReset += DAY;
1297 /// <ul><li> Handle auctions when the timer has passed
1298 if (m_timers[WUPDATE_AUCTIONS].Passed())
1300 m_timers[WUPDATE_AUCTIONS].Reset();
1302 ///- Update mails (return old mails with item, or delete them)
1303 //(tested... works on win)
1304 if (++mail_timer > mail_timer_expires)
1306 mail_timer = 0;
1307 objmgr.ReturnOrDeleteOldMails(true);
1310 AuctionHouseObject* AuctionMap;
1311 for (int i = 0; i < 3; i++)
1313 switch (i)
1315 case 0:
1316 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1317 break;
1318 case 1:
1319 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1320 break;
1321 case 2:
1322 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1323 break;
1326 ///- Handle expired auctions
1327 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1328 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1330 next = itr;
1331 ++next;
1332 if (m_gameTime > (itr->second->time))
1334 ///- Either cancel the auction if there was no bidder
1335 if (itr->second->bidder == 0)
1337 objmgr.SendAuctionExpiredMail( itr->second );
1339 ///- Or perform the transaction
1340 else
1342 //we should send an "item sold" message if the seller is online
1343 //we send the item to the winner
1344 //we send the money to the seller
1345 objmgr.SendAuctionSuccessfulMail( itr->second );
1346 objmgr.SendAuctionWonMail( itr->second );
1349 ///- In any case clear the auction
1350 //No SQL injection (Id is integer)
1351 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1352 objmgr.RemoveAItem(itr->second->item_guidlow);
1353 delete itr->second;
1354 AuctionMap->RemoveAuction(itr->first);
1360 /// <li> Handle session updates when the timer has passed
1361 if (m_timers[WUPDATE_SESSIONS].Passed())
1363 m_timers[WUPDATE_SESSIONS].Reset();
1365 UpdateSessions(diff);
1368 /// <li> Handle weather updates when the timer has passed
1369 if (m_timers[WUPDATE_WEATHERS].Passed())
1371 m_timers[WUPDATE_WEATHERS].Reset();
1373 ///- Send an update signal to Weather objects
1374 WeatherMap::iterator itr, next;
1375 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1377 next = itr;
1378 ++next;
1380 ///- and remove Weather objects for zones with no player
1381 //As interval > WorldTick
1382 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1384 delete itr->second;
1385 m_weathers.erase(itr);
1389 /// <li> Update uptime table
1390 if (m_timers[WUPDATE_UPTIME].Passed())
1392 uint32 tmpDiff = (m_gameTime - m_startTime);
1393 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1395 m_timers[WUPDATE_UPTIME].Reset();
1396 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1399 /// <li> Handle all other objects
1400 if (m_timers[WUPDATE_OBJECTS].Passed())
1402 m_timers[WUPDATE_OBJECTS].Reset();
1403 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1404 MapManager::Instance().Update(diff); // As interval = 0
1406 ///- Process necessary scripts
1407 if (!m_scriptSchedule.empty())
1408 ScriptsProcess();
1410 sBattleGroundMgr.Update(diff);
1413 // execute callbacks from sql queries that were queued recently
1414 UpdateResultQueue();
1416 ///- Erase corpses once every 20 minutes
1417 if (m_timers[WUPDATE_CORPSES].Passed())
1419 m_timers[WUPDATE_CORPSES].Reset();
1421 CorpsesErase();
1424 ///- Process Game events when necessary
1425 if (m_timers[WUPDATE_EVENTS].Passed())
1427 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1428 uint32 nextGameEvent = gameeventmgr.Update();
1429 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1430 m_timers[WUPDATE_EVENTS].Reset();
1433 /// </ul>
1434 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1435 MapManager::Instance().DoDelayedMovesAndRemoves();
1437 // update the instance reset times
1438 sInstanceSaveManager.Update();
1440 // And last, but not least handle the issued cli commands
1441 ProcessCliCommands();
1444 /// Put scripts in the execution queue
1445 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1447 ///- Find the script map
1448 ScriptMapMap::const_iterator s = scripts.find(id);
1449 if (s == scripts.end())
1450 return;
1452 // prepare static data
1453 uint64 sourceGUID = source->GetGUID();
1454 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1455 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1457 ///- Schedule script execution for all scripts in the script map
1458 ScriptMap const *s2 = &(s->second);
1459 bool immedScript = false;
1460 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1462 ScriptAction sa;
1463 sa.sourceGUID = sourceGUID;
1464 sa.targetGUID = targetGUID;
1465 sa.ownerGUID = ownerGUID;
1467 sa.script = &iter->second;
1468 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1469 if (iter->first == 0)
1470 immedScript = true;
1472 ///- If one of the effects should be immediate, launch the script execution
1473 if (immedScript)
1474 ScriptsProcess();
1477 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1479 // NOTE: script record _must_ exist until command executed
1481 // prepare static data
1482 uint64 sourceGUID = source->GetGUID();
1483 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1484 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1486 ScriptAction sa;
1487 sa.sourceGUID = sourceGUID;
1488 sa.targetGUID = targetGUID;
1489 sa.ownerGUID = ownerGUID;
1491 sa.script = &script;
1492 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1494 ///- If effects should be immediate, launch the script execution
1495 if(delay == 0)
1496 ScriptsProcess();
1499 /// Process queued scripts
1500 void World::ScriptsProcess()
1502 if (m_scriptSchedule.empty())
1503 return;
1505 ///- Process overdue queued scripts
1506 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1507 // ok as multimap is a *sorted* associative container
1508 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1510 ScriptAction const& step = iter->second;
1512 Object* source = NULL;
1514 if(step.sourceGUID)
1516 switch(GUID_HIPART(step.sourceGUID))
1518 case HIGHGUID_ITEM:
1519 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1521 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1522 if(player)
1523 source = player->GetItemByGuid(step.sourceGUID);
1524 break;
1526 case HIGHGUID_UNIT:
1527 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1528 break;
1529 case HIGHGUID_PET:
1530 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1531 break;
1532 case HIGHGUID_PLAYER:
1533 source = HashMapHolder<Player>::Find(step.sourceGUID);
1534 break;
1535 case HIGHGUID_GAMEOBJECT:
1536 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1537 break;
1538 case HIGHGUID_CORPSE:
1539 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1540 break;
1541 default:
1542 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1543 break;
1547 if(source && !source->IsInWorld()) source = NULL;
1549 Object* target = NULL;
1551 if(step.targetGUID)
1553 switch(GUID_HIPART(step.targetGUID))
1555 case HIGHGUID_UNIT:
1556 target = HashMapHolder<Creature>::Find(step.targetGUID);
1557 break;
1558 case HIGHGUID_PET:
1559 target = HashMapHolder<Pet>::Find(step.targetGUID);
1560 break;
1561 case HIGHGUID_PLAYER: // empty GUID case also
1562 target = HashMapHolder<Player>::Find(step.targetGUID);
1563 break;
1564 case HIGHGUID_GAMEOBJECT:
1565 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1566 break;
1567 case HIGHGUID_CORPSE:
1568 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1569 break;
1570 default:
1571 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1572 break;
1576 if(target && !target->IsInWorld()) target = NULL;
1578 switch (step.script->command)
1580 case SCRIPT_COMMAND_TALK:
1582 if(!source)
1584 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1585 break;
1588 if(source->GetTypeId()!=TYPEID_UNIT)
1590 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1591 break;
1594 uint64 unit_target = target ? target->GetGUID() : 0;
1596 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1597 switch(step.script->datalong)
1599 case 0: // Say
1600 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1601 break;
1602 case 1: // Whisper
1603 if(!unit_target)
1605 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1606 break;
1608 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1609 break;
1610 case 2: // Yell
1611 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1612 break;
1613 case 3: // Emote text
1614 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1615 break;
1616 default:
1617 break; // must be already checked at load
1619 break;
1622 case SCRIPT_COMMAND_EMOTE:
1623 if(!source)
1625 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1626 break;
1629 if(source->GetTypeId()!=TYPEID_UNIT)
1631 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1632 break;
1635 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1636 break;
1637 case SCRIPT_COMMAND_FIELD_SET:
1638 if(!source)
1640 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1641 break;
1643 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1645 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1646 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1647 break;
1650 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1651 break;
1652 case SCRIPT_COMMAND_MOVE_TO:
1653 if(!source)
1655 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1656 break;
1659 if(source->GetTypeId()!=TYPEID_UNIT)
1661 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1662 break;
1664 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1665 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1666 break;
1667 case SCRIPT_COMMAND_FLAG_SET:
1668 if(!source)
1670 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1671 break;
1673 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1675 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1676 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1677 break;
1680 source->SetFlag(step.script->datalong, step.script->datalong2);
1681 break;
1682 case SCRIPT_COMMAND_FLAG_REMOVE:
1683 if(!source)
1685 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1686 break;
1688 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1690 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1691 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1692 break;
1695 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1696 break;
1698 case SCRIPT_COMMAND_TELEPORT_TO:
1700 // accept player in any one from target/source arg
1701 if (!target && !source)
1703 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1704 break;
1707 // must be only Player
1708 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1710 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1711 break;
1714 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1716 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1717 break;
1720 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1722 if(!step.script->datalong) // creature not specified
1724 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1725 break;
1728 if(!source)
1730 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1731 break;
1734 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1736 if(!summoner)
1738 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1739 break;
1742 float x = step.script->x;
1743 float y = step.script->y;
1744 float z = step.script->z;
1745 float o = step.script->o;
1747 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1748 if (!pCreature)
1750 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1751 break;
1754 break;
1757 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1759 if(!step.script->datalong) // gameobject not specified
1761 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1762 break;
1765 if(!source)
1767 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1768 break;
1771 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1773 if(!summoner)
1775 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1776 break;
1779 GameObject *go = NULL;
1780 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1782 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1783 Cell cell(p);
1784 cell.data.Part.reserved = ALL_DISTRICT;
1786 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1787 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1789 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1790 CellLock<GridReadGuard> cell_lock(cell, p);
1791 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1793 if ( !go )
1795 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1796 break;
1799 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1800 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1801 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1802 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1803 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1805 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1806 break;
1809 if( go->isSpawned() )
1810 break; //gameobject already spawned
1812 go->SetLootState(GO_READY);
1813 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1815 go->GetMap()->Add(go);
1816 break;
1818 case SCRIPT_COMMAND_OPEN_DOOR:
1820 if(!step.script->datalong) // door not specified
1822 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1823 break;
1826 if(!source)
1828 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1829 break;
1832 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1834 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1835 break;
1838 Unit* caster = (Unit*)source;
1840 GameObject *door = NULL;
1841 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1843 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1844 Cell cell(p);
1845 cell.data.Part.reserved = ALL_DISTRICT;
1847 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1848 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1850 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1851 CellLock<GridReadGuard> cell_lock(cell, p);
1852 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1854 if ( !door )
1856 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1857 break;
1859 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1861 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1862 break;
1865 if( !door->GetGoState() )
1866 break; //door already open
1868 door->UseDoorOrButton(time_to_close);
1870 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1871 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1872 break;
1874 case SCRIPT_COMMAND_CLOSE_DOOR:
1876 if(!step.script->datalong) // guid for door not specified
1878 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1879 break;
1882 if(!source)
1884 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1885 break;
1888 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1890 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1891 break;
1894 Unit* caster = (Unit*)source;
1896 GameObject *door = NULL;
1897 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1899 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1900 Cell cell(p);
1901 cell.data.Part.reserved = ALL_DISTRICT;
1903 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1904 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1906 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1907 CellLock<GridReadGuard> cell_lock(cell, p);
1908 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1910 if ( !door )
1912 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1913 break;
1915 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1917 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1918 break;
1921 if( door->GetGoState() )
1922 break; //door already closed
1924 door->UseDoorOrButton(time_to_open);
1926 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1927 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1929 break;
1931 case SCRIPT_COMMAND_QUEST_EXPLORED:
1933 if(!source)
1935 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1936 break;
1939 if(!target)
1941 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1942 break;
1945 // when script called for item spell casting then target == (unit or GO) and source is player
1946 WorldObject* worldObject;
1947 Player* player;
1949 if(target->GetTypeId()==TYPEID_PLAYER)
1951 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1953 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1954 break;
1957 worldObject = (WorldObject*)source;
1958 player = (Player*)target;
1960 else
1962 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1964 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1965 break;
1968 if(source->GetTypeId()!=TYPEID_PLAYER)
1970 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1971 break;
1974 worldObject = (WorldObject*)target;
1975 player = (Player*)source;
1978 // quest id and flags checked at script loading
1979 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1980 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1981 player->AreaExploredOrEventHappens(step.script->datalong);
1982 else
1983 player->FailQuest(step.script->datalong);
1985 break;
1988 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1990 if(!source)
1992 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1993 break;
1996 if(!source->isType(TYPEMASK_UNIT))
1998 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1999 break;
2002 if(!target)
2004 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2005 break;
2008 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2010 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2011 break;
2014 Unit* caster = (Unit*)source;
2016 GameObject *go = (GameObject*)target;
2018 go->Use(caster);
2019 break;
2022 case SCRIPT_COMMAND_REMOVE_AURA:
2024 Object* cmdTarget = step.script->datalong2 ? source : target;
2026 if(!cmdTarget)
2028 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2029 break;
2032 if(!cmdTarget->isType(TYPEMASK_UNIT))
2034 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2035 break;
2038 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2039 break;
2042 case SCRIPT_COMMAND_CAST_SPELL:
2044 if(!source)
2046 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2047 break;
2050 if(!source->isType(TYPEMASK_UNIT))
2052 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2053 break;
2056 Object* cmdTarget = step.script->datalong2 ? source : target;
2058 if(!cmdTarget)
2060 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2061 break;
2064 if(!cmdTarget->isType(TYPEMASK_UNIT))
2066 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2067 break;
2070 Unit* spellTarget = (Unit*)cmdTarget;
2072 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2073 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2075 break;
2078 default:
2079 sLog.outError("Unknown script command %u called.",step.script->command);
2080 break;
2083 m_scriptSchedule.erase(iter);
2085 iter = m_scriptSchedule.begin();
2087 return;
2090 /// Send a packet to all players (except self if mentioned)
2091 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2093 SessionMap::iterator itr;
2094 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2096 if (itr->second &&
2097 itr->second->GetPlayer() &&
2098 itr->second->GetPlayer()->IsInWorld() &&
2099 itr->second != self &&
2100 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2102 itr->second->SendPacket(packet);
2107 /// Send a System Message to all players (except self if mentioned)
2108 void World::SendWorldText(int32 string_id, ...)
2110 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2112 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2114 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2115 continue;
2117 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2118 uint32 cache_idx = loc_idx+1;
2120 std::vector<WorldPacket*>* data_list;
2122 // create if not cached yet
2123 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2125 if(data_cache.size() < cache_idx+1)
2126 data_cache.resize(cache_idx+1);
2128 data_list = &data_cache[cache_idx];
2130 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2132 char buf[1000];
2134 va_list argptr;
2135 va_start( argptr, string_id );
2136 vsnprintf( buf,1000, text, argptr );
2137 va_end( argptr );
2139 char* pos = &buf[0];
2141 while(char* line = ChatHandler::LineFromMessage(pos))
2143 WorldPacket* data = new WorldPacket();
2144 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2145 data_list->push_back(data);
2148 else
2149 data_list = &data_cache[cache_idx];
2151 for(int i = 0; i < data_list->size(); ++i)
2152 itr->second->SendPacket((*data_list)[i]);
2155 // free memory
2156 for(int i = 0; i < data_cache.size(); ++i)
2157 for(int j = 0; j < data_cache[i].size(); ++j)
2158 delete data_cache[i][j];
2161 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2162 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2164 SessionMap::iterator itr;
2165 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2167 if (itr->second &&
2168 itr->second->GetPlayer() &&
2169 itr->second->GetPlayer()->IsInWorld() &&
2170 itr->second->GetPlayer()->GetZoneId() == zone &&
2171 itr->second != self &&
2172 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2174 itr->second->SendPacket(packet);
2179 /// Send a System Message to all players in the zone (except self if mentioned)
2180 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2182 WorldPacket data;
2183 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2184 SendZoneMessage(zone, &data, self,team);
2187 /// Kick (and save) all players
2188 void World::KickAll()
2190 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2192 // session not removed at kick and will removed in next update tick
2193 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2194 itr->second->KickPlayer();
2197 /// Kick (and save) all players with security level less `sec`
2198 void World::KickAllLess(AccountTypes sec)
2200 // session not removed at kick and will removed in next update tick
2201 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2202 if(itr->second->GetSecurity() < sec)
2203 itr->second->KickPlayer();
2206 /// Kick (and save) the designated player
2207 bool World::KickPlayer(std::string playerName)
2209 SessionMap::iterator itr;
2211 // session not removed at kick and will removed in next update tick
2212 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2214 if(!itr->second)
2215 continue;
2216 Player *player = itr->second->GetPlayer();
2217 if(!player)
2218 continue;
2219 if( player->IsInWorld() )
2221 if (playerName == player->GetName())
2223 itr->second->KickPlayer();
2224 return true;
2228 return false;
2231 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2232 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2234 loginDatabase.escape_string(nameOrIP);
2235 loginDatabase.escape_string(reason);
2236 std::string safe_author=author;
2237 loginDatabase.escape_string(safe_author);
2239 uint32 duration_secs = TimeStringToSecs(duration);
2240 QueryResult *resultAccounts = NULL; //used for kicking
2242 ///- Update the database with ban information
2243 switch(mode)
2245 case BAN_IP:
2246 //No SQL injection as strings are escaped
2247 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2248 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());
2249 break;
2250 case BAN_ACCOUNT:
2251 //No SQL injection as string is escaped
2252 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2253 break;
2254 case BAN_CHARACTER:
2255 //No SQL injection as string is escaped
2256 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2257 break;
2258 default:
2259 return BAN_SYNTAX_ERROR;
2262 if(!resultAccounts)
2264 if(mode==BAN_IP)
2265 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2266 else
2267 return BAN_NOTFOUND; // Nobody to ban
2270 ///- Disconnect all affected players (for IP it can be several)
2273 Field* fieldsAccount = resultAccounts->Fetch();
2274 uint32 account = fieldsAccount->GetUInt32();
2276 if(mode!=BAN_IP)
2278 //No SQL injection as strings are escaped
2279 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2280 account,duration_secs,safe_author.c_str(),reason.c_str());
2283 if (WorldSession* sess = FindSession(account))
2284 if(std::string(sess->GetPlayerName()) != author)
2285 sess->KickPlayer();
2287 while( resultAccounts->NextRow() );
2289 delete resultAccounts;
2290 return BAN_SUCCESS;
2293 /// Remove a ban from an account or IP address
2294 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2296 if (mode == BAN_IP)
2298 loginDatabase.escape_string(nameOrIP);
2299 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2301 else
2303 uint32 account = 0;
2304 if (mode == BAN_ACCOUNT)
2305 account = accmgr.GetId (nameOrIP);
2306 else if (mode == BAN_CHARACTER)
2307 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2309 if (!account)
2310 return false;
2312 //NO SQL injection as account is uint32
2313 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2315 return true;
2318 /// Update the game time
2319 void World::_UpdateGameTime()
2321 ///- update the time
2322 time_t thisTime = time(NULL);
2323 uint32 elapsed = uint32(thisTime - m_gameTime);
2324 m_gameTime = thisTime;
2326 ///- if there is a shutdown timer
2327 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2329 ///- ... and it is overdue, stop the world (set m_stopEvent)
2330 if( m_ShutdownTimer <= elapsed )
2332 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2333 m_stopEvent = true; // exist code already set
2334 else
2335 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2337 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2338 else
2340 m_ShutdownTimer -= elapsed;
2342 ShutdownMsg();
2347 /// Shutdown the server
2348 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2350 // ignore if server shutdown at next tick
2351 if(m_stopEvent)
2352 return;
2354 m_ShutdownMask = options;
2355 m_ExitCode = exitcode;
2357 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2358 if(time==0)
2360 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2361 m_stopEvent = true; // exist code already set
2362 else
2363 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2365 ///- Else set the shutdown timer and warn users
2366 else
2368 m_ShutdownTimer = time;
2369 ShutdownMsg(true);
2373 /// Display a shutdown message to the user(s)
2374 void World::ShutdownMsg(bool show, Player* player)
2376 // not show messages for idle shutdown mode
2377 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2378 return;
2380 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2381 if ( show ||
2382 (m_ShutdownTimer < 10) ||
2383 // < 30 sec; every 5 sec
2384 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2385 // < 5 min ; every 1 min
2386 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2387 // < 30 min ; every 5 min
2388 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2389 // < 12 h ; every 1 h
2390 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2391 // > 12 h ; every 12 h
2392 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2394 std::string str = secsToTimeString(m_ShutdownTimer);
2396 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2398 SendServerMessage(msgid,str.c_str(),player);
2399 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2403 /// Cancel a planned server shutdown
2404 void World::ShutdownCancel()
2406 // nothing cancel or too later
2407 if(!m_ShutdownTimer || m_stopEvent)
2408 return;
2410 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2412 m_ShutdownMask = 0;
2413 m_ShutdownTimer = 0;
2414 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2415 SendServerMessage(msgid);
2417 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2420 /// Send a server message to the user(s)
2421 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2423 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2424 data << uint32(type);
2425 if(type <= SERVER_MSG_STRING)
2426 data << text;
2428 if(player)
2429 player->GetSession()->SendPacket(&data);
2430 else
2431 SendGlobalMessage( &data );
2434 void World::UpdateSessions( time_t diff )
2436 ///- Add new sessions
2437 while(!addSessQueue.empty())
2439 WorldSession* sess = addSessQueue.next ();
2440 AddSession_ (sess);
2443 ///- Then send an update signal to remaining ones
2444 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2446 next = itr;
2447 ++next;
2449 if(!itr->second)
2450 continue;
2452 ///- and remove not active sessions from the list
2453 if(!itr->second->Update(diff)) // As interval = 0
2455 RemoveQueuedPlayer (itr->second);
2456 delete itr->second;
2457 m_sessions.erase(itr);
2462 // This handles the issued and queued CLI commands
2463 void World::ProcessCliCommands()
2465 if (cliCmdQueue.empty())
2466 return;
2468 CliCommandHolder::Print* zprint;
2470 while (!cliCmdQueue.empty())
2472 sLog.outDebug("CLI command under processing...");
2473 CliCommandHolder *command = cliCmdQueue.next();
2475 zprint = command->m_print;
2477 CliHandler(zprint).ParseCommands(command->m_command);
2479 delete command;
2482 // print the console message here so it looks right
2483 zprint("mangos>");
2486 void World::InitResultQueue()
2488 m_resultQueue = new SqlResultQueue;
2489 CharacterDatabase.SetResultQueue(m_resultQueue);
2492 void World::UpdateResultQueue()
2494 m_resultQueue->Update();
2497 void World::UpdateRealmCharCount(uint32 accountId)
2499 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2500 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2503 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2505 if (resultCharCount)
2507 Field *fields = resultCharCount->Fetch();
2508 uint32 charCount = fields[0].GetUInt32();
2509 delete resultCharCount;
2510 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2511 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2515 void World::InitDailyQuestResetTime()
2517 time_t mostRecentQuestTime;
2519 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2520 if(result)
2522 Field *fields = result->Fetch();
2524 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2525 delete result;
2527 else
2528 mostRecentQuestTime = 0;
2530 // client built-in time for reset is 6:00 AM
2531 // FIX ME: client not show day start time
2532 time_t curTime = time(NULL);
2533 tm localTm = *localtime(&curTime);
2534 localTm.tm_hour = 6;
2535 localTm.tm_min = 0;
2536 localTm.tm_sec = 0;
2538 // current day reset time
2539 time_t curDayResetTime = mktime(&localTm);
2541 // last reset time before current moment
2542 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2544 // need reset (if we have quest time before last reset time (not processed by some reason)
2545 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2546 m_NextDailyQuestReset = mostRecentQuestTime;
2547 else
2549 // plan next reset time
2550 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2554 void World::ResetDailyQuests()
2556 sLog.outDetail("Daily quests reset for all characters.");
2557 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2558 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2559 if(itr->second->GetPlayer())
2560 itr->second->GetPlayer()->ResetDailyQuestStatus();
2563 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2565 if(limit < -SEC_ADMINISTRATOR)
2566 limit = -SEC_ADMINISTRATOR;
2568 // lock update need
2569 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2571 m_playerLimit = limit;
2573 if(db_update_need)
2574 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2577 void World::UpdateMaxSessionCounters()
2579 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2580 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2583 void World::LoadDBVersion()
2585 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2586 if(result)
2588 Field* fields = result->Fetch();
2590 m_DBVersion = fields[0].GetString();
2591 delete result;
2593 else
2594 m_DBVersion = "unknown world database";