[2008_10_31_01_mangos_creature_template.sql] Creature related code and DB cleanups.
[auctionmangos.git] / src / game / World.cpp
bloba8bc9a66983e19c64e72c62c5b6189c7a7053f1d
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 "Util.h"
61 INSTANTIATE_SINGLETON_1( World );
63 volatile bool World::m_stopEvent = false;
64 volatile uint32 World::m_worldLoopCounter = 0;
66 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
67 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
68 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_VisibleUnitGreyDistance = 0;
71 float World::m_VisibleObjectGreyDistance = 0;
73 // ServerMessages.dbc
74 enum ServerMessageType
76 SERVER_MSG_SHUTDOWN_TIME = 1,
77 SERVER_MSG_RESTART_TIME = 2,
78 SERVER_MSG_STRING = 3,
79 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
80 SERVER_MSG_RESTART_CANCELLED = 5
83 struct ScriptAction
85 uint64 sourceGUID;
86 uint64 targetGUID;
87 uint64 ownerGUID; // owner of source if source is item
88 ScriptInfo const* script; // pointer to static script data
91 /// World constructor
92 World::World()
94 m_playerLimit = 0;
95 m_allowMovement = true;
96 m_ShutdownMask = 0;
97 m_ShutdownTimer = 0;
98 m_gameTime=time(NULL);
99 m_startTime=m_gameTime;
100 m_maxActiveSessionCount = 0;
101 m_maxQueuedSessionCount = 0;
102 m_resultQueue = NULL;
103 m_NextDailyQuestReset = 0;
105 m_defaultDbcLocale = LOCALE_enUS;
106 m_availableDbcLocaleMask = 0;
109 /// World destructor
110 World::~World()
112 ///- Empty the kicked session set
113 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
114 delete *itr;
116 m_kicked_sessions.clear();
118 ///- Empty the WeatherMap
119 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
120 delete itr->second;
122 m_weathers.clear();
124 VMAP::VMapFactory::clear();
126 if(m_resultQueue) delete m_resultQueue;
128 //TODO free addSessQueue
131 /// Find a player in a specified zone
132 Player* World::FindPlayerInZone(uint32 zone)
134 ///- circle through active sessions and return the first player found in the zone
135 SessionMap::iterator itr;
136 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
138 if(!itr->second)
139 continue;
140 Player *player = itr->second->GetPlayer();
141 if(!player)
142 continue;
143 if( player->IsInWorld() && player->GetZoneId() == zone )
145 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
146 return player;
149 return NULL;
152 /// Find a session by its id
153 WorldSession* World::FindSession(uint32 id) const
155 SessionMap::const_iterator itr = m_sessions.find(id);
157 if(itr != m_sessions.end())
158 return itr->second; // also can return NULL for kicked session
159 else
160 return NULL;
163 /// Remove a given session
164 bool World::RemoveSession(uint32 id)
166 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
167 SessionMap::iterator itr = m_sessions.find(id);
169 if(itr != m_sessions.end() && itr->second)
171 if (itr->second->PlayerLoading())
172 return false;
173 itr->second->KickPlayer();
176 return true;
179 void World::AddSession(WorldSession* s)
181 addSessQueue.add(s);
184 void
185 World::AddSession_ (WorldSession* s)
187 ASSERT (s);
189 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
191 ///- kick already loaded player with same account (if any) and remove session
192 ///- if player is in loading and want to load again, return
193 if (!RemoveSession (s->GetAccountId ()))
195 s->KickPlayer ();
196 m_kicked_sessions.insert (s);
197 return;
200 WorldSession* old = m_sessions[s->GetAccountId ()];
201 m_sessions[s->GetAccountId ()] = s;
203 // if session already exist, prepare to it deleting at next world update
204 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
205 if (old)
206 m_kicked_sessions.insert (old);
208 uint32 Sessions = GetActiveAndQueuedSessionCount ();
209 uint32 pLimit = GetPlayerAmountLimit ();
210 uint32 QueueSize = GetQueueSize (); //number of players in the queue
211 bool inQueue = false;
212 //so we don't count the user trying to
213 //login as a session and queue the socket that we are using
214 --Sessions;
216 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
218 AddQueuedPlayer (s);
219 UpdateMaxSessionCounters ();
220 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
221 return;
224 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
225 packet << uint8 (AUTH_OK);
226 packet << uint32 (0); // unknown random value...
227 packet << uint8 (0);
228 packet << uint32 (0);
229 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
230 s->SendPacket (&packet);
232 UpdateMaxSessionCounters ();
234 // Updates the population
235 if (pLimit > 0)
237 float popu = GetActiveSessionCount (); //updated number of users on the server
238 popu /= pLimit;
239 popu *= 2;
240 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
241 sLog.outDetail ("Server Population (%f).", popu);
245 int32 World::GetQueuePos(WorldSession* sess)
247 uint32 position = 1;
249 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
250 if((*iter) == sess)
251 return position;
253 return 0;
256 void World::AddQueuedPlayer(WorldSession* sess)
258 m_QueuedPlayer.push_back (sess);
260 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
261 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
262 packet << uint8 (AUTH_WAIT_QUEUE);
263 packet << uint32 (0); // unknown random value...
264 packet << uint8 (0);
265 packet << uint32 (0);
266 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
267 packet << uint32(GetQueuePos (sess));
268 sess->SendPacket (&packet);
270 //sess->SendAuthWaitQue (GetQueuePos (sess));
273 void World::RemoveQueuedPlayer(WorldSession* sess)
275 // sessions count including queued to remove (if removed_session set)
276 uint32 sessions = GetActiveSessionCount();
278 uint32 position = 1;
279 Queue::iterator iter = m_QueuedPlayer.begin();
281 // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
282 bool decrease_session = true;
284 // search to remove and count skipped positions
285 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
287 if(*iter==sess)
289 Queue::iterator iter2 = iter;
290 ++iter;
291 m_QueuedPlayer.erase(iter2);
292 decrease_session = false; // removing queued session
293 break;
297 // iter point to next socked after removed or end()
298 // position store position of removed socket and then new position next socket after removed
300 // decrease for case session queued for removing
301 if(decrease_session && sessions)
302 --sessions;
304 // accept first in queue
305 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
307 WorldSession * socket = m_QueuedPlayer.front();
308 socket->SendAuthWaitQue(0);
309 m_QueuedPlayer.pop_front();
311 // update iter to point first queued socket or end() if queue is empty now
312 iter = m_QueuedPlayer.begin();
313 position = 1;
316 // update position from iter to end()
317 // iter point to first not updated socket, position store new position
318 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
319 (*iter)->SendAuthWaitQue(position);
322 /// Find a Weather object by the given zoneid
323 Weather* World::FindWeather(uint32 id) const
325 WeatherMap::const_iterator itr = m_weathers.find(id);
327 if(itr != m_weathers.end())
328 return itr->second;
329 else
330 return 0;
333 /// Remove a Weather object for the given zoneid
334 void World::RemoveWeather(uint32 id)
336 // not called at the moment. Kept for completeness
337 WeatherMap::iterator itr = m_weathers.find(id);
339 if(itr != m_weathers.end())
341 delete itr->second;
342 m_weathers.erase(itr);
346 /// Add a Weather object to the list
347 Weather* World::AddWeather(uint32 zone_id)
349 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
351 // zone not have weather, ignore
352 if(!weatherChances)
353 return NULL;
355 Weather* w = new Weather(zone_id,weatherChances);
356 m_weathers[w->GetZone()] = w;
357 w->ReGenerate();
358 w->UpdateWeather();
359 return w;
362 /// Initialize config values
363 void World::LoadConfigSettings(bool reload)
365 if(reload)
367 if(!sConfig.Reload())
369 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
370 return;
374 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
375 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
376 if(!confVersion)
378 sLog.outError("*****************************************************************************");
379 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
380 sLog.outError(" Your configuration file may be out of date!");
381 sLog.outError("*****************************************************************************");
382 clock_t pause = 3000 + clock();
383 while (pause > clock());
385 else
387 if (confVersion < _MANGOSDCONFVERSION)
389 sLog.outError("*****************************************************************************");
390 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
391 sLog.outError(" Please check for updates, as your current default values may cause");
392 sLog.outError(" unexpected behavior.");
393 sLog.outError("*****************************************************************************");
394 clock_t pause = 3000 + clock();
395 while (pause > clock());
399 ///- Read the player limit and the Message of the day from the config file
400 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
401 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
403 ///- Read all rates from the config file
404 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
405 if(rate_values[RATE_HEALTH] < 0)
407 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
408 rate_values[RATE_HEALTH] = 1;
410 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
411 if(rate_values[RATE_POWER_MANA] < 0)
413 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
414 rate_values[RATE_POWER_MANA] = 1;
416 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
417 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
418 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
420 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
421 rate_values[RATE_POWER_RAGE_LOSS] = 1;
423 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
424 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
425 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
426 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
427 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
428 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
429 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
430 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
431 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
432 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
433 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
434 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
435 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
436 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
437 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
438 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
439 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
440 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
441 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
442 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
443 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
444 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
445 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
446 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
447 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
448 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
449 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
450 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
451 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
452 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
453 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
454 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
455 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
456 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
457 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
458 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
459 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
460 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
461 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
462 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
463 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
464 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
465 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
466 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
467 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
468 if(rate_values[RATE_TALENT] < 0.0f)
470 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
471 rate_values[RATE_TALENT] = 1.0f;
473 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
475 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
476 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
478 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
479 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
481 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
483 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
484 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
487 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
488 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
490 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
491 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
493 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
494 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
496 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
497 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
499 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
500 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
502 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
503 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
505 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
506 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
508 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
509 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
512 ///- Read other configuration items from the config file
514 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
515 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
517 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
518 m_configs[CONFIG_COMPRESSION] = 1;
520 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
521 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
522 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
524 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
525 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
527 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
528 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
530 if(reload)
531 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
533 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
534 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
536 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
537 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
539 if(reload)
540 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
542 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
544 if(reload)
546 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
547 if(val!=m_configs[CONFIG_PORT_WORLD])
548 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
550 else
551 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
553 if(reload)
555 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
556 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
557 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
559 else
560 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
562 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
563 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
564 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
565 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
567 if(reload)
569 uint32 val = sConfig.GetIntDefault("GameType", 0);
570 if(val!=m_configs[CONFIG_GAME_TYPE])
571 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
573 else
574 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
576 if(reload)
578 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
579 if(val!=m_configs[CONFIG_REALM_ZONE])
580 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
582 else
583 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
585 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
586 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
587 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
588 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
589 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
590 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
591 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
592 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
593 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
594 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
595 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
596 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
598 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
600 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
601 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
603 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
604 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
607 // must be after CONFIG_CHARACTERS_PER_REALM
608 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
609 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
611 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
612 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
615 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
616 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
618 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
619 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
622 if(reload)
624 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
625 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
626 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
628 else
629 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
630 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
632 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
633 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
636 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
637 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
639 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]);
640 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
642 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
644 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]);
645 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
647 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
648 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
650 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
651 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
653 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
654 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
655 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
657 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
658 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
659 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
661 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
662 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
663 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
665 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
666 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
669 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
670 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
671 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
672 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
674 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
675 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
676 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
678 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
680 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
682 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
683 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
685 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
686 m_configs[CONFIG_UPTIME_UPDATE] = 10;
688 if(reload)
690 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
691 m_timers[WUPDATE_UPTIME].Reset();
694 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
695 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
696 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
697 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
699 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
700 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
702 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
704 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
705 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
707 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
708 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
711 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
712 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
714 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
715 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
718 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
719 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
721 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
722 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
725 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
726 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
728 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
729 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
732 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
733 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
735 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
736 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
739 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
740 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
742 if(reload)
744 uint32 val = sConfig.GetIntDefault("Expansion",1);
745 if(val!=m_configs[CONFIG_EXPANSION])
746 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
748 else
749 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
751 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
752 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
753 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
755 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
757 m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
759 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
761 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
762 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
763 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
764 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
765 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
766 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
767 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
769 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
771 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
772 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
774 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
775 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
777 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
778 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
779 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
780 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
781 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
783 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
784 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
785 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
787 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
789 // always use declined names in the russian client
790 m_configs[CONFIG_DECLINED_NAMES_USED] =
791 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
793 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
794 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
795 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
797 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
798 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
800 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
801 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
803 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
804 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
806 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
807 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
810 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
811 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
813 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
814 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
816 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
818 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
819 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
821 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
822 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
824 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
825 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
827 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
829 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
830 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
832 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
833 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
835 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
836 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
838 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
840 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
841 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
843 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
844 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
846 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
847 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
850 ///- Read the "Data" directory from the config file
851 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
852 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
853 dataPath.append("/");
855 if(reload)
857 if(dataPath!=m_dataPath)
858 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
860 else
862 m_dataPath = dataPath;
863 sLog.outString("Using DataDir %s",m_dataPath.c_str());
866 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
867 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
868 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
869 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
870 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
871 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
872 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
873 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
874 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
875 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
876 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
879 /// Initialize the World
880 void World::SetInitialWorldSettings()
882 ///- Initialize the random number generator
883 srand((unsigned int)time(NULL));
885 ///- Initialize config settings
886 LoadConfigSettings();
888 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
889 objmgr.SetHighestGuids();
891 ///- Check the existence of the map files for all races' startup areas.
892 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
893 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
894 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
895 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
896 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
897 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
898 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
899 ||m_configs[CONFIG_EXPANSION] && (
900 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
902 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());
903 exit(1);
906 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
907 sLog.outString( "" );
908 sLog.outString( "Loading MaNGOS strings..." );
909 if (!objmgr.LoadMangosStrings())
910 exit(1); // Error message displayed in function already
912 ///- Update the realm entry in the database with the realm type from the config file
913 //No SQL injection as values are treated as integers
915 // not send custom type REALM_FFA_PVP to realm list
916 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
917 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
918 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
920 ///- Remove the bones after a restart
921 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
923 ///- Load the DBC files
924 sLog.outString("Initialize data stores...");
925 LoadDBCStores(m_dataPath);
926 DetectDBCLang();
928 sLog.outString( "Loading InstanceTemplate" );
929 objmgr.LoadInstanceTemplate();
931 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
932 spellmgr.LoadSkillLineAbilityMap();
934 ///- Clean up and pack instances
935 sLog.outString( "Cleaning up instances..." );
936 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
938 sLog.outString( "Packing instances..." );
939 sInstanceSaveManager.PackInstances();
941 sLog.outString( "Loading Localization strings..." );
942 objmgr.LoadCreatureLocales();
943 objmgr.LoadGameObjectLocales();
944 objmgr.LoadItemLocales();
945 objmgr.LoadQuestLocales();
946 objmgr.LoadNpcTextLocales();
947 objmgr.LoadPageTextLocales();
948 objmgr.LoadNpcOptionLocales();
949 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
951 sLog.outString( "Loading Page Texts..." );
952 objmgr.LoadPageTexts();
954 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
955 objmgr.LoadGameobjectInfo();
957 sLog.outString( "Loading Spell Chain Data..." );
958 spellmgr.LoadSpellChains();
960 sLog.outString( "Loading Spell Elixir types..." );
961 spellmgr.LoadSpellElixirs();
963 sLog.outString( "Loading Spell Learn Skills..." );
964 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
966 sLog.outString( "Loading Spell Learn Spells..." );
967 spellmgr.LoadSpellLearnSpells();
969 sLog.outString( "Loading Spell Proc Event conditions..." );
970 spellmgr.LoadSpellProcEvents();
972 sLog.outString( "Loading Aggro Spells Definitions...");
973 spellmgr.LoadSpellThreats();
975 sLog.outString( "Loading NPC Texts..." );
976 objmgr.LoadGossipText();
978 sLog.outString( "Loading Item Random Enchantments Table..." );
979 LoadRandomEnchantmentsTable();
981 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
982 objmgr.LoadItemPrototypes();
984 sLog.outString( "Loading Item Texts..." );
985 objmgr.LoadItemTexts();
987 sLog.outString( "Loading Creature Model Based Info Data..." );
988 objmgr.LoadCreatureModelInfo();
990 sLog.outString( "Loading Equipment templates...");
991 objmgr.LoadEquipmentTemplates();
993 sLog.outString( "Loading Creature templates..." );
994 objmgr.LoadCreatureTemplates();
996 sLog.outString( "Loading SpellsScriptTarget...");
997 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
999 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1000 objmgr.LoadReputationOnKill();
1002 sLog.outString( "Loading Pet Create Spells..." );
1003 objmgr.LoadPetCreateSpells();
1005 sLog.outString( "Loading Creature Data..." );
1006 objmgr.LoadCreatures();
1008 sLog.outString( "Loading Creature Addon Data..." );
1009 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1011 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1012 objmgr.LoadCreatureRespawnTimes();
1014 sLog.outString( "Loading Gameobject Data..." );
1015 objmgr.LoadGameobjects();
1017 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1018 objmgr.LoadGameobjectRespawnTimes();
1020 sLog.outString( "Loading Game Event Data...");
1021 gameeventmgr.LoadFromDB();
1023 sLog.outString( "Loading Weather Data..." );
1024 objmgr.LoadWeatherZoneChances();
1026 sLog.outString( "Loading Quests..." );
1027 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1029 sLog.outString( "Loading Quests Relations..." );
1030 objmgr.LoadQuestRelations(); // must be after quest load
1032 sLog.outString( "Loading AreaTrigger definitions..." );
1033 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1035 sLog.outString( "Loading Quest Area Triggers..." );
1036 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1038 sLog.outString( "Loading Tavern Area Triggers..." );
1039 objmgr.LoadTavernAreaTriggers();
1041 sLog.outString( "Loading AreaTrigger script names..." );
1042 objmgr.LoadAreaTriggerScripts();
1044 sLog.outString( "Loading Graveyard-zone links...");
1045 objmgr.LoadGraveyardZones();
1047 sLog.outString( "Loading Spell target coordinates..." );
1048 spellmgr.LoadSpellTargetPositions();
1050 sLog.outString( "Loading SpellAffect definitions..." );
1051 spellmgr.LoadSpellAffects();
1053 sLog.outString( "Loading spell pet auras..." );
1054 spellmgr.LoadSpellPetAuras();
1056 sLog.outString( "Loading player Create Info & Level Stats..." );
1057 objmgr.LoadPlayerInfo();
1059 sLog.outString( "Loading Exploration BaseXP Data..." );
1060 objmgr.LoadExplorationBaseXP();
1062 sLog.outString( "Loading Pet Name Parts..." );
1063 objmgr.LoadPetNames();
1065 sLog.outString( "Loading the max pet number..." );
1066 objmgr.LoadPetNumber();
1068 sLog.outString( "Loading pet level stats..." );
1069 objmgr.LoadPetLevelInfo();
1071 sLog.outString( "Loading Player Corpses..." );
1072 objmgr.LoadCorpses();
1074 sLog.outString( "Loading Loot Tables..." );
1075 LoadLootTables();
1077 sLog.outString( "Loading Skill Discovery Table..." );
1078 LoadSkillDiscoveryTable();
1080 sLog.outString( "Loading Skill Extra Item Table..." );
1081 LoadSkillExtraItemTable();
1083 sLog.outString( "Loading Skill Fishing base level requirements..." );
1084 objmgr.LoadFishingBaseSkillLevel();
1086 ///- Load dynamic data tables from the database
1087 sLog.outString( "Loading Auctions..." );
1088 objmgr.LoadAuctionItems();
1089 objmgr.LoadAuctions();
1091 sLog.outString( "Loading Guilds..." );
1092 objmgr.LoadGuilds();
1094 sLog.outString( "Loading ArenaTeams..." );
1095 objmgr.LoadArenaTeams();
1097 sLog.outString( "Loading Groups..." );
1098 objmgr.LoadGroups();
1100 sLog.outString( "Loading ReservedNames..." );
1101 objmgr.LoadReservedPlayersNames();
1103 sLog.outString( "Loading GameObject for quests..." );
1104 objmgr.LoadGameObjectForQuests();
1106 sLog.outString( "Loading BattleMasters..." );
1107 objmgr.LoadBattleMastersEntry();
1109 sLog.outString( "Loading GameTeleports..." );
1110 objmgr.LoadGameTele();
1112 sLog.outString( "Loading Npc Text Id..." );
1113 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1115 sLog.outString( "Loading Npc Options..." );
1116 objmgr.LoadNpcOptions();
1118 sLog.outString( "Loading vendors..." );
1119 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1121 sLog.outString( "Loading trainers..." );
1122 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1124 sLog.outString( "Loading Waypoints..." );
1125 WaypointMgr.Load();
1127 ///- Handle outdated emails (delete/return)
1128 sLog.outString( "Returning old mails..." );
1129 objmgr.ReturnOrDeleteOldMails(false);
1131 ///- Load and initialize scripts
1132 sLog.outString( "Loading Scripts..." );
1133 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1134 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1135 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1136 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1137 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1139 sLog.outString( "Initializing Scripts..." );
1140 if(!LoadScriptingModule())
1141 exit(1);
1143 ///- Initialize game time and timers
1144 sLog.outString( "DEBUG:: Initialize game time and timers" );
1145 m_gameTime = time(NULL);
1146 m_startTime=m_gameTime;
1148 tm local;
1149 time_t curr;
1150 time(&curr);
1151 local=*(localtime(&curr)); // dereference and assign
1152 char isoDate[128];
1153 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1154 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1156 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1158 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1159 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1160 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1161 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1162 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1163 //Update "uptime" table based on configuration entry in minutes.
1164 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1166 //to set mailtimer to return mails every day between 4 and 5 am
1167 //mailtimer is increased when updating auctions
1168 //one second is 1000 -(tested on win system)
1169 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1170 //1440
1171 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1172 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1174 ///- Initilize static helper structures
1175 AIRegistry::Initialize();
1176 WaypointMovementGenerator<Creature>::Initialize();
1177 Player::InitVisibleBits();
1179 ///- Initialize MapManager
1180 sLog.outString( "Starting Map System" );
1181 MapManager::Instance().Initialize();
1183 ///- Initialize Battlegrounds
1184 sLog.outString( "Starting BattleGround System" );
1185 sBattleGroundMgr.CreateInitialBattleGrounds();
1187 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1188 sLog.outString( "Loading Transports..." );
1189 MapManager::Instance().LoadTransports();
1191 sLog.outString("Deleting expired bans..." );
1192 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1194 sLog.outString("Calculate next daily quest reset time..." );
1195 InitDailyQuestResetTime();
1197 sLog.outString("Starting Game Event system..." );
1198 uint32 nextGameEvent = gameeventmgr.Initialize();
1199 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1201 sLog.outString( "WORLD: World initialized" );
1204 void World::DetectDBCLang()
1206 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1208 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1210 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1211 m_lang_confid = LOCALE_enUS;
1214 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1216 std::string availableLocalsStr;
1218 int default_locale = MAX_LOCALE;
1219 for (int i = MAX_LOCALE-1; i >= 0; --i)
1221 if ( strlen(race->name[i]) > 0) // check by race names
1223 default_locale = i;
1224 m_availableDbcLocaleMask |= (1 << i);
1225 availableLocalsStr += localeNames[i];
1226 availableLocalsStr += " ";
1230 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1231 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1233 default_locale = m_lang_confid;
1236 if(default_locale >= MAX_LOCALE)
1238 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1239 exit(1);
1242 m_defaultDbcLocale = LocaleConstant(default_locale);
1244 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1247 /// Update the World !
1248 void World::Update(time_t diff)
1250 ///- Update the different timers
1251 for(int i = 0; i < WUPDATE_COUNT; i++)
1252 if(m_timers[i].GetCurrent()>=0)
1253 m_timers[i].Update(diff);
1254 else m_timers[i].SetCurrent(0);
1256 ///- Update the game time and check for shutdown time
1257 _UpdateGameTime();
1259 /// Handle daily quests reset time
1260 if(m_gameTime > m_NextDailyQuestReset)
1262 ResetDailyQuests();
1263 m_NextDailyQuestReset += DAY;
1266 /// <ul><li> Handle auctions when the timer has passed
1267 if (m_timers[WUPDATE_AUCTIONS].Passed())
1269 m_timers[WUPDATE_AUCTIONS].Reset();
1271 ///- Update mails (return old mails with item, or delete them)
1272 //(tested... works on win)
1273 if (++mail_timer > mail_timer_expires)
1275 mail_timer = 0;
1276 objmgr.ReturnOrDeleteOldMails(true);
1279 AuctionHouseObject* AuctionMap;
1280 for (int i = 0; i < 3; i++)
1282 switch (i)
1284 case 0:
1285 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1286 break;
1287 case 1:
1288 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1289 break;
1290 case 2:
1291 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1292 break;
1295 ///- Handle expired auctions
1296 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1297 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1299 next = itr;
1300 ++next;
1301 if (m_gameTime > (itr->second->time))
1303 ///- Either cancel the auction if there was no bidder
1304 if (itr->second->bidder == 0)
1306 objmgr.SendAuctionExpiredMail( itr->second );
1308 ///- Or perform the transaction
1309 else
1311 //we should send an "item sold" message if the seller is online
1312 //we send the item to the winner
1313 //we send the money to the seller
1314 objmgr.SendAuctionSuccessfulMail( itr->second );
1315 objmgr.SendAuctionWonMail( itr->second );
1318 ///- In any case clear the auction
1319 //No SQL injection (Id is integer)
1320 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1321 objmgr.RemoveAItem(itr->second->item_guidlow);
1322 delete itr->second;
1323 AuctionMap->RemoveAuction(itr->first);
1329 /// <li> Handle session updates when the timer has passed
1330 if (m_timers[WUPDATE_SESSIONS].Passed())
1332 m_timers[WUPDATE_SESSIONS].Reset();
1334 UpdateSessions(diff);
1337 /// <li> Handle weather updates when the timer has passed
1338 if (m_timers[WUPDATE_WEATHERS].Passed())
1340 m_timers[WUPDATE_WEATHERS].Reset();
1342 ///- Send an update signal to Weather objects
1343 WeatherMap::iterator itr, next;
1344 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1346 next = itr;
1347 ++next;
1349 ///- and remove Weather objects for zones with no player
1350 //As interval > WorldTick
1351 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1353 delete itr->second;
1354 m_weathers.erase(itr);
1358 /// <li> Update uptime table
1359 if (m_timers[WUPDATE_UPTIME].Passed())
1361 uint32 tmpDiff = (m_gameTime - m_startTime);
1362 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1364 m_timers[WUPDATE_UPTIME].Reset();
1365 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1368 /// <li> Handle all other objects
1369 if (m_timers[WUPDATE_OBJECTS].Passed())
1371 m_timers[WUPDATE_OBJECTS].Reset();
1372 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1373 MapManager::Instance().Update(diff); // As interval = 0
1375 ///- Process necessary scripts
1376 if (!m_scriptSchedule.empty())
1377 ScriptsProcess();
1379 sBattleGroundMgr.Update(diff);
1382 // execute callbacks from sql queries that were queued recently
1383 UpdateResultQueue();
1385 ///- Erase corpses once every 20 minutes
1386 if (m_timers[WUPDATE_CORPSES].Passed())
1388 m_timers[WUPDATE_CORPSES].Reset();
1390 CorpsesErase();
1393 ///- Process Game events when necessary
1394 if (m_timers[WUPDATE_EVENTS].Passed())
1396 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1397 uint32 nextGameEvent = gameeventmgr.Update();
1398 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1399 m_timers[WUPDATE_EVENTS].Reset();
1402 /// </ul>
1403 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1404 MapManager::Instance().DoDelayedMovesAndRemoves();
1406 // update the instance reset times
1407 sInstanceSaveManager.Update();
1409 // And last, but not least handle the issued cli commands
1410 ProcessCliCommands();
1413 /// Put scripts in the execution queue
1414 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1416 ///- Find the script map
1417 ScriptMapMap::const_iterator s = scripts.find(id);
1418 if (s == scripts.end())
1419 return;
1421 // prepare static data
1422 uint64 sourceGUID = source->GetGUID();
1423 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1424 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1426 ///- Schedule script execution for all scripts in the script map
1427 ScriptMap const *s2 = &(s->second);
1428 bool immedScript = false;
1429 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1431 ScriptAction sa;
1432 sa.sourceGUID = sourceGUID;
1433 sa.targetGUID = targetGUID;
1434 sa.ownerGUID = ownerGUID;
1436 sa.script = &iter->second;
1437 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1438 if (iter->first == 0)
1439 immedScript = true;
1441 ///- If one of the effects should be immediate, launch the script execution
1442 if (immedScript)
1443 ScriptsProcess();
1446 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1448 // NOTE: script record _must_ exist until command executed
1450 // prepare static data
1451 uint64 sourceGUID = source->GetGUID();
1452 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1453 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1455 ScriptAction sa;
1456 sa.sourceGUID = sourceGUID;
1457 sa.targetGUID = targetGUID;
1458 sa.ownerGUID = ownerGUID;
1460 sa.script = &script;
1461 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1463 ///- If effects should be immediate, launch the script execution
1464 if(delay == 0)
1465 ScriptsProcess();
1468 /// Process queued scripts
1469 void World::ScriptsProcess()
1471 if (m_scriptSchedule.empty())
1472 return;
1474 ///- Process overdue queued scripts
1475 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1476 // ok as multimap is a *sorted* associative container
1477 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1479 ScriptAction const& step = iter->second;
1481 Object* source = NULL;
1483 if(step.sourceGUID)
1485 switch(GUID_HIPART(step.sourceGUID))
1487 case HIGHGUID_ITEM:
1488 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1490 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1491 if(player)
1492 source = player->GetItemByGuid(step.sourceGUID);
1493 break;
1495 case HIGHGUID_UNIT:
1496 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1497 break;
1498 case HIGHGUID_PET:
1499 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1500 break;
1501 case HIGHGUID_PLAYER:
1502 source = HashMapHolder<Player>::Find(step.sourceGUID);
1503 break;
1504 case HIGHGUID_GAMEOBJECT:
1505 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1506 break;
1507 case HIGHGUID_CORPSE:
1508 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1509 break;
1510 default:
1511 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1512 break;
1516 Object* target = NULL;
1518 if(step.targetGUID)
1520 switch(GUID_HIPART(step.targetGUID))
1522 case HIGHGUID_UNIT:
1523 target = HashMapHolder<Creature>::Find(step.targetGUID);
1524 break;
1525 case HIGHGUID_PET:
1526 target = HashMapHolder<Pet>::Find(step.targetGUID);
1527 break;
1528 case HIGHGUID_PLAYER: // empty GUID case also
1529 target = HashMapHolder<Player>::Find(step.targetGUID);
1530 break;
1531 case HIGHGUID_GAMEOBJECT:
1532 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1533 break;
1534 case HIGHGUID_CORPSE:
1535 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1536 break;
1537 default:
1538 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1539 break;
1543 switch (step.script->command)
1545 case SCRIPT_COMMAND_TALK:
1547 if(!source)
1549 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1550 break;
1553 if(source->GetTypeId()!=TYPEID_UNIT)
1555 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1556 break;
1558 if(step.script->datalong > 3)
1560 sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1561 break;
1564 uint64 unit_target = target ? target->GetGUID() : 0;
1566 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1567 switch(step.script->datalong)
1569 case 0: // Say
1570 ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1571 break;
1572 case 1: // Whisper
1573 if(!unit_target)
1575 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1576 break;
1578 ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1579 break;
1580 case 2: // Yell
1581 ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1582 break;
1583 case 3: // Emote text
1584 ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1585 break;
1586 default:
1587 break; // must be already checked at load
1589 break;
1592 case SCRIPT_COMMAND_EMOTE:
1593 if(!source)
1595 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1596 break;
1599 if(source->GetTypeId()!=TYPEID_UNIT)
1601 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1602 break;
1605 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1606 break;
1607 case SCRIPT_COMMAND_FIELD_SET:
1608 if(!source)
1610 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1611 break;
1613 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1615 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1616 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1617 break;
1620 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1621 break;
1622 case SCRIPT_COMMAND_MOVE_TO:
1623 if(!source)
1625 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1626 break;
1629 if(source->GetTypeId()!=TYPEID_UNIT)
1631 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1632 break;
1634 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1635 MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1636 break;
1637 case SCRIPT_COMMAND_FLAG_SET:
1638 if(!source)
1640 sLog.outError("SCRIPT_COMMAND_FLAG_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_FLAG_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->SetFlag(step.script->datalong, step.script->datalong2);
1651 break;
1652 case SCRIPT_COMMAND_FLAG_REMOVE:
1653 if(!source)
1655 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1656 break;
1658 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1660 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1661 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1662 break;
1665 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1666 break;
1668 case SCRIPT_COMMAND_TELEPORT_TO:
1670 // accept player in any one from target/source arg
1671 if (!target && !source)
1673 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1674 break;
1677 // must be only Player
1678 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1680 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1681 break;
1684 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1686 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1687 break;
1690 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1692 if(!step.script->datalong) // creature not specified
1694 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1695 break;
1698 if(!source)
1700 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1701 break;
1704 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1706 if(!summoner)
1708 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1709 break;
1712 float x = step.script->x;
1713 float y = step.script->y;
1714 float z = step.script->z;
1715 float o = step.script->o;
1717 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1718 if (!pCreature)
1720 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1721 break;
1724 break;
1727 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1729 if(!step.script->datalong) // gameobject not specified
1731 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1732 break;
1735 if(!source)
1737 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1738 break;
1741 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1743 if(!summoner)
1745 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1746 break;
1749 GameObject *go = NULL;
1750 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1752 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1753 Cell cell(p);
1754 cell.data.Part.reserved = ALL_DISTRICT;
1756 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1757 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1759 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1760 CellLock<GridReadGuard> cell_lock(cell, p);
1761 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1763 if ( !go )
1765 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1766 break;
1769 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1770 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1771 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1772 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1773 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1775 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1776 break;
1779 if( go->isSpawned() )
1780 break; //gameobject already spawned
1782 go->SetLootState(GO_READY);
1783 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1785 MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1786 break;
1788 case SCRIPT_COMMAND_OPEN_DOOR:
1790 if(!step.script->datalong) // door not specified
1792 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1793 break;
1796 if(!source)
1798 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1799 break;
1802 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1804 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1805 break;
1808 Unit* caster = (Unit*)source;
1810 GameObject *door = NULL;
1811 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1813 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1814 Cell cell(p);
1815 cell.data.Part.reserved = ALL_DISTRICT;
1817 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1818 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1820 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1821 CellLock<GridReadGuard> cell_lock(cell, p);
1822 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1824 if ( !door )
1826 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1827 break;
1829 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1831 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1832 break;
1835 if( !door->GetGoState() )
1836 break; //door already open
1838 door->UseDoorOrButton(time_to_close);
1840 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1841 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1842 break;
1844 case SCRIPT_COMMAND_CLOSE_DOOR:
1846 if(!step.script->datalong) // guid for door not specified
1848 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1849 break;
1852 if(!source)
1854 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1855 break;
1858 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1860 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1861 break;
1864 Unit* caster = (Unit*)source;
1866 GameObject *door = NULL;
1867 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1869 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1870 Cell cell(p);
1871 cell.data.Part.reserved = ALL_DISTRICT;
1873 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1874 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1876 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1877 CellLock<GridReadGuard> cell_lock(cell, p);
1878 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1880 if ( !door )
1882 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1883 break;
1885 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1887 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1888 break;
1891 if( door->GetGoState() )
1892 break; //door already closed
1894 door->UseDoorOrButton(time_to_open);
1896 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1897 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1899 break;
1901 case SCRIPT_COMMAND_QUEST_EXPLORED:
1903 if(!source)
1905 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1906 break;
1909 if(!target)
1911 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1912 break;
1915 // when script called for item spell casting then target == (unit or GO) and source is player
1916 WorldObject* worldObject;
1917 Player* player;
1919 if(target->GetTypeId()==TYPEID_PLAYER)
1921 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1923 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1924 break;
1927 worldObject = (WorldObject*)source;
1928 player = (Player*)target;
1930 else
1932 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1934 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1935 break;
1938 if(source->GetTypeId()!=TYPEID_PLAYER)
1940 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1941 break;
1944 worldObject = (WorldObject*)target;
1945 player = (Player*)source;
1948 // quest id and flags checked at script loading
1949 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1950 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1951 player->AreaExploredOrEventHappens(step.script->datalong);
1952 else
1953 player->FailQuest(step.script->datalong);
1955 break;
1958 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1960 if(!source)
1962 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1963 break;
1966 if(!source->isType(TYPEMASK_UNIT))
1968 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1969 break;
1972 if(!target)
1974 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1975 break;
1978 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1980 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1981 break;
1984 Unit* caster = (Unit*)source;
1986 GameObject *go = (GameObject*)target;
1988 go->Use(caster);
1989 break;
1992 case SCRIPT_COMMAND_REMOVE_AURA:
1994 Object* cmdTarget = step.script->datalong2 ? source : target;
1996 if(!cmdTarget)
1998 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
1999 break;
2002 if(!cmdTarget->isType(TYPEMASK_UNIT))
2004 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2005 break;
2008 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2009 break;
2012 case SCRIPT_COMMAND_CAST_SPELL:
2014 if(!source)
2016 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2017 break;
2020 if(!source->isType(TYPEMASK_UNIT))
2022 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2023 break;
2026 Object* cmdTarget = step.script->datalong2 ? source : target;
2028 if(!cmdTarget)
2030 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2031 break;
2034 if(!cmdTarget->isType(TYPEMASK_UNIT))
2036 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2037 break;
2040 Unit* spellTarget = (Unit*)cmdTarget;
2042 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2043 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2045 break;
2048 default:
2049 sLog.outError("Unknown script command %u called.",step.script->command);
2050 break;
2053 m_scriptSchedule.erase(iter);
2055 iter = m_scriptSchedule.begin();
2057 return;
2060 /// Send a packet to all players (except self if mentioned)
2061 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2063 SessionMap::iterator itr;
2064 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2066 if (itr->second &&
2067 itr->second->GetPlayer() &&
2068 itr->second->GetPlayer()->IsInWorld() &&
2069 itr->second != self &&
2070 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2072 itr->second->SendPacket(packet);
2077 /// Send a System Message to all players (except self if mentioned)
2078 void World::SendWorldText(int32 string_id, ...)
2080 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2082 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2084 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2085 continue;
2087 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2088 uint32 cache_idx = loc_idx+1;
2090 std::vector<WorldPacket*>* data_list;
2092 // create if not cached yet
2093 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2095 if(data_cache.size() < cache_idx+1)
2096 data_cache.resize(cache_idx+1);
2098 data_list = &data_cache[cache_idx];
2100 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2102 char buf[1000];
2104 va_list argptr;
2105 va_start( argptr, string_id );
2106 vsnprintf( buf,1000, text, argptr );
2107 va_end( argptr );
2109 char* pos = &buf[0];
2111 while(char* line = ChatHandler::LineFromMessage(pos))
2113 WorldPacket* data = new WorldPacket();
2114 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2115 data_list->push_back(data);
2118 else
2119 data_list = &data_cache[cache_idx];
2121 for(int i = 0; i < data_list->size(); ++i)
2122 itr->second->SendPacket((*data_list)[i]);
2125 // free memory
2126 for(int i = 0; i < data_cache.size(); ++i)
2127 for(int j = 0; j < data_cache[i].size(); ++j)
2128 delete data_cache[i][j];
2131 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2132 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2134 SessionMap::iterator itr;
2135 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2137 if (itr->second &&
2138 itr->second->GetPlayer() &&
2139 itr->second->GetPlayer()->IsInWorld() &&
2140 itr->second->GetPlayer()->GetZoneId() == zone &&
2141 itr->second != self &&
2142 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2144 itr->second->SendPacket(packet);
2149 /// Send a System Message to all players in the zone (except self if mentioned)
2150 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2152 WorldPacket data;
2153 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2154 SendZoneMessage(zone, &data, self,team);
2157 /// Kick (and save) all players
2158 void World::KickAll()
2160 // session not removed at kick and will removed in next update tick
2161 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2162 itr->second->KickPlayer();
2165 /// Kick (and save) all players with security level less `sec`
2166 void World::KickAllLess(AccountTypes sec)
2168 // session not removed at kick and will removed in next update tick
2169 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2170 if(itr->second->GetSecurity() < sec)
2171 itr->second->KickPlayer();
2174 /// Kick all queued players
2175 void World::KickAllQueued()
2177 // session not removed at kick and will removed in next update tick
2178 //TODO here
2179 // for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2180 // if(WorldSession* session = (*itr)->GetSession())
2181 // session->KickPlayer();
2183 m_QueuedPlayer.empty();
2186 /// Kick (and save) the designated player
2187 bool World::KickPlayer(std::string playerName)
2189 SessionMap::iterator itr;
2191 // session not removed at kick and will removed in next update tick
2192 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2194 if(!itr->second)
2195 continue;
2196 Player *player = itr->second->GetPlayer();
2197 if(!player)
2198 continue;
2199 if( player->IsInWorld() )
2201 if (playerName == player->GetName())
2203 itr->second->KickPlayer();
2204 return true;
2208 return false;
2211 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2212 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2214 loginDatabase.escape_string(nameOrIP);
2215 loginDatabase.escape_string(reason);
2216 std::string safe_author=author;
2217 loginDatabase.escape_string(safe_author);
2219 uint32 duration_secs = TimeStringToSecs(duration);
2220 QueryResult *resultAccounts = NULL; //used for kicking
2222 ///- Update the database with ban information
2223 switch(mode)
2225 case BAN_IP:
2226 //No SQL injection as strings are escaped
2227 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2228 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());
2229 break;
2230 case BAN_ACCOUNT:
2231 //No SQL injection as string is escaped
2232 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2233 break;
2234 case BAN_CHARACTER:
2235 //No SQL injection as string is escaped
2236 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2237 break;
2238 default:
2239 return BAN_SYNTAX_ERROR;
2242 if(!resultAccounts)
2244 if(mode==BAN_IP)
2245 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2246 else
2247 return BAN_NOTFOUND; // Nobody to ban
2250 ///- Disconnect all affected players (for IP it can be several)
2253 Field* fieldsAccount = resultAccounts->Fetch();
2254 uint32 account = fieldsAccount->GetUInt32();
2256 if(mode!=BAN_IP)
2258 //No SQL injection as strings are escaped
2259 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2260 account,duration_secs,safe_author.c_str(),reason.c_str());
2263 if (WorldSession* sess = FindSession(account))
2264 if(std::string(sess->GetPlayerName()) != author)
2265 sess->KickPlayer();
2267 while( resultAccounts->NextRow() );
2269 delete resultAccounts;
2270 return BAN_SUCCESS;
2273 /// Remove a ban from an account or IP address
2274 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2276 if (mode == BAN_IP)
2278 loginDatabase.escape_string(nameOrIP);
2279 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2281 else
2283 uint32 account = 0;
2284 if (mode == BAN_ACCOUNT)
2285 account = accmgr.GetId (nameOrIP);
2286 else if (mode == BAN_CHARACTER)
2287 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2289 if (!account)
2290 return false;
2292 //NO SQL injection as account is uint32
2293 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2295 return true;
2298 /// Update the game time
2299 void World::_UpdateGameTime()
2301 ///- update the time
2302 time_t thisTime = time(NULL);
2303 uint32 elapsed = uint32(thisTime - m_gameTime);
2304 m_gameTime = thisTime;
2306 ///- if there is a shutdown timer
2307 if(m_ShutdownTimer > 0 && elapsed > 0)
2309 ///- ... and it is overdue, stop the world (set m_stopEvent)
2310 if( m_ShutdownTimer <= elapsed )
2312 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2313 m_stopEvent = true;
2314 else
2315 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2317 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2318 else
2320 m_ShutdownTimer -= elapsed;
2322 ShutdownMsg();
2327 /// Shutdown the server
2328 void World::ShutdownServ(uint32 time, uint32 options)
2330 m_ShutdownMask = options;
2332 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2333 if(time==0)
2335 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2336 m_stopEvent = true;
2337 else
2338 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2340 ///- Else set the shutdown timer and warn users
2341 else
2343 m_ShutdownTimer = time;
2344 ShutdownMsg(true);
2348 /// Display a shutdown message to the user(s)
2349 void World::ShutdownMsg(bool show, Player* player)
2351 // not show messages for idle shutdown mode
2352 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2353 return;
2355 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2356 if ( show ||
2357 (m_ShutdownTimer < 10) ||
2358 // < 30 sec; every 5 sec
2359 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2360 // < 5 min ; every 1 min
2361 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2362 // < 30 min ; every 5 min
2363 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2364 // < 12 h ; every 1 h
2365 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2366 // > 12 h ; every 12 h
2367 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2369 std::string str = secsToTimeString(m_ShutdownTimer);
2371 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2373 SendServerMessage(msgid,str.c_str(),player);
2374 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2378 /// Cancel a planned server shutdown
2379 void World::ShutdownCancel()
2381 if(!m_ShutdownTimer)
2382 return;
2384 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2386 m_ShutdownMask = 0;
2387 m_ShutdownTimer = 0;
2388 SendServerMessage(msgid);
2390 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2393 /// Send a server message to the user(s)
2394 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2396 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2397 data << uint32(type);
2398 if(type <= SERVER_MSG_STRING)
2399 data << text;
2401 if(player)
2402 player->GetSession()->SendPacket(&data);
2403 else
2404 SendGlobalMessage( &data );
2407 void World::UpdateSessions( time_t diff )
2409 while(!addSessQueue.empty())
2411 WorldSession* sess = addSessQueue.next ();
2412 AddSession_ (sess);
2415 ///- Delete kicked sessions at add new session
2416 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2418 RemoveQueuedPlayer (*itr);
2419 delete *itr;
2421 m_kicked_sessions.clear();
2423 ///- Then send an update signal to remaining ones
2424 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2426 next = itr;
2427 ++next;
2429 if(!itr->second)
2430 continue;
2432 ///- and remove not active sessions from the list
2433 if(!itr->second->Update(diff)) // As interval = 0
2435 delete itr->second;
2436 m_sessions.erase(itr);
2441 // This handles the issued and queued CLI commands
2442 void World::ProcessCliCommands()
2444 if (cliCmdQueue.empty())
2445 return;
2447 CliCommandHolder::Print* zprint;
2449 while (!cliCmdQueue.empty())
2451 sLog.outDebug("CLI command under processing...");
2452 CliCommandHolder *command = cliCmdQueue.next();
2454 zprint = command->m_print;
2456 CliHandler(zprint).ParseCommands(command->m_command);
2458 delete command;
2461 // print the console message here so it looks right
2462 zprint("mangos>");
2465 void World::InitResultQueue()
2467 m_resultQueue = new SqlResultQueue;
2468 CharacterDatabase.SetResultQueue(m_resultQueue);
2471 void World::UpdateResultQueue()
2473 m_resultQueue->Update();
2476 void World::UpdateRealmCharCount(uint32 accountId)
2478 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2479 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2482 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2484 if (resultCharCount)
2486 Field *fields = resultCharCount->Fetch();
2487 uint32 charCount = fields[0].GetUInt32();
2488 delete resultCharCount;
2489 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2490 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2494 void World::InitDailyQuestResetTime()
2496 time_t mostRecentQuestTime;
2498 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2499 if(result)
2501 Field *fields = result->Fetch();
2503 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2504 delete result;
2506 else
2507 mostRecentQuestTime = 0;
2509 // client built-in time for reset is 6:00 AM
2510 // FIX ME: client not show day start time
2511 time_t curTime = time(NULL);
2512 tm localTm = *localtime(&curTime);
2513 localTm.tm_hour = 6;
2514 localTm.tm_min = 0;
2515 localTm.tm_sec = 0;
2517 // current day reset time
2518 time_t curDayResetTime = mktime(&localTm);
2520 // last reset time before current moment
2521 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2523 // need reset (if we have quest time before last reset time (not processed by some reason)
2524 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2525 m_NextDailyQuestReset = mostRecentQuestTime;
2526 else
2528 // plan next reset time
2529 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2533 void World::ResetDailyQuests()
2535 sLog.outDetail("Daily quests reset for all characters.");
2536 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2537 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2538 if(itr->second->GetPlayer())
2539 itr->second->GetPlayer()->ResetDailyQuestStatus();
2542 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2544 if(limit < -SEC_ADMINISTRATOR)
2545 limit = -SEC_ADMINISTRATOR;
2547 // lock update need
2548 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2550 m_playerLimit = limit;
2552 if(db_update_need)
2553 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2556 void World::UpdateMaxSessionCounters()
2558 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2559 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2562 void World::LoadDBVersion()
2564 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2565 if(result)
2567 Field* fields = result->Fetch();
2569 m_DBVersion = fields[0].GetString();
2570 delete result;
2572 else
2573 m_DBVersion = "unknown world database";