[8191] Drop code related to use long time empty `spell_affect` table.
[getmangos.git] / src / game / World.cpp
blob0aec60ef41a3f77e7554d2c6de3ecccdb4c26b5a
1 /*
2 * Copyright (C) 2005-2009 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 "Database/DatabaseEnv.h"
25 #include "Config/ConfigEnv.h"
26 #include "SystemConfig.h"
27 #include "Log.h"
28 #include "Opcodes.h"
29 #include "WorldSession.h"
30 #include "WorldPacket.h"
31 #include "Weather.h"
32 #include "Player.h"
33 #include "Vehicle.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
41 #include "CreatureEventAIMgr.h"
42 #include "SpellMgr.h"
43 #include "Chat.h"
44 #include "DBCStores.h"
45 #include "LootMgr.h"
46 #include "ItemEnchantmentMgr.h"
47 #include "MapManager.h"
48 #include "ScriptCalls.h"
49 #include "CreatureAIRegistry.h"
50 #include "Policies/SingletonImp.h"
51 #include "BattleGroundMgr.h"
52 #include "TemporarySummon.h"
53 #include "WaypointMovementGenerator.h"
54 #include "VMapFactory.h"
55 #include "GlobalEvents.h"
56 #include "GameEventMgr.h"
57 #include "PoolHandler.h"
58 #include "Database/DatabaseImpl.h"
59 #include "GridNotifiersImpl.h"
60 #include "CellImpl.h"
61 #include "InstanceSaveMgr.h"
62 #include "WaypointManager.h"
63 #include "GMTicketMgr.h"
64 #include "Util.h"
66 INSTANTIATE_SINGLETON_1( World );
68 volatile bool World::m_stopEvent = false;
69 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
70 volatile uint32 World::m_worldLoopCounter = 0;
72 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
74 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
75 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
76 float World::m_VisibleUnitGreyDistance = 0;
77 float World::m_VisibleObjectGreyDistance = 0;
79 struct ScriptAction
81 uint64 sourceGUID;
82 uint64 targetGUID;
83 uint64 ownerGUID; // owner of source if source is item
84 ScriptInfo const* script; // pointer to static script data
87 /// World constructor
88 World::World()
90 m_playerLimit = 0;
91 m_allowMovement = true;
92 m_ShutdownMask = 0;
93 m_ShutdownTimer = 0;
94 m_gameTime=time(NULL);
95 m_startTime=m_gameTime;
96 m_maxActiveSessionCount = 0;
97 m_maxQueuedSessionCount = 0;
98 m_resultQueue = NULL;
99 m_NextDailyQuestReset = 0;
101 m_defaultDbcLocale = LOCALE_enUS;
102 m_availableDbcLocaleMask = 0;
105 /// World destructor
106 World::~World()
108 ///- Empty the kicked session set
109 while (!m_sessions.empty())
111 // not remove from queue, prevent loading new sessions
112 delete m_sessions.begin()->second;
113 m_sessions.erase(m_sessions.begin());
116 ///- Empty the WeatherMap
117 for (WeatherMap::const_iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
118 delete itr->second;
120 m_weathers.clear();
122 while (!cliCmdQueue.empty())
123 delete cliCmdQueue.next();
125 VMAP::VMapFactory::clear();
127 if(m_resultQueue) delete m_resultQueue;
129 //TODO free addSessQueue
132 /// Find a player in a specified zone
133 Player* World::FindPlayerInZone(uint32 zone)
135 ///- circle through active sessions and return the first player found in the zone
136 SessionMap::const_iterator itr;
137 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
139 if(!itr->second)
140 continue;
141 Player *player = itr->second->GetPlayer();
142 if(!player)
143 continue;
144 if( player->IsInWorld() && player->GetZoneId() == zone )
146 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
147 return player;
150 return NULL;
153 /// Find a session by its id
154 WorldSession* World::FindSession(uint32 id) const
156 SessionMap::const_iterator itr = m_sessions.find(id);
158 if(itr != m_sessions.end())
159 return itr->second; // also can return NULL for kicked session
160 else
161 return NULL;
164 /// Remove a given session
165 bool World::RemoveSession(uint32 id)
167 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
168 SessionMap::const_iterator itr = m_sessions.find(id);
170 if(itr != m_sessions.end() && itr->second)
172 if (itr->second->PlayerLoading())
173 return false;
174 itr->second->KickPlayer();
177 return true;
180 void World::AddSession(WorldSession* s)
182 addSessQueue.add(s);
185 void
186 World::AddSession_ (WorldSession* s)
188 ASSERT (s);
190 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
192 ///- kick already loaded player with same account (if any) and remove session
193 ///- if player is in loading and want to load again, return
194 if (!RemoveSession (s->GetAccountId ()))
196 s->KickPlayer ();
197 delete s; // session not added yet in session list, so not listed in queue
198 return;
201 // decrease session counts only at not reconnection case
202 bool decrease_session = true;
204 // if session already exist, prepare to it deleting at next world update
205 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
207 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
209 if(old != m_sessions.end())
211 // prevent decrease sessions count if session queued
212 if(RemoveQueuedPlayer(old->second))
213 decrease_session = false;
214 // not remove replaced session form queue if listed
215 delete old->second;
219 m_sessions[s->GetAccountId ()] = s;
221 uint32 Sessions = GetActiveAndQueuedSessionCount ();
222 uint32 pLimit = GetPlayerAmountLimit ();
223 uint32 QueueSize = GetQueueSize (); //number of players in the queue
225 //so we don't count the user trying to
226 //login as a session and queue the socket that we are using
227 if(decrease_session)
228 --Sessions;
230 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
232 AddQueuedPlayer (s);
233 UpdateMaxSessionCounters ();
234 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
235 return;
238 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
239 packet << uint8 (AUTH_OK);
240 packet << uint32 (0); // BillingTimeRemaining
241 packet << uint8 (0); // BillingPlanFlags
242 packet << uint32 (0); // BillingTimeRested
243 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
244 s->SendPacket (&packet);
246 s->SendAddonsInfo();
247 s->SendTutorialsData();
249 UpdateMaxSessionCounters ();
251 // Updates the population
252 if (pLimit > 0)
254 float popu = GetActiveSessionCount (); //updated number of users on the server
255 popu /= pLimit;
256 popu *= 2;
257 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
258 sLog.outDetail ("Server Population (%f).", popu);
262 int32 World::GetQueuePos(WorldSession* sess)
264 uint32 position = 1;
266 for(Queue::const_iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
267 if((*iter) == sess)
268 return position;
270 return 0;
273 void World::AddQueuedPlayer(WorldSession* sess)
275 sess->SetInQueue(true);
276 m_QueuedPlayer.push_back (sess);
278 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
279 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
280 packet << uint8 (AUTH_WAIT_QUEUE);
281 packet << uint32 (0); // BillingTimeRemaining
282 packet << uint8 (0); // BillingPlanFlags
283 packet << uint32 (0); // BillingTimeRested
284 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
285 packet << uint32(GetQueuePos (sess));
286 sess->SendPacket (&packet);
288 //sess->SendAuthWaitQue (GetQueuePos (sess));
291 bool World::RemoveQueuedPlayer(WorldSession* sess)
293 // sessions count including queued to remove (if removed_session set)
294 uint32 sessions = GetActiveSessionCount();
296 uint32 position = 1;
297 Queue::iterator iter = m_QueuedPlayer.begin();
299 // search to remove and count skipped positions
300 bool found = false;
302 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
304 if(*iter==sess)
306 sess->SetInQueue(false);
307 iter = m_QueuedPlayer.erase(iter);
308 found = true; // removing queued session
309 break;
313 // iter point to next socked after removed or end()
314 // position store position of removed socket and then new position next socket after removed
316 // if session not queued then we need decrease sessions count
317 if(!found && sessions)
318 --sessions;
320 // accept first in queue
321 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
323 WorldSession* pop_sess = m_QueuedPlayer.front();
324 pop_sess->SetInQueue(false);
325 pop_sess->SendAuthWaitQue(0);
326 m_QueuedPlayer.pop_front();
328 // update iter to point first queued socket or end() if queue is empty now
329 iter = m_QueuedPlayer.begin();
330 position = 1;
333 // update position from iter to end()
334 // iter point to first not updated socket, position store new position
335 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
336 (*iter)->SendAuthWaitQue(position);
338 return found;
341 /// Find a Weather object by the given zoneid
342 Weather* World::FindWeather(uint32 id) const
344 WeatherMap::const_iterator itr = m_weathers.find(id);
346 if(itr != m_weathers.end())
347 return itr->second;
348 else
349 return 0;
352 /// Remove a Weather object for the given zoneid
353 void World::RemoveWeather(uint32 id)
355 // not called at the moment. Kept for completeness
356 WeatherMap::iterator itr = m_weathers.find(id);
358 if(itr != m_weathers.end())
360 delete itr->second;
361 m_weathers.erase(itr);
365 /// Add a Weather object to the list
366 Weather* World::AddWeather(uint32 zone_id)
368 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
370 // zone not have weather, ignore
371 if(!weatherChances)
372 return NULL;
374 Weather* w = new Weather(zone_id,weatherChances);
375 m_weathers[w->GetZone()] = w;
376 w->ReGenerate();
377 w->UpdateWeather();
378 return w;
381 /// Initialize config values
382 void World::LoadConfigSettings(bool reload)
384 if(reload)
386 if(!sConfig.Reload())
388 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
389 return;
393 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
394 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
395 if(!confVersion)
397 sLog.outError("*****************************************************************************");
398 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
399 sLog.outError(" Your configuration file may be out of date!");
400 sLog.outError("*****************************************************************************");
401 clock_t pause = 3000 + clock();
402 while (pause > clock())
403 ; // empty body
405 else
407 if (confVersion < _MANGOSDCONFVERSION)
409 sLog.outError("*****************************************************************************");
410 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
411 sLog.outError(" Please check for updates, as your current default values may cause");
412 sLog.outError(" unexpected behavior.");
413 sLog.outError("*****************************************************************************");
414 clock_t pause = 3000 + clock();
415 while (pause > clock())
416 ; // empty body
420 ///- Read the player limit and the Message of the day from the config file
421 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
422 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
424 ///- Read all rates from the config file
425 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
426 if(rate_values[RATE_HEALTH] < 0)
428 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
429 rate_values[RATE_HEALTH] = 1;
431 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
432 if(rate_values[RATE_POWER_MANA] < 0)
434 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
435 rate_values[RATE_POWER_MANA] = 1;
437 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
438 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
439 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
441 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
442 rate_values[RATE_POWER_RAGE_LOSS] = 1;
444 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
445 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
446 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
448 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
449 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
451 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
452 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
453 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
454 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
455 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
456 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
457 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
458 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
459 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
460 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
461 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
462 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
463 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
464 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
465 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
466 rate_values[RATE_REPUTATION_LOWLEVEL_KILL] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f);
467 rate_values[RATE_REPUTATION_LOWLEVEL_QUEST] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f);
468 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
469 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
473 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
477 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
478 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
482 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
483 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
484 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
485 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
486 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
487 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
488 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
489 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
490 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
491 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
492 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
493 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
494 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
495 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
496 if(rate_values[RATE_TALENT] < 0.0f)
498 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
499 rate_values[RATE_TALENT] = 1.0f;
501 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
503 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
504 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
506 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
507 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
509 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
511 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
512 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
513 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
516 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
517 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
519 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
520 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
522 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
523 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
525 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
526 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
528 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
529 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
531 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
532 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
534 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
535 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
537 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
538 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
541 ///- Read other configuration items from the config file
543 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
544 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
546 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
547 m_configs[CONFIG_COMPRESSION] = 1;
549 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
550 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
551 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
553 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
554 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
556 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
557 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
559 if(reload)
560 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
562 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
563 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
565 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
566 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
568 if(reload)
569 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
571 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
573 if(reload)
575 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
576 if(val!=m_configs[CONFIG_PORT_WORLD])
577 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
579 else
580 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
582 if(reload)
584 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
585 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
586 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
588 else
589 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
591 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
592 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
593 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
594 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
596 if(reload)
598 uint32 val = sConfig.GetIntDefault("GameType", 0);
599 if(val!=m_configs[CONFIG_GAME_TYPE])
600 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
602 else
603 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
605 if(reload)
607 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
608 if(val!=m_configs[CONFIG_REALM_ZONE])
609 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
611 else
612 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
614 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
615 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
617 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
621 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
622 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
623 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
624 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
625 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
627 m_configs[CONFIG_MIN_PLAYER_NAME] = sConfig.GetIntDefault ("MinPlayerName", 2);
628 if(m_configs[CONFIG_MIN_PLAYER_NAME] < 1 || m_configs[CONFIG_MIN_PLAYER_NAME] > MAX_PLAYER_NAME)
630 sLog.outError("MinPlayerName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PLAYER_NAME],MAX_PLAYER_NAME);
631 m_configs[CONFIG_MIN_PLAYER_NAME] = 2;
634 m_configs[CONFIG_MIN_CHARTER_NAME] = sConfig.GetIntDefault ("MinCharterName", 2);
635 if(m_configs[CONFIG_MIN_CHARTER_NAME] < 1 || m_configs[CONFIG_MIN_CHARTER_NAME] > MAX_CHARTER_NAME)
637 sLog.outError("MinCharterName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_CHARTER_NAME],MAX_CHARTER_NAME);
638 m_configs[CONFIG_MIN_CHARTER_NAME] = 2;
641 m_configs[CONFIG_MIN_PET_NAME] = sConfig.GetIntDefault ("MinPetName", 2);
642 if(m_configs[CONFIG_MIN_PET_NAME] < 1 || m_configs[CONFIG_MIN_PET_NAME] > MAX_PET_NAME)
644 sLog.outError("MinPetName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PET_NAME],MAX_PET_NAME);
645 m_configs[CONFIG_MIN_PET_NAME] = 2;
648 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
650 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
651 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
653 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
654 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
657 // must be after CONFIG_CHARACTERS_PER_REALM
658 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
659 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
661 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
662 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
665 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
666 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
668 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
669 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
672 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
674 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
675 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
677 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
678 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
681 if(reload)
683 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 80);
684 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
685 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
687 else
688 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 80);
690 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
692 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
693 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
696 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
697 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
699 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]);
700 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
702 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
704 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]);
705 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
708 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
709 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
711 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
712 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
713 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
715 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
717 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
718 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
719 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
722 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
723 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
725 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
726 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
728 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
730 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
731 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
732 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
735 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
736 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
738 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
739 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
742 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
743 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
745 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
746 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
747 m_configs[CONFIG_START_HONOR_POINTS] = 0;
749 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
751 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
752 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
753 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
756 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
757 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
759 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
760 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
763 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
764 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
766 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
767 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
768 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
770 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
772 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
773 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
774 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
777 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
779 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
780 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
782 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
783 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
784 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
786 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
787 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
788 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
790 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
791 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
794 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
795 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
796 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
797 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
798 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
800 m_configs[CONFIG_GM_LEVEL_IN_GM_LIST] = sConfig.GetIntDefault("GM.InGMList.Level", SEC_ADMINISTRATOR);
801 m_configs[CONFIG_GM_LEVEL_IN_WHO_LIST] = sConfig.GetIntDefault("GM.InWhoList.Level", SEC_ADMINISTRATOR);
802 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
804 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
805 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
807 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
808 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
809 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
811 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
813 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
814 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
816 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
817 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
819 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
821 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
823 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
824 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
826 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
827 m_configs[CONFIG_UPTIME_UPDATE] = 10;
829 if(reload)
831 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
832 m_timers[WUPDATE_UPTIME].Reset();
835 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
836 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
837 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
838 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
840 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
841 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
843 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
844 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
846 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
847 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
849 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
850 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
853 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
854 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
856 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
857 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
860 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
861 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
863 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
864 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
867 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
868 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
870 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
871 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
874 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
875 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
877 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
878 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
881 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
882 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
884 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
886 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
888 if(reload)
890 uint32 val = sConfig.GetIntDefault("Expansion",1);
891 if(val!=m_configs[CONFIG_EXPANSION])
892 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
894 else
895 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
897 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
898 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
899 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
901 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
903 m_configs[CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyFleeAssistanceRadius",30);
904 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
905 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
906 m_configs[CONFIG_CREATURE_FAMILY_FLEE_DELAY] = sConfig.GetIntDefault("CreatureFamilyFleeDelay",7000);
908 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
910 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
911 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
912 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
913 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
914 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
915 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
916 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
918 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
920 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
921 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
923 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
924 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
926 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
927 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
928 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
929 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
930 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
932 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
933 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
934 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
935 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
936 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
938 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
940 // always use declined names in the russian client
941 m_configs[CONFIG_DECLINED_NAMES_USED] =
942 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
944 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
945 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
946 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
948 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
949 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
950 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
951 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
952 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
953 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
954 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
955 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
956 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
957 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
958 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
959 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
960 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
962 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
964 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
966 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
967 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
969 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
970 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
972 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
973 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
975 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
976 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
979 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
980 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
982 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
983 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
985 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
987 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
988 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
990 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
991 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
993 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
994 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
996 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
998 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
999 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1001 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Object", DEFAULT_VISIBILITY_DISTANCE);
1002 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
1004 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
1005 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
1007 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1009 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1010 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1012 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
1013 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1015 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1016 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1019 ///- Read the "Data" directory from the config file
1020 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
1021 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
1022 dataPath.append("/");
1024 if(reload)
1026 if(dataPath!=m_dataPath)
1027 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1029 else
1031 m_dataPath = dataPath;
1032 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1035 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1036 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1037 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1038 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1039 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1040 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1041 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1042 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1043 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1044 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1045 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1048 /// Initialize the World
1049 void World::SetInitialWorldSettings()
1051 ///- Initialize the random number generator
1052 srand((unsigned int)time(NULL));
1054 ///- Initialize config settings
1055 LoadConfigSettings();
1057 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1058 objmgr.SetHighestGuids();
1060 ///- Check the existence of the map files for all races' startup areas.
1061 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1062 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1063 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1064 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1065 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1066 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1067 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1068 ||m_configs[CONFIG_EXPANSION] && (
1069 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1071 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());
1072 exit(1);
1075 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1076 sLog.outString();
1077 sLog.outString("Loading MaNGOS strings...");
1078 if (!objmgr.LoadMangosStrings())
1079 exit(1); // Error message displayed in function already
1081 ///- Update the realm entry in the database with the realm type from the config file
1082 //No SQL injection as values are treated as integers
1084 // not send custom type REALM_FFA_PVP to realm list
1085 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1086 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1087 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1089 ///- Remove the bones after a restart
1090 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1092 ///- Load the DBC files
1093 sLog.outString("Initialize data stores...");
1094 LoadDBCStores(m_dataPath);
1095 DetectDBCLang();
1097 sLog.outString( "Loading Script Names...");
1098 objmgr.LoadScriptNames();
1100 sLog.outString( "Loading InstanceTemplate..." );
1101 objmgr.LoadInstanceTemplate();
1103 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1104 spellmgr.LoadSkillLineAbilityMap();
1106 ///- Clean up and pack instances
1107 sLog.outString( "Cleaning up instances..." );
1108 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1110 sLog.outString( "Packing instances..." );
1111 sInstanceSaveManager.PackInstances();
1113 sLog.outString();
1114 sLog.outString( "Loading Localization strings..." );
1115 objmgr.LoadCreatureLocales();
1116 objmgr.LoadGameObjectLocales();
1117 objmgr.LoadItemLocales();
1118 objmgr.LoadQuestLocales();
1119 objmgr.LoadNpcTextLocales();
1120 objmgr.LoadPageTextLocales();
1121 objmgr.LoadNpcOptionLocales();
1122 objmgr.LoadPointOfInterestLocales();
1123 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1124 sLog.outString( ">>> Localization strings loaded" );
1125 sLog.outString();
1127 sLog.outString( "Loading Page Texts..." );
1128 objmgr.LoadPageTexts();
1130 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1131 objmgr.LoadGameobjectInfo();
1133 sLog.outString( "Loading Spell Chain Data..." );
1134 spellmgr.LoadSpellChains();
1136 sLog.outString( "Loading Spell Elixir types..." );
1137 spellmgr.LoadSpellElixirs();
1139 sLog.outString( "Loading Spell Learn Skills..." );
1140 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1142 sLog.outString( "Loading Spell Learn Spells..." );
1143 spellmgr.LoadSpellLearnSpells();
1145 sLog.outString( "Loading Spell Proc Event conditions..." );
1146 spellmgr.LoadSpellProcEvents();
1148 sLog.outString( "Loading Spell Bonus Data..." );
1149 spellmgr.LoadSpellBonusess();
1151 sLog.outString( "Loading Aggro Spells Definitions...");
1152 spellmgr.LoadSpellThreats();
1154 sLog.outString( "Loading NPC Texts..." );
1155 objmgr.LoadGossipText();
1157 sLog.outString( "Loading Item Random Enchantments Table..." );
1158 LoadRandomEnchantmentsTable();
1160 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1161 objmgr.LoadItemPrototypes();
1163 sLog.outString( "Loading Item Texts..." );
1164 objmgr.LoadItemTexts();
1166 sLog.outString( "Loading Creature Model Based Info Data..." );
1167 objmgr.LoadCreatureModelInfo();
1169 sLog.outString( "Loading Equipment templates...");
1170 objmgr.LoadEquipmentTemplates();
1172 sLog.outString( "Loading Creature templates..." );
1173 objmgr.LoadCreatureTemplates();
1175 sLog.outString( "Loading SpellsScriptTarget...");
1176 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1178 sLog.outString( "Loading ItemRequiredTarget...");
1179 objmgr.LoadItemRequiredTarget();
1181 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1182 objmgr.LoadReputationOnKill();
1184 sLog.outString( "Loading Points Of Interest Data..." );
1185 objmgr.LoadPointsOfInterest();
1187 sLog.outString( "Loading Creature Data..." );
1188 objmgr.LoadCreatures();
1190 sLog.outString( "Loading pet levelup spells..." );
1191 spellmgr.LoadPetLevelupSpellMap();
1193 sLog.outString( "Loading pet default spell additional to levelup spells..." );
1194 spellmgr.LoadPetDefaultSpells();
1196 sLog.outString( "Loading Creature Addon Data..." );
1197 sLog.outString();
1198 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1199 sLog.outString( ">>> Creature Addon Data loaded" );
1200 sLog.outString();
1202 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1203 objmgr.LoadCreatureRespawnTimes();
1205 sLog.outString( "Loading Gameobject Data..." );
1206 objmgr.LoadGameobjects();
1208 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1209 objmgr.LoadGameobjectRespawnTimes();
1211 sLog.outString( "Loading Objects Pooling Data...");
1212 poolhandler.LoadFromDB();
1214 sLog.outString( "Loading Game Event Data...");
1215 sLog.outString();
1216 gameeventmgr.LoadFromDB();
1217 sLog.outString( ">>> Game Event Data loaded" );
1218 sLog.outString();
1220 sLog.outString( "Loading Weather Data..." );
1221 objmgr.LoadWeatherZoneChances();
1223 sLog.outString( "Loading Quests..." );
1224 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1226 sLog.outString( "Loading Quests Relations..." );
1227 sLog.outString();
1228 objmgr.LoadQuestRelations(); // must be after quest load
1229 sLog.outString( ">>> Quests Relations loaded" );
1230 sLog.outString();
1232 sLog.outString( "Loading UNIT_NPC_FLAG_SPELLCLICK Data..." );
1233 objmgr.LoadNPCSpellClickSpells();
1235 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1236 spellmgr.LoadSpellAreas();
1238 sLog.outString( "Loading AreaTrigger definitions..." );
1239 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1241 sLog.outString( "Loading Quest Area Triggers..." );
1242 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1244 sLog.outString( "Loading Tavern Area Triggers..." );
1245 objmgr.LoadTavernAreaTriggers();
1247 sLog.outString( "Loading AreaTrigger script names..." );
1248 objmgr.LoadAreaTriggerScripts();
1250 sLog.outString( "Loading Graveyard-zone links...");
1251 objmgr.LoadGraveyardZones();
1253 sLog.outString( "Loading Spell target coordinates..." );
1254 spellmgr.LoadSpellTargetPositions();
1256 sLog.outString( "Loading spell pet auras..." );
1257 spellmgr.LoadSpellPetAuras();
1259 sLog.outString( "Loading Player Create Info & Level Stats..." );
1260 sLog.outString();
1261 objmgr.LoadPlayerInfo();
1262 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1263 sLog.outString();
1265 sLog.outString( "Loading Exploration BaseXP Data..." );
1266 objmgr.LoadExplorationBaseXP();
1268 sLog.outString( "Loading Pet Name Parts..." );
1269 objmgr.LoadPetNames();
1271 sLog.outString( "Loading the max pet number..." );
1272 objmgr.LoadPetNumber();
1274 sLog.outString( "Loading pet level stats..." );
1275 objmgr.LoadPetLevelInfo();
1277 sLog.outString( "Loading Player Corpses..." );
1278 objmgr.LoadCorpses();
1280 sLog.outString( "Loading Loot Tables..." );
1281 sLog.outString();
1282 LoadLootTables();
1283 sLog.outString( ">>> Loot Tables loaded" );
1284 sLog.outString();
1286 sLog.outString( "Loading Skill Discovery Table..." );
1287 LoadSkillDiscoveryTable();
1289 sLog.outString( "Loading Skill Extra Item Table..." );
1290 LoadSkillExtraItemTable();
1292 sLog.outString( "Loading Skill Fishing base level requirements..." );
1293 objmgr.LoadFishingBaseSkillLevel();
1295 sLog.outString( "Loading Achievements..." );
1296 sLog.outString();
1297 achievementmgr.LoadAchievementReferenceList();
1298 achievementmgr.LoadAchievementCriteriaList();
1299 achievementmgr.LoadAchievementCriteriaData();
1300 achievementmgr.LoadRewards();
1301 achievementmgr.LoadRewardLocales();
1302 achievementmgr.LoadCompletedAchievements();
1303 sLog.outString( ">>> Achievements loaded" );
1304 sLog.outString();
1306 ///- Load dynamic data tables from the database
1307 sLog.outString( "Loading Auctions..." );
1308 sLog.outString();
1309 auctionmgr.LoadAuctionItems();
1310 auctionmgr.LoadAuctions();
1311 sLog.outString( ">>> Auctions loaded" );
1312 sLog.outString();
1314 sLog.outString( "Loading Guilds..." );
1315 objmgr.LoadGuilds();
1317 sLog.outString( "Loading ArenaTeams..." );
1318 objmgr.LoadArenaTeams();
1320 sLog.outString( "Loading Groups..." );
1321 objmgr.LoadGroups();
1323 sLog.outString( "Loading ReservedNames..." );
1324 objmgr.LoadReservedPlayersNames();
1326 sLog.outString( "Loading GameObjects for quests..." );
1327 objmgr.LoadGameObjectForQuests();
1329 sLog.outString( "Loading BattleMasters..." );
1330 sBattleGroundMgr.LoadBattleMastersEntry();
1332 sLog.outString( "Loading GameTeleports..." );
1333 objmgr.LoadGameTele();
1335 sLog.outString( "Loading Npc Text Id..." );
1336 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1338 sLog.outString( "Loading Npc Options..." );
1339 objmgr.LoadNpcOptions();
1341 sLog.outString( "Loading Vendors..." );
1342 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1344 sLog.outString( "Loading Trainers..." );
1345 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1347 sLog.outString( "Loading Waypoints..." );
1348 sLog.outString();
1349 WaypointMgr.Load();
1351 sLog.outString( "Loading GM tickets...");
1352 ticketmgr.LoadGMTickets();
1354 ///- Handle outdated emails (delete/return)
1355 sLog.outString( "Returning old mails..." );
1356 objmgr.ReturnOrDeleteOldMails(false);
1358 ///- Load and initialize scripts
1359 sLog.outString( "Loading Scripts..." );
1360 sLog.outString();
1361 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1362 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1363 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1364 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1365 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1366 sLog.outString( ">>> Scripts loaded" );
1367 sLog.outString();
1369 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1370 objmgr.LoadDbScriptStrings();
1372 sLog.outString( "Loading CreatureEventAI Texts...");
1373 CreatureEAI_Mgr.LoadCreatureEventAI_Texts();
1375 sLog.outString( "Loading CreatureEventAI Summons...");
1376 CreatureEAI_Mgr.LoadCreatureEventAI_Summons();
1378 sLog.outString( "Loading CreatureEventAI Scripts...");
1379 CreatureEAI_Mgr.LoadCreatureEventAI_Scripts();
1381 sLog.outString( "Initializing Scripts..." );
1382 if(!LoadScriptingModule())
1383 exit(1);
1385 ///- Initialize game time and timers
1386 sLog.outString( "DEBUG:: Initialize game time and timers" );
1387 m_gameTime = time(NULL);
1388 m_startTime=m_gameTime;
1390 tm local;
1391 time_t curr;
1392 time(&curr);
1393 local=*(localtime(&curr)); // dereference and assign
1394 char isoDate[128];
1395 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1396 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1398 loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " UI64FMTD ", '%s', 0)",
1399 realmID, uint64(m_startTime), isoDate);
1401 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1402 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1403 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1404 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1405 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1406 //Update "uptime" table based on configuration entry in minutes.
1407 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1408 //erase corpses every 20 minutes
1410 //to set mailtimer to return mails every day between 4 and 5 am
1411 //mailtimer is increased when updating auctions
1412 //one second is 1000 -(tested on win system)
1413 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1414 //1440
1415 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1416 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1418 ///- Initilize static helper structures
1419 AIRegistry::Initialize();
1420 WaypointMovementGenerator<Creature>::Initialize();
1421 Player::InitVisibleBits();
1423 ///- Initialize MapManager
1424 sLog.outString( "Starting Map System" );
1425 MapManager::Instance().Initialize();
1427 ///- Initialize Battlegrounds
1428 sLog.outString( "Starting BattleGround System" );
1429 sBattleGroundMgr.CreateInitialBattleGrounds();
1430 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1432 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1433 sLog.outString( "Loading Transports..." );
1434 MapManager::Instance().LoadTransports();
1436 sLog.outString("Deleting expired bans..." );
1437 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1439 sLog.outString("Calculate next daily quest reset time..." );
1440 InitDailyQuestResetTime();
1442 sLog.outString("Starting objects Pooling system..." );
1443 poolhandler.Initialize();
1445 sLog.outString("Starting Game Event system..." );
1446 uint32 nextGameEvent = gameeventmgr.Initialize();
1447 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1449 sLog.outString( "WORLD: World initialized" );
1452 void World::DetectDBCLang()
1454 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1456 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1458 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1459 m_lang_confid = LOCALE_enUS;
1462 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1464 std::string availableLocalsStr;
1466 int default_locale = MAX_LOCALE;
1467 for (int i = MAX_LOCALE-1; i >= 0; --i)
1469 if ( strlen(race->name[i]) > 0) // check by race names
1471 default_locale = i;
1472 m_availableDbcLocaleMask |= (1 << i);
1473 availableLocalsStr += localeNames[i];
1474 availableLocalsStr += " ";
1478 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1479 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1481 default_locale = m_lang_confid;
1484 if(default_locale >= MAX_LOCALE)
1486 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1487 exit(1);
1490 m_defaultDbcLocale = LocaleConstant(default_locale);
1492 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1493 sLog.outString();
1496 /// Update the World !
1497 void World::Update(uint32 diff)
1499 ///- Update the different timers
1500 for(int i = 0; i < WUPDATE_COUNT; ++i)
1501 if(m_timers[i].GetCurrent()>=0)
1502 m_timers[i].Update(diff);
1503 else m_timers[i].SetCurrent(0);
1505 ///- Update the game time and check for shutdown time
1506 _UpdateGameTime();
1508 /// Handle daily quests reset time
1509 if(m_gameTime > m_NextDailyQuestReset)
1511 ResetDailyQuests();
1512 m_NextDailyQuestReset += DAY;
1515 /// <ul><li> Handle auctions when the timer has passed
1516 if (m_timers[WUPDATE_AUCTIONS].Passed())
1518 m_timers[WUPDATE_AUCTIONS].Reset();
1520 ///- Update mails (return old mails with item, or delete them)
1521 //(tested... works on win)
1522 if (++mail_timer > mail_timer_expires)
1524 mail_timer = 0;
1525 objmgr.ReturnOrDeleteOldMails(true);
1528 ///- Handle expired auctions
1529 auctionmgr.Update();
1532 /// <li> Handle session updates when the timer has passed
1533 if (m_timers[WUPDATE_SESSIONS].Passed())
1535 m_timers[WUPDATE_SESSIONS].Reset();
1537 UpdateSessions(diff);
1540 /// <li> Handle weather updates when the timer has passed
1541 if (m_timers[WUPDATE_WEATHERS].Passed())
1543 m_timers[WUPDATE_WEATHERS].Reset();
1545 ///- Send an update signal to Weather objects
1546 WeatherMap::iterator itr, next;
1547 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1549 next = itr;
1550 ++next;
1552 ///- and remove Weather objects for zones with no player
1553 //As interval > WorldTick
1554 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1556 delete itr->second;
1557 m_weathers.erase(itr);
1561 /// <li> Update uptime table
1562 if (m_timers[WUPDATE_UPTIME].Passed())
1564 uint32 tmpDiff = (m_gameTime - m_startTime);
1565 uint32 maxClientsNum = GetMaxActiveSessionCount();
1567 m_timers[WUPDATE_UPTIME].Reset();
1568 loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
1571 /// <li> Handle all other objects
1572 if (m_timers[WUPDATE_OBJECTS].Passed())
1574 m_timers[WUPDATE_OBJECTS].Reset();
1575 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1576 MapManager::Instance().Update(diff); // As interval = 0
1578 ///- Process necessary scripts
1579 if (!m_scriptSchedule.empty())
1580 ScriptsProcess();
1582 sBattleGroundMgr.Update(diff);
1585 // execute callbacks from sql queries that were queued recently
1586 UpdateResultQueue();
1588 ///- Erase corpses once every 20 minutes
1589 if (m_timers[WUPDATE_CORPSES].Passed())
1591 m_timers[WUPDATE_CORPSES].Reset();
1593 CorpsesErase();
1596 ///- Process Game events when necessary
1597 if (m_timers[WUPDATE_EVENTS].Passed())
1599 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1600 uint32 nextGameEvent = gameeventmgr.Update();
1601 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1602 m_timers[WUPDATE_EVENTS].Reset();
1605 /// </ul>
1606 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1607 MapManager::Instance().DoDelayedMovesAndRemoves();
1609 // update the instance reset times
1610 sInstanceSaveManager.Update();
1612 // And last, but not least handle the issued cli commands
1613 ProcessCliCommands();
1616 /// Put scripts in the execution queue
1617 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1619 ///- Find the script map
1620 ScriptMapMap::const_iterator s = scripts.find(id);
1621 if (s == scripts.end())
1622 return;
1624 // prepare static data
1625 uint64 sourceGUID = source->GetGUID();
1626 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1627 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1629 ///- Schedule script execution for all scripts in the script map
1630 ScriptMap const *s2 = &(s->second);
1631 bool immedScript = false;
1632 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1634 ScriptAction sa;
1635 sa.sourceGUID = sourceGUID;
1636 sa.targetGUID = targetGUID;
1637 sa.ownerGUID = ownerGUID;
1639 sa.script = &iter->second;
1640 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1641 if (iter->first == 0)
1642 immedScript = true;
1644 ///- If one of the effects should be immediate, launch the script execution
1645 if (immedScript)
1646 ScriptsProcess();
1649 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1651 // NOTE: script record _must_ exist until command executed
1653 // prepare static data
1654 uint64 sourceGUID = source->GetGUID();
1655 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1656 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1658 ScriptAction sa;
1659 sa.sourceGUID = sourceGUID;
1660 sa.targetGUID = targetGUID;
1661 sa.ownerGUID = ownerGUID;
1663 sa.script = &script;
1664 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1666 ///- If effects should be immediate, launch the script execution
1667 if(delay == 0)
1668 ScriptsProcess();
1671 /// Process queued scripts
1672 void World::ScriptsProcess()
1674 if (m_scriptSchedule.empty())
1675 return;
1677 ///- Process overdue queued scripts
1678 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1679 // ok as multimap is a *sorted* associative container
1680 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1682 ScriptAction const& step = iter->second;
1684 Object* source = NULL;
1686 if(step.sourceGUID)
1688 switch(GUID_HIPART(step.sourceGUID))
1690 case HIGHGUID_ITEM:
1691 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1693 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1694 if(player)
1695 source = player->GetItemByGuid(step.sourceGUID);
1696 break;
1698 case HIGHGUID_UNIT:
1699 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1700 break;
1701 case HIGHGUID_PET:
1702 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1703 break;
1704 case HIGHGUID_VEHICLE:
1705 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
1706 break;
1707 case HIGHGUID_PLAYER:
1708 source = HashMapHolder<Player>::Find(step.sourceGUID);
1709 break;
1710 case HIGHGUID_GAMEOBJECT:
1711 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1712 break;
1713 case HIGHGUID_CORPSE:
1714 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1715 break;
1716 default:
1717 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1718 break;
1722 if(source && !source->IsInWorld()) source = NULL;
1724 Object* target = NULL;
1726 if(step.targetGUID)
1728 switch(GUID_HIPART(step.targetGUID))
1730 case HIGHGUID_UNIT:
1731 target = HashMapHolder<Creature>::Find(step.targetGUID);
1732 break;
1733 case HIGHGUID_PET:
1734 target = HashMapHolder<Pet>::Find(step.targetGUID);
1735 break;
1736 case HIGHGUID_VEHICLE:
1737 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
1738 break;
1739 case HIGHGUID_PLAYER: // empty GUID case also
1740 target = HashMapHolder<Player>::Find(step.targetGUID);
1741 break;
1742 case HIGHGUID_GAMEOBJECT:
1743 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1744 break;
1745 case HIGHGUID_CORPSE:
1746 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1747 break;
1748 default:
1749 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1750 break;
1754 if(target && !target->IsInWorld()) target = NULL;
1756 switch (step.script->command)
1758 case SCRIPT_COMMAND_TALK:
1760 if(!source)
1762 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1763 break;
1766 if(source->GetTypeId()!=TYPEID_UNIT)
1768 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1769 break;
1772 uint64 unit_target = target ? target->GetGUID() : 0;
1774 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1775 switch(step.script->datalong)
1777 case 0: // Say
1778 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1779 break;
1780 case 1: // Whisper
1781 if(!unit_target)
1783 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1784 break;
1786 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1787 break;
1788 case 2: // Yell
1789 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1790 break;
1791 case 3: // Emote text
1792 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1793 break;
1794 default:
1795 break; // must be already checked at load
1797 break;
1800 case SCRIPT_COMMAND_EMOTE:
1801 if(!source)
1803 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1804 break;
1807 if(source->GetTypeId()!=TYPEID_UNIT)
1809 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1810 break;
1813 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1814 break;
1815 case SCRIPT_COMMAND_FIELD_SET:
1816 if(!source)
1818 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1819 break;
1821 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1823 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1824 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1825 break;
1828 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1829 break;
1830 case SCRIPT_COMMAND_MOVE_TO:
1831 if(!source)
1833 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1834 break;
1837 if(source->GetTypeId()!=TYPEID_UNIT)
1839 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1840 break;
1842 ((Creature*)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
1843 ((Creature*)source)->GetMap()->CreatureRelocation(((Creature*)source), step.script->x, step.script->y, step.script->z, 0);
1844 break;
1845 case SCRIPT_COMMAND_FLAG_SET:
1846 if(!source)
1848 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1849 break;
1851 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1853 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1854 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1855 break;
1858 source->SetFlag(step.script->datalong, step.script->datalong2);
1859 break;
1860 case SCRIPT_COMMAND_FLAG_REMOVE:
1861 if(!source)
1863 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1864 break;
1866 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1868 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1869 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1870 break;
1873 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1874 break;
1876 case SCRIPT_COMMAND_TELEPORT_TO:
1878 // accept player in any one from target/source arg
1879 if (!target && !source)
1881 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1882 break;
1885 // must be only Player
1886 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1888 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1889 break;
1892 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1894 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1895 break;
1898 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1900 if(!step.script->datalong) // creature not specified
1902 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1903 break;
1906 if(!source)
1908 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1909 break;
1912 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1914 if(!summoner)
1916 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1917 break;
1920 float x = step.script->x;
1921 float y = step.script->y;
1922 float z = step.script->z;
1923 float o = step.script->o;
1925 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1926 if (!pCreature)
1928 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1929 break;
1932 break;
1935 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1937 if(!step.script->datalong) // gameobject not specified
1939 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1940 break;
1943 if(!source)
1945 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1946 break;
1949 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1951 if(!summoner)
1953 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1954 break;
1957 GameObject *go = NULL;
1958 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1960 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1961 Cell cell(p);
1962 cell.data.Part.reserved = ALL_DISTRICT;
1964 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1965 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
1967 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1968 CellLock<GridReadGuard> cell_lock(cell, p);
1969 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1971 if ( !go )
1973 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1974 break;
1977 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1978 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1979 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1980 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1982 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1983 break;
1986 if( go->isSpawned() )
1987 break; //gameobject already spawned
1989 go->SetLootState(GO_READY);
1990 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1992 go->GetMap()->Add(go);
1993 break;
1995 case SCRIPT_COMMAND_OPEN_DOOR:
1997 if(!step.script->datalong) // door not specified
1999 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
2000 break;
2003 if(!source)
2005 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
2006 break;
2009 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2011 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2012 break;
2015 Unit* caster = (Unit*)source;
2017 GameObject *door = NULL;
2018 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2020 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2021 Cell cell(p);
2022 cell.data.Part.reserved = ALL_DISTRICT;
2024 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2025 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2027 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2028 CellLock<GridReadGuard> cell_lock(cell, p);
2029 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2031 if (!door)
2033 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2034 break;
2036 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
2038 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2039 break;
2042 if (door->GetGoState() != GO_STATE_READY)
2043 break; //door already open
2045 door->UseDoorOrButton(time_to_close);
2047 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2048 ((GameObject*)target)->UseDoorOrButton(time_to_close);
2049 break;
2051 case SCRIPT_COMMAND_CLOSE_DOOR:
2053 if(!step.script->datalong) // guid for door not specified
2055 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2056 break;
2059 if(!source)
2061 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2062 break;
2065 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2067 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2068 break;
2071 Unit* caster = (Unit*)source;
2073 GameObject *door = NULL;
2074 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2076 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2077 Cell cell(p);
2078 cell.data.Part.reserved = ALL_DISTRICT;
2080 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2081 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2083 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2084 CellLock<GridReadGuard> cell_lock(cell, p);
2085 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2087 if ( !door )
2089 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2090 break;
2092 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2094 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2095 break;
2098 if( door->GetGoState() == GO_STATE_READY )
2099 break; //door already closed
2101 door->UseDoorOrButton(time_to_open);
2103 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2104 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2106 break;
2108 case SCRIPT_COMMAND_QUEST_EXPLORED:
2110 if(!source)
2112 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2113 break;
2116 if(!target)
2118 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2119 break;
2122 // when script called for item spell casting then target == (unit or GO) and source is player
2123 WorldObject* worldObject;
2124 Player* player;
2126 if(target->GetTypeId()==TYPEID_PLAYER)
2128 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2130 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2131 break;
2134 worldObject = (WorldObject*)source;
2135 player = (Player*)target;
2137 else
2139 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2141 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2142 break;
2145 if(source->GetTypeId()!=TYPEID_PLAYER)
2147 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2148 break;
2151 worldObject = (WorldObject*)target;
2152 player = (Player*)source;
2155 // quest id and flags checked at script loading
2156 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2157 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2158 player->AreaExploredOrEventHappens(step.script->datalong);
2159 else
2160 player->FailQuest(step.script->datalong);
2162 break;
2165 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2167 if(!source)
2169 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2170 break;
2173 if(!source->isType(TYPEMASK_UNIT))
2175 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2176 break;
2179 if(!target)
2181 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2182 break;
2185 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2187 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2188 break;
2191 Unit* caster = (Unit*)source;
2193 GameObject *go = (GameObject*)target;
2195 go->Use(caster);
2196 break;
2199 case SCRIPT_COMMAND_REMOVE_AURA:
2201 Object* cmdTarget = step.script->datalong2 ? source : target;
2203 if(!cmdTarget)
2205 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2206 break;
2209 if(!cmdTarget->isType(TYPEMASK_UNIT))
2211 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2212 break;
2215 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2216 break;
2219 case SCRIPT_COMMAND_CAST_SPELL:
2221 if(!source)
2223 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2224 break;
2227 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
2229 if(!cmdTarget)
2231 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
2232 break;
2235 if(!cmdTarget->isType(TYPEMASK_UNIT))
2237 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
2238 break;
2241 Unit* spellTarget = (Unit*)cmdTarget;
2243 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
2245 if(!cmdSource)
2247 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
2248 break;
2251 if(!cmdSource->isType(TYPEMASK_UNIT))
2253 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
2254 break;
2257 Unit* spellSource = (Unit*)cmdSource;
2259 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2260 spellSource->CastSpell(spellTarget,step.script->datalong,false);
2262 break;
2265 case SCRIPT_COMMAND_PLAY_SOUND:
2267 if(!source)
2269 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
2270 break;
2273 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
2274 if(!pSource)
2276 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
2277 break;
2280 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2281 Player* pTarget = NULL;
2282 if(step.script->datalong2 & 1)
2284 if(!target)
2286 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
2287 break;
2290 if(target->GetTypeId()!=TYPEID_PLAYER)
2292 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
2293 break;
2296 pTarget = (Player*)target;
2299 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2300 if(step.script->datalong2 & 2)
2301 pSource->PlayDistanceSound(step.script->datalong,pTarget);
2302 else
2303 pSource->PlayDirectSound(step.script->datalong,pTarget);
2304 break;
2306 default:
2307 sLog.outError("Unknown script command %u called.",step.script->command);
2308 break;
2311 m_scriptSchedule.erase(iter);
2313 iter = m_scriptSchedule.begin();
2315 return;
2318 /// Send a packet to all players (except self if mentioned)
2319 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2321 SessionMap::const_iterator itr;
2322 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2324 if (itr->second &&
2325 itr->second->GetPlayer() &&
2326 itr->second->GetPlayer()->IsInWorld() &&
2327 itr->second != self &&
2328 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2330 itr->second->SendPacket(packet);
2335 namespace MaNGOS
2337 class WorldWorldTextBuilder
2339 public:
2340 typedef std::vector<WorldPacket*> WorldPacketList;
2341 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
2342 void operator()(WorldPacketList& data_list, int32 loc_idx)
2344 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
2346 if(i_args)
2348 // we need copy va_list before use or original va_list will corrupted
2349 va_list ap;
2350 va_copy(ap,*i_args);
2352 char str [2048];
2353 vsnprintf(str,2048,text, ap );
2354 va_end(ap);
2356 do_helper(data_list,&str[0]);
2358 else
2359 do_helper(data_list,(char*)text);
2361 private:
2362 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
2363 void do_helper(WorldPacketList& data_list, char* text)
2365 char* pos = text;
2367 while(char* line = lineFromMessage(pos))
2369 WorldPacket* data = new WorldPacket();
2371 uint32 lineLength = (line ? strlen(line) : 0) + 1;
2373 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
2374 *data << uint8(CHAT_MSG_SYSTEM);
2375 *data << uint32(LANG_UNIVERSAL);
2376 *data << uint64(0);
2377 *data << uint32(0); // can be chat msg group or something
2378 *data << uint64(0);
2379 *data << uint32(lineLength);
2380 *data << line;
2381 *data << uint8(0);
2383 data_list.push_back(data);
2387 int32 i_textId;
2388 va_list* i_args;
2390 } // namespace MaNGOS
2392 /// Send a System Message to all players (except self if mentioned)
2393 void World::SendWorldText(int32 string_id, ...)
2395 va_list ap;
2396 va_start(ap, string_id);
2398 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
2399 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
2400 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2402 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2403 continue;
2405 wt_do(itr->second->GetPlayer());
2408 va_end(ap);
2411 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2412 void World::SendGlobalText(const char* text, WorldSession *self)
2414 WorldPacket data;
2416 // need copy to prevent corruption by strtok call in LineFromMessage original string
2417 char* buf = strdup(text);
2418 char* pos = buf;
2420 while(char* line = ChatHandler::LineFromMessage(pos))
2422 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2423 SendGlobalMessage(&data, self);
2426 free(buf);
2429 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2430 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2432 SessionMap::const_iterator itr;
2433 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2435 if (itr->second &&
2436 itr->second->GetPlayer() &&
2437 itr->second->GetPlayer()->IsInWorld() &&
2438 itr->second->GetPlayer()->GetZoneId() == zone &&
2439 itr->second != self &&
2440 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2442 itr->second->SendPacket(packet);
2447 /// Send a System Message to all players in the zone (except self if mentioned)
2448 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2450 WorldPacket data;
2451 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2452 SendZoneMessage(zone, &data, self,team);
2455 /// Kick (and save) all players
2456 void World::KickAll()
2458 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2460 // session not removed at kick and will removed in next update tick
2461 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2462 itr->second->KickPlayer();
2465 /// Kick (and save) all players with security level less `sec`
2466 void World::KickAllLess(AccountTypes sec)
2468 // session not removed at kick and will removed in next update tick
2469 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2470 if(itr->second->GetSecurity() < sec)
2471 itr->second->KickPlayer();
2474 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2475 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2477 loginDatabase.escape_string(nameOrIP);
2478 loginDatabase.escape_string(reason);
2479 std::string safe_author=author;
2480 loginDatabase.escape_string(safe_author);
2482 uint32 duration_secs = TimeStringToSecs(duration);
2483 QueryResult *resultAccounts = NULL; //used for kicking
2485 ///- Update the database with ban information
2486 switch(mode)
2488 case BAN_IP:
2489 //No SQL injection as strings are escaped
2490 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2491 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());
2492 break;
2493 case BAN_ACCOUNT:
2494 //No SQL injection as string is escaped
2495 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2496 break;
2497 case BAN_CHARACTER:
2498 //No SQL injection as string is escaped
2499 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2500 break;
2501 default:
2502 return BAN_SYNTAX_ERROR;
2505 if(!resultAccounts)
2507 if(mode==BAN_IP)
2508 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2509 else
2510 return BAN_NOTFOUND; // Nobody to ban
2513 ///- Disconnect all affected players (for IP it can be several)
2516 Field* fieldsAccount = resultAccounts->Fetch();
2517 uint32 account = fieldsAccount->GetUInt32();
2519 if(mode!=BAN_IP)
2521 //No SQL injection as strings are escaped
2522 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2523 account,duration_secs,safe_author.c_str(),reason.c_str());
2526 if (WorldSession* sess = FindSession(account))
2527 if(std::string(sess->GetPlayerName()) != author)
2528 sess->KickPlayer();
2530 while( resultAccounts->NextRow() );
2532 delete resultAccounts;
2533 return BAN_SUCCESS;
2536 /// Remove a ban from an account or IP address
2537 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2539 if (mode == BAN_IP)
2541 loginDatabase.escape_string(nameOrIP);
2542 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2544 else
2546 uint32 account = 0;
2547 if (mode == BAN_ACCOUNT)
2548 account = accmgr.GetId (nameOrIP);
2549 else if (mode == BAN_CHARACTER)
2550 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2552 if (!account)
2553 return false;
2555 //NO SQL injection as account is uint32
2556 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2558 return true;
2561 /// Update the game time
2562 void World::_UpdateGameTime()
2564 ///- update the time
2565 time_t thisTime = time(NULL);
2566 uint32 elapsed = uint32(thisTime - m_gameTime);
2567 m_gameTime = thisTime;
2569 ///- if there is a shutdown timer
2570 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2572 ///- ... and it is overdue, stop the world (set m_stopEvent)
2573 if( m_ShutdownTimer <= elapsed )
2575 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2576 m_stopEvent = true; // exist code already set
2577 else
2578 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2580 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2581 else
2583 m_ShutdownTimer -= elapsed;
2585 ShutdownMsg();
2590 /// Shutdown the server
2591 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2593 // ignore if server shutdown at next tick
2594 if(m_stopEvent)
2595 return;
2597 m_ShutdownMask = options;
2598 m_ExitCode = exitcode;
2600 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2601 if(time==0)
2603 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2604 m_stopEvent = true; // exist code already set
2605 else
2606 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2608 ///- Else set the shutdown timer and warn users
2609 else
2611 m_ShutdownTimer = time;
2612 ShutdownMsg(true);
2616 /// Display a shutdown message to the user(s)
2617 void World::ShutdownMsg(bool show, Player* player)
2619 // not show messages for idle shutdown mode
2620 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2621 return;
2623 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2624 if ( show ||
2625 (m_ShutdownTimer < 10) ||
2626 // < 30 sec; every 5 sec
2627 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2628 // < 5 min ; every 1 min
2629 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2630 // < 30 min ; every 5 min
2631 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2632 // < 12 h ; every 1 h
2633 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2634 // > 12 h ; every 12 h
2635 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2637 std::string str = secsToTimeString(m_ShutdownTimer);
2639 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2641 SendServerMessage(msgid,str.c_str(),player);
2642 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2646 /// Cancel a planned server shutdown
2647 void World::ShutdownCancel()
2649 // nothing cancel or too later
2650 if(!m_ShutdownTimer || m_stopEvent)
2651 return;
2653 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2655 m_ShutdownMask = 0;
2656 m_ShutdownTimer = 0;
2657 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2658 SendServerMessage(msgid);
2660 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2663 /// Send a server message to the user(s)
2664 void World::SendServerMessage(ServerMessageType type, const char *text, Player* player)
2666 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2667 data << uint32(type);
2668 if(type <= SERVER_MSG_STRING)
2669 data << text;
2671 if(player)
2672 player->GetSession()->SendPacket(&data);
2673 else
2674 SendGlobalMessage( &data );
2677 void World::UpdateSessions( uint32 diff )
2679 ///- Add new sessions
2680 while(!addSessQueue.empty())
2682 WorldSession* sess = addSessQueue.next ();
2683 AddSession_ (sess);
2686 ///- Then send an update signal to remaining ones
2687 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2689 next = itr;
2690 ++next;
2692 if(!itr->second)
2693 continue;
2695 ///- and remove not active sessions from the list
2696 if(!itr->second->Update(diff)) // As interval = 0
2698 RemoveQueuedPlayer (itr->second);
2699 delete itr->second;
2700 m_sessions.erase(itr);
2705 // This handles the issued and queued CLI commands
2706 void World::ProcessCliCommands()
2708 if (cliCmdQueue.empty())
2709 return;
2711 CliCommandHolder::Print* zprint;
2713 while (!cliCmdQueue.empty())
2715 sLog.outDebug("CLI command under processing...");
2716 CliCommandHolder *command = cliCmdQueue.next();
2718 zprint = command->m_print;
2720 CliHandler(zprint).ParseCommands(command->m_command);
2722 delete command;
2725 // print the console message here so it looks right
2726 zprint("mangos>");
2729 void World::InitResultQueue()
2731 m_resultQueue = new SqlResultQueue;
2732 CharacterDatabase.SetResultQueue(m_resultQueue);
2735 void World::UpdateResultQueue()
2737 m_resultQueue->Update();
2740 void World::UpdateRealmCharCount(uint32 accountId)
2742 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2743 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2746 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2748 if (resultCharCount)
2750 Field *fields = resultCharCount->Fetch();
2751 uint32 charCount = fields[0].GetUInt32();
2752 delete resultCharCount;
2753 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2754 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2758 void World::InitDailyQuestResetTime()
2760 time_t mostRecentQuestTime;
2762 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2763 if(result)
2765 Field *fields = result->Fetch();
2767 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2768 delete result;
2770 else
2771 mostRecentQuestTime = 0;
2773 // client built-in time for reset is 6:00 AM
2774 // FIX ME: client not show day start time
2775 time_t curTime = time(NULL);
2776 tm localTm = *localtime(&curTime);
2777 localTm.tm_hour = 6;
2778 localTm.tm_min = 0;
2779 localTm.tm_sec = 0;
2781 // current day reset time
2782 time_t curDayResetTime = mktime(&localTm);
2784 // last reset time before current moment
2785 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2787 // need reset (if we have quest time before last reset time (not processed by some reason)
2788 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2789 m_NextDailyQuestReset = mostRecentQuestTime;
2790 else
2792 // plan next reset time
2793 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2797 void World::ResetDailyQuests()
2799 sLog.outDetail("Daily quests reset for all characters.");
2800 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2801 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2802 if(itr->second->GetPlayer())
2803 itr->second->GetPlayer()->ResetDailyQuestStatus();
2806 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2808 if(limit < -SEC_ADMINISTRATOR)
2809 limit = -SEC_ADMINISTRATOR;
2811 // lock update need
2812 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2814 m_playerLimit = limit;
2816 if(db_update_need)
2817 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2820 void World::UpdateMaxSessionCounters()
2822 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2823 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2826 void World::LoadDBVersion()
2828 QueryResult* result = WorldDatabase.Query("SELECT version, creature_ai_version FROM db_version LIMIT 1");
2829 if(result)
2831 Field* fields = result->Fetch();
2833 m_DBVersion = fields[0].GetCppString();
2834 m_CreatureEventAIVersion = fields[1].GetCppString();
2835 delete result;
2838 if(m_DBVersion.empty())
2839 m_DBVersion = "Unknown world database.";
2841 if(m_CreatureEventAIVersion.empty())
2842 m_CreatureEventAIVersion = "Unknown creature EventAI.";