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
24 //#include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
43 #include "Database/DBCStores.h"
45 #include "ItemEnchantmentMgr.h"
46 #include "MapManager.h"
47 #include "ScriptCalls.h"
48 #include "CreatureAIRegistry.h"
49 #include "Policies/SingletonImp.h"
50 #include "BattleGroundMgr.h"
51 #include "TemporarySummon.h"
52 #include "WaypointMovementGenerator.h"
53 #include "VMapFactory.h"
54 #include "GlobalEvents.h"
55 #include "GameEvent.h"
56 #include "Database/DatabaseImpl.h"
57 #include "GridNotifiersImpl.h"
59 #include "InstanceSaveMgr.h"
60 #include "WaypointManager.h"
61 #include "GMTicketMgr.h"
64 INSTANTIATE_SINGLETON_1( World
);
66 volatile bool World::m_stopEvent
= false;
67 uint8
World::m_ExitCode
= SHUTDOWN_EXIT_CODE
;
68 volatile uint32
World::m_worldLoopCounter
= 0;
70 float World::m_MaxVisibleDistanceForCreature
= DEFAULT_VISIBILITY_DISTANCE
;
71 float World::m_MaxVisibleDistanceForPlayer
= DEFAULT_VISIBILITY_DISTANCE
;
72 float World::m_MaxVisibleDistanceForObject
= DEFAULT_VISIBILITY_DISTANCE
;
73 float World::m_MaxVisibleDistanceInFlight
= DEFAULT_VISIBILITY_DISTANCE
;
74 float World::m_VisibleUnitGreyDistance
= 0;
75 float World::m_VisibleObjectGreyDistance
= 0;
78 enum ServerMessageType
80 SERVER_MSG_SHUTDOWN_TIME
= 1,
81 SERVER_MSG_RESTART_TIME
= 2,
82 SERVER_MSG_STRING
= 3,
83 SERVER_MSG_SHUTDOWN_CANCELLED
= 4,
84 SERVER_MSG_RESTART_CANCELLED
= 5
91 uint64 ownerGUID
; // owner of source if source is item
92 ScriptInfo
const* script
; // pointer to static script data
99 m_allowMovement
= true;
102 m_gameTime
=time(NULL
);
103 m_startTime
=m_gameTime
;
104 m_maxActiveSessionCount
= 0;
105 m_maxQueuedSessionCount
= 0;
106 m_resultQueue
= NULL
;
107 m_NextDailyQuestReset
= 0;
109 m_defaultDbcLocale
= LOCALE_enUS
;
110 m_availableDbcLocaleMask
= 0;
116 ///- Empty the kicked session set
117 while (!m_sessions
.empty())
119 // not remove from queue, prevent loading new sessions
120 delete m_sessions
.begin()->second
;
121 m_sessions
.erase(m_sessions
.begin());
124 ///- Empty the WeatherMap
125 for (WeatherMap::iterator itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); ++itr
)
130 while (!cliCmdQueue
.empty())
131 delete cliCmdQueue
.next();
133 VMAP::VMapFactory::clear();
135 if(m_resultQueue
) delete m_resultQueue
;
137 //TODO free addSessQueue
140 /// Find a player in a specified zone
141 Player
* World::FindPlayerInZone(uint32 zone
)
143 ///- circle through active sessions and return the first player found in the zone
144 SessionMap::iterator itr
;
145 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
149 Player
*player
= itr
->second
->GetPlayer();
152 if( player
->IsInWorld() && player
->GetZoneId() == zone
)
154 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
161 /// Find a session by its id
162 WorldSession
* World::FindSession(uint32 id
) const
164 SessionMap::const_iterator itr
= m_sessions
.find(id
);
166 if(itr
!= m_sessions
.end())
167 return itr
->second
; // also can return NULL for kicked session
172 /// Remove a given session
173 bool World::RemoveSession(uint32 id
)
175 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
176 SessionMap::iterator itr
= m_sessions
.find(id
);
178 if(itr
!= m_sessions
.end() && itr
->second
)
180 if (itr
->second
->PlayerLoading())
182 itr
->second
->KickPlayer();
188 void World::AddSession(WorldSession
* s
)
194 World::AddSession_ (WorldSession
* s
)
198 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
200 ///- kick already loaded player with same account (if any) and remove session
201 ///- if player is in loading and want to load again, return
202 if (!RemoveSession (s
->GetAccountId ()))
205 delete s
; // session not added yet in session list, so not listed in queue
209 // decrease session counts only at not reconnection case
210 bool decrease_session
= true;
212 // if session already exist, prepare to it deleting at next world update
213 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
215 SessionMap::const_iterator old
= m_sessions
.find(s
->GetAccountId ());
217 if(old
!= m_sessions
.end())
219 // prevent decrease sessions count if session queued
220 if(RemoveQueuedPlayer(old
->second
))
221 decrease_session
= false;
222 // not remove replaced session form queue if listed
227 m_sessions
[s
->GetAccountId ()] = s
;
229 uint32 Sessions
= GetActiveAndQueuedSessionCount ();
230 uint32 pLimit
= GetPlayerAmountLimit ();
231 uint32 QueueSize
= GetQueueSize (); //number of players in the queue
233 //so we don't count the user trying to
234 //login as a session and queue the socket that we are using
238 if (pLimit
> 0 && Sessions
>= pLimit
&& s
->GetSecurity () == SEC_PLAYER
)
241 UpdateMaxSessionCounters ();
242 sLog
.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s
->GetAccountId (), ++QueueSize
);
246 WorldPacket
packet(SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
247 packet
<< uint8 (AUTH_OK
);
248 packet
<< uint32 (0); // BillingTimeRemaining
249 packet
<< uint8 (0); // BillingPlanFlags
250 packet
<< uint32 (0); // BillingTimeRested
251 packet
<< uint8 (s
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
252 s
->SendPacket (&packet
);
254 UpdateMaxSessionCounters ();
256 // Updates the population
259 float popu
= GetActiveSessionCount (); //updated number of users on the server
262 loginDatabase
.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu
, realmID
);
263 sLog
.outDetail ("Server Population (%f).", popu
);
267 int32
World::GetQueuePos(WorldSession
* sess
)
271 for(Queue::iterator iter
= m_QueuedPlayer
.begin(); iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
278 void World::AddQueuedPlayer(WorldSession
* sess
)
280 sess
->SetInQueue(true);
281 m_QueuedPlayer
.push_back (sess
);
283 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
284 WorldPacket
packet (SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
285 packet
<< uint8 (AUTH_WAIT_QUEUE
);
286 packet
<< uint32 (0); // BillingTimeRemaining
287 packet
<< uint8 (0); // BillingPlanFlags
288 packet
<< uint32 (0); // BillingTimeRested
289 packet
<< uint8 (sess
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
290 packet
<< uint32(GetQueuePos (sess
));
291 sess
->SendPacket (&packet
);
293 //sess->SendAuthWaitQue (GetQueuePos (sess));
296 bool World::RemoveQueuedPlayer(WorldSession
* sess
)
298 // sessions count including queued to remove (if removed_session set)
299 uint32 sessions
= GetActiveSessionCount();
302 Queue::iterator iter
= m_QueuedPlayer
.begin();
304 // search to remove and count skipped positions
307 for(;iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
311 sess
->SetInQueue(false);
312 iter
= m_QueuedPlayer
.erase(iter
);
313 found
= true; // removing queued session
318 // iter point to next socked after removed or end()
319 // position store position of removed socket and then new position next socket after removed
321 // if session not queued then we need decrease sessions count
322 if(!found
&& sessions
)
325 // accept first in queue
326 if( (!m_playerLimit
|| sessions
< m_playerLimit
) && !m_QueuedPlayer
.empty() )
328 WorldSession
* pop_sess
= m_QueuedPlayer
.front();
329 pop_sess
->SetInQueue(false);
330 pop_sess
->SendAuthWaitQue(0);
331 m_QueuedPlayer
.pop_front();
333 // update iter to point first queued socket or end() if queue is empty now
334 iter
= m_QueuedPlayer
.begin();
338 // update position from iter to end()
339 // iter point to first not updated socket, position store new position
340 for(; iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
341 (*iter
)->SendAuthWaitQue(position
);
346 /// Find a Weather object by the given zoneid
347 Weather
* World::FindWeather(uint32 id
) const
349 WeatherMap::const_iterator itr
= m_weathers
.find(id
);
351 if(itr
!= m_weathers
.end())
357 /// Remove a Weather object for the given zoneid
358 void World::RemoveWeather(uint32 id
)
360 // not called at the moment. Kept for completeness
361 WeatherMap::iterator itr
= m_weathers
.find(id
);
363 if(itr
!= m_weathers
.end())
366 m_weathers
.erase(itr
);
370 /// Add a Weather object to the list
371 Weather
* World::AddWeather(uint32 zone_id
)
373 WeatherZoneChances
const* weatherChances
= objmgr
.GetWeatherChances(zone_id
);
375 // zone not have weather, ignore
379 Weather
* w
= new Weather(zone_id
,weatherChances
);
380 m_weathers
[w
->GetZone()] = w
;
386 /// Initialize config values
387 void World::LoadConfigSettings(bool reload
)
391 if(!sConfig
.Reload())
393 sLog
.outError("World settings reload fail: can't read settings from %s.",sConfig
.GetFilename().c_str());
398 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
399 uint32 confVersion
= sConfig
.GetIntDefault("ConfVersion", 0);
402 sLog
.outError("*****************************************************************************");
403 sLog
.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
404 sLog
.outError(" Your configuration file may be out of date!");
405 sLog
.outError("*****************************************************************************");
406 clock_t pause
= 3000 + clock();
407 while (pause
> clock());
411 if (confVersion
< _MANGOSDCONFVERSION
)
413 sLog
.outError("*****************************************************************************");
414 sLog
.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
415 sLog
.outError(" Please check for updates, as your current default values may cause");
416 sLog
.outError(" unexpected behavior.");
417 sLog
.outError("*****************************************************************************");
418 clock_t pause
= 3000 + clock();
419 while (pause
> clock());
423 ///- Read the player limit and the Message of the day from the config file
424 SetPlayerLimit( sConfig
.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT
), true );
425 SetMotd( sConfig
.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
427 ///- Read all rates from the config file
428 rate_values
[RATE_HEALTH
] = sConfig
.GetFloatDefault("Rate.Health", 1);
429 if(rate_values
[RATE_HEALTH
] < 0)
431 sLog
.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values
[RATE_HEALTH
]);
432 rate_values
[RATE_HEALTH
] = 1;
434 rate_values
[RATE_POWER_MANA
] = sConfig
.GetFloatDefault("Rate.Mana", 1);
435 if(rate_values
[RATE_POWER_MANA
] < 0)
437 sLog
.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_MANA
]);
438 rate_values
[RATE_POWER_MANA
] = 1;
440 rate_values
[RATE_POWER_RAGE_INCOME
] = sConfig
.GetFloatDefault("Rate.Rage.Income", 1);
441 rate_values
[RATE_POWER_RAGE_LOSS
] = sConfig
.GetFloatDefault("Rate.Rage.Loss", 1);
442 if(rate_values
[RATE_POWER_RAGE_LOSS
] < 0)
444 sLog
.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RAGE_LOSS
]);
445 rate_values
[RATE_POWER_RAGE_LOSS
] = 1;
447 rate_values
[RATE_POWER_RUNICPOWER_INCOME
] = sConfig
.GetFloatDefault("Rate.RunicPower.Income", 1);
448 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = sConfig
.GetFloatDefault("Rate.RunicPower.Loss", 1);
449 if(rate_values
[RATE_POWER_RUNICPOWER_LOSS
] < 0)
451 sLog
.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RUNICPOWER_LOSS
]);
452 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = 1;
454 rate_values
[RATE_POWER_FOCUS
] = sConfig
.GetFloatDefault("Rate.Focus", 1.0f
);
455 rate_values
[RATE_SKILL_DISCOVERY
] = sConfig
.GetFloatDefault("Rate.Skill.Discovery", 1.0f
);
456 rate_values
[RATE_DROP_ITEM_POOR
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f
);
457 rate_values
[RATE_DROP_ITEM_NORMAL
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f
);
458 rate_values
[RATE_DROP_ITEM_UNCOMMON
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f
);
459 rate_values
[RATE_DROP_ITEM_RARE
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f
);
460 rate_values
[RATE_DROP_ITEM_EPIC
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f
);
461 rate_values
[RATE_DROP_ITEM_LEGENDARY
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f
);
462 rate_values
[RATE_DROP_ITEM_ARTIFACT
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f
);
463 rate_values
[RATE_DROP_ITEM_REFERENCED
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f
);
464 rate_values
[RATE_DROP_MONEY
] = sConfig
.GetFloatDefault("Rate.Drop.Money", 1.0f
);
465 rate_values
[RATE_XP_KILL
] = sConfig
.GetFloatDefault("Rate.XP.Kill", 1.0f
);
466 rate_values
[RATE_XP_QUEST
] = sConfig
.GetFloatDefault("Rate.XP.Quest", 1.0f
);
467 rate_values
[RATE_XP_EXPLORE
] = sConfig
.GetFloatDefault("Rate.XP.Explore", 1.0f
);
468 rate_values
[RATE_REPUTATION_GAIN
] = sConfig
.GetFloatDefault("Rate.Reputation.Gain", 1.0f
);
469 rate_values
[RATE_CREATURE_NORMAL_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f
);
470 rate_values
[RATE_CREATURE_ELITE_ELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f
);
471 rate_values
[RATE_CREATURE_ELITE_RAREELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f
);
472 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f
);
473 rate_values
[RATE_CREATURE_ELITE_RARE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f
);
474 rate_values
[RATE_CREATURE_NORMAL_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f
);
475 rate_values
[RATE_CREATURE_ELITE_ELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f
);
476 rate_values
[RATE_CREATURE_ELITE_RAREELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f
);
477 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f
);
478 rate_values
[RATE_CREATURE_ELITE_RARE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f
);
479 rate_values
[RATE_CREATURE_NORMAL_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f
);
480 rate_values
[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f
);
481 rate_values
[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f
);
482 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f
);
483 rate_values
[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f
);
484 rate_values
[RATE_CREATURE_AGGRO
] = sConfig
.GetFloatDefault("Rate.Creature.Aggro", 1.0f
);
485 rate_values
[RATE_REST_INGAME
] = sConfig
.GetFloatDefault("Rate.Rest.InGame", 1.0f
);
486 rate_values
[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f
);
487 rate_values
[RATE_REST_OFFLINE_IN_WILDERNESS
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f
);
488 rate_values
[RATE_DAMAGE_FALL
] = sConfig
.GetFloatDefault("Rate.Damage.Fall", 1.0f
);
489 rate_values
[RATE_AUCTION_TIME
] = sConfig
.GetFloatDefault("Rate.Auction.Time", 1.0f
);
490 rate_values
[RATE_AUCTION_DEPOSIT
] = sConfig
.GetFloatDefault("Rate.Auction.Deposit", 1.0f
);
491 rate_values
[RATE_AUCTION_CUT
] = sConfig
.GetFloatDefault("Rate.Auction.Cut", 1.0f
);
492 rate_values
[RATE_HONOR
] = sConfig
.GetFloatDefault("Rate.Honor",1.0f
);
493 rate_values
[RATE_MINING_AMOUNT
] = sConfig
.GetFloatDefault("Rate.Mining.Amount",1.0f
);
494 rate_values
[RATE_MINING_NEXT
] = sConfig
.GetFloatDefault("Rate.Mining.Next",1.0f
);
495 rate_values
[RATE_INSTANCE_RESET_TIME
] = sConfig
.GetFloatDefault("Rate.InstanceResetTime",1.0f
);
496 rate_values
[RATE_TALENT
] = sConfig
.GetFloatDefault("Rate.Talent",1.0f
);
497 if(rate_values
[RATE_TALENT
] < 0.0f
)
499 sLog
.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values
[RATE_TALENT
]);
500 rate_values
[RATE_TALENT
] = 1.0f
;
502 rate_values
[RATE_CORPSE_DECAY_LOOTED
] = sConfig
.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f
);
504 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = sConfig
.GetFloatDefault("TargetPosRecalculateRange",1.5f
);
505 if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] < CONTACT_DISTANCE
)
507 sLog
.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],CONTACT_DISTANCE
,CONTACT_DISTANCE
);
508 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = CONTACT_DISTANCE
;
510 else if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] > ATTACK_DISTANCE
)
512 sLog
.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
513 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],ATTACK_DISTANCE
,ATTACK_DISTANCE
);
514 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = ATTACK_DISTANCE
;
517 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = sConfig
.GetFloatDefault("DurabilityLossChance.Damage",0.5f
);
518 if(rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] < 0.0f
)
520 sLog
.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_DAMAGE
]);
521 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = 0.0f
;
523 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = sConfig
.GetFloatDefault("DurabilityLossChance.Absorb",0.5f
);
524 if(rate_values
[RATE_DURABILITY_LOSS_ABSORB
] < 0.0f
)
526 sLog
.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_ABSORB
]);
527 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = 0.0f
;
529 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = sConfig
.GetFloatDefault("DurabilityLossChance.Parry",0.05f
);
530 if(rate_values
[RATE_DURABILITY_LOSS_PARRY
] < 0.0f
)
532 sLog
.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_PARRY
]);
533 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = 0.0f
;
535 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = sConfig
.GetFloatDefault("DurabilityLossChance.Block",0.05f
);
536 if(rate_values
[RATE_DURABILITY_LOSS_BLOCK
] < 0.0f
)
538 sLog
.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_BLOCK
]);
539 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = 0.0f
;
542 ///- Read other configuration items from the config file
544 m_configs
[CONFIG_COMPRESSION
] = sConfig
.GetIntDefault("Compression", 1);
545 if(m_configs
[CONFIG_COMPRESSION
] < 1 || m_configs
[CONFIG_COMPRESSION
] > 9)
547 sLog
.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs
[CONFIG_COMPRESSION
]);
548 m_configs
[CONFIG_COMPRESSION
] = 1;
550 m_configs
[CONFIG_ADDON_CHANNEL
] = sConfig
.GetBoolDefault("AddonChannel", true);
551 m_configs
[CONFIG_GRID_UNLOAD
] = sConfig
.GetBoolDefault("GridUnload", true);
552 m_configs
[CONFIG_INTERVAL_SAVE
] = sConfig
.GetIntDefault("PlayerSaveInterval", 900000);
554 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = sConfig
.GetIntDefault("GridCleanUpDelay", 300000);
555 if(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] < MIN_GRID_DELAY
)
557 sLog
.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_GRIDCLEAN
],MIN_GRID_DELAY
);
558 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = MIN_GRID_DELAY
;
561 MapManager::Instance().SetGridCleanUpDelay(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
]);
563 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = sConfig
.GetIntDefault("MapUpdateInterval", 100);
564 if(m_configs
[CONFIG_INTERVAL_MAPUPDATE
] < MIN_MAP_UPDATE_DELAY
)
566 sLog
.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_MAPUPDATE
],MIN_MAP_UPDATE_DELAY
);
567 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = MIN_MAP_UPDATE_DELAY
;
570 MapManager::Instance().SetMapUpdateInterval(m_configs
[CONFIG_INTERVAL_MAPUPDATE
]);
572 m_configs
[CONFIG_INTERVAL_CHANGEWEATHER
] = sConfig
.GetIntDefault("ChangeWeatherInterval", 600000);
576 uint32 val
= sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
577 if(val
!=m_configs
[CONFIG_PORT_WORLD
])
578 sLog
.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_PORT_WORLD
]);
581 m_configs
[CONFIG_PORT_WORLD
] = sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
585 uint32 val
= sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
586 if(val
!=m_configs
[CONFIG_SOCKET_SELECTTIME
])
587 sLog
.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[DEFAULT_SOCKET_SELECT_TIME
]);
590 m_configs
[CONFIG_SOCKET_SELECTTIME
] = sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
592 m_configs
[CONFIG_GROUP_XP_DISTANCE
] = sConfig
.GetIntDefault("MaxGroupXPDistance", 74);
593 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
594 m_configs
[CONFIG_SIGHT_MONSTER
] = sConfig
.GetIntDefault("MonsterSight", 50);
595 m_configs
[CONFIG_SIGHT_GUARDER
] = sConfig
.GetIntDefault("GuarderSight", 50);
599 uint32 val
= sConfig
.GetIntDefault("GameType", 0);
600 if(val
!=m_configs
[CONFIG_GAME_TYPE
])
601 sLog
.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_GAME_TYPE
]);
604 m_configs
[CONFIG_GAME_TYPE
] = sConfig
.GetIntDefault("GameType", 0);
608 uint32 val
= sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
609 if(val
!=m_configs
[CONFIG_REALM_ZONE
])
610 sLog
.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_REALM_ZONE
]);
613 m_configs
[CONFIG_REALM_ZONE
] = sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
615 m_configs
[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS
] = sConfig
.GetBoolDefault("AllowTwoSide.Accounts", false);
616 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
617 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
618 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
619 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
620 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
621 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
622 m_configs
[CONFIG_ALLOW_TWO_SIDE_WHO_LIST
] = sConfig
.GetBoolDefault("AllowTwoSide.WhoList", false);
623 m_configs
[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND
] = sConfig
.GetBoolDefault("AllowTwoSide.AddFriend", false);
624 m_configs
[CONFIG_STRICT_PLAYER_NAMES
] = sConfig
.GetIntDefault("StrictPlayerNames", 0);
625 m_configs
[CONFIG_STRICT_CHARTER_NAMES
] = sConfig
.GetIntDefault("StrictCharterNames", 0);
626 m_configs
[CONFIG_STRICT_PET_NAMES
] = sConfig
.GetIntDefault("StrictPetNames", 0);
628 m_configs
[CONFIG_CHARACTERS_CREATING_DISABLED
] = sConfig
.GetIntDefault("CharactersCreatingDisabled", 0);
630 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("CharactersPerRealm", 10);
631 if(m_configs
[CONFIG_CHARACTERS_PER_REALM
] < 1 || m_configs
[CONFIG_CHARACTERS_PER_REALM
] > 10)
633 sLog
.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
634 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = 10;
637 // must be after CONFIG_CHARACTERS_PER_REALM
638 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = sConfig
.GetIntDefault("CharactersPerAccount", 50);
639 if(m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] < m_configs
[CONFIG_CHARACTERS_PER_REALM
])
641 sLog
.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
],m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
642 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = m_configs
[CONFIG_CHARACTERS_PER_REALM
];
645 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("HeroicCharactersPerRealm", 1);
646 if(m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] < 0 || m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] > 10)
648 sLog
.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
]);
649 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = 1;
652 m_configs
[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING
] = sConfig
.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
654 m_configs
[CONFIG_SKIP_CINEMATICS
] = sConfig
.GetIntDefault("SkipCinematics", 0);
655 if(m_configs
[CONFIG_SKIP_CINEMATICS
] < 0 || m_configs
[CONFIG_SKIP_CINEMATICS
] > 2)
657 sLog
.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs
[CONFIG_SKIP_CINEMATICS
]);
658 m_configs
[CONFIG_SKIP_CINEMATICS
] = 0;
663 uint32 val
= sConfig
.GetIntDefault("MaxPlayerLevel", 60);
664 if(val
!=m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
665 sLog
.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
668 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = sConfig
.GetIntDefault("MaxPlayerLevel", 60);
670 if(m_configs
[CONFIG_MAX_PLAYER_LEVEL
] > MAX_LEVEL
)
672 sLog
.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs
[CONFIG_MAX_PLAYER_LEVEL
],MAX_LEVEL
,MAX_LEVEL
);
673 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = MAX_LEVEL
;
676 m_configs
[CONFIG_START_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartPlayerLevel", 1);
677 if(m_configs
[CONFIG_START_PLAYER_LEVEL
] < 1)
679 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
]);
680 m_configs
[CONFIG_START_PLAYER_LEVEL
] = 1;
682 else if(m_configs
[CONFIG_START_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
684 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
]);
685 m_configs
[CONFIG_START_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
688 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartHeroicPlayerLevel", 55);
689 if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] < 1)
691 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
692 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
693 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = 55;
695 else if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
697 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
698 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
699 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
702 m_configs
[CONFIG_START_PLAYER_MONEY
] = sConfig
.GetIntDefault("StartPlayerMoney", 0);
703 if(m_configs
[CONFIG_START_PLAYER_MONEY
] < 0)
705 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,0);
706 m_configs
[CONFIG_START_PLAYER_MONEY
] = 0;
708 else if(m_configs
[CONFIG_START_PLAYER_MONEY
] > MAX_MONEY_AMOUNT
)
710 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
711 m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,MAX_MONEY_AMOUNT
);
712 m_configs
[CONFIG_START_PLAYER_MONEY
] = MAX_MONEY_AMOUNT
;
715 m_configs
[CONFIG_MAX_HONOR_POINTS
] = sConfig
.GetIntDefault("MaxHonorPoints", 75000);
716 if(m_configs
[CONFIG_MAX_HONOR_POINTS
] < 0)
718 sLog
.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_HONOR_POINTS
]);
719 m_configs
[CONFIG_MAX_HONOR_POINTS
] = 0;
722 m_configs
[CONFIG_START_HONOR_POINTS
] = sConfig
.GetIntDefault("StartHonorPoints", 0);
723 if(m_configs
[CONFIG_START_HONOR_POINTS
] < 0)
725 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
726 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],0);
727 m_configs
[CONFIG_MAX_HONOR_POINTS
] = 0;
729 else if(m_configs
[CONFIG_START_HONOR_POINTS
] > m_configs
[CONFIG_MAX_HONOR_POINTS
])
731 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
732 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
]);
733 m_configs
[CONFIG_START_HONOR_POINTS
] = m_configs
[CONFIG_MAX_HONOR_POINTS
];
736 m_configs
[CONFIG_MAX_ARENA_POINTS
] = sConfig
.GetIntDefault("MaxArenaPoints", 5000);
737 if(m_configs
[CONFIG_MAX_ARENA_POINTS
] < 0)
739 sLog
.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_ARENA_POINTS
]);
740 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
743 m_configs
[CONFIG_START_ARENA_POINTS
] = sConfig
.GetIntDefault("StartArenaPoints", 0);
744 if(m_configs
[CONFIG_START_ARENA_POINTS
] < 0)
746 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
747 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],0);
748 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
750 else if(m_configs
[CONFIG_START_ARENA_POINTS
] > m_configs
[CONFIG_MAX_ARENA_POINTS
])
752 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
753 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
]);
754 m_configs
[CONFIG_START_ARENA_POINTS
] = m_configs
[CONFIG_MAX_ARENA_POINTS
];
757 m_configs
[CONFIG_ALL_TAXI_PATHS
] = sConfig
.GetBoolDefault("AllFlightPaths", false);
759 m_configs
[CONFIG_INSTANCE_IGNORE_LEVEL
] = sConfig
.GetBoolDefault("Instance.IgnoreLevel", false);
760 m_configs
[CONFIG_INSTANCE_IGNORE_RAID
] = sConfig
.GetBoolDefault("Instance.IgnoreRaid", false);
762 m_configs
[CONFIG_BATTLEGROUND_CAST_DESERTER
] = sConfig
.GetBoolDefault("Battleground.CastDeserter", true);
763 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
764 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
765 m_configs
[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
766 m_configs
[CONFIG_ARENA_SEASON_ID
] = sConfig
.GetIntDefault ("Arena.ArenaSeason.ID", 1);
767 m_configs
[CONFIG_ARENA_SEASON_IN_PROGRESS
] = sConfig
.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
769 m_configs
[CONFIG_CAST_UNSTUCK
] = sConfig
.GetBoolDefault("CastUnstuck", true);
770 m_configs
[CONFIG_INSTANCE_RESET_TIME_HOUR
] = sConfig
.GetIntDefault("Instance.ResetTimeHour", 4);
771 m_configs
[CONFIG_INSTANCE_UNLOAD_DELAY
] = sConfig
.GetIntDefault("Instance.UnloadDelay", 1800000);
773 m_configs
[CONFIG_MAX_PRIMARY_TRADE_SKILL
] = sConfig
.GetIntDefault("MaxPrimaryTradeSkill", 2);
774 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = sConfig
.GetIntDefault("MinPetitionSigns", 9);
775 if(m_configs
[CONFIG_MIN_PETITION_SIGNS
] > 9)
777 sLog
.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs
[CONFIG_MIN_PETITION_SIGNS
]);
778 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = 9;
781 m_configs
[CONFIG_GM_LOGIN_STATE
] = sConfig
.GetIntDefault("GM.LoginState", 2);
782 m_configs
[CONFIG_GM_VISIBLE_STATE
] = sConfig
.GetIntDefault("GM.Visible", 2);
783 m_configs
[CONFIG_GM_ACCEPT_TICKETS
] = sConfig
.GetIntDefault("GM.AcceptTickets", 2);
784 m_configs
[CONFIG_GM_CHAT
] = sConfig
.GetIntDefault("GM.Chat", 2);
785 m_configs
[CONFIG_GM_WISPERING_TO
] = sConfig
.GetIntDefault("GM.WhisperingTo", 2);
787 m_configs
[CONFIG_GM_IN_GM_LIST
] = sConfig
.GetBoolDefault("GM.InGMList", false);
788 m_configs
[CONFIG_GM_IN_WHO_LIST
] = sConfig
.GetBoolDefault("GM.InWhoList", false);
789 m_configs
[CONFIG_GM_LOG_TRADE
] = sConfig
.GetBoolDefault("GM.LogTrade", false);
791 m_configs
[CONFIG_START_GM_LEVEL
] = sConfig
.GetIntDefault("GM.StartLevel", 1);
792 if(m_configs
[CONFIG_START_GM_LEVEL
] < m_configs
[CONFIG_START_PLAYER_LEVEL
])
794 sLog
.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
795 m_configs
[CONFIG_START_GM_LEVEL
],m_configs
[CONFIG_START_PLAYER_LEVEL
], MAX_LEVEL
, m_configs
[CONFIG_START_PLAYER_LEVEL
]);
796 m_configs
[CONFIG_START_GM_LEVEL
] = m_configs
[CONFIG_START_PLAYER_LEVEL
];
798 else if(m_configs
[CONFIG_START_GM_LEVEL
] > MAX_LEVEL
)
800 sLog
.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs
[CONFIG_START_GM_LEVEL
], MAX_LEVEL
, MAX_LEVEL
);
801 m_configs
[CONFIG_START_GM_LEVEL
] = MAX_LEVEL
;
803 m_configs
[CONFIG_GM_LOWER_SECURITY
] = sConfig
.GetBoolDefault("GM.LowerSecurity", false);
804 m_configs
[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS
] = sConfig
.GetBoolDefault("GM.AllowAchievementGain", true);
806 m_configs
[CONFIG_GROUP_VISIBILITY
] = sConfig
.GetIntDefault("Visibility.GroupMode",0);
808 m_configs
[CONFIG_MAIL_DELIVERY_DELAY
] = sConfig
.GetIntDefault("MailDeliveryDelay",HOUR
);
810 m_configs
[CONFIG_UPTIME_UPDATE
] = sConfig
.GetIntDefault("UpdateUptimeInterval", 10);
811 if(m_configs
[CONFIG_UPTIME_UPDATE
]<=0)
813 sLog
.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs
[CONFIG_UPTIME_UPDATE
]);
814 m_configs
[CONFIG_UPTIME_UPDATE
] = 10;
818 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*1000);
819 m_timers
[WUPDATE_UPTIME
].Reset();
822 m_configs
[CONFIG_SKILL_CHANCE_ORANGE
] = sConfig
.GetIntDefault("SkillChance.Orange",100);
823 m_configs
[CONFIG_SKILL_CHANCE_YELLOW
] = sConfig
.GetIntDefault("SkillChance.Yellow",75);
824 m_configs
[CONFIG_SKILL_CHANCE_GREEN
] = sConfig
.GetIntDefault("SkillChance.Green",25);
825 m_configs
[CONFIG_SKILL_CHANCE_GREY
] = sConfig
.GetIntDefault("SkillChance.Grey",0);
827 m_configs
[CONFIG_SKILL_CHANCE_MINING_STEPS
] = sConfig
.GetIntDefault("SkillChance.MiningSteps",75);
828 m_configs
[CONFIG_SKILL_CHANCE_SKINNING_STEPS
] = sConfig
.GetIntDefault("SkillChance.SkinningSteps",75);
830 m_configs
[CONFIG_SKILL_PROSPECTING
] = sConfig
.GetBoolDefault("SkillChance.Prospecting",false);
831 m_configs
[CONFIG_SKILL_MILLING
] = sConfig
.GetBoolDefault("SkillChance.Milling",false);
833 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = sConfig
.GetIntDefault("SkillGain.Crafting", 1);
834 if(m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] < 0)
836 sLog
.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_CRAFTING
]);
837 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = 1;
840 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = sConfig
.GetIntDefault("SkillGain.Defense", 1);
841 if(m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] < 0)
843 sLog
.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_DEFENSE
]);
844 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = 1;
847 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = sConfig
.GetIntDefault("SkillGain.Gathering", 1);
848 if(m_configs
[CONFIG_SKILL_GAIN_GATHERING
] < 0)
850 sLog
.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_GATHERING
]);
851 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = 1;
854 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = sConfig
.GetIntDefault("SkillGain.Weapon", 1);
855 if(m_configs
[CONFIG_SKILL_GAIN_WEAPON
] < 0)
857 sLog
.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_WEAPON
]);
858 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = 1;
861 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = sConfig
.GetIntDefault("MaxOverspeedPings",2);
862 if(m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] != 0 && m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] < 2)
864 sLog
.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs
[CONFIG_MAX_OVERSPEED_PINGS
]);
865 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = 2;
868 m_configs
[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY
] = sConfig
.GetBoolDefault("SaveRespawnTimeImmediately",true);
869 m_configs
[CONFIG_WEATHER
] = sConfig
.GetBoolDefault("ActivateWeather",true);
871 m_configs
[CONFIG_DISABLE_BREATHING
] = sConfig
.GetIntDefault("DisableWaterBreath", SEC_CONSOLE
);
873 m_configs
[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
] = sConfig
.GetBoolDefault("AlwaysMaxSkillForLevel", false);
877 uint32 val
= sConfig
.GetIntDefault("Expansion",1);
878 if(val
!=m_configs
[CONFIG_EXPANSION
])
879 sLog
.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_EXPANSION
]);
882 m_configs
[CONFIG_EXPANSION
] = sConfig
.GetIntDefault("Expansion",1);
884 m_configs
[CONFIG_CHATFLOOD_MESSAGE_COUNT
] = sConfig
.GetIntDefault("ChatFlood.MessageCount",10);
885 m_configs
[CONFIG_CHATFLOOD_MESSAGE_DELAY
] = sConfig
.GetIntDefault("ChatFlood.MessageDelay",1);
886 m_configs
[CONFIG_CHATFLOOD_MUTE_TIME
] = sConfig
.GetIntDefault("ChatFlood.MuteTime",10);
888 m_configs
[CONFIG_EVENT_ANNOUNCE
] = sConfig
.GetIntDefault("Event.Announce",0);
890 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceRadius",10);
891 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
893 m_configs
[CONFIG_WORLD_BOSS_LEVEL_DIFF
] = sConfig
.GetIntDefault("WorldBossLevelDiff",3);
895 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
896 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.LowLevelHideDiff", 4);
897 if(m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
898 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
899 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.HighLevelHideDiff", 7);
900 if(m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
901 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
903 m_configs
[CONFIG_DETECT_POS_COLLISION
] = sConfig
.GetBoolDefault("DetectPosCollision", true);
905 m_configs
[CONFIG_RESTRICTED_LFG_CHANNEL
] = sConfig
.GetBoolDefault("Channel.RestrictedLfg", true);
906 m_configs
[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL
] = sConfig
.GetBoolDefault("Channel.SilentlyGMJoin", false);
908 m_configs
[CONFIG_TALENTS_INSPECTING
] = sConfig
.GetBoolDefault("TalentsInspecting", true);
909 m_configs
[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING
] = sConfig
.GetBoolDefault("ChatFakeMessagePreventing", false);
911 m_configs
[CONFIG_CORPSE_DECAY_NORMAL
] = sConfig
.GetIntDefault("Corpse.Decay.NORMAL", 60);
912 m_configs
[CONFIG_CORPSE_DECAY_RARE
] = sConfig
.GetIntDefault("Corpse.Decay.RARE", 300);
913 m_configs
[CONFIG_CORPSE_DECAY_ELITE
] = sConfig
.GetIntDefault("Corpse.Decay.ELITE", 300);
914 m_configs
[CONFIG_CORPSE_DECAY_RAREELITE
] = sConfig
.GetIntDefault("Corpse.Decay.RAREELITE", 300);
915 m_configs
[CONFIG_CORPSE_DECAY_WORLDBOSS
] = sConfig
.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
917 m_configs
[CONFIG_DEATH_SICKNESS_LEVEL
] = sConfig
.GetIntDefault("Death.SicknessLevel", 11);
918 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
919 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
920 m_configs
[CONFIG_DEATH_BONES_WORLD
] = sConfig
.GetBoolDefault("Death.Bones.World", true);
921 m_configs
[CONFIG_DEATH_BONES_BG_OR_ARENA
] = sConfig
.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
923 m_configs
[CONFIG_THREAT_RADIUS
] = sConfig
.GetIntDefault("ThreatRadius", 100);
925 // always use declined names in the russian client
926 m_configs
[CONFIG_DECLINED_NAMES_USED
] =
927 (m_configs
[CONFIG_REALM_ZONE
] == REALM_ZONE_RUSSIAN
) ? true : sConfig
.GetBoolDefault("DeclinedNames", false);
929 m_configs
[CONFIG_LISTEN_RANGE_SAY
] = sConfig
.GetIntDefault("ListenRange.Say", 25);
930 m_configs
[CONFIG_LISTEN_RANGE_TEXTEMOTE
] = sConfig
.GetIntDefault("ListenRange.TextEmote", 25);
931 m_configs
[CONFIG_LISTEN_RANGE_YELL
] = sConfig
.GetIntDefault("ListenRange.Yell", 300);
933 m_configs
[CONFIG_ARENA_MAX_RATING_DIFFERENCE
] = sConfig
.GetIntDefault("Arena.MaxRatingDifference", 0);
934 m_configs
[CONFIG_ARENA_RATING_DISCARD_TIMER
] = sConfig
.GetIntDefault("Arena.RatingDiscardTimer",300000);
935 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS
] = sConfig
.GetBoolDefault("Arena.AutoDistributePoints", false);
936 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS
] = sConfig
.GetIntDefault("Arena.AutoDistributeInterval", 7);
938 m_configs
[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER
] = sConfig
.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
939 m_configs
[CONFIG_INSTANT_LOGOUT
] = sConfig
.GetIntDefault("InstantLogout", SEC_MODERATOR
);
941 m_VisibleUnitGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
942 if(m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
944 sLog
.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE
);
945 m_VisibleUnitGreyDistance
= MAX_VISIBILITY_DISTANCE
;
947 m_VisibleObjectGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
948 if(m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
950 sLog
.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
);
951 m_VisibleObjectGreyDistance
= MAX_VISIBILITY_DISTANCE
;
954 m_MaxVisibleDistanceForCreature
= sConfig
.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE
);
955 if(m_MaxVisibleDistanceForCreature
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
957 sLog
.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
958 m_MaxVisibleDistanceForCreature
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
960 else if(m_MaxVisibleDistanceForCreature
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
962 sLog
.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
963 m_MaxVisibleDistanceForCreature
= MAX_VISIBILITY_DISTANCE
-m_VisibleUnitGreyDistance
;
965 m_MaxVisibleDistanceForPlayer
= sConfig
.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE
);
966 if(m_MaxVisibleDistanceForPlayer
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
968 sLog
.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
969 m_MaxVisibleDistanceForPlayer
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
971 else if(m_MaxVisibleDistanceForPlayer
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
973 sLog
.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
974 m_MaxVisibleDistanceForPlayer
= MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
;
976 m_MaxVisibleDistanceForObject
= sConfig
.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE
);
977 if(m_MaxVisibleDistanceForObject
< INTERACTION_DISTANCE
)
979 sLog
.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE
));
980 m_MaxVisibleDistanceForObject
= INTERACTION_DISTANCE
;
982 else if(m_MaxVisibleDistanceForObject
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
984 sLog
.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
985 m_MaxVisibleDistanceForObject
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
987 m_MaxVisibleDistanceInFlight
= sConfig
.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE
);
988 if(m_MaxVisibleDistanceInFlight
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
990 sLog
.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
991 m_MaxVisibleDistanceInFlight
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
994 ///- Read the "Data" directory from the config file
995 std::string dataPath
= sConfig
.GetStringDefault("DataDir","./");
996 if( dataPath
.at(dataPath
.length()-1)!='/' && dataPath
.at(dataPath
.length()-1)!='\\' )
997 dataPath
.append("/");
1001 if(dataPath
!=m_dataPath
)
1002 sLog
.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath
.c_str());
1006 m_dataPath
= dataPath
;
1007 sLog
.outString("Using DataDir %s",m_dataPath
.c_str());
1010 bool enableLOS
= sConfig
.GetBoolDefault("vmap.enableLOS", false);
1011 bool enableHeight
= sConfig
.GetBoolDefault("vmap.enableHeight", false);
1012 std::string ignoreMapIds
= sConfig
.GetStringDefault("vmap.ignoreMapIds", "");
1013 std::string ignoreSpellIds
= sConfig
.GetStringDefault("vmap.ignoreSpellIds", "");
1014 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS
);
1015 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight
);
1016 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds
.c_str());
1017 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds
.c_str());
1018 sLog
.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS
, enableHeight
);
1019 sLog
.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath
.c_str());
1020 sLog
.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1023 /// Initialize the World
1024 void World::SetInitialWorldSettings()
1026 ///- Initialize the random number generator
1027 srand((unsigned int)time(NULL
));
1029 ///- Initialize config settings
1030 LoadConfigSettings();
1032 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1033 objmgr
.SetHighestGuids();
1035 ///- Check the existence of the map files for all races' startup areas.
1036 if( !MapManager::ExistMapAndVMap(0,-6240.32f
, 331.033f
)
1037 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1038 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1039 ||!MapManager::ExistMapAndVMap(1,-618.518f
,-4251.67f
)
1040 ||!MapManager::ExistMapAndVMap(0, 1676.35f
, 1677.45f
)
1041 ||!MapManager::ExistMapAndVMap(1, 10311.3f
, 832.463f
)
1042 ||!MapManager::ExistMapAndVMap(1,-2917.58f
,-257.98f
)
1043 ||m_configs
[CONFIG_EXPANSION
] && (
1044 !MapManager::ExistMapAndVMap(530,10349.6f
,-6357.29f
) || !MapManager::ExistMapAndVMap(530,-3961.64f
,-13931.2f
) ) )
1046 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());
1050 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1051 sLog
.outString( "" );
1052 sLog
.outString( "Loading MaNGOS strings..." );
1053 if (!objmgr
.LoadMangosStrings())
1054 exit(1); // Error message displayed in function already
1056 ///- Update the realm entry in the database with the realm type from the config file
1057 //No SQL injection as values are treated as integers
1059 // not send custom type REALM_FFA_PVP to realm list
1060 uint32 server_type
= IsFFAPvPRealm() ? REALM_TYPE_PVP
: getConfig(CONFIG_GAME_TYPE
);
1061 uint32 realm_zone
= getConfig(CONFIG_REALM_ZONE
);
1062 loginDatabase
.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type
, realm_zone
, realmID
);
1064 ///- Remove the bones after a restart
1065 CharacterDatabase
.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1067 ///- Load the DBC files
1068 sLog
.outString("Initialize data stores...");
1069 LoadDBCStores(m_dataPath
);
1072 sLog
.outString( "Loading Script Names...");
1073 objmgr
.LoadScriptNames();
1075 sLog
.outString( "Loading InstanceTemplate..." );
1076 objmgr
.LoadInstanceTemplate();
1078 sLog
.outString( "Loading SkillLineAbilityMultiMap Data..." );
1079 spellmgr
.LoadSkillLineAbilityMap();
1081 ///- Clean up and pack instances
1082 sLog
.outString( "Cleaning up instances..." );
1083 sInstanceSaveManager
.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1085 sLog
.outString( "Packing instances..." );
1086 sInstanceSaveManager
.PackInstances();
1089 sLog
.outString( "Loading Localization strings..." );
1090 objmgr
.LoadCreatureLocales();
1091 objmgr
.LoadGameObjectLocales();
1092 objmgr
.LoadItemLocales();
1093 objmgr
.LoadQuestLocales();
1094 objmgr
.LoadNpcTextLocales();
1095 objmgr
.LoadPageTextLocales();
1096 objmgr
.LoadNpcOptionLocales();
1097 objmgr
.LoadPointOfInterestLocales();
1098 objmgr
.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1099 sLog
.outString( ">>> Localization strings loaded" );
1102 sLog
.outString( "Loading Page Texts..." );
1103 objmgr
.LoadPageTexts();
1105 sLog
.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1106 objmgr
.LoadGameobjectInfo();
1108 sLog
.outString( "Loading Spell Chain Data..." );
1109 spellmgr
.LoadSpellChains();
1111 sLog
.outString( "Loading Spell Elixir types..." );
1112 spellmgr
.LoadSpellElixirs();
1114 sLog
.outString( "Loading Spell Learn Skills..." );
1115 spellmgr
.LoadSpellLearnSkills(); // must be after LoadSpellChains
1117 sLog
.outString( "Loading Spell Learn Spells..." );
1118 spellmgr
.LoadSpellLearnSpells();
1120 sLog
.outString( "Loading Spell Proc Event conditions..." );
1121 spellmgr
.LoadSpellProcEvents();
1123 sLog
.outString( "Loading Spell Bonus Data..." );
1124 spellmgr
.LoadSpellBonusess();
1126 sLog
.outString( "Loading Aggro Spells Definitions...");
1127 spellmgr
.LoadSpellThreats();
1129 sLog
.outString( "Loading NPC Texts..." );
1130 objmgr
.LoadGossipText();
1132 sLog
.outString( "Loading Item Random Enchantments Table..." );
1133 LoadRandomEnchantmentsTable();
1135 sLog
.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1136 objmgr
.LoadItemPrototypes();
1138 sLog
.outString( "Loading Item Texts..." );
1139 objmgr
.LoadItemTexts();
1141 sLog
.outString( "Loading Creature Model Based Info Data..." );
1142 objmgr
.LoadCreatureModelInfo();
1144 sLog
.outString( "Loading Equipment templates...");
1145 objmgr
.LoadEquipmentTemplates();
1147 sLog
.outString( "Loading Creature templates..." );
1148 objmgr
.LoadCreatureTemplates();
1150 sLog
.outString( "Loading SpellsScriptTarget...");
1151 spellmgr
.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1153 sLog
.outString( "Loading Creature Reputation OnKill Data..." );
1154 objmgr
.LoadReputationOnKill();
1156 sLog
.outString( "Loading Points Of Interest Data..." );
1157 objmgr
.LoadPointsOfInterest();
1159 sLog
.outString( "Loading Pet Create Spells..." );
1160 objmgr
.LoadPetCreateSpells();
1162 sLog
.outString( "Loading Creature Data..." );
1163 objmgr
.LoadCreatures();
1165 sLog
.outString( "Loading Creature Addon Data..." );
1167 objmgr
.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1168 sLog
.outString( ">>> Creature Addon Data loaded" );
1171 sLog
.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1172 objmgr
.LoadCreatureRespawnTimes();
1174 sLog
.outString( "Loading Gameobject Data..." );
1175 objmgr
.LoadGameobjects();
1177 sLog
.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1178 objmgr
.LoadGameobjectRespawnTimes();
1180 sLog
.outString( "Loading Game Event Data...");
1182 gameeventmgr
.LoadFromDB();
1183 sLog
.outString( ">>> Game Event Data loaded" );
1186 sLog
.outString( "Loading Weather Data..." );
1187 objmgr
.LoadWeatherZoneChances();
1189 sLog
.outString( "Loading Quests..." );
1190 objmgr
.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1192 sLog
.outString( "Loading Quests Relations..." );
1194 objmgr
.LoadQuestRelations(); // must be after quest load
1195 sLog
.outString( ">>> Quests Relations loaded" );
1198 sLog
.outString( "Loading AreaTrigger definitions..." );
1199 objmgr
.LoadAreaTriggerTeleports(); // must be after item template load
1201 sLog
.outString( "Loading Quest Area Triggers..." );
1202 objmgr
.LoadQuestAreaTriggers(); // must be after LoadQuests
1204 sLog
.outString( "Loading Tavern Area Triggers..." );
1205 objmgr
.LoadTavernAreaTriggers();
1207 sLog
.outString( "Loading AreaTrigger script names..." );
1208 objmgr
.LoadAreaTriggerScripts();
1210 sLog
.outString( "Loading Graveyard-zone links...");
1211 objmgr
.LoadGraveyardZones();
1213 sLog
.outString( "Loading Spell target coordinates..." );
1214 spellmgr
.LoadSpellTargetPositions();
1216 sLog
.outString( "Loading SpellAffect definitions..." );
1217 spellmgr
.LoadSpellAffects();
1219 sLog
.outString( "Loading spell pet auras..." );
1220 spellmgr
.LoadSpellPetAuras();
1222 sLog
.outString( "Loading pet levelup spells..." );
1223 spellmgr
.LoadPetLevelupSpellMap();
1225 sLog
.outString( "Loading Player Create Info & Level Stats..." );
1227 objmgr
.LoadPlayerInfo();
1228 sLog
.outString( ">>> Player Create Info & Level Stats loaded" );
1231 sLog
.outString( "Loading Exploration BaseXP Data..." );
1232 objmgr
.LoadExplorationBaseXP();
1234 sLog
.outString( "Loading Pet Name Parts..." );
1235 objmgr
.LoadPetNames();
1237 sLog
.outString( "Loading the max pet number..." );
1238 objmgr
.LoadPetNumber();
1240 sLog
.outString( "Loading pet level stats..." );
1241 objmgr
.LoadPetLevelInfo();
1243 sLog
.outString( "Loading Player Corpses..." );
1244 objmgr
.LoadCorpses();
1246 sLog
.outString( "Loading Loot Tables..." );
1249 sLog
.outString( ">>> Loot Tables loaded" );
1252 sLog
.outString( "Loading Skill Discovery Table..." );
1253 LoadSkillDiscoveryTable();
1255 sLog
.outString( "Loading Skill Extra Item Table..." );
1256 LoadSkillExtraItemTable();
1258 sLog
.outString( "Loading Skill Fishing base level requirements..." );
1259 objmgr
.LoadFishingBaseSkillLevel();
1261 sLog
.outString( "Loading Achievements..." );
1263 achievementmgr
.LoadAchievementCriteriaList();
1264 achievementmgr
.LoadRewards();
1265 achievementmgr
.LoadRewardLocales();
1266 achievementmgr
.LoadCompletedAchievements();
1267 sLog
.outString( ">>> Achievements loaded" );
1270 ///- Load dynamic data tables from the database
1271 sLog
.outString( "Loading Auctions..." );
1273 auctionmgr
.LoadAuctionItems();
1274 auctionmgr
.LoadAuctions();
1275 sLog
.outString( ">>> Auctions loaded" );
1278 sLog
.outString( "Loading Guilds..." );
1279 objmgr
.LoadGuilds();
1281 sLog
.outString( "Loading ArenaTeams..." );
1282 objmgr
.LoadArenaTeams();
1284 sLog
.outString( "Loading Groups..." );
1285 objmgr
.LoadGroups();
1287 sLog
.outString( "Loading ReservedNames..." );
1288 objmgr
.LoadReservedPlayersNames();
1290 sLog
.outString( "Loading GameObjects for quests..." );
1291 objmgr
.LoadGameObjectForQuests();
1293 sLog
.outString( "Loading BattleMasters..." );
1294 sBattleGroundMgr
.LoadBattleMastersEntry();
1296 sLog
.outString( "Loading GameTeleports..." );
1297 objmgr
.LoadGameTele();
1299 sLog
.outString( "Loading Npc Text Id..." );
1300 objmgr
.LoadNpcTextId(); // must be after load Creature and NpcText
1302 sLog
.outString( "Loading Npc Options..." );
1303 objmgr
.LoadNpcOptions();
1305 sLog
.outString( "Loading Vendors..." );
1306 objmgr
.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1308 sLog
.outString( "Loading Trainers..." );
1309 objmgr
.LoadTrainerSpell(); // must be after load CreatureTemplate
1311 sLog
.outString( "Loading Waypoints..." );
1315 sLog
.outString( "Loading GM tickets...");
1316 ticketmgr
.LoadGMTickets();
1318 ///- Handle outdated emails (delete/return)
1319 sLog
.outString( "Returning old mails..." );
1320 objmgr
.ReturnOrDeleteOldMails(false);
1322 ///- Load and initialize scripts
1323 sLog
.outString( "Loading Scripts..." );
1325 objmgr
.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1326 objmgr
.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1327 objmgr
.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1328 objmgr
.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1329 objmgr
.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1330 sLog
.outString( ">>> Scripts loaded" );
1333 sLog
.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1334 objmgr
.LoadDbScriptStrings();
1336 sLog
.outString( "Initializing Scripts..." );
1337 if(!LoadScriptingModule())
1340 ///- Initialize game time and timers
1341 sLog
.outString( "DEBUG:: Initialize game time and timers" );
1342 m_gameTime
= time(NULL
);
1343 m_startTime
=m_gameTime
;
1348 local
=*(localtime(&curr
)); // dereference and assign
1350 sprintf( isoDate
, "%04d-%02d-%02d %02d:%02d:%02d",
1351 local
.tm_year
+1900, local
.tm_mon
+1, local
.tm_mday
, local
.tm_hour
, local
.tm_min
, local
.tm_sec
);
1353 WorldDatabase
.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD
", 0)",
1354 isoDate
, uint64(m_startTime
));
1356 m_timers
[WUPDATE_OBJECTS
].SetInterval(0);
1357 m_timers
[WUPDATE_SESSIONS
].SetInterval(0);
1358 m_timers
[WUPDATE_WEATHERS
].SetInterval(1000);
1359 m_timers
[WUPDATE_AUCTIONS
].SetInterval(MINUTE
*1000); //set auction update interval to 1 minute
1360 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*1000);
1361 //Update "uptime" table based on configuration entry in minutes.
1362 m_timers
[WUPDATE_CORPSES
].SetInterval(20*MINUTE
*1000); //erase corpses every 20 minutes
1364 //to set mailtimer to return mails every day between 4 and 5 am
1365 //mailtimer is increased when updating auctions
1366 //one second is 1000 -(tested on win system)
1367 mail_timer
= ((((localtime( &m_gameTime
)->tm_hour
+ 20) % 24)* HOUR
* 1000) / m_timers
[WUPDATE_AUCTIONS
].GetInterval() );
1369 mail_timer_expires
= ( (DAY
* 1000) / (m_timers
[WUPDATE_AUCTIONS
].GetInterval()));
1370 sLog
.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer
, mail_timer_expires
);
1372 ///- Initilize static helper structures
1373 AIRegistry::Initialize();
1374 WaypointMovementGenerator
<Creature
>::Initialize();
1375 Player::InitVisibleBits();
1377 ///- Initialize MapManager
1378 sLog
.outString( "Starting Map System" );
1379 MapManager::Instance().Initialize();
1381 ///- Initialize Battlegrounds
1382 sLog
.outString( "Starting BattleGround System" );
1383 sBattleGroundMgr
.CreateInitialBattleGrounds();
1384 sBattleGroundMgr
.InitAutomaticArenaPointDistribution();
1386 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1387 sLog
.outString( "Loading Transports..." );
1388 MapManager::Instance().LoadTransports();
1390 sLog
.outString("Deleting expired bans..." );
1391 loginDatabase
.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1393 sLog
.outString("Calculate next daily quest reset time..." );
1394 InitDailyQuestResetTime();
1396 sLog
.outString("Starting Game Event system..." );
1397 uint32 nextGameEvent
= gameeventmgr
.Initialize();
1398 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
); //depend on next event
1400 sLog
.outString( "WORLD: World initialized" );
1403 void World::DetectDBCLang()
1405 uint32 m_lang_confid
= sConfig
.GetIntDefault("DBC.Locale", 255);
1407 if(m_lang_confid
!= 255 && m_lang_confid
>= MAX_LOCALE
)
1409 sLog
.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE
);
1410 m_lang_confid
= LOCALE_enUS
;
1413 ChrRacesEntry
const* race
= sChrRacesStore
.LookupEntry(1);
1415 std::string availableLocalsStr
;
1417 int default_locale
= MAX_LOCALE
;
1418 for (int i
= MAX_LOCALE
-1; i
>= 0; --i
)
1420 if ( strlen(race
->name
[i
]) > 0) // check by race names
1423 m_availableDbcLocaleMask
|= (1 << i
);
1424 availableLocalsStr
+= localeNames
[i
];
1425 availableLocalsStr
+= " ";
1429 if( default_locale
!= m_lang_confid
&& m_lang_confid
< MAX_LOCALE
&&
1430 (m_availableDbcLocaleMask
& (1 << m_lang_confid
)) )
1432 default_locale
= m_lang_confid
;
1435 if(default_locale
>= MAX_LOCALE
)
1437 sLog
.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1441 m_defaultDbcLocale
= LocaleConstant(default_locale
);
1443 sLog
.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames
[m_defaultDbcLocale
],availableLocalsStr
.empty() ? "<none>" : availableLocalsStr
.c_str());
1447 /// Update the World !
1448 void World::Update(uint32 diff
)
1450 ///- Update the different timers
1451 for(int i
= 0; i
< WUPDATE_COUNT
; i
++)
1452 if(m_timers
[i
].GetCurrent()>=0)
1453 m_timers
[i
].Update(diff
);
1454 else m_timers
[i
].SetCurrent(0);
1456 ///- Update the game time and check for shutdown time
1459 /// Handle daily quests reset time
1460 if(m_gameTime
> m_NextDailyQuestReset
)
1463 m_NextDailyQuestReset
+= DAY
;
1466 /// <ul><li> Handle auctions when the timer has passed
1467 if (m_timers
[WUPDATE_AUCTIONS
].Passed())
1469 m_timers
[WUPDATE_AUCTIONS
].Reset();
1471 ///- Update mails (return old mails with item, or delete them)
1472 //(tested... works on win)
1473 if (++mail_timer
> mail_timer_expires
)
1476 objmgr
.ReturnOrDeleteOldMails(true);
1479 ///- Handle expired auctions
1480 auctionmgr
.Update();
1483 /// <li> Handle session updates when the timer has passed
1484 if (m_timers
[WUPDATE_SESSIONS
].Passed())
1486 m_timers
[WUPDATE_SESSIONS
].Reset();
1488 UpdateSessions(diff
);
1491 /// <li> Handle weather updates when the timer has passed
1492 if (m_timers
[WUPDATE_WEATHERS
].Passed())
1494 m_timers
[WUPDATE_WEATHERS
].Reset();
1496 ///- Send an update signal to Weather objects
1497 WeatherMap::iterator itr
, next
;
1498 for (itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); itr
= next
)
1503 ///- and remove Weather objects for zones with no player
1504 //As interval > WorldTick
1505 if(!itr
->second
->Update(m_timers
[WUPDATE_WEATHERS
].GetInterval()))
1508 m_weathers
.erase(itr
);
1512 /// <li> Update uptime table
1513 if (m_timers
[WUPDATE_UPTIME
].Passed())
1515 uint32 tmpDiff
= (m_gameTime
- m_startTime
);
1516 uint32 maxClientsNum
= sWorld
.GetMaxActiveSessionCount();
1518 m_timers
[WUPDATE_UPTIME
].Reset();
1519 WorldDatabase
.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD
, tmpDiff
, maxClientsNum
, uint64(m_startTime
));
1522 /// <li> Handle all other objects
1523 if (m_timers
[WUPDATE_OBJECTS
].Passed())
1525 m_timers
[WUPDATE_OBJECTS
].Reset();
1526 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1527 MapManager::Instance().Update(diff
); // As interval = 0
1529 ///- Process necessary scripts
1530 if (!m_scriptSchedule
.empty())
1533 sBattleGroundMgr
.Update(diff
);
1536 // execute callbacks from sql queries that were queued recently
1537 UpdateResultQueue();
1539 ///- Erase corpses once every 20 minutes
1540 if (m_timers
[WUPDATE_CORPSES
].Passed())
1542 m_timers
[WUPDATE_CORPSES
].Reset();
1547 ///- Process Game events when necessary
1548 if (m_timers
[WUPDATE_EVENTS
].Passed())
1550 m_timers
[WUPDATE_EVENTS
].Reset(); // to give time for Update() to be processed
1551 uint32 nextGameEvent
= gameeventmgr
.Update();
1552 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
);
1553 m_timers
[WUPDATE_EVENTS
].Reset();
1557 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1558 MapManager::Instance().DoDelayedMovesAndRemoves();
1560 // update the instance reset times
1561 sInstanceSaveManager
.Update();
1563 // And last, but not least handle the issued cli commands
1564 ProcessCliCommands();
1567 /// Put scripts in the execution queue
1568 void World::ScriptsStart(ScriptMapMap
const& scripts
, uint32 id
, Object
* source
, Object
* target
)
1570 ///- Find the script map
1571 ScriptMapMap::const_iterator s
= scripts
.find(id
);
1572 if (s
== scripts
.end())
1575 // prepare static data
1576 uint64 sourceGUID
= source
->GetGUID();
1577 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1578 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1580 ///- Schedule script execution for all scripts in the script map
1581 ScriptMap
const *s2
= &(s
->second
);
1582 bool immedScript
= false;
1583 for (ScriptMap::const_iterator iter
= s2
->begin(); iter
!= s2
->end(); ++iter
)
1586 sa
.sourceGUID
= sourceGUID
;
1587 sa
.targetGUID
= targetGUID
;
1588 sa
.ownerGUID
= ownerGUID
;
1590 sa
.script
= &iter
->second
;
1591 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ iter
->first
, sa
));
1592 if (iter
->first
== 0)
1595 ///- If one of the effects should be immediate, launch the script execution
1600 void World::ScriptCommandStart(ScriptInfo
const& script
, uint32 delay
, Object
* source
, Object
* target
)
1602 // NOTE: script record _must_ exist until command executed
1604 // prepare static data
1605 uint64 sourceGUID
= source
->GetGUID();
1606 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1607 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1610 sa
.sourceGUID
= sourceGUID
;
1611 sa
.targetGUID
= targetGUID
;
1612 sa
.ownerGUID
= ownerGUID
;
1614 sa
.script
= &script
;
1615 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ delay
, sa
));
1617 ///- If effects should be immediate, launch the script execution
1622 /// Process queued scripts
1623 void World::ScriptsProcess()
1625 if (m_scriptSchedule
.empty())
1628 ///- Process overdue queued scripts
1629 std::multimap
<time_t, ScriptAction
>::iterator iter
= m_scriptSchedule
.begin();
1630 // ok as multimap is a *sorted* associative container
1631 while (!m_scriptSchedule
.empty() && (iter
->first
<= m_gameTime
))
1633 ScriptAction
const& step
= iter
->second
;
1635 Object
* source
= NULL
;
1639 switch(GUID_HIPART(step
.sourceGUID
))
1642 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1644 Player
* player
= HashMapHolder
<Player
>::Find(step
.ownerGUID
);
1646 source
= player
->GetItemByGuid(step
.sourceGUID
);
1650 source
= HashMapHolder
<Creature
>::Find(step
.sourceGUID
);
1653 source
= HashMapHolder
<Pet
>::Find(step
.sourceGUID
);
1655 case HIGHGUID_VEHICLE
:
1656 source
= HashMapHolder
<Vehicle
>::Find(step
.sourceGUID
);
1658 case HIGHGUID_PLAYER
:
1659 source
= HashMapHolder
<Player
>::Find(step
.sourceGUID
);
1661 case HIGHGUID_GAMEOBJECT
:
1662 source
= HashMapHolder
<GameObject
>::Find(step
.sourceGUID
);
1664 case HIGHGUID_CORPSE
:
1665 source
= HashMapHolder
<Corpse
>::Find(step
.sourceGUID
);
1668 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.sourceGUID
));
1673 if(source
&& !source
->IsInWorld()) source
= NULL
;
1675 Object
* target
= NULL
;
1679 switch(GUID_HIPART(step
.targetGUID
))
1682 target
= HashMapHolder
<Creature
>::Find(step
.targetGUID
);
1685 target
= HashMapHolder
<Pet
>::Find(step
.targetGUID
);
1687 case HIGHGUID_VEHICLE
:
1688 target
= HashMapHolder
<Vehicle
>::Find(step
.targetGUID
);
1690 case HIGHGUID_PLAYER
: // empty GUID case also
1691 target
= HashMapHolder
<Player
>::Find(step
.targetGUID
);
1693 case HIGHGUID_GAMEOBJECT
:
1694 target
= HashMapHolder
<GameObject
>::Find(step
.targetGUID
);
1696 case HIGHGUID_CORPSE
:
1697 target
= HashMapHolder
<Corpse
>::Find(step
.targetGUID
);
1700 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.targetGUID
));
1705 if(target
&& !target
->IsInWorld()) target
= NULL
;
1707 switch (step
.script
->command
)
1709 case SCRIPT_COMMAND_TALK
:
1713 sLog
.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1717 if(source
->GetTypeId()!=TYPEID_UNIT
)
1719 sLog
.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1723 uint64 unit_target
= target
? target
->GetGUID() : 0;
1725 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1726 switch(step
.script
->datalong
)
1729 ((Creature
*)source
)->Say(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1734 sLog
.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step
.script
->datalong
);
1737 ((Creature
*)source
)->Whisper(step
.script
->dataint
,unit_target
);
1740 ((Creature
*)source
)->Yell(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1742 case 3: // Emote text
1743 ((Creature
*)source
)->TextEmote(step
.script
->dataint
, unit_target
);
1746 break; // must be already checked at load
1751 case SCRIPT_COMMAND_EMOTE
:
1754 sLog
.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1758 if(source
->GetTypeId()!=TYPEID_UNIT
)
1760 sLog
.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1764 ((Creature
*)source
)->HandleEmoteCommand(step
.script
->datalong
);
1766 case SCRIPT_COMMAND_FIELD_SET
:
1769 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1772 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1774 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1775 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1779 source
->SetUInt32Value(step
.script
->datalong
, step
.script
->datalong2
);
1781 case SCRIPT_COMMAND_MOVE_TO
:
1784 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1788 if(source
->GetTypeId()!=TYPEID_UNIT
)
1790 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1793 ((Unit
*)source
)->SendMonsterMoveWithSpeed(step
.script
->x
, step
.script
->y
, step
.script
->z
, ((Unit
*)source
)->GetUnitMovementFlags(), step
.script
->datalong2
);
1794 ((Unit
*)source
)->GetMap()->CreatureRelocation(((Creature
*)source
), step
.script
->x
, step
.script
->y
, step
.script
->z
, 0);
1796 case SCRIPT_COMMAND_FLAG_SET
:
1799 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1802 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1804 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1805 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1809 source
->SetFlag(step
.script
->datalong
, step
.script
->datalong2
);
1811 case SCRIPT_COMMAND_FLAG_REMOVE
:
1814 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1817 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1819 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1820 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1824 source
->RemoveFlag(step
.script
->datalong
, step
.script
->datalong2
);
1827 case SCRIPT_COMMAND_TELEPORT_TO
:
1829 // accept player in any one from target/source arg
1830 if (!target
&& !source
)
1832 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1836 // must be only Player
1837 if((!target
|| target
->GetTypeId() != TYPEID_PLAYER
) && (!source
|| source
->GetTypeId() != TYPEID_PLAYER
))
1839 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source
? source
->GetTypeId() : 0, target
? target
->GetTypeId() : 0);
1843 Player
* pSource
= target
&& target
->GetTypeId() == TYPEID_PLAYER
? (Player
*)target
: (Player
*)source
;
1845 pSource
->TeleportTo(step
.script
->datalong
, step
.script
->x
, step
.script
->y
, step
.script
->z
, step
.script
->o
);
1849 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE
:
1851 if(!step
.script
->datalong
) // creature not specified
1853 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1859 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1863 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1867 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1871 float x
= step
.script
->x
;
1872 float y
= step
.script
->y
;
1873 float z
= step
.script
->z
;
1874 float o
= step
.script
->o
;
1876 Creature
* pCreature
= summoner
->SummonCreature(step
.script
->datalong
, x
, y
, z
, o
,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN
,step
.script
->datalong2
);
1879 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step
.script
->datalong
);
1886 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT
:
1888 if(!step
.script
->datalong
) // gameobject not specified
1890 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1896 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1900 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1904 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1908 GameObject
*go
= NULL
;
1909 int32 time_to_despawn
= step
.script
->datalong2
<5 ? 5 : (int32
)step
.script
->datalong2
;
1911 CellPair
p(MaNGOS::ComputeCellPair(summoner
->GetPositionX(), summoner
->GetPositionY()));
1913 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1915 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*summoner
,step
.script
->datalong
);
1916 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(summoner
, go
,go_check
);
1918 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
1919 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1920 cell_lock
->Visit(cell_lock
, object_checker
, *summoner
->GetMap());
1924 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step
.script
->datalong
);
1928 if( go
->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE
||
1929 go
->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE
||
1930 go
->GetGoType()==GAMEOBJECT_TYPE_DOOR
||
1931 go
->GetGoType()==GAMEOBJECT_TYPE_BUTTON
||
1932 go
->GetGoType()==GAMEOBJECT_TYPE_TRAP
)
1934 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go
->GetGoType()), step
.script
->datalong
);
1938 if( go
->isSpawned() )
1939 break; //gameobject already spawned
1941 go
->SetLootState(GO_READY
);
1942 go
->SetRespawnTime(time_to_despawn
); //despawn object in ? seconds
1944 go
->GetMap()->Add(go
);
1947 case SCRIPT_COMMAND_OPEN_DOOR
:
1949 if(!step
.script
->datalong
) // door not specified
1951 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1957 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1961 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
1963 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
1967 Unit
* caster
= (Unit
*)source
;
1969 GameObject
*door
= NULL
;
1970 int32 time_to_close
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
1972 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
1974 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1976 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
1977 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
1979 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
1980 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1981 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
1985 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
1988 if ( door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
1990 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
1994 if( !door
->GetGoState() )
1995 break; //door already open
1997 door
->UseDoorOrButton(time_to_close
);
1999 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2000 ((GameObject
*)target
)->UseDoorOrButton(time_to_close
);
2003 case SCRIPT_COMMAND_CLOSE_DOOR
:
2005 if(!step
.script
->datalong
) // guid for door not specified
2007 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2013 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2017 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
2019 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
2023 Unit
* caster
= (Unit
*)source
;
2025 GameObject
*door
= NULL
;
2026 int32 time_to_open
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
2028 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
2030 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
2032 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
2033 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
2035 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
2036 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
2037 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
2041 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
2044 if ( door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
2046 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
2050 if( door
->GetGoState() )
2051 break; //door already closed
2053 door
->UseDoorOrButton(time_to_open
);
2055 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2056 ((GameObject
*)target
)->UseDoorOrButton(time_to_open
);
2060 case SCRIPT_COMMAND_QUEST_EXPLORED
:
2064 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2070 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2074 // when script called for item spell casting then target == (unit or GO) and source is player
2075 WorldObject
* worldObject
;
2078 if(target
->GetTypeId()==TYPEID_PLAYER
)
2080 if(source
->GetTypeId()!=TYPEID_UNIT
&& source
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2082 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source
->GetTypeId());
2086 worldObject
= (WorldObject
*)source
;
2087 player
= (Player
*)target
;
2091 if(target
->GetTypeId()!=TYPEID_UNIT
&& target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2093 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2097 if(source
->GetTypeId()!=TYPEID_PLAYER
)
2099 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source
->GetTypeId());
2103 worldObject
= (WorldObject
*)target
;
2104 player
= (Player
*)source
;
2107 // quest id and flags checked at script loading
2108 if( (worldObject
->GetTypeId()!=TYPEID_UNIT
|| ((Unit
*)worldObject
)->isAlive()) &&
2109 (step
.script
->datalong2
==0 || worldObject
->IsWithinDistInMap(player
,float(step
.script
->datalong2
))) )
2110 player
->AreaExploredOrEventHappens(step
.script
->datalong
);
2112 player
->FailQuest(step
.script
->datalong
);
2117 case SCRIPT_COMMAND_ACTIVATE_OBJECT
:
2121 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2125 if(!source
->isType(TYPEMASK_UNIT
))
2127 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2133 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2137 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2139 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2143 Unit
* caster
= (Unit
*)source
;
2145 GameObject
*go
= (GameObject
*)target
;
2151 case SCRIPT_COMMAND_REMOVE_AURA
:
2153 Object
* cmdTarget
= step
.script
->datalong2
? source
: target
;
2157 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step
.script
->datalong2
? "source" : "target");
2161 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2163 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
? "source" : "target",cmdTarget
->GetTypeId());
2167 ((Unit
*)cmdTarget
)->RemoveAurasDueToSpell(step
.script
->datalong
);
2171 case SCRIPT_COMMAND_CAST_SPELL
:
2175 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2179 if(!source
->isType(TYPEMASK_UNIT
))
2181 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2185 Object
* cmdTarget
= step
.script
->datalong2
? source
: target
;
2189 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step
.script
->datalong2
? "source" : "target");
2193 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2195 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
? "source" : "target",cmdTarget
->GetTypeId());
2199 Unit
* spellTarget
= (Unit
*)cmdTarget
;
2201 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2202 ((Unit
*)source
)->CastSpell(spellTarget
,step
.script
->datalong
,false);
2208 sLog
.outError("Unknown script command %u called.",step
.script
->command
);
2212 m_scriptSchedule
.erase(iter
);
2214 iter
= m_scriptSchedule
.begin();
2219 /// Send a packet to all players (except self if mentioned)
2220 void World::SendGlobalMessage(WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2222 SessionMap::iterator itr
;
2223 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2226 itr
->second
->GetPlayer() &&
2227 itr
->second
->GetPlayer()->IsInWorld() &&
2228 itr
->second
!= self
&&
2229 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2231 itr
->second
->SendPacket(packet
);
2236 /// Send a System Message to all players (except self if mentioned)
2237 void World::SendWorldText(int32 string_id
, ...)
2239 std::vector
<std::vector
<WorldPacket
*> > data_cache
; // 0 = default, i => i-1 locale index
2241 for(SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2243 if(!itr
->second
|| !itr
->second
->GetPlayer() || !itr
->second
->GetPlayer()->IsInWorld() )
2246 uint32 loc_idx
= itr
->second
->GetSessionDbLocaleIndex();
2247 uint32 cache_idx
= loc_idx
+1;
2249 std::vector
<WorldPacket
*>* data_list
;
2251 // create if not cached yet
2252 if(data_cache
.size() < cache_idx
+1 || data_cache
[cache_idx
].empty())
2254 if(data_cache
.size() < cache_idx
+1)
2255 data_cache
.resize(cache_idx
+1);
2257 data_list
= &data_cache
[cache_idx
];
2259 char const* text
= objmgr
.GetMangosString(string_id
,loc_idx
);
2264 va_start( argptr
, string_id
);
2265 vsnprintf( buf
,1000, text
, argptr
);
2268 char* pos
= &buf
[0];
2270 while(char* line
= ChatHandler::LineFromMessage(pos
))
2272 WorldPacket
* data
= new WorldPacket();
2273 ChatHandler::FillMessageData(data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, line
, NULL
);
2274 data_list
->push_back(data
);
2278 data_list
= &data_cache
[cache_idx
];
2280 for(int i
= 0; i
< data_list
->size(); ++i
)
2281 itr
->second
->SendPacket((*data_list
)[i
]);
2285 for(int i
= 0; i
< data_cache
.size(); ++i
)
2286 for(int j
= 0; j
< data_cache
[i
].size(); ++j
)
2287 delete data_cache
[i
][j
];
2290 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2291 void World::SendGlobalText(const char* text
, WorldSession
*self
)
2295 // need copy to prevent corruption by strtok call in LineFromMessage original string
2296 char* buf
= strdup(text
);
2299 while(char* line
= ChatHandler::LineFromMessage(pos
))
2301 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, line
, NULL
);
2302 SendGlobalMessage(&data
, self
);
2308 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2309 void World::SendZoneMessage(uint32 zone
, WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2311 SessionMap::iterator itr
;
2312 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2315 itr
->second
->GetPlayer() &&
2316 itr
->second
->GetPlayer()->IsInWorld() &&
2317 itr
->second
->GetPlayer()->GetZoneId() == zone
&&
2318 itr
->second
!= self
&&
2319 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2321 itr
->second
->SendPacket(packet
);
2326 /// Send a System Message to all players in the zone (except self if mentioned)
2327 void World::SendZoneText(uint32 zone
, const char* text
, WorldSession
*self
, uint32 team
)
2330 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, text
, NULL
);
2331 SendZoneMessage(zone
, &data
, self
,team
);
2334 /// Kick (and save) all players
2335 void World::KickAll()
2337 m_QueuedPlayer
.clear(); // prevent send queue update packet and login queued sessions
2339 // session not removed at kick and will removed in next update tick
2340 for (SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2341 itr
->second
->KickPlayer();
2344 /// Kick (and save) all players with security level less `sec`
2345 void World::KickAllLess(AccountTypes sec
)
2347 // session not removed at kick and will removed in next update tick
2348 for (SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2349 if(itr
->second
->GetSecurity() < sec
)
2350 itr
->second
->KickPlayer();
2353 /// Kick (and save) the designated player
2354 bool World::KickPlayer(const std::string
& playerName
)
2356 SessionMap::iterator itr
;
2358 // session not removed at kick and will removed in next update tick
2359 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2363 Player
*player
= itr
->second
->GetPlayer();
2366 if( player
->IsInWorld() )
2368 if (playerName
== player
->GetName())
2370 itr
->second
->KickPlayer();
2378 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2379 BanReturn
World::BanAccount(BanMode mode
, std::string nameOrIP
, std::string duration
, std::string reason
, std::string author
)
2381 loginDatabase
.escape_string(nameOrIP
);
2382 loginDatabase
.escape_string(reason
);
2383 std::string safe_author
=author
;
2384 loginDatabase
.escape_string(safe_author
);
2386 uint32 duration_secs
= TimeStringToSecs(duration
);
2387 QueryResult
*resultAccounts
= NULL
; //used for kicking
2389 ///- Update the database with ban information
2393 //No SQL injection as strings are escaped
2394 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP
.c_str());
2395 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());
2398 //No SQL injection as string is escaped
2399 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP
.c_str());
2402 //No SQL injection as string is escaped
2403 resultAccounts
= CharacterDatabase
.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP
.c_str());
2406 return BAN_SYNTAX_ERROR
;
2412 return BAN_SUCCESS
; // ip correctly banned but nobody affected (yet)
2414 return BAN_NOTFOUND
; // Nobody to ban
2417 ///- Disconnect all affected players (for IP it can be several)
2420 Field
* fieldsAccount
= resultAccounts
->Fetch();
2421 uint32 account
= fieldsAccount
->GetUInt32();
2425 //No SQL injection as strings are escaped
2426 loginDatabase
.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2427 account
,duration_secs
,safe_author
.c_str(),reason
.c_str());
2430 if (WorldSession
* sess
= FindSession(account
))
2431 if(std::string(sess
->GetPlayerName()) != author
)
2434 while( resultAccounts
->NextRow() );
2436 delete resultAccounts
;
2440 /// Remove a ban from an account or IP address
2441 bool World::RemoveBanAccount(BanMode mode
, std::string nameOrIP
)
2445 loginDatabase
.escape_string(nameOrIP
);
2446 loginDatabase
.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP
.c_str());
2451 if (mode
== BAN_ACCOUNT
)
2452 account
= accmgr
.GetId (nameOrIP
);
2453 else if (mode
== BAN_CHARACTER
)
2454 account
= objmgr
.GetPlayerAccountIdByPlayerName (nameOrIP
);
2459 //NO SQL injection as account is uint32
2460 loginDatabase
.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account
);
2465 /// Update the game time
2466 void World::_UpdateGameTime()
2468 ///- update the time
2469 time_t thisTime
= time(NULL
);
2470 uint32 elapsed
= uint32(thisTime
- m_gameTime
);
2471 m_gameTime
= thisTime
;
2473 ///- if there is a shutdown timer
2474 if(!m_stopEvent
&& m_ShutdownTimer
> 0 && elapsed
> 0)
2476 ///- ... and it is overdue, stop the world (set m_stopEvent)
2477 if( m_ShutdownTimer
<= elapsed
)
2479 if(!(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2480 m_stopEvent
= true; // exist code already set
2482 m_ShutdownTimer
= 1; // minimum timer value to wait idle state
2484 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2487 m_ShutdownTimer
-= elapsed
;
2494 /// Shutdown the server
2495 void World::ShutdownServ(uint32 time
, uint32 options
, uint8 exitcode
)
2497 // ignore if server shutdown at next tick
2501 m_ShutdownMask
= options
;
2502 m_ExitCode
= exitcode
;
2504 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2507 if(!(options
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2508 m_stopEvent
= true; // exist code already set
2510 m_ShutdownTimer
= 1; //So that the session count is re-evaluated at next world tick
2512 ///- Else set the shutdown timer and warn users
2515 m_ShutdownTimer
= time
;
2520 /// Display a shutdown message to the user(s)
2521 void World::ShutdownMsg(bool show
, Player
* player
)
2523 // not show messages for idle shutdown mode
2524 if(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
)
2527 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2529 (m_ShutdownTimer
< 10) ||
2530 // < 30 sec; every 5 sec
2531 (m_ShutdownTimer
<30 && (m_ShutdownTimer
% 5 )==0) ||
2532 // < 5 min ; every 1 min
2533 (m_ShutdownTimer
<5*MINUTE
&& (m_ShutdownTimer
% MINUTE
)==0) ||
2534 // < 30 min ; every 5 min
2535 (m_ShutdownTimer
<30*MINUTE
&& (m_ShutdownTimer
% (5*MINUTE
))==0) ||
2536 // < 12 h ; every 1 h
2537 (m_ShutdownTimer
<12*HOUR
&& (m_ShutdownTimer
% HOUR
)==0) ||
2538 // > 12 h ; every 12 h
2539 (m_ShutdownTimer
>12*HOUR
&& (m_ShutdownTimer
% (12*HOUR
) )==0))
2541 std::string str
= secsToTimeString(m_ShutdownTimer
);
2543 uint32 msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_TIME
: SERVER_MSG_SHUTDOWN_TIME
;
2545 SendServerMessage(msgid
,str
.c_str(),player
);
2546 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"),str
.c_str());
2550 /// Cancel a planned server shutdown
2551 void World::ShutdownCancel()
2553 // nothing cancel or too later
2554 if(!m_ShutdownTimer
|| m_stopEvent
)
2557 uint32 msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_CANCELLED
: SERVER_MSG_SHUTDOWN_CANCELLED
;
2560 m_ShutdownTimer
= 0;
2561 m_ExitCode
= SHUTDOWN_EXIT_CODE
; // to default value
2562 SendServerMessage(msgid
);
2564 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"));
2567 /// Send a server message to the user(s)
2568 void World::SendServerMessage(uint32 type
, const char *text
, Player
* player
)
2570 WorldPacket
data(SMSG_SERVER_MESSAGE
, 50); // guess size
2571 data
<< uint32(type
);
2572 if(type
<= SERVER_MSG_STRING
)
2576 player
->GetSession()->SendPacket(&data
);
2578 SendGlobalMessage( &data
);
2581 void World::UpdateSessions( uint32 diff
)
2583 ///- Add new sessions
2584 while(!addSessQueue
.empty())
2586 WorldSession
* sess
= addSessQueue
.next ();
2590 ///- Then send an update signal to remaining ones
2591 for (SessionMap::iterator itr
= m_sessions
.begin(), next
; itr
!= m_sessions
.end(); itr
= next
)
2599 ///- and remove not active sessions from the list
2600 if(!itr
->second
->Update(diff
)) // As interval = 0
2602 RemoveQueuedPlayer (itr
->second
);
2604 m_sessions
.erase(itr
);
2609 // This handles the issued and queued CLI commands
2610 void World::ProcessCliCommands()
2612 if (cliCmdQueue
.empty())
2615 CliCommandHolder::Print
* zprint
;
2617 while (!cliCmdQueue
.empty())
2619 sLog
.outDebug("CLI command under processing...");
2620 CliCommandHolder
*command
= cliCmdQueue
.next();
2622 zprint
= command
->m_print
;
2624 CliHandler(zprint
).ParseCommands(command
->m_command
);
2629 // print the console message here so it looks right
2633 void World::InitResultQueue()
2635 m_resultQueue
= new SqlResultQueue
;
2636 CharacterDatabase
.SetResultQueue(m_resultQueue
);
2639 void World::UpdateResultQueue()
2641 m_resultQueue
->Update();
2644 void World::UpdateRealmCharCount(uint32 accountId
)
2646 CharacterDatabase
.AsyncPQuery(this, &World::_UpdateRealmCharCount
, accountId
,
2647 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId
);
2650 void World::_UpdateRealmCharCount(QueryResult
*resultCharCount
, uint32 accountId
)
2652 if (resultCharCount
)
2654 Field
*fields
= resultCharCount
->Fetch();
2655 uint32 charCount
= fields
[0].GetUInt32();
2656 delete resultCharCount
;
2657 loginDatabase
.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId
, realmID
);
2658 loginDatabase
.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount
, accountId
, realmID
);
2662 void World::InitDailyQuestResetTime()
2664 time_t mostRecentQuestTime
;
2666 QueryResult
* result
= CharacterDatabase
.Query("SELECT MAX(time) FROM character_queststatus_daily");
2669 Field
*fields
= result
->Fetch();
2671 mostRecentQuestTime
= (time_t)fields
[0].GetUInt64();
2675 mostRecentQuestTime
= 0;
2677 // client built-in time for reset is 6:00 AM
2678 // FIX ME: client not show day start time
2679 time_t curTime
= time(NULL
);
2680 tm localTm
= *localtime(&curTime
);
2681 localTm
.tm_hour
= 6;
2685 // current day reset time
2686 time_t curDayResetTime
= mktime(&localTm
);
2688 // last reset time before current moment
2689 time_t resetTime
= (curTime
< curDayResetTime
) ? curDayResetTime
- DAY
: curDayResetTime
;
2691 // need reset (if we have quest time before last reset time (not processed by some reason)
2692 if(mostRecentQuestTime
&& mostRecentQuestTime
<= resetTime
)
2693 m_NextDailyQuestReset
= mostRecentQuestTime
;
2696 // plan next reset time
2697 m_NextDailyQuestReset
= (curTime
>= curDayResetTime
) ? curDayResetTime
+ DAY
: curDayResetTime
;
2701 void World::ResetDailyQuests()
2703 sLog
.outDetail("Daily quests reset for all characters.");
2704 CharacterDatabase
.Execute("DELETE FROM character_queststatus_daily");
2705 for(SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2706 if(itr
->second
->GetPlayer())
2707 itr
->second
->GetPlayer()->ResetDailyQuestStatus();
2710 void World::SetPlayerLimit( int32 limit
, bool needUpdate
)
2712 if(limit
< -SEC_ADMINISTRATOR
)
2713 limit
= -SEC_ADMINISTRATOR
;
2716 bool db_update_need
= needUpdate
|| (limit
< 0) != (m_playerLimit
< 0) || (limit
< 0 && m_playerLimit
< 0 && limit
!= m_playerLimit
);
2718 m_playerLimit
= limit
;
2721 loginDatabase
.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID
);
2724 void World::UpdateMaxSessionCounters()
2726 m_maxActiveSessionCount
= std::max(m_maxActiveSessionCount
,uint32(m_sessions
.size()-m_QueuedPlayer
.size()));
2727 m_maxQueuedSessionCount
= std::max(m_maxQueuedSessionCount
,uint32(m_QueuedPlayer
.size()));
2730 void World::LoadDBVersion()
2732 QueryResult
* result
= WorldDatabase
.Query("SELECT version FROM db_version LIMIT 1");
2735 Field
* fields
= result
->Fetch();
2737 m_DBVersion
= fields
[0].GetString();
2741 m_DBVersion
= "unknown world database";