Various Cleanups (game T-Z)

This commit is contained in:
Schmoozerd 2012-07-19 21:52:26 +02:00
parent 08fd085549
commit 6379a746d7
34 changed files with 2858 additions and 2852 deletions

View file

@ -27,7 +27,7 @@
//-----------------------------------------------// //-----------------------------------------------//
template<class T, typename D> template<class T, typename D>
void TargetedMovementGeneratorMedium<T,D>::_setTargetLocation(T &owner) void TargetedMovementGeneratorMedium<T,D>::_setTargetLocation(T& owner)
{ {
if (!i_target.isValid() || !i_target->IsInWorld()) if (!i_target.isValid() || !i_target->IsInWorld())
return; return;
@ -48,7 +48,7 @@ void TargetedMovementGeneratorMedium<T,D>::_setTargetLocation(T &owner)
else if (!i_offset) else if (!i_offset)
{ {
// to nearest contact position // to nearest contact position
i_target->GetContactPoint( &owner, x, y, z ); i_target->GetContactPoint(&owner, x, y, z);
} }
else else
{ {
@ -73,14 +73,14 @@ void TargetedMovementGeneratorMedium<T,D>::_setTargetLocation(T &owner)
return; return;
*/ */
if(!i_path) if (!i_path)
i_path = new PathFinder(&owner); i_path = new PathFinder(&owner);
// allow pets following their master to cheat while generating paths // allow pets following their master to cheat while generating paths
bool forceDest = (owner.GetTypeId() == TYPEID_UNIT && ((Creature*)&owner)->IsPet() bool forceDest = (owner.GetTypeId() == TYPEID_UNIT && ((Creature*)&owner)->IsPet()
&& owner.hasUnitState(UNIT_STAT_FOLLOW)); && owner.hasUnitState(UNIT_STAT_FOLLOW));
i_path->calculate(x, y, z, forceDest); i_path->calculate(x, y, z, forceDest);
if(i_path->getPathType() & PATHFIND_NOPATH) if (i_path->getPathType() & PATHFIND_NOPATH)
return; return;
D::_addUnitStateMove(owner); D::_addUnitStateMove(owner);
@ -120,7 +120,7 @@ void TargetedMovementGeneratorMedium<Creature,FollowMovementGenerator<Creature>
} }
template<class T, typename D> template<class T, typename D>
bool TargetedMovementGeneratorMedium<T,D>::Update(T &owner, const uint32 & time_diff) bool TargetedMovementGeneratorMedium<T,D>::Update(T& owner, const uint32& time_diff)
{ {
if (!i_target.isValid() || !i_target->IsInWorld()) if (!i_target.isValid() || !i_target->IsInWorld())
return false; return false;
@ -189,21 +189,21 @@ bool TargetedMovementGeneratorMedium<T,D>::Update(T &owner, const uint32 & time_
//-----------------------------------------------// //-----------------------------------------------//
template<class T> template<class T>
void ChaseMovementGenerator<T>::_reachTarget(T &owner) void ChaseMovementGenerator<T>::_reachTarget(T& owner)
{ {
if (owner.CanReachWithMeleeAttack(this->i_target.getTarget())) if (owner.CanReachWithMeleeAttack(this->i_target.getTarget()))
owner.Attack(this->i_target.getTarget(),true); owner.Attack(this->i_target.getTarget(),true);
} }
template<> template<>
void ChaseMovementGenerator<Player>::Initialize(Player &owner) void ChaseMovementGenerator<Player>::Initialize(Player& owner)
{ {
owner.addUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE); owner.addUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE);
_setTargetLocation(owner); _setTargetLocation(owner);
} }
template<> template<>
void ChaseMovementGenerator<Creature>::Initialize(Creature &owner) void ChaseMovementGenerator<Creature>::Initialize(Creature& owner)
{ {
owner.SetWalk(false); owner.SetWalk(false);
owner.addUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE); owner.addUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE);
@ -211,19 +211,19 @@ void ChaseMovementGenerator<Creature>::Initialize(Creature &owner)
} }
template<class T> template<class T>
void ChaseMovementGenerator<T>::Finalize(T &owner) void ChaseMovementGenerator<T>::Finalize(T& owner)
{ {
owner.clearUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE); owner.clearUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE);
} }
template<class T> template<class T>
void ChaseMovementGenerator<T>::Interrupt(T &owner) void ChaseMovementGenerator<T>::Interrupt(T& owner)
{ {
owner.clearUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE); owner.clearUnitState(UNIT_STAT_CHASE|UNIT_STAT_CHASE_MOVE);
} }
template<class T> template<class T>
void ChaseMovementGenerator<T>::Reset(T &owner) void ChaseMovementGenerator<T>::Reset(T& owner)
{ {
Initialize(owner); Initialize(owner);
} }
@ -242,13 +242,13 @@ bool FollowMovementGenerator<Player>::EnableWalking() const
} }
template<> template<>
void FollowMovementGenerator<Player>::_updateSpeed(Player &/*u*/) void FollowMovementGenerator<Player>::_updateSpeed(Player& /*u*/)
{ {
// nothing to do for Player // nothing to do for Player
} }
template<> template<>
void FollowMovementGenerator<Creature>::_updateSpeed(Creature &u) void FollowMovementGenerator<Creature>::_updateSpeed(Creature& u)
{ {
// pet only sync speed with owner // pet only sync speed with owner
if (!((Creature&)u).IsPet() || !i_target.isValid() || i_target->GetObjectGuid() != u.GetOwnerGuid()) if (!((Creature&)u).IsPet() || !i_target.isValid() || i_target->GetObjectGuid() != u.GetOwnerGuid())
@ -260,7 +260,7 @@ void FollowMovementGenerator<Creature>::_updateSpeed(Creature &u)
} }
template<> template<>
void FollowMovementGenerator<Player>::Initialize(Player &owner) void FollowMovementGenerator<Player>::Initialize(Player& owner)
{ {
owner.addUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE); owner.addUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE);
_updateSpeed(owner); _updateSpeed(owner);
@ -268,7 +268,7 @@ void FollowMovementGenerator<Player>::Initialize(Player &owner)
} }
template<> template<>
void FollowMovementGenerator<Creature>::Initialize(Creature &owner) void FollowMovementGenerator<Creature>::Initialize(Creature& owner)
{ {
owner.addUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE); owner.addUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE);
_updateSpeed(owner); _updateSpeed(owner);
@ -276,47 +276,47 @@ void FollowMovementGenerator<Creature>::Initialize(Creature &owner)
} }
template<class T> template<class T>
void FollowMovementGenerator<T>::Finalize(T &owner) void FollowMovementGenerator<T>::Finalize(T& owner)
{ {
owner.clearUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE); owner.clearUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE);
_updateSpeed(owner); _updateSpeed(owner);
} }
template<class T> template<class T>
void FollowMovementGenerator<T>::Interrupt(T &owner) void FollowMovementGenerator<T>::Interrupt(T& owner)
{ {
owner.clearUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE); owner.clearUnitState(UNIT_STAT_FOLLOW|UNIT_STAT_FOLLOW_MOVE);
_updateSpeed(owner); _updateSpeed(owner);
} }
template<class T> template<class T>
void FollowMovementGenerator<T>::Reset(T &owner) void FollowMovementGenerator<T>::Reset(T& owner)
{ {
Initialize(owner); Initialize(owner);
} }
//-----------------------------------------------// //-----------------------------------------------//
template void TargetedMovementGeneratorMedium<Player,ChaseMovementGenerator<Player> >::_setTargetLocation(Player &); template void TargetedMovementGeneratorMedium<Player,ChaseMovementGenerator<Player> >::_setTargetLocation(Player&);
template void TargetedMovementGeneratorMedium<Player,FollowMovementGenerator<Player> >::_setTargetLocation(Player &); template void TargetedMovementGeneratorMedium<Player,FollowMovementGenerator<Player> >::_setTargetLocation(Player&);
template void TargetedMovementGeneratorMedium<Creature,ChaseMovementGenerator<Creature> >::_setTargetLocation(Creature &); template void TargetedMovementGeneratorMedium<Creature,ChaseMovementGenerator<Creature> >::_setTargetLocation(Creature&);
template void TargetedMovementGeneratorMedium<Creature,FollowMovementGenerator<Creature> >::_setTargetLocation(Creature &); template void TargetedMovementGeneratorMedium<Creature,FollowMovementGenerator<Creature> >::_setTargetLocation(Creature&);
template bool TargetedMovementGeneratorMedium<Player,ChaseMovementGenerator<Player> >::Update(Player &, const uint32 &); template bool TargetedMovementGeneratorMedium<Player,ChaseMovementGenerator<Player> >::Update(Player&, const uint32&);
template bool TargetedMovementGeneratorMedium<Player,FollowMovementGenerator<Player> >::Update(Player &, const uint32 &); template bool TargetedMovementGeneratorMedium<Player,FollowMovementGenerator<Player> >::Update(Player&, const uint32&);
template bool TargetedMovementGeneratorMedium<Creature,ChaseMovementGenerator<Creature> >::Update(Creature &, const uint32 &); template bool TargetedMovementGeneratorMedium<Creature,ChaseMovementGenerator<Creature> >::Update(Creature&, const uint32&);
template bool TargetedMovementGeneratorMedium<Creature,FollowMovementGenerator<Creature> >::Update(Creature &, const uint32 &); template bool TargetedMovementGeneratorMedium<Creature,FollowMovementGenerator<Creature> >::Update(Creature&, const uint32&);
template void ChaseMovementGenerator<Player>::_reachTarget(Player &); template void ChaseMovementGenerator<Player>::_reachTarget(Player&);
template void ChaseMovementGenerator<Creature>::_reachTarget(Creature &); template void ChaseMovementGenerator<Creature>::_reachTarget(Creature&);
template void ChaseMovementGenerator<Player>::Finalize(Player &); template void ChaseMovementGenerator<Player>::Finalize(Player&);
template void ChaseMovementGenerator<Creature>::Finalize(Creature &); template void ChaseMovementGenerator<Creature>::Finalize(Creature&);
template void ChaseMovementGenerator<Player>::Interrupt(Player &); template void ChaseMovementGenerator<Player>::Interrupt(Player&);
template void ChaseMovementGenerator<Creature>::Interrupt(Creature &); template void ChaseMovementGenerator<Creature>::Interrupt(Creature&);
template void ChaseMovementGenerator<Player>::Reset(Player &); template void ChaseMovementGenerator<Player>::Reset(Player&);
template void ChaseMovementGenerator<Creature>::Reset(Creature &); template void ChaseMovementGenerator<Creature>::Reset(Creature&);
template void FollowMovementGenerator<Player>::Finalize(Player &); template void FollowMovementGenerator<Player>::Finalize(Player&);
template void FollowMovementGenerator<Creature>::Finalize(Creature &); template void FollowMovementGenerator<Creature>::Finalize(Creature&);
template void FollowMovementGenerator<Player>::Interrupt(Player &); template void FollowMovementGenerator<Player>::Interrupt(Player&);
template void FollowMovementGenerator<Creature>::Interrupt(Creature &); template void FollowMovementGenerator<Creature>::Interrupt(Creature&);
template void FollowMovementGenerator<Player>::Reset(Player &); template void FollowMovementGenerator<Player>::Reset(Player&);
template void FollowMovementGenerator<Creature>::Reset(Creature &); template void FollowMovementGenerator<Creature>::Reset(Creature&);

View file

@ -27,7 +27,7 @@
class MANGOS_DLL_SPEC TargetedMovementGeneratorBase class MANGOS_DLL_SPEC TargetedMovementGeneratorBase
{ {
public: public:
TargetedMovementGeneratorBase(Unit &target) { i_target.link(&target, this); } TargetedMovementGeneratorBase(Unit& target) { i_target.link(&target, this); }
void stopFollowing() { } void stopFollowing() { }
protected: protected:
FollowerReference i_target; FollowerReference i_target;
@ -35,10 +35,10 @@ class MANGOS_DLL_SPEC TargetedMovementGeneratorBase
template<class T, typename D> template<class T, typename D>
class MANGOS_DLL_SPEC TargetedMovementGeneratorMedium class MANGOS_DLL_SPEC TargetedMovementGeneratorMedium
: public MovementGeneratorMedium< T, D >, public TargetedMovementGeneratorBase : public MovementGeneratorMedium< T, D >, public TargetedMovementGeneratorBase
{ {
protected: protected:
TargetedMovementGeneratorMedium(Unit &target, float offset, float angle) : TargetedMovementGeneratorMedium(Unit& target, float offset, float angle) :
TargetedMovementGeneratorBase(target), i_offset(offset), i_angle(angle), TargetedMovementGeneratorBase(target), i_offset(offset), i_angle(angle),
i_recalculateTravel(false), i_targetReached(false), i_recheckDistance(0), i_recalculateTravel(false), i_targetReached(false), i_recheckDistance(0),
i_path(NULL) i_path(NULL)
@ -47,7 +47,7 @@ class MANGOS_DLL_SPEC TargetedMovementGeneratorMedium
~TargetedMovementGeneratorMedium() { delete i_path; } ~TargetedMovementGeneratorMedium() { delete i_path; }
public: public:
bool Update(T &, const uint32 &); bool Update(T&, const uint32&);
bool IsReachable() const bool IsReachable() const
{ {
@ -60,7 +60,7 @@ class MANGOS_DLL_SPEC TargetedMovementGeneratorMedium
void UpdateFinalDistance(float fDistance); void UpdateFinalDistance(float fDistance);
protected: protected:
void _setTargetLocation(T &); void _setTargetLocation(T&);
ShortTimeTracker i_recheckDistance; ShortTimeTracker i_recheckDistance;
float i_offset; float i_offset;
@ -75,50 +75,50 @@ template<class T>
class MANGOS_DLL_SPEC ChaseMovementGenerator : public TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> > class MANGOS_DLL_SPEC ChaseMovementGenerator : public TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >
{ {
public: public:
ChaseMovementGenerator(Unit &target) ChaseMovementGenerator(Unit& target)
: TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target) {} : TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target) {}
ChaseMovementGenerator(Unit &target, float offset, float angle) ChaseMovementGenerator(Unit& target, float offset, float angle)
: TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target, offset, angle) {} : TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target, offset, angle) {}
~ChaseMovementGenerator() {} ~ChaseMovementGenerator() {}
MovementGeneratorType GetMovementGeneratorType() const { return CHASE_MOTION_TYPE; } MovementGeneratorType GetMovementGeneratorType() const { return CHASE_MOTION_TYPE; }
void Initialize(T &); void Initialize(T&);
void Finalize(T &); void Finalize(T&);
void Interrupt(T &); void Interrupt(T&);
void Reset(T &); void Reset(T&);
static void _clearUnitStateMove(T &u) { u.clearUnitState(UNIT_STAT_CHASE_MOVE); } static void _clearUnitStateMove(T& u) { u.clearUnitState(UNIT_STAT_CHASE_MOVE); }
static void _addUnitStateMove(T &u) { u.addUnitState(UNIT_STAT_CHASE_MOVE); } static void _addUnitStateMove(T& u) { u.addUnitState(UNIT_STAT_CHASE_MOVE); }
bool EnableWalking() const { return false;} bool EnableWalking() const { return false;}
bool _lostTarget(T &u) const { return u.getVictim() != this->GetTarget(); } bool _lostTarget(T& u) const { return u.getVictim() != this->GetTarget(); }
void _reachTarget(T &); void _reachTarget(T&);
}; };
template<class T> template<class T>
class MANGOS_DLL_SPEC FollowMovementGenerator : public TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> > class MANGOS_DLL_SPEC FollowMovementGenerator : public TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >
{ {
public: public:
FollowMovementGenerator(Unit &target) FollowMovementGenerator(Unit& target)
: TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target){} : TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target) {}
FollowMovementGenerator(Unit &target, float offset, float angle) FollowMovementGenerator(Unit& target, float offset, float angle)
: TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target, offset, angle) {} : TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target, offset, angle) {}
~FollowMovementGenerator() {} ~FollowMovementGenerator() {}
MovementGeneratorType GetMovementGeneratorType() const { return FOLLOW_MOTION_TYPE; } MovementGeneratorType GetMovementGeneratorType() const { return FOLLOW_MOTION_TYPE; }
void Initialize(T &); void Initialize(T&);
void Finalize(T &); void Finalize(T&);
void Interrupt(T &); void Interrupt(T&);
void Reset(T &); void Reset(T&);
static void _clearUnitStateMove(T &u) { u.clearUnitState(UNIT_STAT_FOLLOW_MOVE); } static void _clearUnitStateMove(T& u) { u.clearUnitState(UNIT_STAT_FOLLOW_MOVE); }
static void _addUnitStateMove(T &u) { u.addUnitState(UNIT_STAT_FOLLOW_MOVE); } static void _addUnitStateMove(T& u) { u.addUnitState(UNIT_STAT_FOLLOW_MOVE); }
bool EnableWalking() const; bool EnableWalking() const;
bool _lostTarget(T &) const { return false; } bool _lostTarget(T&) const { return false; }
void _reachTarget(T &) {} void _reachTarget(T&) {}
private: private:
void _updateSpeed(T &u); void _updateSpeed(T& u);
}; };
#endif #endif

View file

@ -28,27 +28,27 @@
#include "Path.h" #include "Path.h"
#include "WaypointMovementGenerator.h" #include "WaypointMovementGenerator.h"
void WorldSession::HandleTaxiNodeStatusQueryOpcode( WorldPacket & recv_data ) void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG("WORLD: Received CMSG_TAXINODE_STATUS_QUERY"); DEBUG_LOG("WORLD: Received CMSG_TAXINODE_STATUS_QUERY");
ObjectGuid guid; ObjectGuid guid;
recv_data >> guid; recv_data >> guid;
SendTaxiStatus( guid ); SendTaxiStatus(guid);
} }
void WorldSession::SendTaxiStatus(ObjectGuid guid) void WorldSession::SendTaxiStatus(ObjectGuid guid)
{ {
// cheating checks // cheating checks
Creature *unit = GetPlayer()->GetMap()->GetCreature(guid); Creature* unit = GetPlayer()->GetMap()->GetCreature(guid);
if (!unit) if (!unit)
{ {
DEBUG_LOG("WorldSession::SendTaxiStatus - %s not found or you can't interact with it.", guid.GetString().c_str()); DEBUG_LOG("WorldSession::SendTaxiStatus - %s not found or you can't interact with it.", guid.GetString().c_str());
return; return;
} }
uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer( )->GetTeam()); uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer()->GetTeam());
// not found nearest // not found nearest
if (curloc == 0) if (curloc == 0)
@ -64,15 +64,15 @@ void WorldSession::SendTaxiStatus(ObjectGuid guid)
DEBUG_LOG("WORLD: Sent SMSG_TAXINODE_STATUS"); DEBUG_LOG("WORLD: Sent SMSG_TAXINODE_STATUS");
} }
void WorldSession::HandleTaxiQueryAvailableNodes( WorldPacket & recv_data ) void WorldSession::HandleTaxiQueryAvailableNodes(WorldPacket& recv_data)
{ {
DEBUG_LOG( "WORLD: Received CMSG_TAXIQUERYAVAILABLENODES" ); DEBUG_LOG("WORLD: Received CMSG_TAXIQUERYAVAILABLENODES");
ObjectGuid guid; ObjectGuid guid;
recv_data >> guid; recv_data >> guid;
// cheating checks // cheating checks
Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER);
if (!unit) if (!unit)
{ {
DEBUG_LOG("WORLD: HandleTaxiQueryAvailableNodes - %s not found or you can't interact with him.", guid.GetString().c_str()); DEBUG_LOG("WORLD: HandleTaxiQueryAvailableNodes - %s not found or you can't interact with him.", guid.GetString().c_str());
@ -80,56 +80,56 @@ void WorldSession::HandleTaxiQueryAvailableNodes( WorldPacket & recv_data )
} }
// remove fake death // remove fake death
if(GetPlayer()->hasUnitState(UNIT_STAT_DIED)) if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
// unknown taxi node case // unknown taxi node case
if( SendLearnNewTaxiNode(unit) ) if (SendLearnNewTaxiNode(unit))
return; return;
// known taxi node case // known taxi node case
SendTaxiMenu( unit ); SendTaxiMenu(unit);
} }
void WorldSession::SendTaxiMenu( Creature* unit ) void WorldSession::SendTaxiMenu(Creature* unit)
{ {
// find current node // find current node
uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer( )->GetTeam()); uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer()->GetTeam());
if ( curloc == 0 ) if (curloc == 0)
return; return;
DEBUG_LOG( "WORLD: CMSG_TAXINODE_STATUS_QUERY %u ",curloc); DEBUG_LOG("WORLD: CMSG_TAXINODE_STATUS_QUERY %u ",curloc);
WorldPacket data( SMSG_SHOWTAXINODES, (4+8+4+8*4) ); WorldPacket data(SMSG_SHOWTAXINODES, (4+8+4+8*4));
data << uint32( 1 ); data << uint32(1);
data << unit->GetObjectGuid(); data << unit->GetObjectGuid();
data << uint32( curloc ); data << uint32(curloc);
GetPlayer()->m_taxi.AppendTaximaskTo(data,GetPlayer()->isTaxiCheater()); GetPlayer()->m_taxi.AppendTaximaskTo(data,GetPlayer()->isTaxiCheater());
SendPacket( &data ); SendPacket(&data);
DEBUG_LOG( "WORLD: Sent SMSG_SHOWTAXINODES" ); DEBUG_LOG("WORLD: Sent SMSG_SHOWTAXINODES");
} }
void WorldSession::SendDoFlight( uint32 mountDisplayId, uint32 path, uint32 pathNode ) void WorldSession::SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathNode)
{ {
// remove fake death // remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
while(GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE) while (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE)
GetPlayer()->GetMotionMaster()->MovementExpired(false); GetPlayer()->GetMotionMaster()->MovementExpired(false);
if (mountDisplayId) if (mountDisplayId)
GetPlayer()->Mount( mountDisplayId ); GetPlayer()->Mount(mountDisplayId);
GetPlayer()->GetMotionMaster()->MoveTaxiFlight(path,pathNode); GetPlayer()->GetMotionMaster()->MoveTaxiFlight(path,pathNode);
} }
bool WorldSession::SendLearnNewTaxiNode( Creature* unit ) bool WorldSession::SendLearnNewTaxiNode(Creature* unit)
{ {
// find current node // find current node
uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer( )->GetTeam()); uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(),unit->GetPositionY(),unit->GetPositionZ(),unit->GetMapId(),GetPlayer()->GetTeam());
if (curloc == 0) if (curloc == 0)
return true; // `true` send to avoid WorldSession::SendTaxiMenu call with one more curlock seartch with same false result. return true; // `true` send to avoid WorldSession::SendTaxiMenu call with one more curlock seartch with same false result.
@ -150,41 +150,41 @@ bool WorldSession::SendLearnNewTaxiNode( Creature* unit )
return false; return false;
} }
void WorldSession::HandleActivateTaxiExpressOpcode ( WorldPacket & recv_data ) void WorldSession::HandleActivateTaxiExpressOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG( "WORLD: Received CMSG_ACTIVATETAXIEXPRESS" ); DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXIEXPRESS");
ObjectGuid guid; ObjectGuid guid;
uint32 node_count; uint32 node_count;
recv_data >> guid >> node_count; recv_data >> guid >> node_count;
Creature *npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER);
if (!npc) if (!npc)
{ {
DEBUG_LOG( "WORLD: HandleActivateTaxiExpressOpcode - %s not found or you can't interact with it.", guid.GetString().c_str()); DEBUG_LOG("WORLD: HandleActivateTaxiExpressOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return; return;
} }
std::vector<uint32> nodes; std::vector<uint32> nodes;
for(uint32 i = 0; i < node_count; ++i) for (uint32 i = 0; i < node_count; ++i)
{ {
uint32 node; uint32 node;
recv_data >> node; recv_data >> node;
nodes.push_back(node); nodes.push_back(node);
} }
if(nodes.empty()) if (nodes.empty())
return; return;
DEBUG_LOG( "WORLD: Received CMSG_ACTIVATETAXIEXPRESS from %d to %d" ,nodes.front(),nodes.back()); DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXIEXPRESS from %d to %d" ,nodes.front(),nodes.back());
GetPlayer()->ActivateTaxiPathTo(nodes, npc); GetPlayer()->ActivateTaxiPathTo(nodes, npc);
} }
void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data) void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG( "WORLD: Received CMSG_MOVE_SPLINE_DONE" ); DEBUG_LOG("WORLD: Received CMSG_MOVE_SPLINE_DONE");
ObjectGuid guid; // used only for proper packet read ObjectGuid guid; // used only for proper packet read
MovementInfo movementInfo; // used only for proper packet read MovementInfo movementInfo; // used only for proper packet read
@ -199,15 +199,15 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data)
// 2) switch from one map to other in case multi-map taxi path // 2) switch from one map to other in case multi-map taxi path
// we need process only (1) // we need process only (1)
uint32 curDest = GetPlayer()->m_taxi.GetTaxiDestination(); uint32 curDest = GetPlayer()->m_taxi.GetTaxiDestination();
if(!curDest) if (!curDest)
return; return;
TaxiNodesEntry const* curDestNode = sTaxiNodesStore.LookupEntry(curDest); TaxiNodesEntry const* curDestNode = sTaxiNodesStore.LookupEntry(curDest);
// far teleport case // far teleport case
if(curDestNode && curDestNode->map_id != GetPlayer()->GetMapId()) if (curDestNode && curDestNode->map_id != GetPlayer()->GetMapId())
{ {
if(GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE) if (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE)
{ {
// short preparations to continue flight // short preparations to continue flight
FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top()); FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top());
@ -224,7 +224,7 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data)
} }
uint32 destinationnode = GetPlayer()->m_taxi.NextTaxiDestination(); uint32 destinationnode = GetPlayer()->m_taxi.NextTaxiDestination();
if ( destinationnode > 0 ) // if more destinations to go if (destinationnode > 0) // if more destinations to go
{ {
// current source node for next destination // current source node for next destination
uint32 sourcenode = GetPlayer()->m_taxi.GetTaxiSource(); uint32 sourcenode = GetPlayer()->m_taxi.GetTaxiSource();
@ -232,22 +232,22 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data)
// Add to taximask middle hubs in taxicheat mode (to prevent having player with disabled taxicheat and not having back flight path) // Add to taximask middle hubs in taxicheat mode (to prevent having player with disabled taxicheat and not having back flight path)
if (GetPlayer()->isTaxiCheater()) if (GetPlayer()->isTaxiCheater())
{ {
if(GetPlayer()->m_taxi.SetTaximaskNode(sourcenode)) if (GetPlayer()->m_taxi.SetTaximaskNode(sourcenode))
{ {
WorldPacket data(SMSG_NEW_TAXI_PATH, 0); WorldPacket data(SMSG_NEW_TAXI_PATH, 0);
_player->GetSession()->SendPacket( &data ); _player->GetSession()->SendPacket(&data);
} }
} }
DEBUG_LOG( "WORLD: Taxi has to go from %u to %u", sourcenode, destinationnode ); DEBUG_LOG("WORLD: Taxi has to go from %u to %u", sourcenode, destinationnode);
uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetPlayer()->GetTeam()); uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetPlayer()->GetTeam());
uint32 path, cost; uint32 path, cost;
sObjectMgr.GetTaxiPath( sourcenode, destinationnode, path, cost); sObjectMgr.GetTaxiPath(sourcenode, destinationnode, path, cost);
if(path && mountDisplayId) if (path && mountDisplayId)
SendDoFlight( mountDisplayId, path, 1 ); // skip start fly node SendDoFlight(mountDisplayId, path, 1); // skip start fly node
else else
GetPlayer()->m_taxi.ClearTaxiDestinations(); // clear problematic path and next GetPlayer()->m_taxi.ClearTaxiDestinations(); // clear problematic path and next
} }
@ -255,7 +255,7 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data)
GetPlayer()->m_taxi.ClearTaxiDestinations(); // not destinations, clear source node GetPlayer()->m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
} }
void WorldSession::HandleActivateTaxiOpcode( WorldPacket & recv_data ) void WorldSession::HandleActivateTaxiOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXI"); DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXI");
@ -265,7 +265,7 @@ void WorldSession::HandleActivateTaxiOpcode( WorldPacket & recv_data )
recv_data >> guid >> nodes[0] >> nodes[1]; recv_data >> guid >> nodes[0] >> nodes[1];
DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXI from %d to %d" ,nodes[0],nodes[1]); DEBUG_LOG("WORLD: Received CMSG_ACTIVATETAXI from %d to %d" ,nodes[0],nodes[1]);
Creature *npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER);
if (!npc) if (!npc)
{ {
DEBUG_LOG("WORLD: HandleActivateTaxiOpcode - %s not found or you can't interact with it.", guid.GetString().c_str()); DEBUG_LOG("WORLD: HandleActivateTaxiOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());

View file

@ -20,14 +20,14 @@
#include "Log.h" #include "Log.h"
#include "CreatureAI.h" #include "CreatureAI.h"
TemporarySummon::TemporarySummon( ObjectGuid summoner ) : TemporarySummon::TemporarySummon(ObjectGuid summoner) :
Creature(CREATURE_SUBTYPE_TEMPORARY_SUMMON), m_type(TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN), m_timer(0), m_lifetime(0), m_summoner(summoner) Creature(CREATURE_SUBTYPE_TEMPORARY_SUMMON), m_type(TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN), m_timer(0), m_lifetime(0), m_summoner(summoner)
{ {
} }
void TemporarySummon::Update( uint32 update_diff, uint32 diff ) void TemporarySummon::Update(uint32 update_diff, uint32 diff)
{ {
switch(m_type) switch (m_type)
{ {
case TEMPSUMMON_MANUAL_DESPAWN: case TEMPSUMMON_MANUAL_DESPAWN:
break; break;
@ -126,7 +126,7 @@ void TemporarySummon::Update( uint32 update_diff, uint32 diff )
return; return;
} }
if (!isInCombat() && isAlive() ) if (!isInCombat() && isAlive())
{ {
if (m_timer <= update_diff) if (m_timer <= update_diff)
{ {
@ -146,7 +146,7 @@ void TemporarySummon::Update( uint32 update_diff, uint32 diff )
break; break;
} }
Creature::Update( update_diff, diff ); Creature::Update(update_diff, diff);
} }
void TemporarySummon::Summon(TempSummonType type, uint32 lifetime) void TemporarySummon::Summon(TempSummonType type, uint32 lifetime)
@ -164,7 +164,7 @@ void TemporarySummon::UnSummon()
CombatStop(); CombatStop();
if (GetSummonerGuid().IsCreatureOrVehicle()) if (GetSummonerGuid().IsCreatureOrVehicle())
if(Creature* sum = GetMap()->GetCreature(GetSummonerGuid())) if (Creature* sum = GetMap()->GetCreature(GetSummonerGuid()))
if (sum->AI()) if (sum->AI())
sum->AI()->SummonedCreatureDespawn(this); sum->AI()->SummonedCreatureDespawn(this);

View file

@ -26,7 +26,7 @@ class TemporarySummon : public Creature
{ {
public: public:
explicit TemporarySummon(ObjectGuid summoner = ObjectGuid()); explicit TemporarySummon(ObjectGuid summoner = ObjectGuid());
virtual ~TemporarySummon(){}; virtual ~TemporarySummon() {};
void Update(uint32 update_diff, uint32 time) override; void Update(uint32 update_diff, uint32 time) override;
void Summon(TempSummonType type, uint32 lifetime); void Summon(TempSummonType type, uint32 lifetime);

View file

@ -30,7 +30,7 @@
//============================================================== //==============================================================
// The pHatingUnit is not used yet // The pHatingUnit is not used yet
float ThreatCalcHelper::CalcThreat(Unit* pHatedUnit, Unit* /*pHatingUnit*/, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const *pThreatSpell) float ThreatCalcHelper::CalcThreat(Unit* pHatedUnit, Unit* /*pHatingUnit*/, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* pThreatSpell)
{ {
// all flat mods applied early // all flat mods applied early
if (!threat) if (!threat)
@ -56,7 +56,7 @@ float ThreatCalcHelper::CalcThreat(Unit* pHatedUnit, Unit* /*pHatingUnit*/, floa
//================= HostileReference ========================== //================= HostileReference ==========================
//============================================================ //============================================================
HostileReference::HostileReference(Unit* pUnit, ThreatManager *pThreatManager, float pThreat) HostileReference::HostileReference(Unit* pUnit, ThreatManager* pThreatManager, float pThreat)
{ {
iThreat = pThreat; iThreat = pThreat;
iTempThreatModifyer = 0.0f; iTempThreatModifyer = 0.0f;
@ -93,7 +93,7 @@ void HostileReference::sourceObjectDestroyLink()
void HostileReference::fireStatusChanged(ThreatRefStatusChangeEvent& pThreatRefStatusChangeEvent) void HostileReference::fireStatusChanged(ThreatRefStatusChangeEvent& pThreatRefStatusChangeEvent)
{ {
if(getSource()) if (getSource())
getSource()->processThreatEvent(&pThreatRefStatusChangeEvent); getSource()->processThreatEvent(&pThreatRefStatusChangeEvent);
} }
@ -104,18 +104,18 @@ void HostileReference::addThreat(float pMod)
iThreat += pMod; iThreat += pMod;
// the threat is changed. Source and target unit have to be availabe // the threat is changed. Source and target unit have to be availabe
// if the link was cut before relink it again // if the link was cut before relink it again
if(!isOnline()) if (!isOnline())
updateOnlineStatus(); updateOnlineStatus();
if(pMod != 0.0f) if (pMod != 0.0f)
{ {
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_THREAT_CHANGE, this, pMod); ThreatRefStatusChangeEvent event(UEV_THREAT_REF_THREAT_CHANGE, this, pMod);
fireStatusChanged(event); fireStatusChanged(event);
} }
if(isValid() && pMod >= 0) if (isValid() && pMod >= 0)
{ {
Unit* victim_owner = getTarget()->GetOwner(); Unit* victim_owner = getTarget()->GetOwner();
if(victim_owner && victim_owner->isAlive()) if (victim_owner && victim_owner->isAlive())
getSource()->addThreat(victim_owner, 0.0f); // create a threat to the owner of a pet, if the pet attacks getSource()->addThreat(victim_owner, 0.0f); // create a threat to the owner of a pet, if the pet attacks
} }
} }
@ -137,15 +137,15 @@ void HostileReference::updateOnlineStatus()
// ref is valid // ref is valid
// target is no player or not gamemaster // target is no player or not gamemaster
// target is not in flight // target is not in flight
if(isValid() && if (isValid() &&
((getTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)getTarget())->isGameMaster()) || ((getTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)getTarget())->isGameMaster()) ||
!getTarget()->IsTaxiFlying())) !getTarget()->IsTaxiFlying()))
{ {
Creature* creature = (Creature* ) getSourceUnit(); Creature* creature = (Creature*) getSourceUnit();
online = getTarget()->isInAccessablePlaceFor(creature); online = getTarget()->isInAccessablePlaceFor(creature);
if(!online) if (!online)
{ {
if(creature->AI()->canReachByRangeAttack(getTarget())) if (creature->AI()->canReachByRangeAttack(getTarget()))
online = true; // not accessable but stays online online = true; // not accessable but stays online
} }
else else
@ -161,10 +161,10 @@ void HostileReference::updateOnlineStatus()
void HostileReference::setOnlineOfflineState(bool pIsOnline) void HostileReference::setOnlineOfflineState(bool pIsOnline)
{ {
if(iOnline != pIsOnline) if (iOnline != pIsOnline)
{ {
iOnline = pIsOnline; iOnline = pIsOnline;
if(!iOnline) if (!iOnline)
setAccessibleState(false); // if not online that not accessable as well setAccessibleState(false); // if not online that not accessable as well
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_ONLINE_STATUS, this); ThreatRefStatusChangeEvent event(UEV_THREAT_REF_ONLINE_STATUS, this);
@ -176,7 +176,7 @@ void HostileReference::setOnlineOfflineState(bool pIsOnline)
void HostileReference::setAccessibleState(bool pIsAccessible) void HostileReference::setAccessibleState(bool pIsAccessible)
{ {
if(iAccessible != pIsAccessible) if (iAccessible != pIsAccessible)
{ {
iAccessible = pIsAccessible; iAccessible = pIsAccessible;
@ -210,10 +210,10 @@ Unit* HostileReference::getSourceUnit()
void ThreatContainer::clearReferences() void ThreatContainer::clearReferences()
{ {
for(ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i) for (ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
{ {
(*i)->unlink(); (*i)->unlink();
delete (*i); delete(*i);
} }
iThreatList.clear(); iThreatList.clear();
} }
@ -224,7 +224,7 @@ HostileReference* ThreatContainer::getReferenceByTarget(Unit* pVictim)
{ {
HostileReference* result = NULL; HostileReference* result = NULL;
ObjectGuid guid = pVictim->GetObjectGuid(); ObjectGuid guid = pVictim->GetObjectGuid();
for(ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i) for (ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
{ {
if ((*i)->getUnitGuid() == guid) if ((*i)->getUnitGuid() == guid)
{ {
@ -242,18 +242,18 @@ HostileReference* ThreatContainer::getReferenceByTarget(Unit* pVictim)
HostileReference* ThreatContainer::addThreat(Unit* pVictim, float pThreat) HostileReference* ThreatContainer::addThreat(Unit* pVictim, float pThreat)
{ {
HostileReference* ref = getReferenceByTarget(pVictim); HostileReference* ref = getReferenceByTarget(pVictim);
if(ref) if (ref)
ref->addThreat(pThreat); ref->addThreat(pThreat);
return ref; return ref;
} }
//============================================================ //============================================================
void ThreatContainer::modifyThreatPercent(Unit *pVictim, int32 pPercent) void ThreatContainer::modifyThreatPercent(Unit* pVictim, int32 pPercent)
{ {
if(HostileReference* ref = getReferenceByTarget(pVictim)) if (HostileReference* ref = getReferenceByTarget(pVictim))
{ {
if(pPercent < -100) if (pPercent < -100)
{ {
ref->removeReference(); ref->removeReference();
delete ref; delete ref;
@ -276,7 +276,7 @@ bool HostileReferenceSortPredicate(const HostileReference* lhs, const HostileRef
void ThreatContainer::update() void ThreatContainer::update()
{ {
if(iDirty && iThreatList.size() >1) if (iDirty && iThreatList.size() >1)
{ {
iThreatList.sort(HostileReferenceSortPredicate); iThreatList.sort(HostileReferenceSortPredicate);
} }
@ -361,8 +361,9 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* pAttacker, Hostile
} }
if (pCurrentRef->getThreat() > 1.3f * pCurrentVictim->getThreat() || if (pCurrentRef->getThreat() > 1.3f * pCurrentVictim->getThreat() ||
(pCurrentRef->getThreat() > 1.1f * pCurrentVictim->getThreat() && pAttacker->CanReachWithMeleeAttack(pTarget))) (pCurrentRef->getThreat() > 1.1f * pCurrentVictim->getThreat() && pAttacker->CanReachWithMeleeAttack(pTarget)))
{ // implement 110% threat rule for targets in melee range {
// implement 110% threat rule for targets in melee range
found = true; // and 130% rule for targets in ranged distances found = true; // and 130% rule for targets in ranged distances
break; // for selecting alive targets break; // for selecting alive targets
} }
@ -386,7 +387,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* pAttacker, Hostile
//============================================================ //============================================================
ThreatManager::ThreatManager(Unit* owner) ThreatManager::ThreatManager(Unit* owner)
: iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL), iUpdateNeed(false) : iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL), iUpdateNeed(false)
{ {
} }
@ -403,7 +404,7 @@ void ThreatManager::clearReferences()
//============================================================ //============================================================
void ThreatManager::addThreat(Unit* pVictim, float pThreat, bool crit, SpellSchoolMask schoolMask, SpellEntry const *pThreatSpell) void ThreatManager::addThreat(Unit* pVictim, float pThreat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* pThreatSpell)
{ {
//function deals with adding threat and adding players and pets into ThreatList //function deals with adding threat and adding players and pets into ThreatList
//mobs, NPCs, guards have ThreatList and HateOfflineList //mobs, NPCs, guards have ThreatList and HateOfflineList
@ -415,11 +416,11 @@ void ThreatManager::addThreat(Unit* pVictim, float pThreat, bool crit, SpellScho
return; return;
// not to GM // not to GM
if (!pVictim || (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()) ) if (!pVictim || (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()))
return; return;
// not to dead and not for dead // not to dead and not for dead
if(!pVictim->isAlive() || !getOwner()->isAlive() ) if (!pVictim->isAlive() || !getOwner()->isAlive())
return; return;
MANGOS_ASSERT(getOwner()->GetTypeId()== TYPEID_UNIT); MANGOS_ASSERT(getOwner()->GetTypeId()== TYPEID_UNIT);
@ -455,21 +456,21 @@ void ThreatManager::addThreatDirectly(Unit* pVictim, float threat)
else else
ref = iThreatOfflineContainer.addThreat(pVictim, threat); ref = iThreatOfflineContainer.addThreat(pVictim, threat);
if(!ref) // there was no ref => create a new one if (!ref) // there was no ref => create a new one
{ {
// threat has to be 0 here // threat has to be 0 here
HostileReference* hostileReference = new HostileReference(pVictim, this, 0); HostileReference* hostileReference = new HostileReference(pVictim, this, 0);
iThreatContainer.addReference(hostileReference); iThreatContainer.addReference(hostileReference);
hostileReference->addThreat(threat); // now we add the real threat hostileReference->addThreat(threat); // now we add the real threat
iUpdateNeed = true; iUpdateNeed = true;
if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()) if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster())
hostileReference->setOnlineOfflineState(false); // GM is always offline hostileReference->setOnlineOfflineState(false); // GM is always offline
} }
} }
//============================================================ //============================================================
void ThreatManager::modifyThreatPercent(Unit *pVictim, int32 pPercent) void ThreatManager::modifyThreatPercent(Unit* pVictim, int32 pPercent)
{ {
iThreatContainer.modifyThreatPercent(pVictim, pPercent); iThreatContainer.modifyThreatPercent(pVictim, pPercent);
iUpdateNeed = true; iUpdateNeed = true;
@ -487,13 +488,13 @@ Unit* ThreatManager::getHostileTarget()
//============================================================ //============================================================
float ThreatManager::getThreat(Unit *pVictim, bool pAlsoSearchOfflineList) float ThreatManager::getThreat(Unit* pVictim, bool pAlsoSearchOfflineList)
{ {
float threat = 0.0f; float threat = 0.0f;
HostileReference* ref = iThreatContainer.getReferenceByTarget(pVictim); HostileReference* ref = iThreatContainer.getReferenceByTarget(pVictim);
if(!ref && pAlsoSearchOfflineList) if (!ref && pAlsoSearchOfflineList)
ref = iThreatOfflineContainer.getReferenceByTarget(pVictim); ref = iThreatOfflineContainer.getReferenceByTarget(pVictim);
if(ref) if (ref)
threat = ref->getThreat(); threat = ref->getThreat();
return threat; return threat;
} }
@ -502,12 +503,12 @@ float ThreatManager::getThreat(Unit *pVictim, bool pAlsoSearchOfflineList)
void ThreatManager::tauntApply(Unit* pTaunter) void ThreatManager::tauntApply(Unit* pTaunter)
{ {
if(HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter)) if (HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter))
{ {
if(getCurrentVictim() && (ref->getThreat() < getCurrentVictim()->getThreat())) if (getCurrentVictim() && (ref->getThreat() < getCurrentVictim()->getThreat()))
{ {
// Ok, temp threat is unused // Ok, temp threat is unused
if(ref->getTempThreatModifyer() == 0.0f) if (ref->getTempThreatModifyer() == 0.0f)
{ {
ref->setTempThreat(getCurrentVictim()->getThreat()); ref->setTempThreat(getCurrentVictim()->getThreat());
iUpdateNeed = true; iUpdateNeed = true;
@ -518,9 +519,9 @@ void ThreatManager::tauntApply(Unit* pTaunter)
//============================================================ //============================================================
void ThreatManager::tauntFadeOut(Unit *pTaunter) void ThreatManager::tauntFadeOut(Unit* pTaunter)
{ {
if(HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter)) if (HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter))
{ {
ref->resetTempThreat(); ref->resetTempThreat();
iUpdateNeed = true; iUpdateNeed = true;
@ -552,15 +553,15 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat
HostileReference* hostileReference = threatRefStatusChangeEvent->getReference(); HostileReference* hostileReference = threatRefStatusChangeEvent->getReference();
switch(threatRefStatusChangeEvent->getType()) switch (threatRefStatusChangeEvent->getType())
{ {
case UEV_THREAT_REF_THREAT_CHANGE: case UEV_THREAT_REF_THREAT_CHANGE:
if((getCurrentVictim() == hostileReference && threatRefStatusChangeEvent->getFValue()<0.0f) || if ((getCurrentVictim() == hostileReference && threatRefStatusChangeEvent->getFValue()<0.0f) ||
(getCurrentVictim() != hostileReference && threatRefStatusChangeEvent->getFValue()>0.0f)) (getCurrentVictim() != hostileReference && threatRefStatusChangeEvent->getFValue()>0.0f))
setDirty(true); // the order in the threat list might have changed setDirty(true); // the order in the threat list might have changed
break; break;
case UEV_THREAT_REF_ONLINE_STATUS: case UEV_THREAT_REF_ONLINE_STATUS:
if(!hostileReference->isOnline()) if (!hostileReference->isOnline())
{ {
if (hostileReference == getCurrentVictim()) if (hostileReference == getCurrentVictim())
{ {
@ -574,7 +575,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat
} }
else else
{ {
if(getCurrentVictim() && hostileReference->getThreat() > (1.1f * getCurrentVictim()->getThreat())) if (getCurrentVictim() && hostileReference->getThreat() > (1.1f * getCurrentVictim()->getThreat()))
setDirty(true); setDirty(true);
iThreatContainer.addReference(hostileReference); iThreatContainer.addReference(hostileReference);
iUpdateNeed = true; iUpdateNeed = true;
@ -587,7 +588,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat
setCurrentVictim(NULL); setCurrentVictim(NULL);
setDirty(true); setDirty(true);
} }
if(hostileReference->isOnline()) if (hostileReference->isOnline())
{ {
iOwner->SendThreatRemove(hostileReference); iOwner->SendThreatRemove(hostileReference);
iThreatContainer.remove(hostileReference); iThreatContainer.remove(hostileReference);

View file

@ -42,14 +42,14 @@ struct SpellEntry;
class ThreatCalcHelper class ThreatCalcHelper
{ {
public: public:
static float CalcThreat(Unit* pHatedUnit, Unit* pHatingUnit, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const *threatSpell); static float CalcThreat(Unit* pHatedUnit, Unit* pHatingUnit, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* threatSpell);
}; };
//============================================================== //==============================================================
class MANGOS_DLL_SPEC HostileReference : public Reference<Unit, ThreatManager> class MANGOS_DLL_SPEC HostileReference : public Reference<Unit, ThreatManager>
{ {
public: public:
HostileReference(Unit* pUnit, ThreatManager *pThreatManager, float pThreat); HostileReference(Unit* pUnit, ThreatManager* pThreatManager, float pThreat);
//================================================= //=================================================
void addThreat(float pMod); void addThreat(float pMod);
@ -72,11 +72,11 @@ class MANGOS_DLL_SPEC HostileReference : public Reference<Unit, ThreatManager>
// used for temporary setting a threat and reducting it later again. // used for temporary setting a threat and reducting it later again.
// the threat modification is stored // the threat modification is stored
void setTempThreat(float pThreat) { iTempThreatModifyer = pThreat - getThreat(); if(iTempThreatModifyer != 0.0f) addThreat(iTempThreatModifyer); } void setTempThreat(float pThreat) { iTempThreatModifyer = pThreat - getThreat(); if (iTempThreatModifyer != 0.0f) addThreat(iTempThreatModifyer); }
void resetTempThreat() void resetTempThreat()
{ {
if(iTempThreatModifyer != 0.0f) if (iTempThreatModifyer != 0.0f)
{ {
addThreat(-iTempThreatModifyer); iTempThreatModifyer = 0.0f; addThreat(-iTempThreatModifyer); iTempThreatModifyer = 0.0f;
} }
@ -106,7 +106,7 @@ class MANGOS_DLL_SPEC HostileReference : public Reference<Unit, ThreatManager>
//================================================= //=================================================
HostileReference* next() { return ((HostileReference* ) Reference<Unit, ThreatManager>::next()); } HostileReference* next() { return ((HostileReference*) Reference<Unit, ThreatManager>::next()); }
//================================================= //=================================================
@ -156,7 +156,7 @@ class MANGOS_DLL_SPEC ThreatContainer
HostileReference* addThreat(Unit* pVictim, float pThreat); HostileReference* addThreat(Unit* pVictim, float pThreat);
void modifyThreatPercent(Unit *pVictim, int32 percent); void modifyThreatPercent(Unit* pVictim, int32 percent);
HostileReference* selectNextVictim(Creature* pAttacker, HostileReference* pCurrentVictim); HostileReference* selectNextVictim(Creature* pAttacker, HostileReference* pCurrentVictim);
@ -180,21 +180,21 @@ class MANGOS_DLL_SPEC ThreatManager
public: public:
friend class HostileReference; friend class HostileReference;
explicit ThreatManager(Unit *pOwner); explicit ThreatManager(Unit* pOwner);
~ThreatManager() { clearReferences(); } ~ThreatManager() { clearReferences(); }
void clearReferences(); void clearReferences();
void addThreat(Unit* pVictim, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const *threatSpell); void addThreat(Unit* pVictim, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* threatSpell);
void addThreat(Unit* pVictim, float threat) { addThreat(pVictim,threat,false,SPELL_SCHOOL_MASK_NONE,NULL); } void addThreat(Unit* pVictim, float threat) { addThreat(pVictim,threat,false,SPELL_SCHOOL_MASK_NONE,NULL); }
// add threat as raw value (ignore redirections and expection all mods applied already to it // add threat as raw value (ignore redirections and expection all mods applied already to it
void addThreatDirectly(Unit* pVictim, float threat); void addThreatDirectly(Unit* pVictim, float threat);
void modifyThreatPercent(Unit *pVictim, int32 pPercent); void modifyThreatPercent(Unit* pVictim, int32 pPercent);
float getThreat(Unit *pVictim, bool pAlsoSearchOfflineList = false); float getThreat(Unit* pVictim, bool pAlsoSearchOfflineList = false);
bool isThreatListEmpty() const { return iThreatContainer.empty(); } bool isThreatListEmpty() const { return iThreatContainer.empty(); }
@ -209,7 +209,7 @@ class MANGOS_DLL_SPEC ThreatManager
Unit* getHostileTarget(); Unit* getHostileTarget();
void tauntApply(Unit* pTaunter); void tauntApply(Unit* pTaunter);
void tauntFadeOut(Unit *pTaunter); void tauntFadeOut(Unit* pTaunter);
void setCurrentVictim(HostileReference* pHostileReference); void setCurrentVictim(HostileReference* pHostileReference);

View file

@ -52,7 +52,7 @@ bool Totem::Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const*
cPos.SelectFinalPoint(this); cPos.SelectFinalPoint(this);
// totem must be at same Z in case swimming caster and etc. // totem must be at same Z in case swimming caster and etc.
if (fabs(cPos.m_pos.z - owner->GetPositionZ() ) > 5.0f) if (fabs(cPos.m_pos.z - owner->GetPositionZ()) > 5.0f)
cPos.m_pos.z = owner->GetPositionZ(); cPos.m_pos.z = owner->GetPositionZ();
if (!cPos.Relocate(this)) if (!cPos.Relocate(this))
@ -69,9 +69,9 @@ bool Totem::Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const*
return true; return true;
} }
void Totem::Update(uint32 update_diff, uint32 time ) void Totem::Update(uint32 update_diff, uint32 time)
{ {
Unit *owner = GetOwner(); Unit* owner = GetOwner();
if (!owner || !owner->isAlive() || !isAlive()) if (!owner || !owner->isAlive() || !isAlive())
{ {
UnSummon(); // remove self UnSummon(); // remove self
@ -86,7 +86,7 @@ void Totem::Update(uint32 update_diff, uint32 time )
else else
m_duration -= update_diff; m_duration -= update_diff;
Creature::Update( update_diff, time ); Creature::Update(update_diff, time);
} }
void Totem::Summon(Unit* owner) void Totem::Summon(Unit* owner)
@ -101,7 +101,7 @@ void Totem::Summon(Unit* owner)
if (!GetSpell()) if (!GetSpell())
return; return;
switch(m_type) switch (m_type)
{ {
case TOTEM_PASSIVE: case TOTEM_PASSIVE:
CastSpell(this, GetSpell(), true); CastSpell(this, GetSpell(), true);
@ -118,7 +118,7 @@ void Totem::UnSummon()
CombatStop(); CombatStop();
RemoveAurasDueToSpell(GetSpell()); RemoveAurasDueToSpell(GetSpell());
if (Unit *owner = GetOwner()) if (Unit* owner = GetOwner())
{ {
owner->_RemoveTotem(this); owner->_RemoveTotem(this);
owner->RemoveAurasDueToSpell(GetSpell()); owner->RemoveAurasDueToSpell(GetSpell());
@ -129,12 +129,12 @@ void Totem::UnSummon()
((Player*)owner)->SendAutoRepeatCancel(this); ((Player*)owner)->SendAutoRepeatCancel(this);
// Not only the player can summon the totem (scripted AI) // Not only the player can summon the totem (scripted AI)
if (Group *pGroup = ((Player*)owner)->GetGroup()) if (Group* pGroup = ((Player*)owner)->GetGroup())
{ {
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{ {
Player* Target = itr->getSource(); Player* Target = itr->getSource();
if(Target && pGroup->SameSubGroup((Player*)owner, Target)) if (Target && pGroup->SameSubGroup((Player*)owner, Target))
Target->RemoveAurasDueToSpell(GetSpell()); Target->RemoveAurasDueToSpell(GetSpell());
} }
} }
@ -159,7 +159,7 @@ void Totem::SetOwner(Unit* owner)
SetLevel(owner->getLevel()); SetLevel(owner->getLevel());
} }
Unit *Totem::GetOwner() Unit* Totem::GetOwner()
{ {
if (ObjectGuid ownerGuid = GetOwnerGuid()) if (ObjectGuid ownerGuid = GetOwnerGuid())
return ObjectAccessor::GetUnit(*this, ownerGuid); return ObjectAccessor::GetUnit(*this, ownerGuid);
@ -167,26 +167,26 @@ Unit *Totem::GetOwner()
return NULL; return NULL;
} }
void Totem::SetTypeBySummonSpell(SpellEntry const * spellProto) void Totem::SetTypeBySummonSpell(SpellEntry const* spellProto)
{ {
// Get spell casted by totem // Get spell casted by totem
SpellEntry const * totemSpell = sSpellStore.LookupEntry(GetSpell()); SpellEntry const* totemSpell = sSpellStore.LookupEntry(GetSpell());
if (totemSpell) if (totemSpell)
{ {
// If spell have cast time -> so its active totem // If spell have cast time -> so its active totem
if (GetSpellCastTime(totemSpell)) if (GetSpellCastTime(totemSpell))
m_type = TOTEM_ACTIVE; m_type = TOTEM_ACTIVE;
} }
if(spellProto->SpellIconID == 2056) if (spellProto->SpellIconID == 2056)
m_type = TOTEM_STATUE; //Jewelery statue m_type = TOTEM_STATUE; //Jewelery statue
} }
bool Totem::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const bool Totem::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
{ {
switch(spellInfo->Effect[index]) switch (spellInfo->Effect[index])
{ {
case SPELL_EFFECT_ATTACK_ME: case SPELL_EFFECT_ATTACK_ME:
// immune to any type of regeneration effects hp/mana etc. // immune to any type of regeneration effects hp/mana etc.
case SPELL_EFFECT_HEAL: case SPELL_EFFECT_HEAL:
case SPELL_EFFECT_HEAL_MAX_HEALTH: case SPELL_EFFECT_HEAL_MAX_HEALTH:
case SPELL_EFFECT_HEAL_MECHANICAL: case SPELL_EFFECT_HEAL_MECHANICAL:

View file

@ -32,16 +32,16 @@ class Totem : public Creature
{ {
public: public:
explicit Totem(); explicit Totem();
virtual ~Totem(){}; virtual ~Totem() {};
bool Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const* cinfo, Unit* owner); bool Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const* cinfo, Unit* owner);
void Update(uint32 update_diff, uint32 time) override; void Update(uint32 update_diff, uint32 time) override;
void Summon(Unit* owner); void Summon(Unit* owner);
void UnSummon(); void UnSummon();
uint32 GetSpell() const { return m_spells[0]; } uint32 GetSpell() const { return m_spells[0]; }
uint32 GetTotemDuration() const { return m_duration; } uint32 GetTotemDuration() const { return m_duration; }
Unit *GetOwner(); Unit* GetOwner();
TotemType GetTotemType() const { return m_type; } TotemType GetTotemType() const { return m_type; }
void SetTypeBySummonSpell(SpellEntry const * spellProto); void SetTypeBySummonSpell(SpellEntry const* spellProto);
void SetDuration(uint32 dur) { m_duration = dur; } void SetDuration(uint32 dur) { m_duration = dur; }
void SetOwner(Unit* owner); void SetOwner(Unit* owner);
@ -51,7 +51,7 @@ class Totem : public Creature
void UpdateArmor() {} void UpdateArmor() {}
void UpdateMaxHealth() {} void UpdateMaxHealth() {}
void UpdateMaxPower(Powers /*power*/) {} void UpdateMaxPower(Powers /*power*/) {}
void UpdateAttackPowerAndDamage(bool /*ranged*/ ) {} void UpdateAttackPowerAndDamage(bool /*ranged*/) {}
void UpdateDamagePhysical(WeaponAttackType /*attType*/) {} void UpdateDamagePhysical(WeaponAttackType /*attType*/) {}
bool IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const; bool IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const;

View file

@ -27,20 +27,20 @@
#include "CellImpl.h" #include "CellImpl.h"
int int
TotemAI::Permissible(const Creature *creature) TotemAI::Permissible(const Creature* creature)
{ {
if( creature->IsTotem() ) if (creature->IsTotem())
return PERMIT_BASE_PROACTIVE; return PERMIT_BASE_PROACTIVE;
return PERMIT_BASE_NO; return PERMIT_BASE_NO;
} }
TotemAI::TotemAI(Creature *c) : CreatureAI(c) TotemAI::TotemAI(Creature* c) : CreatureAI(c)
{ {
} }
void void
TotemAI::MoveInLineOfSight(Unit *) TotemAI::MoveInLineOfSight(Unit*)
{ {
} }
@ -59,7 +59,7 @@ TotemAI::UpdateAI(const uint32 /*diff*/)
return; return;
// Search spell // Search spell
SpellEntry const *spellInfo = sSpellStore.LookupEntry(getTotem().GetSpell()); SpellEntry const* spellInfo = sSpellStore.LookupEntry(getTotem().GetSpell());
if (!spellInfo) if (!spellInfo)
return; return;
@ -73,9 +73,9 @@ TotemAI::UpdateAI(const uint32 /*diff*/)
Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid); Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid);
// Search victim if no, not attackable, or out of range, or friendly (possible in case duel end) // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end)
if( !victim || if (!victim ||
!victim->isTargetableForAttack() || !m_creature->IsWithinDistInMap(victim, max_range) || !victim->isTargetableForAttack() || !m_creature->IsWithinDistInMap(victim, max_range) ||
m_creature->IsFriendlyTo(victim) || !victim->isVisibleForOrDetect(m_creature,m_creature,false) ) m_creature->IsFriendlyTo(victim) || !victim->isVisibleForOrDetect(m_creature,m_creature,false))
{ {
victim = NULL; victim = NULL;
@ -99,13 +99,13 @@ TotemAI::UpdateAI(const uint32 /*diff*/)
} }
bool bool
TotemAI::IsVisible(Unit *) const TotemAI::IsVisible(Unit*) const
{ {
return false; return false;
} }
void void
TotemAI::AttackStart(Unit *) TotemAI::AttackStart(Unit*)
{ {
} }

View file

@ -30,15 +30,15 @@ class MANGOS_DLL_DECL TotemAI : public CreatureAI
{ {
public: public:
explicit TotemAI(Creature *c); explicit TotemAI(Creature* c);
void MoveInLineOfSight(Unit *); void MoveInLineOfSight(Unit*);
void AttackStart(Unit *); void AttackStart(Unit*);
void EnterEvadeMode(); void EnterEvadeMode();
bool IsVisible(Unit *) const; bool IsVisible(Unit*) const;
void UpdateAI(const uint32); void UpdateAI(const uint32);
static int Permissible(const Creature *); static int Permissible(const Creature*);
protected: protected:
Totem& getTotem(); Totem& getTotem();

View file

@ -34,7 +34,7 @@ void WorldSession::SendTradeStatus(TradeStatus status)
{ {
WorldPacket data; WorldPacket data;
switch(status) switch (status)
{ {
case TRADE_STATUS_BEGIN_TRADE: case TRADE_STATUS_BEGIN_TRADE:
data.Initialize(SMSG_TRADE_STATUS, 4+8); data.Initialize(SMSG_TRADE_STATUS, 4+8);
@ -69,13 +69,13 @@ void WorldSession::SendTradeStatus(TradeStatus status)
void WorldSession::HandleIgnoreTradeOpcode(WorldPacket& /*recvPacket*/) void WorldSession::HandleIgnoreTradeOpcode(WorldPacket& /*recvPacket*/)
{ {
DEBUG_LOG( "WORLD: Ignore Trade %u",_player->GetGUIDLow()); DEBUG_LOG("WORLD: Ignore Trade %u",_player->GetGUIDLow());
// recvPacket.print_storage(); // recvPacket.print_storage();
} }
void WorldSession::HandleBusyTradeOpcode(WorldPacket& /*recvPacket*/) void WorldSession::HandleBusyTradeOpcode(WorldPacket& /*recvPacket*/)
{ {
DEBUG_LOG( "WORLD: Busy Trade %u",_player->GetGUIDLow()); DEBUG_LOG("WORLD: Busy Trade %u",_player->GetGUIDLow());
// recvPacket.print_storage(); // recvPacket.print_storage();
} }
@ -91,7 +91,7 @@ void WorldSession::SendUpdateTrade(bool trader_state /*= true*/)
data << uint32(view_trade->GetMoney()); // trader gold data << uint32(view_trade->GetMoney()); // trader gold
data << uint32(view_trade->GetSpell()); // spell casted on lowest slot item data << uint32(view_trade->GetSpell()); // spell casted on lowest slot item
for(uint8 i = 0; i < TRADE_SLOT_COUNT; ++i) for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i)
{ {
data << uint8(i); // trade slot number, if not specified, then end of packet data << uint8(i); // trade slot number, if not specified, then end of packet
@ -100,27 +100,27 @@ void WorldSession::SendUpdateTrade(bool trader_state /*= true*/)
data << uint32(item->GetProto()->ItemId); // entry data << uint32(item->GetProto()->ItemId); // entry
data << uint32(item->GetProto()->DisplayInfoID);// display id data << uint32(item->GetProto()->DisplayInfoID);// display id
data << uint32(item->GetCount()); // stack count data << uint32(item->GetCount()); // stack count
// wrapped: hide stats but show giftcreator name // wrapped: hide stats but show giftcreator name
data << uint32(item->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED) ? 1 : 0); data << uint32(item->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED) ? 1 : 0);
data << item->GetGuidValue(ITEM_FIELD_GIFTCREATOR); data << item->GetGuidValue(ITEM_FIELD_GIFTCREATOR);
data << uint32(item->GetEnchantmentId(PERM_ENCHANTMENT_SLOT)); data << uint32(item->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot)
data << uint32(item->GetEnchantmentId(EnchantmentSlot(enchant_slot))); data << uint32(item->GetEnchantmentId(EnchantmentSlot(enchant_slot)));
// creator // creator
data << item->GetGuidValue(ITEM_FIELD_CREATOR); data << item->GetGuidValue(ITEM_FIELD_CREATOR);
data << uint32(item->GetSpellCharges()); // charges data << uint32(item->GetSpellCharges()); // charges
data << uint32(item->GetItemSuffixFactor()); // SuffixFactor data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
data << uint32(item->GetItemRandomPropertyId());// random properties id data << uint32(item->GetItemRandomPropertyId());// random properties id
data << uint32(item->GetProto()->LockID); // lock id data << uint32(item->GetProto()->LockID); // lock id
// max durability // max durability
data << uint32(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); data << uint32(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY));
// durability // durability
data << uint32(item->GetUInt32Value(ITEM_FIELD_DURABILITY)); data << uint32(item->GetUInt32Value(ITEM_FIELD_DURABILITY));
} }
else else
{ {
for(uint8 j = 0; j < 18; ++j) for (uint8 j = 0; j < 18; ++j)
data << uint32(0); data << uint32(0);
} }
} }
@ -136,13 +136,13 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
if (!trader) if (!trader)
return; return;
for(int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{ {
ItemPosCountVec traderDst; ItemPosCountVec traderDst;
ItemPosCountVec playerDst; ItemPosCountVec playerDst;
bool traderCanTrade = (myItems[i]==NULL || trader->CanStoreItem( NULL_BAG, NULL_SLOT, traderDst, myItems[i], false ) == EQUIP_ERR_OK); bool traderCanTrade = (myItems[i]==NULL || trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, myItems[i], false) == EQUIP_ERR_OK);
bool playerCanTrade = (hisItems[i]==NULL || _player->CanStoreItem( NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false ) == EQUIP_ERR_OK); bool playerCanTrade = (hisItems[i]==NULL || _player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK);
if (traderCanTrade && playerCanTrade ) if (traderCanTrade && playerCanTrade)
{ {
// Ok, if trade item exists and can be stored // Ok, if trade item exists and can be stored
// If we trade in both directions we had to check, if the trade will work before we actually do it // If we trade in both directions we had to check, if the trade will work before we actually do it
@ -154,13 +154,13 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
if (_player->GetSession()->GetSecurity() > SEC_PLAYER && sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE)) if (_player->GetSession()->GetSecurity() > SEC_PLAYER && sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE))
{ {
sLog.outCommand(_player->GetSession()->GetAccountId(),"GM %s (Account: %u) trade: %s (Entry: %d Count: %u) to player: %s (Account: %u)", sLog.outCommand(_player->GetSession()->GetAccountId(),"GM %s (Account: %u) trade: %s (Entry: %d Count: %u) to player: %s (Account: %u)",
_player->GetName(), _player->GetSession()->GetAccountId(), _player->GetName(), _player->GetSession()->GetAccountId(),
myItems[i]->GetProto()->Name1, myItems[i]->GetEntry(), myItems[i]->GetCount(), myItems[i]->GetProto()->Name1, myItems[i]->GetEntry(), myItems[i]->GetCount(),
trader->GetName(), trader->GetSession()->GetAccountId()); trader->GetName(), trader->GetSession()->GetAccountId());
} }
// store // store
trader->MoveItemToInventory( traderDst, myItems[i], true, true); trader->MoveItemToInventory(traderDst, myItems[i], true, true);
} }
if (hisItems[i]) if (hisItems[i])
@ -170,13 +170,13 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
if (trader->GetSession()->GetSecurity() > SEC_PLAYER && sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE)) if (trader->GetSession()->GetSecurity() > SEC_PLAYER && sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE))
{ {
sLog.outCommand(trader->GetSession()->GetAccountId(),"GM %s (Account: %u) trade: %s (Entry: %d Count: %u) to player: %s (Account: %u)", sLog.outCommand(trader->GetSession()->GetAccountId(),"GM %s (Account: %u) trade: %s (Entry: %d Count: %u) to player: %s (Account: %u)",
trader->GetName(), trader->GetSession()->GetAccountId(), trader->GetName(), trader->GetSession()->GetAccountId(),
hisItems[i]->GetProto()->Name1, hisItems[i]->GetEntry(), hisItems[i]->GetCount(), hisItems[i]->GetProto()->Name1, hisItems[i]->GetEntry(), hisItems[i]->GetCount(),
_player->GetName(), _player->GetSession()->GetAccountId()); _player->GetName(), _player->GetSession()->GetAccountId());
} }
// store // store
_player->MoveItemToInventory( playerDst, hisItems[i], true, true); _player->MoveItemToInventory(playerDst, hisItems[i], true, true);
} }
} }
else else
@ -187,7 +187,7 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
{ {
if (!traderCanTrade) if (!traderCanTrade)
sLog.outError("trader can't store item: %s", myItems[i]->GetGuidStr().c_str()); sLog.outError("trader can't store item: %s", myItems[i]->GetGuidStr().c_str());
if (_player->CanStoreItem( NULL_BAG, NULL_SLOT, playerDst, myItems[i], false ) == EQUIP_ERR_OK) if (_player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, myItems[i], false) == EQUIP_ERR_OK)
_player->MoveItemToInventory(playerDst, myItems[i], true, true); _player->MoveItemToInventory(playerDst, myItems[i], true, true);
else else
sLog.outError("player can't take item back: %s", myItems[i]->GetGuidStr().c_str()); sLog.outError("player can't take item back: %s", myItems[i]->GetGuidStr().c_str());
@ -197,7 +197,7 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
{ {
if (!playerCanTrade) if (!playerCanTrade)
sLog.outError("player can't store item: %s", hisItems[i]->GetGuidStr().c_str()); sLog.outError("player can't store item: %s", hisItems[i]->GetGuidStr().c_str());
if (trader->CanStoreItem( NULL_BAG, NULL_SLOT, traderDst, hisItems[i], false ) == EQUIP_ERR_OK) if (trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, hisItems[i], false) == EQUIP_ERR_OK)
trader->MoveItemToInventory(traderDst, hisItems[i], true, true); trader->MoveItemToInventory(traderDst, hisItems[i], true, true);
else else
sLog.outError("trader can't take item back: %s", hisItems[i]->GetGuidStr().c_str()); sLog.outError("trader can't take item back: %s", hisItems[i]->GetGuidStr().c_str());
@ -207,13 +207,13 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[])
} }
//============================================================== //==============================================================
static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item **myItems, Item **hisItems) static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item** myItems, Item** hisItems)
{ {
myTrade->SetInAcceptProcess(true); myTrade->SetInAcceptProcess(true);
hisTrade->SetInAcceptProcess(true); hisTrade->SetInAcceptProcess(true);
// store items in local list and set 'in-trade' flag // store items in local list and set 'in-trade' flag
for(int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{ {
if (Item* item = myTrade->GetItem(TradeSlots(i))) if (Item* item = myTrade->GetItem(TradeSlots(i)))
{ {
@ -238,7 +238,7 @@ static void clearAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade)
hisTrade->SetInAcceptProcess(false); hisTrade->SetInAcceptProcess(false);
} }
static void clearAcceptTradeMode(Item **myItems, Item **hisItems) static void clearAcceptTradeMode(Item** myItems, Item** hisItems)
{ {
// clear 'in-trade' flag // clear 'in-trade' flag
for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
@ -264,8 +264,8 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
if (!his_trade) if (!his_trade)
return; return;
Item *myItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; Item* myItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL };
Item *hisItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; Item* hisItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL };
bool myCanCompleteTrade=true,hisCanCompleteTrade=true; bool myCanCompleteTrade=true,hisCanCompleteTrade=true;
// set before checks to properly undo at problems (it already set in to client) // set before checks to properly undo at problems (it already set in to client)
@ -282,13 +282,13 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
// not accept case incorrect money amount // not accept case incorrect money amount
if (his_trade->GetMoney() > trader->GetMoney()) if (his_trade->GetMoney() > trader->GetMoney())
{ {
trader->GetSession( )->SendNotification(LANG_NOT_ENOUGH_GOLD); trader->GetSession()->SendNotification(LANG_NOT_ENOUGH_GOLD);
his_trade->SetAccepted(false, true); his_trade->SetAccepted(false, true);
return; return;
} }
// not accept if some items now can't be trade (cheating) // not accept if some items now can't be trade (cheating)
for(int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{ {
if (Item* item = my_trade->GetItem(TradeSlots(i))) if (Item* item = my_trade->GetItem(TradeSlots(i)))
{ {
@ -326,7 +326,7 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
Item* castItem = my_trade->GetSpellCastItem(); Item* castItem = my_trade->GetSpellCastItem();
if (!spellEntry || !his_trade->GetItem(TRADE_SLOT_NONTRADED) || if (!spellEntry || !his_trade->GetItem(TRADE_SLOT_NONTRADED) ||
(my_trade->HasSpellCastItem() && !castItem)) (my_trade->HasSpellCastItem() && !castItem))
{ {
clearAcceptTradeMode(my_trade, his_trade); clearAcceptTradeMode(my_trade, his_trade);
clearAcceptTradeMode(myItems, hisItems); clearAcceptTradeMode(myItems, hisItems);
@ -361,7 +361,7 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
Item* castItem = his_trade->GetSpellCastItem(); Item* castItem = his_trade->GetSpellCastItem();
if (!spellEntry || !my_trade->GetItem(TRADE_SLOT_NONTRADED) || if (!spellEntry || !my_trade->GetItem(TRADE_SLOT_NONTRADED) ||
(his_trade->HasSpellCastItem() && !castItem)) (his_trade->HasSpellCastItem() && !castItem))
{ {
delete my_spell; delete my_spell;
his_trade->SetSpell(0); his_trade->SetSpell(0);
@ -396,18 +396,18 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
trader->GetSession()->SendTradeStatus(TRADE_STATUS_TRADE_ACCEPT); trader->GetSession()->SendTradeStatus(TRADE_STATUS_TRADE_ACCEPT);
// test if item will fit in each inventory // test if item will fit in each inventory
hisCanCompleteTrade = (trader->CanStoreItems( myItems,TRADE_SLOT_TRADED_COUNT )== EQUIP_ERR_OK); hisCanCompleteTrade = (trader->CanStoreItems(myItems,TRADE_SLOT_TRADED_COUNT)== EQUIP_ERR_OK);
myCanCompleteTrade = (_player->CanStoreItems( hisItems,TRADE_SLOT_TRADED_COUNT ) == EQUIP_ERR_OK); myCanCompleteTrade = (_player->CanStoreItems(hisItems,TRADE_SLOT_TRADED_COUNT) == EQUIP_ERR_OK);
clearAcceptTradeMode(myItems, hisItems); clearAcceptTradeMode(myItems, hisItems);
// in case of missing space report error // in case of missing space report error
if(!myCanCompleteTrade) if (!myCanCompleteTrade)
{ {
clearAcceptTradeMode(my_trade, his_trade); clearAcceptTradeMode(my_trade, his_trade);
SendNotification(LANG_NOT_FREE_TRADE_SLOTS); SendNotification(LANG_NOT_FREE_TRADE_SLOTS);
trader->GetSession( )->SendNotification(LANG_NOT_PARTNER_FREE_TRADE_SLOTS); trader->GetSession()->SendNotification(LANG_NOT_PARTNER_FREE_TRADE_SLOTS);
my_trade->SetAccepted(false); my_trade->SetAccepted(false);
his_trade->SetAccepted(false); his_trade->SetAccepted(false);
return; return;
@ -424,7 +424,7 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
} }
// execute trade: 1. remove // execute trade: 1. remove
for(int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{ {
if (Item* item = myItems[i]) if (Item* item = myItems[i])
{ {
@ -447,23 +447,23 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket)
if (_player->GetSession()->GetSecurity() > SEC_PLAYER && my_trade->GetMoney() > 0) if (_player->GetSession()->GetSecurity() > SEC_PLAYER && my_trade->GetMoney() > 0)
{ {
sLog.outCommand(_player->GetSession()->GetAccountId(),"GM %s (Account: %u) give money (Amount: %u) to player: %s (Account: %u)", sLog.outCommand(_player->GetSession()->GetAccountId(),"GM %s (Account: %u) give money (Amount: %u) to player: %s (Account: %u)",
_player->GetName(),_player->GetSession()->GetAccountId(), _player->GetName(),_player->GetSession()->GetAccountId(),
my_trade->GetMoney(), my_trade->GetMoney(),
trader->GetName(), trader->GetSession()->GetAccountId()); trader->GetName(), trader->GetSession()->GetAccountId());
} }
if (trader->GetSession()->GetSecurity() > SEC_PLAYER && his_trade->GetMoney() > 0) if (trader->GetSession()->GetSecurity() > SEC_PLAYER && his_trade->GetMoney() > 0)
{ {
sLog.outCommand(trader->GetSession()->GetAccountId(),"GM %s (Account: %u) give money (Amount: %u) to player: %s (Account: %u)", sLog.outCommand(trader->GetSession()->GetAccountId(),"GM %s (Account: %u) give money (Amount: %u) to player: %s (Account: %u)",
trader->GetName(), trader->GetSession()->GetAccountId(), trader->GetName(), trader->GetSession()->GetAccountId(),
his_trade->GetMoney(), his_trade->GetMoney(),
_player->GetName(),_player->GetSession()->GetAccountId()); _player->GetName(),_player->GetSession()->GetAccountId());
} }
} }
// update money // update money
_player->ModifyMoney( -int32(my_trade->GetMoney()) ); _player->ModifyMoney(-int32(my_trade->GetMoney()));
_player->ModifyMoney(his_trade->GetMoney()); _player->ModifyMoney(his_trade->GetMoney());
trader->ModifyMoney( -int32(his_trade->GetMoney()) ); trader->ModifyMoney(-int32(his_trade->GetMoney()));
trader->ModifyMoney(my_trade->GetMoney()); trader->ModifyMoney(my_trade->GetMoney());
if (my_spell) if (my_spell)
@ -560,7 +560,7 @@ void WorldSession::HandleInitiateTradeOpcode(WorldPacket& recvPacket)
return; return;
} }
Player* pOther = ObjectAccessor::FindPlayer( otherGuid ); Player* pOther = ObjectAccessor::FindPlayer(otherGuid);
if (!pOther) if (!pOther)
{ {
@ -604,7 +604,7 @@ void WorldSession::HandleInitiateTradeOpcode(WorldPacket& recvPacket)
return; return;
} }
if (pOther->GetTeam() !=_player->GetTeam() ) if (pOther->GetTeam() !=_player->GetTeam())
{ {
SendTradeStatus(TRADE_STATUS_WRONG_FACTION); SendTradeStatus(TRADE_STATUS_WRONG_FACTION);
return; return;

View file

@ -31,17 +31,17 @@
void MapManager::LoadTransports() void MapManager::LoadTransports()
{ {
QueryResult *result = WorldDatabase.Query("SELECT entry, name, period FROM transports"); QueryResult* result = WorldDatabase.Query("SELECT entry, name, period FROM transports");
uint32 count = 0; uint32 count = 0;
if( !result ) if (!result)
{ {
BarGoLink bar(1); BarGoLink bar(1);
bar.step(); bar.step();
sLog.outString(); sLog.outString();
sLog.outString( ">> Loaded %u transports", count ); sLog.outString(">> Loaded %u transports", count);
return; return;
} }
@ -51,24 +51,24 @@ void MapManager::LoadTransports()
{ {
bar.step(); bar.step();
Transport *t = new Transport; Transport* t = new Transport;
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32(); uint32 entry = fields[0].GetUInt32();
std::string name = fields[1].GetCppString(); std::string name = fields[1].GetCppString();
t->m_period = fields[2].GetUInt32(); t->m_period = fields[2].GetUInt32();
const GameObjectInfo *goinfo = ObjectMgr::GetGameObjectInfo(entry); const GameObjectInfo* goinfo = ObjectMgr::GetGameObjectInfo(entry);
if(!goinfo) if (!goinfo)
{ {
sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template missing", entry, name.c_str()); sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template missing", entry, name.c_str());
delete t; delete t;
continue; continue;
} }
if(goinfo->type != GAMEOBJECT_TYPE_MO_TRANSPORT) if (goinfo->type != GAMEOBJECT_TYPE_MO_TRANSPORT)
{ {
sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template type wrong", entry, name.c_str()); sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template type wrong", entry, name.c_str());
delete t; delete t;
@ -79,7 +79,7 @@ void MapManager::LoadTransports()
std::set<uint32> mapsUsed; std::set<uint32> mapsUsed;
if(!t->GenerateWaypoints(goinfo->moTransport.taxiPathId, mapsUsed)) if (!t->GenerateWaypoints(goinfo->moTransport.taxiPathId, mapsUsed))
// skip transports with empty waypoints list // skip transports with empty waypoints list
{ {
sLog.outErrorDb("Transport (path id %u) path size = 0. Transport ignored, check DBC files or transport GO data0 field.",goinfo->moTransport.taxiPathId); sLog.outErrorDb("Transport (path id %u) path size = 0. Transport ignored, check DBC files or transport GO data0 field.",goinfo->moTransport.taxiPathId);
@ -93,7 +93,7 @@ void MapManager::LoadTransports()
//current code does not support transports in dungeon! //current code does not support transports in dungeon!
const MapEntry* pMapInfo = sMapStore.LookupEntry(mapid); const MapEntry* pMapInfo = sMapStore.LookupEntry(mapid);
if(!pMapInfo || pMapInfo->Instanceable()) if (!pMapInfo || pMapInfo->Instanceable())
{ {
delete t; delete t;
continue; continue;
@ -116,26 +116,27 @@ void MapManager::LoadTransports()
//t->GetMap()->Add<GameObject>((GameObject *)t); //t->GetMap()->Add<GameObject>((GameObject *)t);
++count; ++count;
} while(result->NextRow()); }
while (result->NextRow());
delete result; delete result;
sLog.outString(); sLog.outString();
sLog.outString( ">> Loaded %u transports", count ); sLog.outString(">> Loaded %u transports", count);
// check transport data DB integrity // check transport data DB integrity
result = WorldDatabase.Query("SELECT gameobject.guid,gameobject.id,transports.name FROM gameobject,transports WHERE gameobject.id = transports.entry"); result = WorldDatabase.Query("SELECT gameobject.guid,gameobject.id,transports.name FROM gameobject,transports WHERE gameobject.id = transports.entry");
if(result) // wrong data found if (result) // wrong data found
{ {
do do
{ {
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 guid = fields[0].GetUInt32(); uint32 guid = fields[0].GetUInt32();
uint32 entry = fields[1].GetUInt32(); uint32 entry = fields[1].GetUInt32();
std::string name = fields[2].GetCppString(); std::string name = fields[2].GetCppString();
sLog.outErrorDb("Transport %u '%s' have record (GUID: %u) in `gameobject`. Transports DON'T must have any records in `gameobject` or its behavior will be unpredictable/bugged.",entry,name.c_str(),guid); sLog.outErrorDb("Transport %u '%s' have record (GUID: %u) in `gameobject`. Transports DON'T must have any records in `gameobject` or its behavior will be unpredictable/bugged.",entry,name.c_str(),guid);
} }
while(result->NextRow()); while (result->NextRow());
delete result; delete result;
} }
@ -151,10 +152,10 @@ bool Transport::Create(uint32 guidlow, uint32 mapid, float x, float y, float z,
Relocate(x,y,z,ang); Relocate(x,y,z,ang);
// instance id and phaseMask isn't set to values different from std. // instance id and phaseMask isn't set to values different from std.
if(!IsPositionValid()) if (!IsPositionValid())
{ {
sLog.outError("Transport (GUID: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)", sLog.outError("Transport (GUID: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)",
guidlow,x,y); guidlow,x,y);
return false; return false;
} }
@ -209,7 +210,7 @@ struct keyFrame
float tFrom, tTo; float tFrom, tTo;
}; };
bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids) bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32>& mapids)
{ {
if (pathid >= sTaxiPathNodesByPath.size()) if (pathid >= sTaxiPathNodesByPath.size())
return false; return false;
@ -262,13 +263,13 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids)
{ {
keyFrames[i].distFromPrev = keyFrames[i].distFromPrev =
sqrt(pow(keyFrames[i].node->x - keyFrames[i - 1].node->x, 2) + sqrt(pow(keyFrames[i].node->x - keyFrames[i - 1].node->x, 2) +
pow(keyFrames[i].node->y - keyFrames[i - 1].node->y, 2) + pow(keyFrames[i].node->y - keyFrames[i - 1].node->y, 2) +
pow(keyFrames[i].node->z - keyFrames[i - 1].node->z, 2)); pow(keyFrames[i].node->z - keyFrames[i - 1].node->z, 2));
} }
if (keyFrames[i].node->actionFlag == 2) if (keyFrames[i].node->actionFlag == 2)
{ {
// remember first stop frame // remember first stop frame
if(firstStop == -1) if (firstStop == -1)
firstStop = i; firstStop = i;
lastStop = i; lastStop = i;
} }
@ -322,7 +323,7 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids)
teleport = true; teleport = true;
WayPoint pos(keyFrames[0].node->mapid, keyFrames[0].node->x, keyFrames[0].node->y, keyFrames[0].node->z, teleport, WayPoint pos(keyFrames[0].node->mapid, keyFrames[0].node->x, keyFrames[0].node->y, keyFrames[0].node->z, teleport,
keyFrames[0].node->arrivalEventID, keyFrames[0].node->departureEventID); keyFrames[0].node->arrivalEventID, keyFrames[0].node->departureEventID);
m_WayPoints[0] = pos; m_WayPoints[0] = pos;
t += keyFrames[0].node->delay * 1000; t += keyFrames[0].node->delay * 1000;
@ -403,7 +404,7 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids)
} }
WayPoint pos(keyFrames[i + 1].node->mapid, keyFrames[i + 1].node->x, keyFrames[i + 1].node->y, keyFrames[i + 1].node->z, teleport, WayPoint pos(keyFrames[i + 1].node->mapid, keyFrames[i + 1].node->x, keyFrames[i + 1].node->y, keyFrames[i + 1].node->z, teleport,
keyFrames[i + 1].node->arrivalEventID, keyFrames[i + 1].node->departureEventID); keyFrames[i + 1].node->arrivalEventID, keyFrames[i + 1].node->departureEventID);
// sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport); // sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport);
@ -443,13 +444,13 @@ void Transport::TeleportTransport(uint32 newMapid, float x, float y, float z)
Map const* oldMap = GetMap(); Map const* oldMap = GetMap();
Relocate(x, y, z); Relocate(x, y, z);
for(PlayerSet::iterator itr = m_passengers.begin(); itr != m_passengers.end();) for (PlayerSet::iterator itr = m_passengers.begin(); itr != m_passengers.end();)
{ {
PlayerSet::iterator it2 = itr; PlayerSet::iterator it2 = itr;
++itr; ++itr;
Player *plr = *it2; Player* plr = *it2;
if(!plr) if (!plr)
{ {
m_passengers.erase(it2); m_passengers.erase(it2);
continue; continue;
@ -469,10 +470,10 @@ void Transport::TeleportTransport(uint32 newMapid, float x, float y, float z)
//we need to create and save new Map object with 'newMapid' because if not done -> lead to invalid Map object reference... //we need to create and save new Map object with 'newMapid' because if not done -> lead to invalid Map object reference...
//player far teleport would try to create same instance, but we need it NOW for transport... //player far teleport would try to create same instance, but we need it NOW for transport...
//correct me if I'm wrong O.o //correct me if I'm wrong O.o
Map * newMap = sMapMgr.CreateMap(newMapid, this); Map* newMap = sMapMgr.CreateMap(newMapid, this);
SetMap(newMap); SetMap(newMap);
if(oldMap != newMap) if (oldMap != newMap)
{ {
UpdateForMap(oldMap); UpdateForMap(oldMap);
UpdateForMap(newMap); UpdateForMap(newMap);
@ -496,7 +497,7 @@ bool Transport::RemovePassenger(Player* passenger)
return true; return true;
} }
void Transport::Update( uint32 update_diff, uint32 /*p_time*/) void Transport::Update(uint32 update_diff, uint32 /*p_time*/)
{ {
if (m_WayPoints.size() <= 1) if (m_WayPoints.size() <= 1)
return; return;
@ -542,14 +543,14 @@ void Transport::Update( uint32 update_diff, uint32 /*p_time*/)
void Transport::UpdateForMap(Map const* targetMap) void Transport::UpdateForMap(Map const* targetMap)
{ {
Map::PlayerList const& pl = targetMap->GetPlayers(); Map::PlayerList const& pl = targetMap->GetPlayers();
if(pl.isEmpty()) if (pl.isEmpty())
return; return;
if(GetMapId()==targetMap->GetId()) if (GetMapId()==targetMap->GetId())
{ {
for(Map::PlayerList::const_iterator itr = pl.begin(); itr != pl.end(); ++itr) for (Map::PlayerList::const_iterator itr = pl.begin(); itr != pl.end(); ++itr)
{ {
if(this != itr->getSource()->GetTransport()) if (this != itr->getSource()->GetTransport())
{ {
UpdateData transData; UpdateData transData;
BuildCreateUpdateBlockForPlayer(&transData, itr->getSource()); BuildCreateUpdateBlockForPlayer(&transData, itr->getSource());
@ -566,8 +567,8 @@ void Transport::UpdateForMap(Map const* targetMap)
WorldPacket out_packet; WorldPacket out_packet;
transData.BuildPacket(&out_packet); transData.BuildPacket(&out_packet);
for(Map::PlayerList::const_iterator itr = pl.begin(); itr != pl.end(); ++itr) for (Map::PlayerList::const_iterator itr = pl.begin(); itr != pl.end(); ++itr)
if(this != itr->getSource()->GetTransport()) if (this != itr->getSource()->GetTransport())
itr->getSource()->SendDirectMessage(&out_packet); itr->getSource()->SendDirectMessage(&out_packet);
} }
} }

View file

@ -31,7 +31,7 @@ class Transport : public GameObject
explicit Transport(); explicit Transport();
bool Create(uint32 guidlow, uint32 mapid, float x, float y, float z, float ang, uint8 animprogress, uint16 dynamicHighValue); bool Create(uint32 guidlow, uint32 mapid, float x, float y, float z, float ang, uint8 animprogress, uint16 dynamicHighValue);
bool GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids); bool GenerateWaypoints(uint32 pathid, std::set<uint32>& mapids);
void Update(uint32 update_diff, uint32 p_time) override; void Update(uint32 update_diff, uint32 p_time) override;
bool AddPassenger(Player* passenger); bool AddPassenger(Player* passenger);
bool RemovePassenger(Player* passenger); bool RemovePassenger(Player* passenger);
@ -45,7 +45,7 @@ class Transport : public GameObject
WayPoint() : mapid(0), x(0), y(0), z(0), teleport(false) {} WayPoint() : mapid(0), x(0), y(0), z(0), teleport(false) {}
WayPoint(uint32 _mapid, float _x, float _y, float _z, bool _teleport, uint32 _arrivalEventID = 0, uint32 _departureEventID = 0) WayPoint(uint32 _mapid, float _x, float _y, float _z, bool _teleport, uint32 _arrivalEventID = 0, uint32 _departureEventID = 0)
: mapid(_mapid), x(_x), y(_y), z(_z), teleport(_teleport), : mapid(_mapid), x(_x), y(_y), z(_z), teleport(_teleport),
arrivalEventID(_arrivalEventID), departureEventID(_departureEventID) arrivalEventID(_arrivalEventID), departureEventID(_departureEventID)
{ {
} }

File diff suppressed because it is too large Load diff

View file

@ -634,15 +634,15 @@ enum MovementFlags
// flags that use in movement check for example at spell casting // flags that use in movement check for example at spell casting
MovementFlags const movementFlagsMask = MovementFlags( MovementFlags const movementFlagsMask = MovementFlags(
MOVEFLAG_FORWARD |MOVEFLAG_BACKWARD |MOVEFLAG_STRAFE_LEFT |MOVEFLAG_STRAFE_RIGHT| MOVEFLAG_FORWARD |MOVEFLAG_BACKWARD |MOVEFLAG_STRAFE_LEFT |MOVEFLAG_STRAFE_RIGHT|
MOVEFLAG_PITCH_UP|MOVEFLAG_PITCH_DOWN|MOVEFLAG_ROOT | MOVEFLAG_PITCH_UP|MOVEFLAG_PITCH_DOWN|MOVEFLAG_ROOT |
MOVEFLAG_FALLING |MOVEFLAG_FALLINGFAR|MOVEFLAG_ASCENDING | MOVEFLAG_FALLING |MOVEFLAG_FALLINGFAR|MOVEFLAG_ASCENDING |
MOVEFLAG_FLYING |MOVEFLAG_SPLINE_ELEVATION MOVEFLAG_FLYING |MOVEFLAG_SPLINE_ELEVATION
); );
MovementFlags const movementOrTurningFlagsMask = MovementFlags( MovementFlags const movementOrTurningFlagsMask = MovementFlags(
movementFlagsMask | MOVEFLAG_TURN_LEFT | MOVEFLAG_TURN_RIGHT movementFlagsMask | MOVEFLAG_TURN_LEFT | MOVEFLAG_TURN_RIGHT
); );
enum MovementFlags2 enum MovementFlags2
{ {
@ -673,8 +673,8 @@ class MovementInfo
t_time(0), t_seat(-1), t_time2(0), s_pitch(0.0f), fallTime(0), u_unk1(0.0f) {} t_time(0), t_seat(-1), t_time2(0), s_pitch(0.0f), fallTime(0), u_unk1(0.0f) {}
// Read/Write methods // Read/Write methods
void Read(ByteBuffer &data); void Read(ByteBuffer& data);
void Write(ByteBuffer &data) const; void Write(ByteBuffer& data) const;
// Movement flags manipulations // Movement flags manipulations
void AddMovementFlag(MovementFlags f) { moveFlags |= f; } void AddMovementFlag(MovementFlags f) { moveFlags |= f; }
@ -685,7 +685,7 @@ class MovementInfo
MovementFlags2 GetMovementFlags2() const { return MovementFlags2(moveFlags2); } MovementFlags2 GetMovementFlags2() const { return MovementFlags2(moveFlags2); }
// Position manipulations // Position manipulations
Position const *GetPos() const { return &pos; } Position const* GetPos() const { return &pos; }
void SetTransportData(ObjectGuid guid, float x, float y, float z, float o, uint32 time, int8 seat) void SetTransportData(ObjectGuid guid, float x, float y, float z, float o, uint32 time, int8 seat)
{ {
t_guid = guid; t_guid = guid;
@ -707,7 +707,7 @@ class MovementInfo
t_seat = -1; t_seat = -1;
} }
ObjectGuid const& GetTransportGuid() const { return t_guid; } ObjectGuid const& GetTransportGuid() const { return t_guid; }
Position const *GetTransportPos() const { return &t_pos; } Position const* GetTransportPos() const { return &t_pos; }
int8 GetTransportSeat() const { return t_seat; } int8 GetTransportSeat() const { return t_seat; }
uint32 GetTransportTime() const { return t_time; } uint32 GetTransportTime() const { return t_time; }
uint32 GetFallTime() const { return fallTime; } uint32 GetFallTime() const { return fallTime; }
@ -756,7 +756,8 @@ inline ByteBuffer& operator>> (ByteBuffer& buf, MovementInfo& mi)
return buf; return buf;
} }
namespace Movement{ namespace Movement
{
class MoveSpline; class MoveSpline;
} }
@ -797,7 +798,7 @@ enum MeleeHitOutcome
struct CleanDamage struct CleanDamage
{ {
CleanDamage(uint32 _damage, WeaponAttackType _attackType, MeleeHitOutcome _hitOutCome) : CleanDamage(uint32 _damage, WeaponAttackType _attackType, MeleeHitOutcome _hitOutCome) :
damage(_damage), attackType(_attackType), hitOutCome(_hitOutCome) {} damage(_damage), attackType(_attackType), hitOutCome(_hitOutCome) {}
uint32 damage; uint32 damage;
WeaponAttackType attackType; WeaponAttackType attackType;
@ -808,8 +809,8 @@ struct CleanDamage
// Need create structure like in SMSG_ATTACKERSTATEUPDATE opcode // Need create structure like in SMSG_ATTACKERSTATEUPDATE opcode
struct CalcDamageInfo struct CalcDamageInfo
{ {
Unit *attacker; // Attacker Unit* attacker; // Attacker
Unit *target; // Target for damage Unit* target; // Target for damage
SpellSchoolMask damageSchoolMask; SpellSchoolMask damageSchoolMask;
uint32 damage; uint32 damage;
uint32 absorb; uint32 absorb;
@ -827,14 +828,15 @@ struct CalcDamageInfo
}; };
// Spell damage info structure based on structure sending in SMSG_SPELLNONMELEEDAMAGELOG opcode // Spell damage info structure based on structure sending in SMSG_SPELLNONMELEEDAMAGELOG opcode
struct SpellNonMeleeDamage{ struct SpellNonMeleeDamage
SpellNonMeleeDamage(Unit *_attacker, Unit *_target, uint32 _SpellID, SpellSchoolMask _schoolMask) {
SpellNonMeleeDamage(Unit* _attacker, Unit* _target, uint32 _SpellID, SpellSchoolMask _schoolMask)
: target(_target), attacker(_attacker), SpellID(_SpellID), damage(0), schoolMask(_schoolMask), : target(_target), attacker(_attacker), SpellID(_SpellID), damage(0), schoolMask(_schoolMask),
absorb(0), resist(0), physicalLog(false), unused(false), blocked(0), HitInfo(0) absorb(0), resist(0), physicalLog(false), unused(false), blocked(0), HitInfo(0)
{} {}
Unit *target; Unit* target;
Unit *attacker; Unit* attacker;
uint32 SpellID; uint32 SpellID;
uint32 damage; uint32 damage;
SpellSchoolMask schoolMask; SpellSchoolMask schoolMask;
@ -848,10 +850,10 @@ struct SpellNonMeleeDamage{
struct SpellPeriodicAuraLogInfo struct SpellPeriodicAuraLogInfo
{ {
SpellPeriodicAuraLogInfo(Aura *_aura, uint32 _damage, uint32 _overDamage, uint32 _absorb, uint32 _resist, float _multiplier, bool _critical = false) SpellPeriodicAuraLogInfo(Aura* _aura, uint32 _damage, uint32 _overDamage, uint32 _absorb, uint32 _resist, float _multiplier, bool _critical = false)
: aura(_aura), damage(_damage), overDamage(_overDamage), absorb(_absorb), resist(_resist), multiplier(_multiplier), critical(_critical) {} : aura(_aura), damage(_damage), overDamage(_overDamage), absorb(_absorb), resist(_resist), multiplier(_multiplier), critical(_critical) {}
Aura *aura; Aura* aura;
uint32 damage; uint32 damage;
uint32 overDamage; // overkill/overheal uint32 overDamage; // overkill/overheal
uint32 absorb; uint32 absorb;
@ -860,7 +862,7 @@ struct SpellPeriodicAuraLogInfo
bool critical; bool critical;
}; };
uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition); uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missCondition);
enum SpellAuraProcResult enum SpellAuraProcResult
{ {
@ -869,7 +871,7 @@ enum SpellAuraProcResult
SPELL_AURA_PROC_CANT_TRIGGER = 2 // aura can't trigger - skip charges taking, move to next aura if exists SPELL_AURA_PROC_CANT_TRIGGER = 2 // aura can't trigger - skip charges taking, move to next aura if exists
}; };
typedef SpellAuraProcResult(Unit::*pAuraProcHandler)(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); typedef SpellAuraProcResult(Unit::*pAuraProcHandler)(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
extern pAuraProcHandler AuraProcHandler[TOTAL_AURAS]; extern pAuraProcHandler AuraProcHandler[TOTAL_AURAS];
#define MAX_DECLINED_NAME_CASES 5 #define MAX_DECLINED_NAME_CASES 5
@ -1006,7 +1008,7 @@ struct CharmInfo
void InitPetActionBar(); void InitPetActionBar();
void InitEmptyActionBar(); void InitEmptyActionBar();
//return true if successful //return true if successful
bool AddSpellToActionBar(uint32 spellid, ActiveStates newstate = ACT_DECIDE); bool AddSpellToActionBar(uint32 spellid, ActiveStates newstate = ACT_DECIDE);
bool RemoveSpellFromActionBar(uint32 spell_id); bool RemoveSpellFromActionBar(uint32 spell_id);
void LoadPetActionBar(const std::string& data); void LoadPetActionBar(const std::string& data);
@ -1082,14 +1084,14 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
typedef std::multimap< uint32, SpellAuraHolder*> SpellAuraHolderMap; typedef std::multimap< uint32, SpellAuraHolder*> SpellAuraHolderMap;
typedef std::pair<SpellAuraHolderMap::iterator, SpellAuraHolderMap::iterator> SpellAuraHolderBounds; typedef std::pair<SpellAuraHolderMap::iterator, SpellAuraHolderMap::iterator> SpellAuraHolderBounds;
typedef std::pair<SpellAuraHolderMap::const_iterator, SpellAuraHolderMap::const_iterator> SpellAuraHolderConstBounds; typedef std::pair<SpellAuraHolderMap::const_iterator, SpellAuraHolderMap::const_iterator> SpellAuraHolderConstBounds;
typedef std::list<SpellAuraHolder *> SpellAuraHolderList; typedef std::list<SpellAuraHolder*> SpellAuraHolderList;
typedef std::list<Aura *> AuraList; typedef std::list<Aura*> AuraList;
typedef std::list<DiminishingReturn> Diminishing; typedef std::list<DiminishingReturn> Diminishing;
typedef std::set<uint32> ComboPointHolderSet; typedef std::set<uint32> ComboPointHolderSet;
typedef std::map<uint8, uint32> VisibleAuraMap; typedef std::map<uint8, uint32> VisibleAuraMap;
typedef std::map<SpellEntry const*, ObjectGuid> SingleCastSpellTargetMap; typedef std::map<SpellEntry const*, ObjectGuid> SingleCastSpellTargetMap;
virtual ~Unit ( ); virtual ~Unit();
void AddToWorld(); void AddToWorld();
void RemoveFromWorld(); void RemoveFromWorld();
@ -1103,7 +1105,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
DiminishingLevels GetDiminishing(DiminishingGroup group); DiminishingLevels GetDiminishing(DiminishingGroup group);
void IncrDiminishing(DiminishingGroup group); void IncrDiminishing(DiminishingGroup group);
void ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster, DiminishingLevels Level, int32 limitduration, bool isReflected); void ApplyDiminishingToDuration(DiminishingGroup group, int32& duration,Unit* caster, DiminishingLevels Level, int32 limitduration, bool isReflected);
void ApplyDiminishingAura(DiminishingGroup group, bool apply); void ApplyDiminishingAura(DiminishingGroup group, bool apply);
void ClearDiminishings() { m_Diminishing.clear(); } void ClearDiminishings() { m_Diminishing.clear(); }
@ -1120,7 +1122,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
if (IsInFeralForm()) if (IsInFeralForm())
return false; return false;
switch(attackType) switch (attackType)
{ {
default: default:
case BASE_ATTACK: case BASE_ATTACK:
@ -1134,17 +1136,17 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool CanReachWithMeleeAttack(Unit* pVictim, float flat_mod = 0.0f) const; bool CanReachWithMeleeAttack(Unit* pVictim, float flat_mod = 0.0f) const;
uint32 m_extraAttacks; uint32 m_extraAttacks;
void _addAttacker(Unit *pAttacker) // must be called only from Unit::Attack(Unit*) void _addAttacker(Unit* pAttacker) // must be called only from Unit::Attack(Unit*)
{ {
AttackerSet::const_iterator itr = m_attackers.find(pAttacker); AttackerSet::const_iterator itr = m_attackers.find(pAttacker);
if(itr == m_attackers.end()) if (itr == m_attackers.end())
m_attackers.insert(pAttacker); m_attackers.insert(pAttacker);
} }
void _removeAttacker(Unit *pAttacker) // must be called only from Unit::AttackStop() void _removeAttacker(Unit* pAttacker) // must be called only from Unit::AttackStop()
{ {
m_attackers.erase(pAttacker); m_attackers.erase(pAttacker);
} }
Unit * getAttackerForHelper() // If someone wants to help, who to give them Unit* getAttackerForHelper() // If someone wants to help, who to give them
{ {
if (getVictim() != NULL) if (getVictim() != NULL)
return getVictim(); return getVictim();
@ -1154,7 +1156,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
return NULL; return NULL;
} }
bool Attack(Unit *victim, bool meleeAttack); bool Attack(Unit* victim, bool meleeAttack);
void AttackedBy(Unit* attacker); void AttackedBy(Unit* attacker);
void CastStop(uint32 except_spellid = 0); void CastStop(uint32 except_spellid = 0);
bool AttackStop(bool targetSwitch = false); bool AttackStop(bool targetSwitch = false);
@ -1199,16 +1201,16 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
uint32 GetHealth() const { return GetUInt32Value(UNIT_FIELD_HEALTH); } uint32 GetHealth() const { return GetUInt32Value(UNIT_FIELD_HEALTH); }
uint32 GetMaxHealth() const { return GetUInt32Value(UNIT_FIELD_MAXHEALTH); } uint32 GetMaxHealth() const { return GetUInt32Value(UNIT_FIELD_MAXHEALTH); }
float GetHealthPercent() const { return (GetHealth()*100.0f) / GetMaxHealth(); } float GetHealthPercent() const { return (GetHealth()*100.0f) / GetMaxHealth(); }
void SetHealth( uint32 val); void SetHealth(uint32 val);
void SetMaxHealth(uint32 val); void SetMaxHealth(uint32 val);
void SetHealthPercent(float percent); void SetHealthPercent(float percent);
int32 ModifyHealth(int32 val); int32 ModifyHealth(int32 val);
Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); } Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); }
void setPowerType(Powers power); void setPowerType(Powers power);
uint32 GetPower( Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 +power); } uint32 GetPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 +power); }
uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1+power); } uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1+power); }
void SetPower( Powers power, uint32 val); void SetPower(Powers power, uint32 val);
void SetMaxPower(Powers power, uint32 val); void SetMaxPower(Powers power, uint32 val);
int32 ModifyPower(Powers power, int32 val); int32 ModifyPower(Powers power, int32 val);
void ApplyPowerMod(Powers power, uint32 val, bool apply); void ApplyPowerMod(Powers power, uint32 val, bool apply);
@ -1220,11 +1222,11 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
void ApplyCastTimePercentMod(float val, bool apply); void ApplyCastTimePercentMod(float val, bool apply);
SheathState GetSheath() const { return SheathState(GetByteValue(UNIT_FIELD_BYTES_2, 0)); } SheathState GetSheath() const { return SheathState(GetByteValue(UNIT_FIELD_BYTES_2, 0)); }
virtual void SetSheath( SheathState sheathed ) { SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); } virtual void SetSheath(SheathState sheathed) { SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); }
// faction template id // faction template id
uint32 getFaction() const { return GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE); } uint32 getFaction() const { return GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE); }
void setFaction(uint32 faction) { SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, faction ); } void setFaction(uint32 faction) { SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, faction); }
FactionTemplateEntry const* getFactionTemplateEntry() const; FactionTemplateEntry const* getFactionTemplateEntry() const;
bool IsHostileTo(Unit const* unit) const; bool IsHostileTo(Unit const* unit) const;
bool IsHostileToPlayers() const; bool IsHostileToPlayers() const;
@ -1232,7 +1234,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool IsNeutralToAll() const; bool IsNeutralToAll() const;
bool IsContestedGuard() const bool IsContestedGuard() const
{ {
if(FactionTemplateEntry const* entry = getFactionTemplateEntry()) if (FactionTemplateEntry const* entry = getFactionTemplateEntry())
return entry->IsContestedGuardFaction(); return entry->IsContestedGuardFaction();
return false; return false;
@ -1256,7 +1258,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
void SetStandFlags(uint8 flags) { SetByteFlag(UNIT_FIELD_BYTES_1, 2,flags); } void SetStandFlags(uint8 flags) { SetByteFlag(UNIT_FIELD_BYTES_1, 2,flags); }
void RemoveStandFlags(uint8 flags) { RemoveByteFlag(UNIT_FIELD_BYTES_1, 2,flags); } void RemoveStandFlags(uint8 flags) { RemoveByteFlag(UNIT_FIELD_BYTES_1, 2,flags); }
bool IsMounted() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT ); } bool IsMounted() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); }
uint32 GetMountID() const { return GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID); } uint32 GetMountID() const { return GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID); }
void Mount(uint32 mount, uint32 spellId = 0); void Mount(uint32 mount, uint32 spellId = 0);
void Unmount(bool from_aura = false); void Unmount(bool from_aura = false);
@ -1266,29 +1268,29 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
void SetVehicleId(uint32 entry); void SetVehicleId(uint32 entry);
uint16 GetMaxSkillValueForLevel(Unit const* target = NULL) const { return (target ? GetLevelForTarget(target) : getLevel()) * 5; } uint16 GetMaxSkillValueForLevel(Unit const* target = NULL) const { return (target ? GetLevelForTarget(target) : getLevel()) * 5; }
void DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb); void DealDamageMods(Unit* pVictim, uint32& damage, uint32* absorb);
uint32 DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss); uint32 DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const* spellProto, bool durabilityLoss);
int32 DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical = false, uint32 absorb = 0); int32 DealHeal(Unit* pVictim, uint32 addhealth, SpellEntry const* spellProto, bool critical = false, uint32 absorb = 0);
void PetOwnerKilledUnit(Unit* pVictim); void PetOwnerKilledUnit(Unit* pVictim);
void ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procEx, uint32 amount, WeaponAttackType attType = BASE_ATTACK, SpellEntry const *procSpell = NULL); void ProcDamageAndSpell(Unit* pVictim, uint32 procAttacker, uint32 procVictim, uint32 procEx, uint32 amount, WeaponAttackType attType = BASE_ATTACK, SpellEntry const* procSpell = NULL);
void ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage ); void ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const* procSpell, uint32 damage);
void HandleEmote(uint32 emote_id); // auto-select command/state void HandleEmote(uint32 emote_id); // auto-select command/state
void HandleEmoteCommand(uint32 emote_id); void HandleEmoteCommand(uint32 emote_id);
void HandleEmoteState(uint32 emote_id); void HandleEmoteState(uint32 emote_id);
void AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType = BASE_ATTACK, bool extra = false ); void AttackerStateUpdate(Unit* pVictim, WeaponAttackType attType = BASE_ATTACK, bool extra = false);
float MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const; float MeleeMissChanceCalc(const Unit* pVictim, WeaponAttackType attType) const;
void CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType = BASE_ATTACK); void CalculateMeleeDamage(Unit* pVictim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType = BASE_ATTACK);
void DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss); void DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss);
bool IsAllowedDamageInArea(Unit * pVictim) const; bool IsAllowedDamageInArea(Unit* pVictim) const;
void CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType = BASE_ATTACK); void CalculateSpellDamage(SpellNonMeleeDamage* damageInfo, int32 damage, SpellEntry const* spellInfo, WeaponAttackType attackType = BASE_ATTACK);
void DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss); void DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss);
// player or player's pet resilience (-1%) // player or player's pet resilience (-1%)
float GetMeleeCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_MELEE); } float GetMeleeCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_MELEE); }
@ -1305,15 +1307,15 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
uint32 GetRangedDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); } uint32 GetRangedDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); }
uint32 GetSpellDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); } uint32 GetSpellDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); }
float MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell); float MeleeSpellMissChance(Unit* pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const* spell);
SpellMissInfo MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell); SpellMissInfo MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell);
SpellMissInfo MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell); SpellMissInfo MagicSpellHitResult(Unit* pVictim, SpellEntry const* spell);
SpellMissInfo SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool canReflect = false); SpellMissInfo SpellHitResult(Unit* pVictim, SpellEntry const* spell, bool canReflect = false);
float GetUnitDodgeChance() const; float GetUnitDodgeChance() const;
float GetUnitParryChance() const; float GetUnitParryChance() const;
float GetUnitBlockChance() const; float GetUnitBlockChance() const;
float GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const; float GetUnitCriticalChance(WeaponAttackType attackType, const Unit* pVictim) const;
virtual uint32 GetShieldBlockValue() const =0; virtual uint32 GetShieldBlockValue() const =0;
uint32 GetUnitMeleeSkill(Unit const* target = NULL) const { return (target ? GetLevelForTarget(target) : getLevel()) * 5; } uint32 GetUnitMeleeSkill(Unit const* target = NULL) const { return (target ? GetLevelForTarget(target) : getLevel()) * 5; }
@ -1322,32 +1324,32 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
float GetWeaponProcChance() const; float GetWeaponProcChance() const;
float GetPPMProcChance(uint32 WeaponSpeed, float PPM) const; float GetPPMProcChance(uint32 WeaponSpeed, float PPM) const;
MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType) const; MeleeHitOutcome RollMeleeOutcomeAgainst(const Unit* pVictim, WeaponAttackType attType) const;
MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const; MeleeHitOutcome RollMeleeOutcomeAgainst(const Unit* pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const;
bool isVendor() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_VENDOR ); } bool isVendor() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_VENDOR); }
bool isTrainer() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TRAINER ); } bool isTrainer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TRAINER); }
bool isQuestGiver() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER ); } bool isQuestGiver() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); }
bool isGossip() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP ); } bool isGossip() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); }
bool isTaxi() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_FLIGHTMASTER ); } bool isTaxi() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_FLIGHTMASTER); }
bool isGuildMaster() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PETITIONER ); } bool isGuildMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PETITIONER); }
bool isBattleMaster() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BATTLEMASTER ); } bool isBattleMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BATTLEMASTER); }
bool isBanker() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BANKER ); } bool isBanker() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BANKER); }
bool isInnkeeper() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_INNKEEPER ); } bool isInnkeeper() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_INNKEEPER); }
bool isSpiritHealer() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER ); } bool isSpiritHealer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER); }
bool isSpiritGuide() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITGUIDE ); } bool isSpiritGuide() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITGUIDE); }
bool isTabardDesigner()const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TABARDDESIGNER ); } bool isTabardDesigner()const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TABARDDESIGNER); }
bool isAuctioner() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_AUCTIONEER ); } bool isAuctioner() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_AUCTIONEER); }
bool isArmorer() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_REPAIR ); } bool isArmorer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_REPAIR); }
bool isServiceProvider() const bool isServiceProvider() const
{ {
return HasFlag( UNIT_NPC_FLAGS, return HasFlag(UNIT_NPC_FLAGS,
UNIT_NPC_FLAG_VENDOR | UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_FLIGHTMASTER | UNIT_NPC_FLAG_VENDOR | UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_FLIGHTMASTER |
UNIT_NPC_FLAG_PETITIONER | UNIT_NPC_FLAG_BATTLEMASTER | UNIT_NPC_FLAG_BANKER | UNIT_NPC_FLAG_PETITIONER | UNIT_NPC_FLAG_BATTLEMASTER | UNIT_NPC_FLAG_BANKER |
UNIT_NPC_FLAG_INNKEEPER | UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_INNKEEPER | UNIT_NPC_FLAG_SPIRITHEALER |
UNIT_NPC_FLAG_SPIRITGUIDE | UNIT_NPC_FLAG_TABARDDESIGNER | UNIT_NPC_FLAG_AUCTIONEER ); UNIT_NPC_FLAG_SPIRITGUIDE | UNIT_NPC_FLAG_TABARDDESIGNER | UNIT_NPC_FLAG_AUCTIONEER);
} }
bool isSpiritService() const { return HasFlag( UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_SPIRITGUIDE ); } bool isSpiritService() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_SPIRITGUIDE); }
bool IsTaxiFlying() const { return hasUnitState(UNIT_STAT_TAXI_FLIGHT); } bool IsTaxiFlying() const { return hasUnitState(UNIT_STAT_TAXI_FLIGHT); }
@ -1384,7 +1386,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool IsPolymorphed() const; bool IsPolymorphed() const;
bool isFrozen() const; bool isFrozen() const;
bool IsIgnoreUnitState(SpellEntry const *spell, IgnoreUnitState ignoreState); bool IsIgnoreUnitState(SpellEntry const* spell, IgnoreUnitState ignoreState);
bool isTargetableForAttack(bool inversAlive = false) const; bool isTargetableForAttack(bool inversAlive = false) const;
bool isPassiveToHostile() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE); } bool isPassiveToHostile() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE); }
@ -1393,25 +1395,25 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
virtual bool IsUnderWater() const; virtual bool IsUnderWater() const;
bool isInAccessablePlaceFor(Creature const* c) const; bool isInAccessablePlaceFor(Creature const* c) const;
void SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical = false, uint32 absorb = 0); void SendHealSpellLog(Unit* pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical = false, uint32 absorb = 0);
void SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage,Powers powertype); void SendEnergizeSpellLog(Unit* pVictim, uint32 SpellID, uint32 Damage,Powers powertype);
void EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype); void EnergizeBySpell(Unit* pVictim, uint32 SpellID, uint32 Damage, Powers powertype);
uint32 SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage); uint32 SpellNonMeleeDamageLog(Unit* pVictim, uint32 spellID, uint32 damage);
void CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item* castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastSpell(Unit* Victim,SpellEntry const* spellInfo, bool triggered, Item* castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void CastCustomSpell(Unit* Victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastCustomSpell(Unit* Victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void CastCustomSpell(Unit* Victim,SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastCustomSpell(Unit* Victim,SpellEntry const* spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem= NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL); void CastSpell(float x, float y, float z, SpellEntry const* spellInfo, bool triggered, Item* castItem = NULL, Aura* triggeredByAura = NULL, ObjectGuid originalCaster = ObjectGuid(), SpellEntry const* triggeredBy = NULL);
void DeMorph(); void DeMorph();
void SendAttackStateUpdate(CalcDamageInfo *damageInfo); void SendAttackStateUpdate(CalcDamageInfo* damageInfo);
void SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount); void SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount);
void SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log); void SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log);
void SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit = false); void SendSpellNonMeleeDamageLog(Unit* target,uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit = false);
void SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo); void SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo);
void SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo); void SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo);
void NearTeleportTo(float x, float y, float z, float orientation, bool casting = false); void NearTeleportTo(float x, float y, float z, float orientation, bool casting = false);
void MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath = false, bool forceDestination = false); void MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath = false, bool forceDestination = false);
@ -1431,7 +1433,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
void SendThreatUpdate(); void SendThreatUpdate();
bool isAlive() const { return (m_deathState == ALIVE); }; bool isAlive() const { return (m_deathState == ALIVE); };
bool isDead() const { return ( m_deathState == DEAD || m_deathState == CORPSE ); }; bool isDead() const { return (m_deathState == DEAD || m_deathState == CORPSE); };
DeathState getDeathState() const { return m_deathState; }; DeathState getDeathState() const { return m_deathState; };
virtual void SetDeathState(DeathState s); // overwritten in Creature/Player/Pet virtual void SetDeathState(DeathState s); // overwritten in Creature/Player/Pet
@ -1476,7 +1478,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
Unit* GetCharmerOrOwner() const { return GetCharmerGuid() ? GetCharmer() : GetOwner(); } Unit* GetCharmerOrOwner() const { return GetCharmerGuid() ? GetCharmer() : GetOwner(); }
Unit* GetCharmerOrOwnerOrSelf() Unit* GetCharmerOrOwnerOrSelf()
{ {
if(Unit* u = GetCharmerOrOwner()) if (Unit* u = GetCharmerOrOwner())
return u; return u;
return this; return this;
@ -1484,7 +1486,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool IsCharmerOrOwnerPlayerOrPlayerItself() const; bool IsCharmerOrOwnerPlayerOrPlayerItself() const;
Player* GetCharmerOrOwnerPlayerOrPlayerItself(); Player* GetCharmerOrOwnerPlayerOrPlayerItself();
Player const* GetCharmerOrOwnerPlayerOrPlayerItself() const; Player const* GetCharmerOrOwnerPlayerOrPlayerItself() const;
float GetCombatDistance( const Unit* target ) const; float GetCombatDistance(const Unit* target) const;
void SetPet(Pet* pet); void SetPet(Pet* pet);
void SetCharm(Unit* pet); void SetCharm(Unit* pet);
@ -1512,21 +1514,21 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
template<typename Func> template<typename Func>
bool CheckAllControlledUnits(Func const& func, uint32 controlledMask) const; bool CheckAllControlledUnits(Func const& func, uint32 controlledMask) const;
bool AddSpellAuraHolder(SpellAuraHolder *holder); bool AddSpellAuraHolder(SpellAuraHolder* holder);
void AddAuraToModList(Aura *aura); void AddAuraToModList(Aura* aura);
// removing specific aura stack // removing specific aura stack
void RemoveAura(Aura* aura, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveAura(Aura* aura, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except = NULL); void RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except = NULL);
void RemoveSpellAuraHolder(SpellAuraHolder *holder, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveSpellAuraHolder(SpellAuraHolder* holder, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveSingleAuraFromSpellAuraHolder(SpellAuraHolder *holder, SpellEffectIndex index, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveSingleAuraFromSpellAuraHolder(SpellAuraHolder* holder, SpellEffectIndex index, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveSingleAuraFromSpellAuraHolder(uint32 id, SpellEffectIndex index, ObjectGuid casterGuid, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveSingleAuraFromSpellAuraHolder(uint32 id, SpellEffectIndex index, ObjectGuid casterGuid, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
// removing specific aura stacks by diff reasons and selections // removing specific aura stacks by diff reasons and selections
void RemoveAurasDueToSpell(uint32 spellId, SpellAuraHolder* except = NULL, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveAurasDueToSpell(uint32 spellId, SpellAuraHolder* except = NULL, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId); void RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId);
void RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid); void RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid);
void RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGuid, Unit *stealer); void RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGuid, Unit* stealer);
void RemoveAurasDueToSpellByCancel(uint32 spellId); void RemoveAurasDueToSpellByCancel(uint32 spellId);
// removing unknown aura stacks by diff reasons and selections // removing unknown aura stacks by diff reasons and selections
@ -1535,7 +1537,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
void RemoveSpellsCausingAura(AuraType auraType); void RemoveSpellsCausingAura(AuraType auraType);
void RemoveSpellsCausingAura(AuraType auraType, SpellAuraHolder* except); void RemoveSpellsCausingAura(AuraType auraType, SpellAuraHolder* except);
void RemoveRankAurasDueToSpell(uint32 spellId); void RemoveRankAurasDueToSpell(uint32 spellId);
bool RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder *holder); bool RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder);
void RemoveAurasWithInterruptFlags(uint32 flags); void RemoveAurasWithInterruptFlags(uint32 flags);
void RemoveAurasWithAttribute(uint32 flags); void RemoveAurasWithAttribute(uint32 flags);
void RemoveAurasWithDispelType(DispelType type, ObjectGuid casterGuid = ObjectGuid()); void RemoveAurasWithDispelType(DispelType type, ObjectGuid casterGuid = ObjectGuid());
@ -1545,18 +1547,18 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
// removing specific aura FROM stack by diff reasons and selections // removing specific aura FROM stack by diff reasons and selections
void RemoveAuraHolderFromStack(uint32 spellId, uint32 stackAmount = 1, ObjectGuid casterGuid = ObjectGuid(), AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveAuraHolderFromStack(uint32 spellId, uint32 stackAmount = 1, ObjectGuid casterGuid = ObjectGuid(), AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, Unit *dispeller); void RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, Unit* dispeller);
void DelaySpellAuraHolder(uint32 spellId, int32 delaytime, ObjectGuid casterGuid); void DelaySpellAuraHolder(uint32 spellId, int32 delaytime, ObjectGuid casterGuid);
float GetResistanceBuffMods(SpellSchools school, bool positive) const { return GetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school ); } float GetResistanceBuffMods(SpellSchools school, bool positive) const { return GetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school); }
void SetResistanceBuffMods(SpellSchools school, bool positive, float val) { SetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school,val); } void SetResistanceBuffMods(SpellSchools school, bool positive, float val) { SetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school,val); }
void ApplyResistanceBuffModsMod(SpellSchools school, bool positive, float val, bool apply) { ApplyModSignedFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); } void ApplyResistanceBuffModsMod(SpellSchools school, bool positive, float val, bool apply) { ApplyModSignedFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); }
void ApplyResistanceBuffModsPercentMod(SpellSchools school, bool positive, float val, bool apply) { ApplyPercentModFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); } void ApplyResistanceBuffModsPercentMod(SpellSchools school, bool positive, float val, bool apply) { ApplyPercentModFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); }
void InitStatBuffMods() void InitStatBuffMods()
{ {
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_POSSTAT0+i, 0); for (int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_POSSTAT0+i, 0);
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_NEGSTAT0+i, 0); for (int i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_NEGSTAT0+i, 0);
} }
void ApplyStatBuffMod(Stats stat, float val, bool apply) { ApplyModSignedFloatValue((val > 0 ? UNIT_FIELD_POSSTAT0+stat : UNIT_FIELD_NEGSTAT0+stat), val, apply); } void ApplyStatBuffMod(Stats stat, float val, bool apply) { ApplyModSignedFloatValue((val > 0 ? UNIT_FIELD_POSSTAT0+stat : UNIT_FIELD_NEGSTAT0+stat), val, apply); }
void ApplyStatPercentBuffMod(Stats stat, float val, bool apply) void ApplyStatPercentBuffMod(Stats stat, float val, bool apply)
@ -1574,8 +1576,8 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
float GetNegStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_NEGSTAT0+stat); } float GetNegStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_NEGSTAT0+stat); }
float GetCreateStat(Stats stat) const { return m_createStats[stat]; } float GetCreateStat(Stats stat) const { return m_createStats[stat]; }
void SetCurrentCastedSpell(Spell * pSpell); void SetCurrentCastedSpell(Spell* pSpell);
virtual void ProhibitSpellSchool(SpellSchoolMask /*idSchoolMask*/, uint32 /*unTimeMs*/ ) { } virtual void ProhibitSpellSchool(SpellSchoolMask /*idSchoolMask*/, uint32 /*unTimeMs*/) { }
void InterruptSpell(CurrentSpellTypes spellType, bool withDelayed = true, bool sendAutoRepeatCancelToClient = true); void InterruptSpell(CurrentSpellTypes spellType, bool withDelayed = true, bool sendAutoRepeatCancelToClient = true);
void FinishSpell(CurrentSpellTypes spellType, bool ok = true); void FinishSpell(CurrentSpellTypes spellType, bool ok = true);
@ -1611,7 +1613,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
{ {
ShapeshiftForm form = GetShapeshiftForm(); ShapeshiftForm form = GetShapeshiftForm();
return form != FORM_NONE && form != FORM_BATTLESTANCE && form != FORM_BERSERKERSTANCE && form != FORM_DEFENSIVESTANCE && return form != FORM_NONE && form != FORM_BATTLESTANCE && form != FORM_BERSERKERSTANCE && form != FORM_DEFENSIVESTANCE &&
form != FORM_SHADOW; form != FORM_SHADOW;
} }
float m_modMeleeHitChance; float m_modMeleeHitChance;
@ -1664,35 +1666,35 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
virtual bool IsVisibleInGridForPlayer(Player* pl) const = 0; virtual bool IsVisibleInGridForPlayer(Player* pl) const = 0;
bool isInvisibleForAlive() const; bool isInvisibleForAlive() const;
SingleCastSpellTargetMap & GetSingleCastSpellTargets() { return m_singleCastSpellTargets; } SingleCastSpellTargetMap& GetSingleCastSpellTargets() { return m_singleCastSpellTargets; }
SingleCastSpellTargetMap const& GetSingleCastSpellTargets() const { return m_singleCastSpellTargets; } SingleCastSpellTargetMap const& GetSingleCastSpellTargets() const { return m_singleCastSpellTargets; }
SpellImmuneList m_spellImmune[MAX_SPELL_IMMUNITY]; SpellImmuneList m_spellImmune[MAX_SPELL_IMMUNITY];
// Threat related methods // Threat related methods
bool CanHaveThreatList() const; bool CanHaveThreatList() const;
void AddThreat(Unit* pVictim, float threat = 0.0f, bool crit = false, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NONE, SpellEntry const *threatSpell = NULL); void AddThreat(Unit* pVictim, float threat = 0.0f, bool crit = false, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NONE, SpellEntry const* threatSpell = NULL);
float ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); float ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL);
void DeleteThreatList(); void DeleteThreatList();
bool IsSecondChoiceTarget(Unit* pTarget, bool checkThreatArea) const; bool IsSecondChoiceTarget(Unit* pTarget, bool checkThreatArea) const;
bool SelectHostileTarget(); bool SelectHostileTarget();
void TauntApply(Unit* pVictim); void TauntApply(Unit* pVictim);
void TauntFadeOut(Unit *taunter); void TauntFadeOut(Unit* taunter);
ThreatManager& getThreatManager() { return m_ThreatManager; } ThreatManager& getThreatManager() { return m_ThreatManager; }
ThreatManager const& getThreatManager() const { return m_ThreatManager; } ThreatManager const& getThreatManager() const { return m_ThreatManager; }
void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); }; void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); };
void removeHatedBy(HostileReference* /*pHostileReference*/ ) { /* nothing to do yet */ } void removeHatedBy(HostileReference* /*pHostileReference*/) { /* nothing to do yet */ }
HostileRefManager& getHostileRefManager() { return m_HostileRefManager; } HostileRefManager& getHostileRefManager() { return m_HostileRefManager; }
uint32 GetVisibleAura(uint8 slot) const uint32 GetVisibleAura(uint8 slot) const
{ {
VisibleAuraMap::const_iterator itr = m_visibleAuras.find(slot); VisibleAuraMap::const_iterator itr = m_visibleAuras.find(slot);
if(itr != m_visibleAuras.end()) if (itr != m_visibleAuras.end())
return itr->second; return itr->second;
return 0; return 0;
} }
void SetVisibleAura(uint8 slot, uint32 spellid) void SetVisibleAura(uint8 slot, uint32 spellid)
{ {
if(spellid == 0) if (spellid == 0)
m_visibleAuras.erase(slot); m_visibleAuras.erase(slot);
else else
m_visibleAuras[slot] = spellid; m_visibleAuras[slot] = spellid;
@ -1702,10 +1704,10 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
Aura* GetAura(uint32 spellId, SpellEffectIndex effindex); Aura* GetAura(uint32 spellId, SpellEffectIndex effindex);
Aura* GetAura(AuraType type, SpellFamily family, uint64 familyFlag, uint32 familyFlag2 = 0, ObjectGuid casterGuid = ObjectGuid()); Aura* GetAura(AuraType type, SpellFamily family, uint64 familyFlag, uint32 familyFlag2 = 0, ObjectGuid casterGuid = ObjectGuid());
SpellAuraHolder* GetSpellAuraHolder (uint32 spellid) const; SpellAuraHolder* GetSpellAuraHolder(uint32 spellid) const;
SpellAuraHolder* GetSpellAuraHolder (uint32 spellid, ObjectGuid casterGUID) const; SpellAuraHolder* GetSpellAuraHolder(uint32 spellid, ObjectGuid casterGUID) const;
SpellAuraHolderMap & GetSpellAuraHolderMap() { return m_spellAuraHolders; } SpellAuraHolderMap& GetSpellAuraHolderMap() { return m_spellAuraHolders; }
SpellAuraHolderMap const& GetSpellAuraHolderMap() const { return m_spellAuraHolders; } SpellAuraHolderMap const& GetSpellAuraHolderMap() const { return m_spellAuraHolders; }
AuraList const& GetAurasByType(AuraType type) const { return m_modAuras[type]; } AuraList const& GetAurasByType(AuraType type) const { return m_modAuras[type]; }
void ApplyAuraProcTriggerDamage(Aura* aura, bool apply); void ApplyAuraProcTriggerDamage(Aura* aura, bool apply);
@ -1762,47 +1764,47 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool HasAuraState(AuraState flag) const { return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)); } bool HasAuraState(AuraState flag) const { return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)); }
bool HasAuraStateForCaster(AuraState flag, ObjectGuid casterGuid) const; bool HasAuraStateForCaster(AuraState flag, ObjectGuid casterGuid) const;
void UnsummonAllTotems(); void UnsummonAllTotems();
Unit* SelectMagnetTarget(Unit *victim, Spell* spell = NULL, SpellEffectIndex eff = EFFECT_INDEX_0); Unit* SelectMagnetTarget(Unit* victim, Spell* spell = NULL, SpellEffectIndex eff = EFFECT_INDEX_0);
int32 SpellBonusWithCoeffs(SpellEntry const *spellProto, int32 total, int32 benefit, int32 ap_benefit, DamageEffectType damagetype, bool donePart, float defCoeffMod = 1.0f); int32 SpellBonusWithCoeffs(SpellEntry const* spellProto, int32 total, int32 benefit, int32 ap_benefit, DamageEffectType damagetype, bool donePart, float defCoeffMod = 1.0f);
int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask); int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask);
int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask); int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask);
uint32 SpellDamageBonusDone(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1); uint32 SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1);
uint32 SpellDamageBonusTaken(Unit *pCaster, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1); uint32 SpellDamageBonusTaken(Unit* pCaster, SpellEntry const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1);
int32 SpellBaseHealingBonusDone(SpellSchoolMask schoolMask); int32 SpellBaseHealingBonusDone(SpellSchoolMask schoolMask);
int32 SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask); int32 SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask);
uint32 SpellHealingBonusDone(Unit *pVictim, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack = 1); uint32 SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack = 1);
uint32 SpellHealingBonusTaken(Unit *pCaster, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack = 1); uint32 SpellHealingBonusTaken(Unit* pCaster, SpellEntry const* spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack = 1);
uint32 MeleeDamageBonusDone(Unit *pVictim, uint32 damage, WeaponAttackType attType, SpellEntry const *spellProto = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, uint32 stack = 1); uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellEntry const* spellProto = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, uint32 stack = 1);
uint32 MeleeDamageBonusTaken(Unit *pCaster, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, uint32 stack = 1); uint32 MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage,WeaponAttackType attType, SpellEntry const* spellProto = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, uint32 stack = 1);
bool IsSpellBlocked(Unit *pCaster, SpellEntry const *spellProto, WeaponAttackType attackType = BASE_ATTACK); bool IsSpellBlocked(Unit* pCaster, SpellEntry const* spellProto, WeaponAttackType attackType = BASE_ATTACK);
bool IsSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType = BASE_ATTACK); bool IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType = BASE_ATTACK);
uint32 SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim); uint32 SpellCriticalDamageBonus(SpellEntry const* spellProto, uint32 damage, Unit* pVictim);
uint32 SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim); uint32 SpellCriticalHealingBonus(SpellEntry const* spellProto, uint32 damage, Unit* pVictim);
bool IsTriggeredAtSpellProcEvent(Unit *pVictim, SpellAuraHolder* holder, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const*& spellProcEvent ); bool IsTriggeredAtSpellProcEvent(Unit* pVictim, SpellAuraHolder* holder, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const*& spellProcEvent);
// Aura proc handlers // Aura proc handlers
SpellAuraProcResult HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleHasteAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleSpellCritChanceAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleProcTriggerSpellAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleProcTriggerDamageAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleProcTriggerDamageAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleOverrideClassScriptAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleMendingAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleMendingAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModCastingSpeedNotStackAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModCastingSpeedNotStackAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleReflectSpellsSchoolAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleReflectSpellsSchoolAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModPowerCostSchoolAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModPowerCostSchoolAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleMechanicImmuneResistanceAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleMechanicImmuneResistanceAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModDamageFromCasterAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModDamageFromCasterAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleAddFlatModifierAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleAddFlatModifierAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleAddPctModifierAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleAddPctModifierAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModDamagePercentDoneAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModDamagePercentDoneAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModRating(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModRating(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleSpellMagnetAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleSpellMagnetAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleManaShieldAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleManaShieldAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleModResistanceAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleModResistanceAuraProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleRemoveByDamageChanceProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); SpellAuraProcResult HandleRemoveByDamageChanceProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
SpellAuraProcResult HandleNULLProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* /*triggeredByAura*/, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) SpellAuraProcResult HandleNULLProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* /*triggeredByAura*/, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{ {
// no proc handler for this aura type // no proc handler for this aura type
@ -1825,24 +1827,24 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
uint32 GetRegenTimer() const { return m_regenTimer; } uint32 GetRegenTimer() const { return m_regenTimer; }
void SetContestedPvP(Player *attackedPlayer = NULL); void SetContestedPvP(Player* attackedPlayer = NULL);
void ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply); void ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply);
void ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply); void ApplySpellDispelImmunity(const SpellEntry* spellProto, DispelType type, bool apply);
virtual bool IsImmuneToSpell(SpellEntry const* spellInfo); virtual bool IsImmuneToSpell(SpellEntry const* spellInfo);
// redefined in Creature // redefined in Creature
bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask); bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask);
virtual bool IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const; virtual bool IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const;
// redefined in Creature // redefined in Creature
uint32 CalcArmorReducedDamage(Unit* pVictim, const uint32 damage); uint32 CalcArmorReducedDamage(Unit* pVictim, const uint32 damage);
void CalculateDamageAbsorbAndResist(Unit *pCaster, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, bool canReflect = false); void CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32* absorb, uint32* resist, bool canReflect = false);
void CalculateAbsorbResistBlock(Unit *pCaster, SpellNonMeleeDamage *damageInfo, SpellEntry const* spellProto, WeaponAttackType attType = BASE_ATTACK); void CalculateAbsorbResistBlock(Unit* pCaster, SpellNonMeleeDamage* damageInfo, SpellEntry const* spellProto, WeaponAttackType attType = BASE_ATTACK);
void CalculateHealAbsorb(uint32 heal, uint32 *absorb); void CalculateHealAbsorb(uint32 heal, uint32* absorb);
void UpdateSpeed(UnitMoveType mtype, bool forced, float ratio = 1.0f); void UpdateSpeed(UnitMoveType mtype, bool forced, float ratio = 1.0f);
float GetSpeed( UnitMoveType mtype ) const; float GetSpeed(UnitMoveType mtype) const;
float GetSpeedRate( UnitMoveType mtype ) const { return m_speed_rate[mtype]; } float GetSpeedRate(UnitMoveType mtype) const { return m_speed_rate[mtype]; }
void SetSpeedRate(UnitMoveType mtype, float rate, bool forced = false); void SetSpeedRate(UnitMoveType mtype, float rate, bool forced = false);
void KnockBackFrom(Unit* target, float horizontalSpeed, float verticalSpeed); void KnockBackFrom(Unit* target, float horizontalSpeed, float verticalSpeed);
@ -1852,14 +1854,14 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
int32 CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 const* basePoints = NULL); int32 CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 const* basePoints = NULL);
uint32 CalcNotIgnoreAbsorbDamage( uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo = NULL); uint32 CalcNotIgnoreAbsorbDamage(uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo = NULL);
uint32 CalcNotIgnoreDamageReduction(uint32 damage, SpellSchoolMask damageSchoolMask); uint32 CalcNotIgnoreDamageReduction(uint32 damage, SpellSchoolMask damageSchoolMask);
int32 CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMask, int32 duration, Unit const* caster); int32 CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMask, int32 duration, Unit const* caster);
float CalculateLevelPenalty(SpellEntry const* spellProto) const; float CalculateLevelPenalty(SpellEntry const* spellProto) const;
void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); } void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); }
void removeFollower(FollowerReference* /*pRef*/ ) { /* nothing to do yet */ } void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ }
MotionMaster* GetMotionMaster() { return &i_motionMaster; } MotionMaster* GetMotionMaster() { return &i_motionMaster; }
@ -1876,8 +1878,8 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
///----------Pet responses methods----------------- ///----------Pet responses methods-----------------
void SendPetCastFail(uint32 spellid, SpellCastResult msg); void SendPetCastFail(uint32 spellid, SpellCastResult msg);
void SendPetActionFeedback (uint8 msg); void SendPetActionFeedback(uint8 msg);
void SendPetTalk (uint32 pettalk); void SendPetTalk(uint32 pettalk);
void SendPetAIReaction(); void SendPetAIReaction();
///----------End of Pet responses methods---------- ///----------End of Pet responses methods----------
@ -1885,7 +1887,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
// reactive attacks // reactive attacks
void ClearAllReactives(); void ClearAllReactives();
void StartReactiveTimer( ReactiveType reactive ) { m_reactiveTimer[reactive] = REACTIVE_TIMER_START;} void StartReactiveTimer(ReactiveType reactive) { m_reactiveTimer[reactive] = REACTIVE_TIMER_START;}
void UpdateReactives(uint32 p_time); void UpdateReactives(uint32 p_time);
// group updates // group updates
@ -1899,7 +1901,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
// Movement info // Movement info
MovementInfo m_movementInfo; MovementInfo m_movementInfo;
Movement::MoveSpline * movespline; Movement::MoveSpline* movespline;
void ScheduleAINotify(uint32 delay); void ScheduleAINotify(uint32 delay);
bool IsAINotifyScheduled() const { return m_AINotifyScheduled;} bool IsAINotifyScheduled() const { return m_AINotifyScheduled;}
@ -1909,7 +1911,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
bool IsLinkingEventTrigger() const { return m_isCreatureLinkingTrigger; } bool IsLinkingEventTrigger() const { return m_isCreatureLinkingTrigger; }
protected: protected:
explicit Unit (); explicit Unit();
void _UpdateSpells(uint32 time); void _UpdateSpells(uint32 time);
void _UpdateAutoRepeatSpell(); void _UpdateAutoRepeatSpell();
@ -1948,7 +1950,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject
float m_speed_rate[MAX_MOVE_TYPE]; float m_speed_rate[MAX_MOVE_TYPE];
CharmInfo *m_charmInfo; CharmInfo* m_charmInfo;
virtual SpellSchoolMask GetMeleeDamageSchoolMask() const; virtual SpellSchoolMask GetMeleeDamageSchoolMask() const;
@ -2039,7 +2041,7 @@ void Unit::CallForAllControlledUnits(Func const& func, uint32 controlledMask)
if (controlledMask & CONTROLLED_TOTEMS) if (controlledMask & CONTROLLED_TOTEMS)
{ {
for (int i = 0; i < MAX_TOTEM_SLOT; ++i) for (int i = 0; i < MAX_TOTEM_SLOT; ++i)
if (Unit *totem = _GetTotem(TotemSlot(i))) if (Unit* totem = _GetTotem(TotemSlot(i)))
func(totem); func(totem);
} }
@ -2058,7 +2060,7 @@ bool Unit::CheckAllControlledUnits(Func const& func, uint32 controlledMask) cons
return true; return true;
if (controlledMask & CONTROLLED_MINIPET) if (controlledMask & CONTROLLED_MINIPET)
if(Unit const* mini = GetMiniPet()) if (Unit const* mini = GetMiniPet())
if (func(mini)) if (func(mini))
return true; return true;

File diff suppressed because it is too large Load diff

View file

@ -35,18 +35,18 @@ void UpdateData::AddOutOfRangeGUID(GuidSet& guids)
m_outOfRangeGUIDs.insert(guids.begin(),guids.end()); m_outOfRangeGUIDs.insert(guids.begin(),guids.end());
} }
void UpdateData::AddOutOfRangeGUID(ObjectGuid const &guid) void UpdateData::AddOutOfRangeGUID(ObjectGuid const& guid)
{ {
m_outOfRangeGUIDs.insert(guid); m_outOfRangeGUIDs.insert(guid);
} }
void UpdateData::AddUpdateBlock(const ByteBuffer &block) void UpdateData::AddUpdateBlock(const ByteBuffer& block)
{ {
m_data.append(block); m_data.append(block);
++m_blockCount; ++m_blockCount;
} }
void UpdateData::Compress(void* dst, uint32 *dst_size, void* src, int src_size) void UpdateData::Compress(void* dst, uint32* dst_size, void* src, int src_size)
{ {
z_stream c_stream; z_stream c_stream;
@ -102,20 +102,20 @@ void UpdateData::Compress(void* dst, uint32 *dst_size, void* src, int src_size)
*dst_size = c_stream.total_out; *dst_size = c_stream.total_out;
} }
bool UpdateData::BuildPacket(WorldPacket *packet) bool UpdateData::BuildPacket(WorldPacket* packet)
{ {
MANGOS_ASSERT(packet->empty()); // shouldn't happen MANGOS_ASSERT(packet->empty()); // shouldn't happen
ByteBuffer buf(4 + (m_outOfRangeGUIDs.empty() ? 0 : 1 + 4 + 9 * m_outOfRangeGUIDs.size()) + m_data.wpos()); ByteBuffer buf(4 + (m_outOfRangeGUIDs.empty() ? 0 : 1 + 4 + 9 * m_outOfRangeGUIDs.size()) + m_data.wpos());
buf << (uint32) (!m_outOfRangeGUIDs.empty() ? m_blockCount + 1 : m_blockCount); buf << (uint32)(!m_outOfRangeGUIDs.empty() ? m_blockCount + 1 : m_blockCount);
if(!m_outOfRangeGUIDs.empty()) if (!m_outOfRangeGUIDs.empty())
{ {
buf << (uint8) UPDATETYPE_OUT_OF_RANGE_OBJECTS; buf << (uint8) UPDATETYPE_OUT_OF_RANGE_OBJECTS;
buf << (uint32) m_outOfRangeGUIDs.size(); buf << (uint32) m_outOfRangeGUIDs.size();
for(GuidSet::const_iterator i = m_outOfRangeGUIDs.begin(); i != m_outOfRangeGUIDs.end(); ++i) for (GuidSet::const_iterator i = m_outOfRangeGUIDs.begin(); i != m_outOfRangeGUIDs.end(); ++i)
buf << i->WriteAsPacked(); buf << i->WriteAsPacked();
} }
@ -123,23 +123,23 @@ bool UpdateData::BuildPacket(WorldPacket *packet)
size_t pSize = buf.wpos(); // use real used data size size_t pSize = buf.wpos(); // use real used data size
if (pSize > 100 ) // compress large packets if (pSize > 100) // compress large packets
{ {
uint32 destsize = compressBound(pSize); uint32 destsize = compressBound(pSize);
packet->resize( destsize + sizeof(uint32) ); packet->resize(destsize + sizeof(uint32));
packet->put<uint32>(0, pSize); packet->put<uint32>(0, pSize);
Compress(const_cast<uint8*>(packet->contents()) + sizeof(uint32), &destsize, (void*)buf.contents(), pSize); Compress(const_cast<uint8*>(packet->contents()) + sizeof(uint32), &destsize, (void*)buf.contents(), pSize);
if (destsize == 0) if (destsize == 0)
return false; return false;
packet->resize( destsize + sizeof(uint32) ); packet->resize(destsize + sizeof(uint32));
packet->SetOpcode( SMSG_COMPRESSED_UPDATE_OBJECT ); packet->SetOpcode(SMSG_COMPRESSED_UPDATE_OBJECT);
} }
else // send small packets without compression else // send small packets without compression
{ {
packet->append( buf ); packet->append(buf);
packet->SetOpcode( SMSG_UPDATE_OBJECT ); packet->SetOpcode(SMSG_UPDATE_OBJECT);
} }
return true; return true;

View file

@ -55,9 +55,9 @@ class UpdateData
UpdateData(); UpdateData();
void AddOutOfRangeGUID(GuidSet& guids); void AddOutOfRangeGUID(GuidSet& guids);
void AddOutOfRangeGUID(ObjectGuid const &guid); void AddOutOfRangeGUID(ObjectGuid const& guid);
void AddUpdateBlock(const ByteBuffer &block); void AddUpdateBlock(const ByteBuffer& block);
bool BuildPacket(WorldPacket *packet); bool BuildPacket(WorldPacket* packet);
bool HasData() { return m_blockCount > 0 || !m_outOfRangeGUIDs.empty(); } bool HasData() { return m_blockCount > 0 || !m_outOfRangeGUIDs.empty(); }
void Clear(); void Clear();
@ -68,6 +68,6 @@ class UpdateData
GuidSet m_outOfRangeGUIDs; GuidSet m_outOfRangeGUIDs;
ByteBuffer m_data; ByteBuffer m_data;
void Compress(void* dst, uint32 *dst_size, void* src, int src_size); void Compress(void* dst, uint32* dst_size, void* src, int src_size);
}; };
#endif #endif

View file

@ -25,28 +25,28 @@
class UpdateMask class UpdateMask
{ {
public: public:
UpdateMask( ) : mCount( 0 ), mBlocks( 0 ), mUpdateMask( 0 ) { } UpdateMask() : mCount(0), mBlocks(0), mUpdateMask(0) { }
UpdateMask( const UpdateMask& mask ) : mUpdateMask( 0 ) { *this = mask; } UpdateMask(const UpdateMask& mask) : mUpdateMask(0) { *this = mask; }
~UpdateMask( ) ~UpdateMask()
{ {
if(mUpdateMask) if (mUpdateMask)
delete [] mUpdateMask; delete [] mUpdateMask;
} }
void SetBit (uint32 index) void SetBit(uint32 index)
{ {
( (uint8 *)mUpdateMask )[ index >> 3 ] |= 1 << ( index & 0x7 ); ((uint8*)mUpdateMask)[ index >> 3 ] |= 1 << (index & 0x7);
} }
void UnsetBit (uint32 index) void UnsetBit(uint32 index)
{ {
( (uint8 *)mUpdateMask )[ index >> 3 ] &= (0xff ^ (1 << ( index & 0x7 ) ) ); ((uint8*)mUpdateMask)[ index >> 3 ] &= (0xff ^ (1 << (index & 0x7)));
} }
bool GetBit (uint32 index) const bool GetBit(uint32 index) const
{ {
return ( ( (uint8 *)mUpdateMask)[ index >> 3 ] & ( 1 << ( index & 0x7 ) )) != 0; return (((uint8*)mUpdateMask)[ index >> 3 ] & (1 << (index & 0x7))) != 0;
} }
uint32 GetBlockCount() const { return mBlocks; } uint32 GetBlockCount() const { return mBlocks; }
@ -54,9 +54,9 @@ class UpdateMask
uint32 GetCount() const { return mCount; } uint32 GetCount() const { return mCount; }
uint8* GetMask() { return (uint8*)mUpdateMask; } uint8* GetMask() { return (uint8*)mUpdateMask; }
void SetCount (uint32 valuesCount) void SetCount(uint32 valuesCount)
{ {
if(mUpdateMask) if (mUpdateMask)
delete [] mUpdateMask; delete [] mUpdateMask;
mCount = valuesCount; mCount = valuesCount;
@ -72,7 +72,7 @@ class UpdateMask
memset(mUpdateMask, 0, mBlocks << 2); memset(mUpdateMask, 0, mBlocks << 2);
} }
UpdateMask& operator = ( const UpdateMask& mask ) UpdateMask& operator = (const UpdateMask& mask)
{ {
SetCount(mask.mCount); SetCount(mask.mCount);
memcpy(mUpdateMask, mask.mUpdateMask, mBlocks << 2); memcpy(mUpdateMask, mask.mUpdateMask, mBlocks << 2);
@ -80,21 +80,21 @@ class UpdateMask
return *this; return *this;
} }
void operator &= ( const UpdateMask& mask ) void operator &= (const UpdateMask& mask)
{ {
MANGOS_ASSERT(mask.mCount <= mCount); MANGOS_ASSERT(mask.mCount <= mCount);
for (uint32 i = 0; i < mBlocks; ++i) for (uint32 i = 0; i < mBlocks; ++i)
mUpdateMask[i] &= mask.mUpdateMask[i]; mUpdateMask[i] &= mask.mUpdateMask[i];
} }
void operator |= ( const UpdateMask& mask ) void operator |= (const UpdateMask& mask)
{ {
MANGOS_ASSERT(mask.mCount <= mCount); MANGOS_ASSERT(mask.mCount <= mCount);
for (uint32 i = 0; i < mBlocks; ++i) for (uint32 i = 0; i < mBlocks; ++i)
mUpdateMask[i] |= mask.mUpdateMask[i]; mUpdateMask[i] |= mask.mUpdateMask[i];
} }
UpdateMask operator & ( const UpdateMask& mask ) const UpdateMask operator & (const UpdateMask& mask) const
{ {
MANGOS_ASSERT(mask.mCount <= mCount); MANGOS_ASSERT(mask.mCount <= mCount);
@ -105,7 +105,7 @@ class UpdateMask
return newmask; return newmask;
} }
UpdateMask operator | ( const UpdateMask& mask ) const UpdateMask operator | (const UpdateMask& mask) const
{ {
MANGOS_ASSERT(mask.mCount <= mCount); MANGOS_ASSERT(mask.mCount <= mCount);
@ -119,6 +119,6 @@ class UpdateMask
private: private:
uint32 mCount; uint32 mCount;
uint32 mBlocks; uint32 mBlocks;
uint32 *mUpdateMask; uint32* mUpdateMask;
}; };
#endif #endif

View file

@ -22,7 +22,7 @@
#include "Opcodes.h" #include "Opcodes.h"
#include "Log.h" #include "Log.h"
void WorldSession::HandleVoiceSessionEnableOpcode( WorldPacket & recv_data ) void WorldSession::HandleVoiceSessionEnableOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG("WORLD: CMSG_VOICE_SESSION_ENABLE"); DEBUG_LOG("WORLD: CMSG_VOICE_SESSION_ENABLE");
// uint8 isVoiceEnabled, uint8 isMicrophoneEnabled // uint8 isVoiceEnabled, uint8 isMicrophoneEnabled
@ -31,14 +31,14 @@ void WorldSession::HandleVoiceSessionEnableOpcode( WorldPacket & recv_data )
recv_data.hexlike(); recv_data.hexlike();
} }
void WorldSession::HandleChannelVoiceOnOpcode( WorldPacket & recv_data ) void WorldSession::HandleChannelVoiceOnOpcode(WorldPacket& recv_data)
{ {
DEBUG_LOG("WORLD: CMSG_CHANNEL_VOICE_ON"); DEBUG_LOG("WORLD: CMSG_CHANNEL_VOICE_ON");
// Enable Voice button in channel context menu // Enable Voice button in channel context menu
recv_data.hexlike(); recv_data.hexlike();
} }
void WorldSession::HandleSetActiveVoiceChannel( WorldPacket & recv_data ) void WorldSession::HandleSetActiveVoiceChannel(WorldPacket& recv_data)
{ {
DEBUG_LOG("WORLD: CMSG_SET_ACTIVE_VOICE_CHANNEL"); DEBUG_LOG("WORLD: CMSG_SET_ACTIVE_VOICE_CHANNEL");
recv_data.read_skip<uint32>(); recv_data.read_skip<uint32>();

View file

@ -32,20 +32,20 @@ bool WaypointBehavior::isEmpty()
if (emote || spell || model1 || model2) if (emote || spell || model1 || model2)
return false; return false;
for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i) for (int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
if(textid[i]) if (textid[i])
return false; return false;
return true; return true;
} }
WaypointBehavior::WaypointBehavior(const WaypointBehavior &b) WaypointBehavior::WaypointBehavior(const WaypointBehavior& b)
{ {
emote = b.emote; emote = b.emote;
spell = b.spell; spell = b.spell;
model1 = b.model1; model1 = b.model1;
model2 = b.model2; model2 = b.model2;
for(int i=0; i < MAX_WAYPOINT_TEXT; ++i) for (int i=0; i < MAX_WAYPOINT_TEXT; ++i)
textid[i] = b.textid[i]; textid[i] = b.textid[i];
} }
@ -59,18 +59,18 @@ void WaypointManager::Load()
std::set<uint32> movementScriptSet; std::set<uint32> movementScriptSet;
for(ScriptMapMap::const_iterator itr = sCreatureMovementScripts.second.begin(); itr != sCreatureMovementScripts.second.end(); ++itr) for (ScriptMapMap::const_iterator itr = sCreatureMovementScripts.second.begin(); itr != sCreatureMovementScripts.second.end(); ++itr)
movementScriptSet.insert(itr->first); movementScriptSet.insert(itr->first);
// creature_movement // creature_movement
QueryResult *result = WorldDatabase.Query("SELECT id, COUNT(point) FROM creature_movement GROUP BY id"); QueryResult* result = WorldDatabase.Query("SELECT id, COUNT(point) FROM creature_movement GROUP BY id");
if (!result) if (!result)
{ {
BarGoLink bar(1); BarGoLink bar(1);
bar.step(); bar.step();
sLog.outString(); sLog.outString();
sLog.outString( ">> Loaded 0 paths. DB table `creature_movement` is empty." ); sLog.outString(">> Loaded 0 paths. DB table `creature_movement` is empty.");
} }
else else
{ {
@ -80,7 +80,7 @@ void WaypointManager::Load()
do do
{ {
bar.step(); bar.step();
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 id = fields[0].GetUInt32(); uint32 id = fields[0].GetUInt32();
uint32 count = fields[1].GetUInt32(); uint32 count = fields[1].GetUInt32();
@ -88,17 +88,17 @@ void WaypointManager::Load()
m_pathMap[id].resize(count); m_pathMap[id].resize(count);
total_nodes += count; total_nodes += count;
} }
while(result->NextRow()); while (result->NextRow());
sLog.outString(); sLog.outString();
sLog.outString( ">> Paths loaded" ); sLog.outString(">> Paths loaded");
delete result; delete result;
// 0 1 2 3 4 5 6 // 0 1 2 3 4 5 6
result = WorldDatabase.Query("SELECT id, point, position_x, position_y, position_z, waittime, script_id," result = WorldDatabase.Query("SELECT id, point, position_x, position_y, position_z, waittime, script_id,"
// 7 8 9 10 11 12 13 14 15 16 // 7 8 9 10 11 12 13 14 15 16
"textid1, textid2, textid3, textid4, textid5, emote, spell, orientation, model1, model2 FROM creature_movement"); "textid1, textid2, textid3, textid4, textid5, emote, spell, orientation, model1, model2 FROM creature_movement");
BarGoLink barRow((int)result->GetRowCount()); BarGoLink barRow((int)result->GetRowCount());
@ -108,7 +108,7 @@ void WaypointManager::Load()
do do
{ {
barRow.step(); barRow.step();
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 id = fields[0].GetUInt32(); uint32 id = fields[0].GetUInt32();
uint32 point = fields[1].GetUInt32(); uint32 point = fields[1].GetUInt32();
@ -123,12 +123,12 @@ void WaypointManager::Load()
if (cData->movementType != WAYPOINT_MOTION_TYPE) if (cData->movementType != WAYPOINT_MOTION_TYPE)
creatureNoMoveType.insert(id); creatureNoMoveType.insert(id);
WaypointPath &path = m_pathMap[id]; WaypointPath& path = m_pathMap[id];
// the cleanup queries make sure the following is true // the cleanup queries make sure the following is true
MANGOS_ASSERT(point >= 1 && point <= path.size()); MANGOS_ASSERT(point >= 1 && point <= path.size());
WaypointNode &node = path[point-1]; WaypointNode& node = path[point-1];
node.x = fields[2].GetFloat(); node.x = fields[2].GetFloat();
node.y = fields[3].GetFloat(); node.y = fields[3].GetFloat();
@ -140,13 +140,13 @@ void WaypointManager::Load()
// prevent using invalid coordinates // prevent using invalid coordinates
if (!MaNGOS::IsValidMapCoord(node.x, node.y, node.z, node.orientation)) if (!MaNGOS::IsValidMapCoord(node.x, node.y, node.z, node.orientation))
{ {
QueryResult *result1 = WorldDatabase.PQuery("SELECT id, map FROM creature WHERE guid = '%u'", id); QueryResult* result1 = WorldDatabase.PQuery("SELECT id, map FROM creature WHERE guid = '%u'", id);
if (result1) if (result1)
sLog.outErrorDb("Creature (guidlow %d, entry %d) have invalid coordinates in his waypoint %d (X: %f, Y: %f).", sLog.outErrorDb("Creature (guidlow %d, entry %d) have invalid coordinates in his waypoint %d (X: %f, Y: %f).",
id, result1->Fetch()[0].GetUInt32(), point, node.x, node.y); id, result1->Fetch()[0].GetUInt32(), point, node.x, node.y);
else else
sLog.outErrorDb("Waypoint path %d, have invalid coordinates in his waypoint %d (X: %f, Y: %f).", sLog.outErrorDb("Waypoint path %d, have invalid coordinates in his waypoint %d (X: %f, Y: %f).",
id, point, node.x, node.y); id, point, node.x, node.y);
MaNGOS::NormalizeMapCoord(node.x); MaNGOS::NormalizeMapCoord(node.x);
MaNGOS::NormalizeMapCoord(node.y); MaNGOS::NormalizeMapCoord(node.y);
@ -179,7 +179,7 @@ void WaypointManager::Load()
be.emote = fields[12].GetUInt32(); be.emote = fields[12].GetUInt32();
be.spell = fields[13].GetUInt32(); be.spell = fields[13].GetUInt32();
for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i) for (int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
{ {
be.textid[i] = fields[7+i].GetUInt32(); be.textid[i] = fields[7+i].GetUInt32();
@ -187,7 +187,7 @@ void WaypointManager::Load()
{ {
if (be.textid[i] < MIN_DB_SCRIPT_STRING_ID || be.textid[i] >= MAX_DB_SCRIPT_STRING_ID) if (be.textid[i] < MIN_DB_SCRIPT_STRING_ID || be.textid[i] >= MAX_DB_SCRIPT_STRING_ID)
{ {
sLog.outErrorDb( "Table `db_script_string` not have string id %u", be.textid[i]); sLog.outErrorDb("Table `db_script_string` not have string id %u", be.textid[i]);
continue; continue;
} }
} }
@ -214,11 +214,11 @@ void WaypointManager::Load()
else else
node.behavior = NULL; node.behavior = NULL;
} }
while(result->NextRow()); while (result->NextRow());
if (!creatureNoMoveType.empty()) if (!creatureNoMoveType.empty())
{ {
for(std::set<uint32>::const_iterator itr = creatureNoMoveType.begin(); itr != creatureNoMoveType.end(); ++itr) for (std::set<uint32>::const_iterator itr = creatureNoMoveType.begin(); itr != creatureNoMoveType.end(); ++itr)
{ {
const CreatureData* cData = sObjectMgr.GetCreatureData(*itr); const CreatureData* cData = sObjectMgr.GetCreatureData(*itr);
const CreatureInfo* cInfo = ObjectMgr::GetCreatureTemplate(cData->id); const CreatureInfo* cInfo = ObjectMgr::GetCreatureTemplate(cData->id);
@ -231,9 +231,9 @@ void WaypointManager::Load()
} }
sLog.outString(); sLog.outString();
sLog.outString( ">> Waypoints and behaviors loaded" ); sLog.outString(">> Waypoints and behaviors loaded");
sLog.outString(); sLog.outString();
sLog.outString( ">>> Loaded %u paths, %u nodes and %u behaviors", total_paths, total_nodes, total_behaviors); sLog.outString(">>> Loaded %u paths, %u nodes and %u behaviors", total_paths, total_nodes, total_behaviors);
delete result; delete result;
} }
@ -246,7 +246,7 @@ void WaypointManager::Load()
BarGoLink bar(1); BarGoLink bar(1);
bar.step(); bar.step();
sLog.outString(); sLog.outString();
sLog.outString( ">> Loaded 0 path templates. DB table `creature_movement_template` is empty." ); sLog.outString(">> Loaded 0 path templates. DB table `creature_movement_template` is empty.");
} }
else else
{ {
@ -258,7 +258,7 @@ void WaypointManager::Load()
do do
{ {
barRow.step(); barRow.step();
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32(); uint32 entry = fields[0].GetUInt32();
uint32 count = fields[1].GetUInt32(); uint32 count = fields[1].GetUInt32();
@ -266,7 +266,7 @@ void WaypointManager::Load()
m_pathTemplateMap[entry].resize(count); m_pathTemplateMap[entry].resize(count);
total_nodes += count; total_nodes += count;
} }
while(result->NextRow()); while (result->NextRow());
delete result; delete result;
@ -275,15 +275,15 @@ void WaypointManager::Load()
// 0 1 2 3 4 5 6 // 0 1 2 3 4 5 6
result = WorldDatabase.Query("SELECT entry, point, position_x, position_y, position_z, waittime, script_id," result = WorldDatabase.Query("SELECT entry, point, position_x, position_y, position_z, waittime, script_id,"
// 7 8 9 10 11 12 13 14 15 16 // 7 8 9 10 11 12 13 14 15 16
"textid1, textid2, textid3, textid4, textid5, emote, spell, orientation, model1, model2 FROM creature_movement_template"); "textid1, textid2, textid3, textid4, textid5, emote, spell, orientation, model1, model2 FROM creature_movement_template");
BarGoLink bar(result->GetRowCount()); BarGoLink bar(result->GetRowCount());
do do
{ {
bar.step(); bar.step();
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32(); uint32 entry = fields[0].GetUInt32();
uint32 point = fields[1].GetUInt32(); uint32 point = fields[1].GetUInt32();
@ -296,12 +296,12 @@ void WaypointManager::Load()
continue; continue;
} }
WaypointPath &path = m_pathTemplateMap[entry]; WaypointPath& path = m_pathTemplateMap[entry];
// the cleanup queries make sure the following is true // the cleanup queries make sure the following is true
MANGOS_ASSERT(point >= 1 && point <= path.size()); MANGOS_ASSERT(point >= 1 && point <= path.size());
WaypointNode &node = path[point-1]; WaypointNode& node = path[point-1];
node.x = fields[2].GetFloat(); node.x = fields[2].GetFloat();
node.y = fields[3].GetFloat(); node.y = fields[3].GetFloat();
@ -314,13 +314,13 @@ void WaypointManager::Load()
if (!MaNGOS::IsValidMapCoord(node.x, node.y, node.z, node.orientation)) if (!MaNGOS::IsValidMapCoord(node.x, node.y, node.z, node.orientation))
{ {
sLog.outErrorDb("Table creature_movement_template for entry %u (point %u) are using invalid coordinates position_x: %f, position_y: %f)", sLog.outErrorDb("Table creature_movement_template for entry %u (point %u) are using invalid coordinates position_x: %f, position_y: %f)",
entry, point, node.x, node.y); entry, point, node.x, node.y);
MaNGOS::NormalizeMapCoord(node.x); MaNGOS::NormalizeMapCoord(node.x);
MaNGOS::NormalizeMapCoord(node.y); MaNGOS::NormalizeMapCoord(node.y);
sLog.outErrorDb("Table creature_movement_template for entry %u (point %u) are auto corrected to normalized position_x=%f, position_y=%f", sLog.outErrorDb("Table creature_movement_template for entry %u (point %u) are auto corrected to normalized position_x=%f, position_y=%f",
entry, point, node.x, node.y); entry, point, node.x, node.y);
WorldDatabase.PExecute("UPDATE creature_movement_template SET position_x = '%f', position_y = '%f' WHERE entry = %u AND point = %u", node.x, node.y, entry, point); WorldDatabase.PExecute("UPDATE creature_movement_template SET position_x = '%f', position_y = '%f' WHERE entry = %u AND point = %u", node.x, node.y, entry, point);
} }
@ -342,7 +342,7 @@ void WaypointManager::Load()
be.emote = fields[12].GetUInt32(); be.emote = fields[12].GetUInt32();
be.spell = fields[13].GetUInt32(); be.spell = fields[13].GetUInt32();
for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i) for (int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
{ {
be.textid[i] = fields[7+i].GetUInt32(); be.textid[i] = fields[7+i].GetUInt32();
@ -350,7 +350,7 @@ void WaypointManager::Load()
{ {
if (be.textid[i] < MIN_DB_SCRIPT_STRING_ID || be.textid[i] >= MAX_DB_SCRIPT_STRING_ID) if (be.textid[i] < MIN_DB_SCRIPT_STRING_ID || be.textid[i] >= MAX_DB_SCRIPT_STRING_ID)
{ {
sLog.outErrorDb( "Table `db_script_string` not have string id %u", be.textid[i]); sLog.outErrorDb("Table `db_script_string` not have string id %u", be.textid[i]);
continue; continue;
} }
} }
@ -377,19 +377,19 @@ void WaypointManager::Load()
else else
node.behavior = NULL; node.behavior = NULL;
} }
while(result->NextRow()); while (result->NextRow());
delete result; delete result;
sLog.outString(); sLog.outString();
sLog.outString( ">> Waypoint templates loaded" ); sLog.outString(">> Waypoint templates loaded");
sLog.outString(); sLog.outString();
sLog.outString( ">>> Loaded %u path templates with %u nodes and %u behaviors", total_paths, total_nodes, total_behaviors); sLog.outString(">>> Loaded %u path templates with %u nodes and %u behaviors", total_paths, total_nodes, total_behaviors);
} }
if (!movementScriptSet.empty()) if (!movementScriptSet.empty())
{ {
for(std::set<uint32>::const_iterator itr = movementScriptSet.begin(); itr != movementScriptSet.end(); ++itr) for (std::set<uint32>::const_iterator itr = movementScriptSet.begin(); itr != movementScriptSet.end(); ++itr)
sLog.outErrorDb("Table `creature_movement_scripts` contain unused script, id %u.", *itr); sLog.outErrorDb("Table `creature_movement_scripts` contain unused script, id %u.", *itr);
} }
} }
@ -397,7 +397,7 @@ void WaypointManager::Load()
void WaypointManager::Cleanup() void WaypointManager::Cleanup()
{ {
// check if points need to be renumbered and do it // check if points need to be renumbered and do it
if (QueryResult *result = WorldDatabase.Query("SELECT 1 from creature_movement As T WHERE point <> (SELECT COUNT(*) FROM creature_movement WHERE id = T.id AND point <= T.point) LIMIT 1")) if (QueryResult* result = WorldDatabase.Query("SELECT 1 from creature_movement As T WHERE point <> (SELECT COUNT(*) FROM creature_movement WHERE id = T.id AND point <= T.point) LIMIT 1"))
{ {
delete result; delete result;
WorldDatabase.DirectExecute("CREATE TEMPORARY TABLE temp LIKE creature_movement"); WorldDatabase.DirectExecute("CREATE TEMPORARY TABLE temp LIKE creature_movement");
@ -412,7 +412,7 @@ void WaypointManager::Cleanup()
MANGOS_ASSERT(!(result = WorldDatabase.Query("SELECT 1 from creature_movement As T WHERE point <> (SELECT COUNT(*) FROM creature_movement WHERE id = T.id AND point <= T.point) LIMIT 1"))); MANGOS_ASSERT(!(result = WorldDatabase.Query("SELECT 1 from creature_movement As T WHERE point <> (SELECT COUNT(*) FROM creature_movement WHERE id = T.id AND point <= T.point) LIMIT 1")));
} }
if (QueryResult *result = WorldDatabase.Query("SELECT 1 from creature_movement_template As T WHERE point <> (SELECT COUNT(*) FROM creature_movement_template WHERE entry = T.entry AND point <= T.point) LIMIT 1")) if (QueryResult* result = WorldDatabase.Query("SELECT 1 from creature_movement_template As T WHERE point <> (SELECT COUNT(*) FROM creature_movement_template WHERE entry = T.entry AND point <= T.point) LIMIT 1"))
{ {
delete result; delete result;
WorldDatabase.DirectExecute("CREATE TEMPORARY TABLE temp LIKE creature_movement_template"); WorldDatabase.DirectExecute("CREATE TEMPORARY TABLE temp LIKE creature_movement_template");
@ -430,15 +430,15 @@ void WaypointManager::Cleanup()
void WaypointManager::Unload() void WaypointManager::Unload()
{ {
for(WaypointPathMap::iterator itr = m_pathMap.begin(); itr != m_pathMap.end(); ++itr) for (WaypointPathMap::iterator itr = m_pathMap.begin(); itr != m_pathMap.end(); ++itr)
_clearPath(itr->second); _clearPath(itr->second);
m_pathMap.clear(); m_pathMap.clear();
} }
void WaypointManager::_clearPath(WaypointPath &path) void WaypointManager::_clearPath(WaypointPath& path)
{ {
for(WaypointPath::const_iterator itr = path.begin(); itr != path.end(); ++itr) for (WaypointPath::const_iterator itr = path.begin(); itr != path.end(); ++itr)
if(itr->behavior) if (itr->behavior)
delete itr->behavior; delete itr->behavior;
path.clear(); path.clear();
} }
@ -452,7 +452,7 @@ void WaypointManager::AddLastNode(uint32 id, float x, float y, float z, float o,
/// - Insert after a certain point /// - Insert after a certain point
void WaypointManager::AddAfterNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid) void WaypointManager::AddAfterNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid)
{ {
for(uint32 i = GetLastPoint(id, 0); i > point; i--) for (uint32 i = GetLastPoint(id, 0); i > point; i--)
WorldDatabase.PExecuteLog("UPDATE creature_movement SET point=point+1 WHERE id=%u AND point=%u", id, i); WorldDatabase.PExecuteLog("UPDATE creature_movement SET point=point+1 WHERE id=%u AND point=%u", id, i);
_addNode(id, point + 1, x, y, z, o, delay, wpGuid); _addNode(id, point + 1, x, y, z, o, delay, wpGuid);
@ -461,12 +461,12 @@ void WaypointManager::AddAfterNode(uint32 id, uint32 point, float x, float y, fl
/// - Insert without checking for collision /// - Insert without checking for collision
void WaypointManager::_addNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid) void WaypointManager::_addNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid)
{ {
if(point == 0) return; // counted from 1 in the DB if (point == 0) return; // counted from 1 in the DB
WorldDatabase.PExecuteLog("INSERT INTO creature_movement (id,point,position_x,position_y,position_z,orientation,wpguid,waittime) " WorldDatabase.PExecuteLog("INSERT INTO creature_movement (id,point,position_x,position_y,position_z,orientation,wpguid,waittime) "
"VALUES (%u,%u, %f,%f,%f,%f, %u,%u)", "VALUES (%u,%u, %f,%f,%f,%f, %u,%u)",
id, point, x, y, z, o, wpGuid, delay); id, point, x, y, z, o, wpGuid, delay);
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
if(itr == m_pathMap.end()) if (itr == m_pathMap.end())
itr = m_pathMap.insert(WaypointPathMap::value_type(id, WaypointPath())).first; itr = m_pathMap.insert(WaypointPathMap::value_type(id, WaypointPath())).first;
itr->second.insert(itr->second.begin() + (point - 1), WaypointNode(x, y, z, o, delay, 0, NULL)); itr->second.insert(itr->second.begin() + (point - 1), WaypointNode(x, y, z, o, delay, 0, NULL));
} }
@ -481,18 +481,18 @@ uint32 WaypointManager::GetLastPoint(uint32 id, uint32 default_notfound)
delete result; delete result;
}*/ }*/
WaypointPathMap::const_iterator itr = m_pathMap.find(id); WaypointPathMap::const_iterator itr = m_pathMap.find(id);
if(itr != m_pathMap.end() && itr->second.size() != 0) if (itr != m_pathMap.end() && itr->second.size() != 0)
point = itr->second.size(); point = itr->second.size();
return point; return point;
} }
void WaypointManager::DeleteNode(uint32 id, uint32 point) void WaypointManager::DeleteNode(uint32 id, uint32 point)
{ {
if(point == 0) return; // counted from 1 in the DB if (point == 0) return; // counted from 1 in the DB
WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id=%u AND point=%u", id, point); WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id=%u AND point=%u", id, point);
WorldDatabase.PExecuteLog("UPDATE creature_movement SET point=point-1 WHERE id=%u AND point>%u", id, point); WorldDatabase.PExecuteLog("UPDATE creature_movement SET point=point-1 WHERE id=%u AND point>%u", id, point);
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
if(itr != m_pathMap.end() && point <= itr->second.size()) if (itr != m_pathMap.end() && point <= itr->second.size())
itr->second.erase(itr->second.begin() + (point-1)); itr->second.erase(itr->second.begin() + (point-1));
} }
@ -500,7 +500,7 @@ void WaypointManager::DeletePath(uint32 id)
{ {
WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id=%u", id); WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id=%u", id);
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
if(itr != m_pathMap.end()) if (itr != m_pathMap.end())
_clearPath(itr->second); _clearPath(itr->second);
// the path is not removed from the map, just cleared // the path is not removed from the map, just cleared
// WMGs have pointers to the path, so deleting them would crash // WMGs have pointers to the path, so deleting them would crash
@ -510,10 +510,10 @@ void WaypointManager::DeletePath(uint32 id)
void WaypointManager::SetNodePosition(uint32 id, uint32 point, float x, float y, float z) void WaypointManager::SetNodePosition(uint32 id, uint32 point, float x, float y, float z)
{ {
if(point == 0) return; // counted from 1 in the DB if (point == 0) return; // counted from 1 in the DB
WorldDatabase.PExecuteLog("UPDATE creature_movement SET position_x=%f, position_y=%f, position_z=%f WHERE id=%u AND point=%u", x, y, z, id, point); WorldDatabase.PExecuteLog("UPDATE creature_movement SET position_x=%f, position_y=%f, position_z=%f WHERE id=%u AND point=%u", x, y, z, id, point);
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
if(itr != m_pathMap.end() && point <= itr->second.size()) if (itr != m_pathMap.end() && point <= itr->second.size())
{ {
itr->second[point-1].x = x; itr->second[point-1].x = x;
itr->second[point-1].y = y; itr->second[point-1].y = y;
@ -521,14 +521,14 @@ void WaypointManager::SetNodePosition(uint32 id, uint32 point, float x, float y,
} }
} }
void WaypointManager::SetNodeText(uint32 id, uint32 point, const char *text_field, const char *text) void WaypointManager::SetNodeText(uint32 id, uint32 point, const char* text_field, const char* text)
{ {
if(point == 0) return; // counted from 1 in the DB if (point == 0) return; // counted from 1 in the DB
if(!text_field) return; if (!text_field) return;
std::string field = text_field; std::string field = text_field;
WorldDatabase.escape_string(field); WorldDatabase.escape_string(field);
if(!text) if (!text)
{ {
WorldDatabase.PExecuteLog("UPDATE creature_movement SET %s=NULL WHERE id='%u' AND point='%u'", field.c_str(), id, point); WorldDatabase.PExecuteLog("UPDATE creature_movement SET %s=NULL WHERE id='%u' AND point='%u'", field.c_str(), id, point);
} }
@ -540,27 +540,27 @@ void WaypointManager::SetNodeText(uint32 id, uint32 point, const char *text_fiel
} }
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
if(itr != m_pathMap.end() && point <= itr->second.size()) if (itr != m_pathMap.end() && point <= itr->second.size())
{ {
WaypointNode &node = itr->second[point-1]; WaypointNode& node = itr->second[point-1];
if(!node.behavior) node.behavior = new WaypointBehavior(); if (!node.behavior) node.behavior = new WaypointBehavior();
// if(field == "text1") node.behavior->text[0] = text ? text : ""; // if(field == "text1") node.behavior->text[0] = text ? text : "";
// if(field == "text2") node.behavior->text[1] = text ? text : ""; // if(field == "text2") node.behavior->text[1] = text ? text : "";
// if(field == "text3") node.behavior->text[2] = text ? text : ""; // if(field == "text3") node.behavior->text[2] = text ? text : "";
// if(field == "text4") node.behavior->text[3] = text ? text : ""; // if(field == "text4") node.behavior->text[3] = text ? text : "";
// if(field == "text5") node.behavior->text[4] = text ? text : ""; // if(field == "text5") node.behavior->text[4] = text ? text : "";
if(field == "emote") node.behavior->emote = text ? atoi(text) : 0; if (field == "emote") node.behavior->emote = text ? atoi(text) : 0;
if(field == "spell") node.behavior->spell = text ? atoi(text) : 0; if (field == "spell") node.behavior->spell = text ? atoi(text) : 0;
if(field == "model1") node.behavior->model1 = text ? atoi(text) : 0; if (field == "model1") node.behavior->model1 = text ? atoi(text) : 0;
if(field == "model2") node.behavior->model2 = text ? atoi(text) : 0; if (field == "model2") node.behavior->model2 = text ? atoi(text) : 0;
} }
} }
void WaypointManager::CheckTextsExistance(std::set<int32>& ids) void WaypointManager::CheckTextsExistance(std::set<int32>& ids)
{ {
WaypointPathMap::const_iterator pmItr = m_pathMap.begin(); WaypointPathMap::const_iterator pmItr = m_pathMap.begin();
for ( ; pmItr != m_pathMap.end(); ++pmItr) for (; pmItr != m_pathMap.end(); ++pmItr)
{ {
for (size_t i = 0; i < pmItr->second.size(); ++i) for (size_t i = 0; i < pmItr->second.size(); ++i)
{ {
@ -604,7 +604,7 @@ void WaypointManager::CheckTextsExistance(std::set<int32>& ids)
} }
WaypointPathTemplateMap::const_iterator wptItr = m_pathTemplateMap.begin(); WaypointPathTemplateMap::const_iterator wptItr = m_pathTemplateMap.begin();
for ( ; wptItr != m_pathTemplateMap.end(); ++wptItr) for (; wptItr != m_pathTemplateMap.end(); ++wptItr)
{ {
for (size_t i = 0; i < wptItr->second.size(); ++i) for (size_t i = 0; i < wptItr->second.size(); ++i)
{ {

View file

@ -36,7 +36,7 @@ struct WaypointBehavior
bool isEmpty(); bool isEmpty();
WaypointBehavior() {} WaypointBehavior() {}
WaypointBehavior(const WaypointBehavior &b); WaypointBehavior(const WaypointBehavior& b);
}; };
struct WaypointNode struct WaypointNode
@ -47,10 +47,10 @@ struct WaypointNode
float orientation; float orientation;
uint32 delay; uint32 delay;
uint32 script_id; // Added may 2010. WaypointBehavior w/DB data should in time be removed. uint32 script_id; // Added may 2010. WaypointBehavior w/DB data should in time be removed.
WaypointBehavior * behavior; WaypointBehavior* behavior;
WaypointNode() : x(0.0f), y(0.0f), z(0.0f), orientation(0.0f), delay(0), script_id(0), behavior(NULL) {} WaypointNode() : x(0.0f), y(0.0f), z(0.0f), orientation(0.0f), delay(0), script_id(0), behavior(NULL) {}
WaypointNode(float _x, float _y, float _z, float _o, uint32 _delay, uint32 _script_id, WaypointBehavior * _behavior) WaypointNode(float _x, float _y, float _z, float _o, uint32 _delay, uint32 _script_id, WaypointBehavior* _behavior)
: x(_x), y(_y), z(_z), orientation(_o), delay(_delay), script_id(_script_id), behavior(_behavior) {} : x(_x), y(_y), z(_z), orientation(_o), delay(_delay), script_id(_script_id), behavior(_behavior) {}
}; };
typedef std::vector<WaypointNode> WaypointPath; typedef std::vector<WaypointNode> WaypointPath;
@ -66,13 +66,13 @@ class WaypointManager
void Cleanup(); void Cleanup();
WaypointPath *GetPath(uint32 id) WaypointPath* GetPath(uint32 id)
{ {
WaypointPathMap::iterator itr = m_pathMap.find(id); WaypointPathMap::iterator itr = m_pathMap.find(id);
return itr != m_pathMap.end() ? &itr->second : NULL; return itr != m_pathMap.end() ? &itr->second : NULL;
} }
WaypointPath *GetPathTemplate(uint32 entry) WaypointPath* GetPathTemplate(uint32 entry)
{ {
WaypointPathTemplateMap::iterator itr = m_pathTemplateMap.find(entry); WaypointPathTemplateMap::iterator itr = m_pathTemplateMap.find(entry);
return itr != m_pathTemplateMap.end() ? &itr->second : NULL; return itr != m_pathTemplateMap.end() ? &itr->second : NULL;
@ -84,12 +84,12 @@ class WaypointManager
void DeleteNode(uint32 id, uint32 point); void DeleteNode(uint32 id, uint32 point);
void DeletePath(uint32 id); void DeletePath(uint32 id);
void SetNodePosition(uint32 id, uint32 point, float x, float y, float z); void SetNodePosition(uint32 id, uint32 point, float x, float y, float z);
void SetNodeText(uint32 id, uint32 point, const char *text_field, const char *text); void SetNodeText(uint32 id, uint32 point, const char* text_field, const char* text);
void CheckTextsExistance(std::set<int32>& ids); void CheckTextsExistance(std::set<int32>& ids);
private: private:
void _addNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid); void _addNode(uint32 id, uint32 point, float x, float y, float z, float o, uint32 delay, uint32 wpGuid);
void _clearPath(WaypointPath &path); void _clearPath(WaypointPath& path);
typedef UNORDERED_MAP<uint32, WaypointPath> WaypointPathMap; typedef UNORDERED_MAP<uint32, WaypointPath> WaypointPathMap;
WaypointPathMap m_pathMap; WaypointPathMap m_pathMap;

View file

@ -45,7 +45,7 @@ alter table creature_movement add `wpguid` int(11) default '0';
#include <cassert> #include <cassert>
//-----------------------------------------------// //-----------------------------------------------//
void WaypointMovementGenerator<Creature>::LoadPath(Creature &creature) void WaypointMovementGenerator<Creature>::LoadPath(Creature& creature)
{ {
DETAIL_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "LoadPath: loading waypoint path for %s", creature.GetGuidStr().c_str()); DETAIL_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "LoadPath: loading waypoint path for %s", creature.GetGuidStr().c_str());
@ -71,7 +71,7 @@ void WaypointMovementGenerator<Creature>::LoadPath(Creature &creature)
if (!i_path) if (!i_path)
{ {
sLog.outErrorDb("WaypointMovementGenerator::LoadPath: creature %s (Entry: %u GUID: %u) doesn't have waypoint path", sLog.outErrorDb("WaypointMovementGenerator::LoadPath: creature %s (Entry: %u GUID: %u) doesn't have waypoint path",
creature.GetName(), creature.GetEntry(), creature.GetGUIDLow()); creature.GetName(), creature.GetEntry(), creature.GetGUIDLow());
return; return;
} }
} }
@ -79,25 +79,25 @@ void WaypointMovementGenerator<Creature>::LoadPath(Creature &creature)
StartMoveNow(creature); StartMoveNow(creature);
} }
void WaypointMovementGenerator<Creature>::Initialize(Creature &creature) void WaypointMovementGenerator<Creature>::Initialize(Creature& creature)
{ {
LoadPath(creature); LoadPath(creature);
creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE);
} }
void WaypointMovementGenerator<Creature>::Finalize(Creature &creature) void WaypointMovementGenerator<Creature>::Finalize(Creature& creature)
{ {
creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE);
creature.SetWalk(false); creature.SetWalk(false);
} }
void WaypointMovementGenerator<Creature>::Interrupt(Creature &creature) void WaypointMovementGenerator<Creature>::Interrupt(Creature& creature)
{ {
creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE);
creature.SetWalk(false); creature.SetWalk(false);
} }
void WaypointMovementGenerator<Creature>::Reset(Creature &creature) void WaypointMovementGenerator<Creature>::Reset(Creature& creature)
{ {
creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE);
StartMoveNow(creature); StartMoveNow(creature);
@ -121,7 +121,7 @@ void WaypointMovementGenerator<Creature>::OnArrived(Creature& creature)
} }
// We have reached the destination and can process behavior // We have reached the destination and can process behavior
if (WaypointBehavior *behavior = i_path->at(i_currentNode).behavior) if (WaypointBehavior* behavior = i_path->at(i_currentNode).behavior)
{ {
if (behavior->emote != 0) if (behavior->emote != 0)
creature.HandleEmote(behavior->emote); creature.HandleEmote(behavior->emote);
@ -139,7 +139,7 @@ void WaypointMovementGenerator<Creature>::OnArrived(Creature& creature)
{ {
// Select one from max 5 texts (0 and 1 already checked) // Select one from max 5 texts (0 and 1 already checked)
int i = 2; int i = 2;
for(; i < MAX_WAYPOINT_TEXT; ++i) for (; i < MAX_WAYPOINT_TEXT; ++i)
{ {
if (!behavior->textid[i]) if (!behavior->textid[i])
break; break;
@ -157,7 +157,7 @@ void WaypointMovementGenerator<Creature>::OnArrived(Creature& creature)
Stop(i_path->at(i_currentNode).delay); Stop(i_path->at(i_currentNode).delay);
} }
void WaypointMovementGenerator<Creature>::StartMove(Creature &creature) void WaypointMovementGenerator<Creature>::StartMove(Creature& creature)
{ {
if (!i_path || i_path->empty()) if (!i_path || i_path->empty())
return; return;
@ -165,7 +165,7 @@ void WaypointMovementGenerator<Creature>::StartMove(Creature &creature)
if (Stopped()) if (Stopped())
return; return;
if (WaypointBehavior *behavior = i_path->at(i_currentNode).behavior) if (WaypointBehavior* behavior = i_path->at(i_currentNode).behavior)
{ {
if (behavior->model2 != 0) if (behavior->model2 != 0)
creature.SetDisplayId(behavior->model2); creature.SetDisplayId(behavior->model2);
@ -179,7 +179,7 @@ void WaypointMovementGenerator<Creature>::StartMove(Creature &creature)
creature.addUnitState(UNIT_STAT_ROAMING_MOVE); creature.addUnitState(UNIT_STAT_ROAMING_MOVE);
const WaypointNode &node = i_path->at(i_currentNode); const WaypointNode& node = i_path->at(i_currentNode);
Movement::MoveSplineInit init(creature); Movement::MoveSplineInit init(creature);
init.MoveTo(node.x, node.y, node.z, true); init.MoveTo(node.x, node.y, node.z, true);
@ -189,7 +189,7 @@ void WaypointMovementGenerator<Creature>::StartMove(Creature &creature)
init.Launch(); init.Launch();
} }
bool WaypointMovementGenerator<Creature>::Update(Creature &creature, const uint32 &diff) bool WaypointMovementGenerator<Creature>::Update(Creature& creature, const uint32& diff)
{ {
// Waypoint movement can be switched on/off // Waypoint movement can be switched on/off
// This is quite handy for escort quests and other stuff // This is quite handy for escort quests and other stuff
@ -224,7 +224,7 @@ bool WaypointMovementGenerator<Creature>::Update(Creature &creature, const uint3
return true; return true;
} }
void WaypointMovementGenerator<Creature>::MovementInform(Creature &creature) void WaypointMovementGenerator<Creature>::MovementInform(Creature& creature)
{ {
if (creature.AI()) if (creature.AI())
creature.AI()->MovementInform(WAYPOINT_MOTION_TYPE, i_currentNode); creature.AI()->MovementInform(WAYPOINT_MOTION_TYPE, i_currentNode);
@ -249,7 +249,7 @@ uint32 FlightPathMovementGenerator::GetPathAtMapEnd() const
uint32 curMapId = (*i_path)[i_currentNode].mapid; uint32 curMapId = (*i_path)[i_currentNode].mapid;
for(uint32 i = i_currentNode; i < i_path->size(); ++i) for (uint32 i = i_currentNode; i < i_path->size(); ++i)
{ {
if ((*i_path)[i].mapid != curMapId) if ((*i_path)[i].mapid != curMapId)
return i; return i;
@ -258,12 +258,12 @@ uint32 FlightPathMovementGenerator::GetPathAtMapEnd() const
return i_path->size(); return i_path->size();
} }
void FlightPathMovementGenerator::Initialize(Player &player) void FlightPathMovementGenerator::Initialize(Player& player)
{ {
Reset(player); Reset(player);
} }
void FlightPathMovementGenerator::Finalize(Player & player) void FlightPathMovementGenerator::Finalize(Player& player)
{ {
// remove flag to prevent send object build movement packets for flight state and crash (movement generator already not at top of stack) // remove flag to prevent send object build movement packets for flight state and crash (movement generator already not at top of stack)
player.clearUnitState(UNIT_STAT_TAXI_FLIGHT); player.clearUnitState(UNIT_STAT_TAXI_FLIGHT);
@ -271,10 +271,10 @@ void FlightPathMovementGenerator::Finalize(Player & player)
player.Unmount(); player.Unmount();
player.RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); player.RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
if(player.m_taxi.empty()) if (player.m_taxi.empty())
{ {
player.getHostileRefManager().setOnlineOfflineState(true); player.getHostileRefManager().setOnlineOfflineState(true);
if(player.pvpInfo.inHostileArea) if (player.pvpInfo.inHostileArea)
player.CastSpell(&player, 2479, true); player.CastSpell(&player, 2479, true);
// update z position to ground and orientation for landing point // update z position to ground and orientation for landing point
@ -284,14 +284,14 @@ void FlightPathMovementGenerator::Finalize(Player & player)
} }
} }
void FlightPathMovementGenerator::Interrupt(Player & player) void FlightPathMovementGenerator::Interrupt(Player& player)
{ {
player.clearUnitState(UNIT_STAT_TAXI_FLIGHT); player.clearUnitState(UNIT_STAT_TAXI_FLIGHT);
} }
#define PLAYER_FLIGHT_SPEED 32.0f #define PLAYER_FLIGHT_SPEED 32.0f
void FlightPathMovementGenerator::Reset(Player & player) void FlightPathMovementGenerator::Reset(Player& player)
{ {
player.getHostileRefManager().setOnlineOfflineState(false); player.getHostileRefManager().setOnlineOfflineState(false);
player.addUnitState(UNIT_STAT_TAXI_FLIGHT); player.addUnitState(UNIT_STAT_TAXI_FLIGHT);
@ -310,7 +310,7 @@ void FlightPathMovementGenerator::Reset(Player & player)
init.Launch(); init.Launch();
} }
bool FlightPathMovementGenerator::Update(Player &player, const uint32 &diff) bool FlightPathMovementGenerator::Update(Player& player, const uint32& diff)
{ {
uint32 pointId = (uint32)player.movespline->currentPathIdx(); uint32 pointId = (uint32)player.movespline->currentPathIdx();
if (pointId > i_currentNode) if (pointId > i_currentNode)
@ -323,7 +323,8 @@ bool FlightPathMovementGenerator::Update(Player &player, const uint32 &diff)
break; break;
i_currentNode += (uint32)departureEvent; i_currentNode += (uint32)departureEvent;
departureEvent = !departureEvent; departureEvent = !departureEvent;
} while(true); }
while (true);
} }
return i_currentNode < (i_path->size()-1); return i_currentNode < (i_path->size()-1);

View file

@ -44,7 +44,7 @@ class MANGOS_DLL_SPEC PathMovementBase
virtual ~PathMovementBase() {}; virtual ~PathMovementBase() {};
// template pattern, not defined .. override required // template pattern, not defined .. override required
void LoadPath(T &); void LoadPath(T&);
uint32 GetCurrentNode() const { return i_currentNode; } uint32 GetCurrentNode() const { return i_currentNode; }
protected: protected:
@ -62,24 +62,24 @@ class MANGOS_DLL_SPEC WaypointMovementGenerator;
template<> template<>
class MANGOS_DLL_SPEC WaypointMovementGenerator<Creature> class MANGOS_DLL_SPEC WaypointMovementGenerator<Creature>
: public MovementGeneratorMedium< Creature, WaypointMovementGenerator<Creature> >, : public MovementGeneratorMedium< Creature, WaypointMovementGenerator<Creature> >,
public PathMovementBase<Creature, WaypointPath const*> public PathMovementBase<Creature, WaypointPath const*>
{ {
public: public:
WaypointMovementGenerator(Creature &) : i_nextMoveTime(0), m_isArrivalDone(false) {} WaypointMovementGenerator(Creature&) : i_nextMoveTime(0), m_isArrivalDone(false) {}
~WaypointMovementGenerator() { i_path = NULL; } ~WaypointMovementGenerator() { i_path = NULL; }
void Initialize(Creature &u); void Initialize(Creature& u);
void Interrupt(Creature &); void Interrupt(Creature&);
void Finalize(Creature &); void Finalize(Creature&);
void Reset(Creature &u); void Reset(Creature& u);
bool Update(Creature &u, const uint32 &diff); bool Update(Creature& u, const uint32& diff);
void MovementInform(Creature &); void MovementInform(Creature&);
MovementGeneratorType GetMovementGeneratorType() const { return WAYPOINT_MOTION_TYPE; } MovementGeneratorType GetMovementGeneratorType() const { return WAYPOINT_MOTION_TYPE; }
// now path movement implmementation // now path movement implmementation
void LoadPath(Creature &c); void LoadPath(Creature& c);
bool GetResetPosition(Creature&, float& x, float& y, float& z); bool GetResetPosition(Creature&, float& x, float& y, float& z);
@ -112,8 +112,8 @@ public PathMovementBase<Creature, WaypointPath const*>
* and hence generates ground and activities for the player. * and hence generates ground and activities for the player.
*/ */
class MANGOS_DLL_SPEC FlightPathMovementGenerator class MANGOS_DLL_SPEC FlightPathMovementGenerator
: public MovementGeneratorMedium< Player, FlightPathMovementGenerator >, : public MovementGeneratorMedium< Player, FlightPathMovementGenerator >,
public PathMovementBase<Player,TaxiPathNodeList const*> public PathMovementBase<Player,TaxiPathNodeList const*>
{ {
public: public:
explicit FlightPathMovementGenerator(TaxiPathNodeList const& pathnodes, uint32 startNode = 0) explicit FlightPathMovementGenerator(TaxiPathNodeList const& pathnodes, uint32 startNode = 0)
@ -121,11 +121,11 @@ public PathMovementBase<Player,TaxiPathNodeList const*>
i_path = &pathnodes; i_path = &pathnodes;
i_currentNode = startNode; i_currentNode = startNode;
} }
void Initialize(Player &); void Initialize(Player&);
void Finalize(Player &); void Finalize(Player&);
void Interrupt(Player &); void Interrupt(Player&);
void Reset(Player &); void Reset(Player&);
bool Update(Player &, const uint32 &); bool Update(Player&, const uint32&);
MovementGeneratorType GetMovementGeneratorType() const { return FLIGHT_MOTION_TYPE; } MovementGeneratorType GetMovementGeneratorType() const { return FLIGHT_MOTION_TYPE; }
TaxiPathNodeList const& GetPath() { return *i_path; } TaxiPathNodeList const& GetPath() { return *i_path; }

View file

@ -35,7 +35,7 @@ Weather::Weather(uint32 zone, WeatherZoneChances const* weatherChances) : m_zone
m_type = WEATHER_TYPE_FINE; m_type = WEATHER_TYPE_FINE;
m_grade = 0; m_grade = 0;
DETAIL_FILTER_LOG(LOG_FILTER_WEATHER, "WORLD: Starting weather system for zone %u (change every %u minutes).", m_zone, (m_timer.GetInterval() / (MINUTE*IN_MILLISECONDS)) ); DETAIL_FILTER_LOG(LOG_FILTER_WEATHER, "WORLD: Starting weather system for zone %u (change every %u minutes).", m_zone, (m_timer.GetInterval() / (MINUTE*IN_MILLISECONDS)));
} }
/// Launch a weather update /// Launch a weather update
@ -44,14 +44,14 @@ bool Weather::Update(time_t diff)
m_timer.Update(diff); m_timer.Update(diff);
///- If the timer has passed, ReGenerate the weather ///- If the timer has passed, ReGenerate the weather
if(m_timer.Passed()) if (m_timer.Passed())
{ {
m_timer.Reset(); m_timer.Reset();
// update only if Regenerate has changed the weather // update only if Regenerate has changed the weather
if(ReGenerate()) if (ReGenerate())
{ {
///- Weather will be removed if not updated (no players in zone anymore) ///- Weather will be removed if not updated (no players in zone anymore)
if(!UpdateWeather()) if (!UpdateWeather())
return false; return false;
} }
} }
@ -85,7 +85,7 @@ bool Weather::ReGenerate()
//78 days between January 1st and March 20nd; 365/4=91 days by season //78 days between January 1st and March 20nd; 365/4=91 days by season
// season source http://aa.usno.navy.mil/data/docs/EarthSeasons.html // season source http://aa.usno.navy.mil/data/docs/EarthSeasons.html
time_t gtime = sWorld.GetGameTime(); time_t gtime = sWorld.GetGameTime();
struct tm * ltime = localtime(&gtime); struct tm* ltime = localtime(&gtime);
uint32 season = ((ltime->tm_yday - 78 + 365)/91)%4; uint32 season = ((ltime->tm_yday - 78 + 365)/91)%4;
static char const* seasonName[WEATHER_SEASONS] = { "spring", "summer", "fall", "winter" }; static char const* seasonName[WEATHER_SEASONS] = { "spring", "summer", "fall", "winter" };
@ -126,7 +126,7 @@ bool Weather::ReGenerate()
{ {
if (m_grade > 0.6666667f) if (m_grade > 0.6666667f)
{ {
// Severe change, but how severe? // Severe change, but how severe?
uint32 rnd = urand(0,99); uint32 rnd = urand(0,99);
if (rnd < 50) if (rnd < 50)
{ {
@ -145,11 +145,11 @@ bool Weather::ReGenerate()
uint32 chance3 = chance2+ m_weatherChances->data[season].stormChance; uint32 chance3 = chance2+ m_weatherChances->data[season].stormChance;
uint32 rnd = urand(0, 99); uint32 rnd = urand(0, 99);
if(rnd <= chance1) if (rnd <= chance1)
m_type = WEATHER_TYPE_RAIN; m_type = WEATHER_TYPE_RAIN;
else if(rnd <= chance2) else if (rnd <= chance2)
m_type = WEATHER_TYPE_SNOW; m_type = WEATHER_TYPE_SNOW;
else if(rnd <= chance3) else if (rnd <= chance3)
m_type = WEATHER_TYPE_STORM; m_type = WEATHER_TYPE_STORM;
else else
m_type = WEATHER_TYPE_FINE; m_type = WEATHER_TYPE_FINE;
@ -182,27 +182,27 @@ bool Weather::ReGenerate()
return m_type != old_type || m_grade != old_grade; return m_type != old_type || m_grade != old_grade;
} }
void Weather::SendWeatherUpdateToPlayer(Player *player) void Weather::SendWeatherUpdateToPlayer(Player* player)
{ {
WorldPacket data( SMSG_WEATHER, (4+4+1) ); WorldPacket data(SMSG_WEATHER, (4+4+1));
data << uint32(GetWeatherState()) << (float)m_grade << uint8(0); data << uint32(GetWeatherState()) << (float)m_grade << uint8(0);
player->GetSession()->SendPacket( &data ); player->GetSession()->SendPacket(&data);
} }
void Weather::SendFineWeatherUpdateToPlayer(Player *player) void Weather::SendFineWeatherUpdateToPlayer(Player* player)
{ {
WorldPacket data( SMSG_WEATHER, (4+4+1) ); WorldPacket data(SMSG_WEATHER, (4+4+1));
data << (uint32)WEATHER_STATE_FINE << (float)0.0f << uint8(0); data << (uint32)WEATHER_STATE_FINE << (float)0.0f << uint8(0);
player->GetSession()->SendPacket( &data ); player->GetSession()->SendPacket(&data);
} }
/// Send the new weather to all players in the zone /// Send the new weather to all players in the zone
bool Weather::UpdateWeather() bool Weather::UpdateWeather()
{ {
Player* player = sWorld.FindPlayerInZone(m_zone); Player* player = sWorld.FindPlayerInZone(m_zone);
if(!player) if (!player)
return false; return false;
///- Send the weather packet to all players in this zone ///- Send the weather packet to all players in this zone
@ -213,13 +213,13 @@ bool Weather::UpdateWeather()
WeatherState state = GetWeatherState(); WeatherState state = GetWeatherState();
WorldPacket data( SMSG_WEATHER, (4+4+1) ); WorldPacket data(SMSG_WEATHER, (4+4+1));
data << uint32(state) << (float)m_grade << uint8(0); data << uint32(state) << (float)m_grade << uint8(0);
player->SendMessageToSet( &data, true ); player->SendMessageToSet(&data, true);
///- Log the event ///- Log the event
char const* wthstr; char const* wthstr;
switch(state) switch (state)
{ {
case WEATHER_STATE_LIGHT_RAIN: case WEATHER_STATE_LIGHT_RAIN:
wthstr = "light rain"; wthstr = "light rain";
@ -268,7 +268,7 @@ bool Weather::UpdateWeather()
/// Set the weather /// Set the weather
void Weather::SetWeather(WeatherType type, float grade) void Weather::SetWeather(WeatherType type, float grade)
{ {
if(m_type == type && m_grade == grade) if (m_type == type && m_grade == grade)
return; return;
m_type = type; m_type = type;
@ -282,26 +282,26 @@ WeatherState Weather::GetWeatherState() const
if (m_grade<0.27f) if (m_grade<0.27f)
return WEATHER_STATE_FINE; return WEATHER_STATE_FINE;
switch(m_type) switch (m_type)
{ {
case WEATHER_TYPE_RAIN: case WEATHER_TYPE_RAIN:
if(m_grade<0.40f) if (m_grade<0.40f)
return WEATHER_STATE_LIGHT_RAIN; return WEATHER_STATE_LIGHT_RAIN;
else if(m_grade<0.70f) else if (m_grade<0.70f)
return WEATHER_STATE_MEDIUM_RAIN; return WEATHER_STATE_MEDIUM_RAIN;
else else
return WEATHER_STATE_HEAVY_RAIN; return WEATHER_STATE_HEAVY_RAIN;
case WEATHER_TYPE_SNOW: case WEATHER_TYPE_SNOW:
if(m_grade<0.40f) if (m_grade<0.40f)
return WEATHER_STATE_LIGHT_SNOW; return WEATHER_STATE_LIGHT_SNOW;
else if(m_grade<0.70f) else if (m_grade<0.70f)
return WEATHER_STATE_MEDIUM_SNOW; return WEATHER_STATE_MEDIUM_SNOW;
else else
return WEATHER_STATE_HEAVY_SNOW; return WEATHER_STATE_HEAVY_SNOW;
case WEATHER_TYPE_STORM: case WEATHER_TYPE_STORM:
if(m_grade<0.40f) if (m_grade<0.40f)
return WEATHER_STATE_LIGHT_SANDSTORM; return WEATHER_STATE_LIGHT_SANDSTORM;
else if(m_grade<0.70f) else if (m_grade<0.70f)
return WEATHER_STATE_MEDIUM_SANDSTORM; return WEATHER_STATE_MEDIUM_SANDSTORM;
else else
return WEATHER_STATE_HEAVY_SANDSTORM; return WEATHER_STATE_HEAVY_SANDSTORM;

View file

@ -55,8 +55,8 @@ class Weather
~Weather() { }; ~Weather() { };
bool ReGenerate(); bool ReGenerate();
bool UpdateWeather(); bool UpdateWeather();
void SendWeatherUpdateToPlayer(Player *player); void SendWeatherUpdateToPlayer(Player* player);
static void SendFineWeatherUpdateToPlayer(Player *player); static void SendFineWeatherUpdateToPlayer(Player* player);
void SetWeather(WeatherType type, float grade); void SetWeather(WeatherType type, float grade);
/// For which zone is this weather? /// For which zone is this weather?
uint32 GetZone() { return m_zone; }; uint32 GetZone() { return m_zone; };

File diff suppressed because it is too large Load diff

View file

@ -360,7 +360,7 @@ enum RealmType
REALM_TYPE_RP = 6, REALM_TYPE_RP = 6,
REALM_TYPE_RPPVP = 8, REALM_TYPE_RPPVP = 8,
REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries
// replaced by REALM_PVP in realm list // replaced by REALM_PVP in realm list
}; };
/// This is values from first column of Cfg_Categories.dbc (1.12.1 have another numeration) /// This is values from first column of Cfg_Categories.dbc (1.12.1 have another numeration)
@ -416,11 +416,11 @@ struct CliCommandHolder
uint32 m_cliAccountId; // 0 for console and real account id for RA/soap uint32 m_cliAccountId; // 0 for console and real account id for RA/soap
AccountTypes m_cliAccessLevel; AccountTypes m_cliAccessLevel;
void* m_callbackArg; void* m_callbackArg;
char *m_command; char* m_command;
Print* m_print; Print* m_print;
CommandFinished* m_commandFinished; CommandFinished* m_commandFinished;
CliCommandHolder(uint32 accountId, AccountTypes cliAccessLevel, void* callbackArg, const char *command, Print* zprint, CommandFinished* commandFinished) CliCommandHolder(uint32 accountId, AccountTypes cliAccessLevel, void* callbackArg, const char* command, Print* zprint, CommandFinished* commandFinished)
: m_cliAccountId(accountId), m_cliAccessLevel(cliAccessLevel), m_callbackArg(callbackArg), m_print(zprint), m_commandFinished(commandFinished) : m_cliAccountId(accountId), m_cliAccessLevel(cliAccessLevel), m_callbackArg(callbackArg), m_print(zprint), m_commandFinished(commandFinished)
{ {
size_t len = strlen(command)+1; size_t len = strlen(command)+1;
@ -441,7 +441,7 @@ class World
~World(); ~World();
WorldSession* FindSession(uint32 id) const; WorldSession* FindSession(uint32 id) const;
void AddSession(WorldSession *s); void AddSession(WorldSession* s);
bool RemoveSession(uint32 id); bool RemoveSession(uint32 id);
/// Get the number of current active sessions /// Get the number of current active sessions
void UpdateMaxSessionCounters(); void UpdateMaxSessionCounters();
@ -524,7 +524,7 @@ class World
void Update(uint32 diff); void Update(uint32 diff);
void UpdateSessions( uint32 diff ); void UpdateSessions(uint32 diff);
/// Get a server configuration element (see #eConfigFloatValues) /// Get a server configuration element (see #eConfigFloatValues)
void setConfig(eConfigFloatValues index,float value) { m_configFloatValues[index]=value; } void setConfig(eConfigFloatValues index,float value) { m_configFloatValues[index]=value; }
@ -575,7 +575,7 @@ class World
void UpdateRealmCharCount(uint32 accid); void UpdateRealmCharCount(uint32 accid);
LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if(m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; } LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if (m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; }
//used World DB version //used World DB version
void LoadDBVersion(); void LoadDBVersion();
@ -585,7 +585,7 @@ class World
protected: protected:
void _UpdateGameTime(); void _UpdateGameTime();
// callback for UpdateRealmCharacters // callback for UpdateRealmCharacters
void _UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId); void _UpdateRealmCharCount(QueryResult* resultCharCount, uint32 accountId);
void InitDailyQuestResetTime(); void InitDailyQuestResetTime();
void InitWeeklyQuestResetTime(); void InitWeeklyQuestResetTime();

View file

@ -48,7 +48,7 @@ static bool MapSessionFilterHelper(WorldSession* session, OpcodeHandler const& o
return false; return false;
// we do not process not loggined player packets // we do not process not loggined player packets
Player * plr = session->GetPlayer(); Player* plr = session->GetPlayer();
if (!plr) if (!plr)
return false; return false;
@ -57,7 +57,7 @@ static bool MapSessionFilterHelper(WorldSession* session, OpcodeHandler const& o
} }
bool MapSessionFilter::Process(WorldPacket * packet) bool MapSessionFilter::Process(WorldPacket* packet)
{ {
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()]; OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
if (opHandle.packetProcessing == PROCESS_INPLACE) if (opHandle.packetProcessing == PROCESS_INPLACE)
@ -81,16 +81,16 @@ bool WorldSessionFilter::Process(WorldPacket* packet)
} }
/// WorldSession constructor /// WorldSession constructor
WorldSession::WorldSession(uint32 id, WorldSocket *sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale) : WorldSession::WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
m_muteTime(mute_time), _player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion), _logoutTime(0), m_muteTime(mute_time), _player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion), _logoutTime(0),
m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_playerSave(false), m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_playerSave(false),
m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(sObjectMgr.GetIndexForLocale(locale)), m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(sObjectMgr.GetIndexForLocale(locale)),
m_latency(0), m_tutorialState(TUTORIALDATA_UNCHANGED) m_latency(0), m_tutorialState(TUTORIALDATA_UNCHANGED)
{ {
if (sock) if (sock)
{ {
m_Address = sock->GetRemoteAddress (); m_Address = sock->GetRemoteAddress();
sock->AddReference (); sock->AddReference();
} }
} }
@ -99,26 +99,26 @@ WorldSession::~WorldSession()
{ {
///- unload player if not unloaded ///- unload player if not unloaded
if (_player) if (_player)
LogoutPlayer (true); LogoutPlayer(true);
/// - If have unclosed socket, close it /// - If have unclosed socket, close it
if (m_Socket) if (m_Socket)
{ {
m_Socket->CloseSocket (); m_Socket->CloseSocket();
m_Socket->RemoveReference (); m_Socket->RemoveReference();
m_Socket = NULL; m_Socket = NULL;
} }
///- empty incoming packet queue ///- empty incoming packet queue
WorldPacket* packet = NULL; WorldPacket* packet = NULL;
while(_recvQueue.next(packet)) while (_recvQueue.next(packet))
delete packet; delete packet;
} }
void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
{ {
sLog.outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt crash server?), skipped", sLog.outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt crash server?), skipped",
GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size); GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
} }
/// Get the player name /// Get the player name
@ -133,7 +133,7 @@ void WorldSession::SendPacket(WorldPacket const* packet)
if (!m_Socket) if (!m_Socket)
return; return;
#ifdef MANGOS_DEBUG #ifdef MANGOS_DEBUG
// Code for network use statistic // Code for network use statistic
static uint64 sendPacketCount = 0; static uint64 sendPacketCount = 0;
@ -147,7 +147,7 @@ void WorldSession::SendPacket(WorldPacket const* packet)
time_t cur_time = time(NULL); time_t cur_time = time(NULL);
if((cur_time - lastTime) < 60) if ((cur_time - lastTime) < 60)
{ {
sendPacketCount+=1; sendPacketCount+=1;
sendPacketBytes+=packet->size(); sendPacketBytes+=packet->size();
@ -167,10 +167,10 @@ void WorldSession::SendPacket(WorldPacket const* packet)
sendLastPacketBytes = packet->wpos(); // wpos is real written size sendLastPacketBytes = packet->wpos(); // wpos is real written size
} }
#endif // !MANGOS_DEBUG #endif // !MANGOS_DEBUG
if (m_Socket->SendPacket (*packet) == -1) if (m_Socket->SendPacket(*packet) == -1)
m_Socket->CloseSocket (); m_Socket->CloseSocket();
} }
/// Add an incoming packet to the queue /// Add an incoming packet to the queue
@ -180,21 +180,21 @@ void WorldSession::QueuePacket(WorldPacket* new_packet)
} }
/// Logging helper for unexpected opcodes /// Logging helper for unexpected opcodes
void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char *reason) void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* reason)
{ {
sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s", sLog.outError("SESSION: received unexpected opcode %s (0x%.4X) %s",
LookupOpcodeName(packet->GetOpcode()), LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(), packet->GetOpcode(),
reason); reason);
} }
/// Logging helper for unexpected opcodes /// Logging helper for unexpected opcodes
void WorldSession::LogUnprocessedTail(WorldPacket *packet) void WorldSession::LogUnprocessedTail(WorldPacket* packet)
{ {
sLog.outError( "SESSION: opcode %s (0x%.4X) have unprocessed tail data (read stop at " SIZEFMTD " from " SIZEFMTD ")", sLog.outError("SESSION: opcode %s (0x%.4X) have unprocessed tail data (read stop at " SIZEFMTD " from " SIZEFMTD ")",
LookupOpcodeName(packet->GetOpcode()), LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(), packet->GetOpcode(),
packet->rpos(),packet->wpos()); packet->rpos(),packet->wpos());
} }
/// Update the WorldSession (triggered by World update) /// Update the WorldSession (triggered by World update)
@ -217,19 +217,19 @@ bool WorldSession::Update(PacketFilter& updater)
switch (opHandle.status) switch (opHandle.status)
{ {
case STATUS_LOGGEDIN: case STATUS_LOGGEDIN:
if(!_player) if (!_player)
{ {
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
if(!m_playerRecentlyLogout) if (!m_playerRecentlyLogout)
LogUnexpectedOpcode(packet, "the player has not logged in yet"); LogUnexpectedOpcode(packet, "the player has not logged in yet");
} }
else if(_player->IsInWorld()) else if (_player->IsInWorld())
ExecuteOpcode(opHandle, packet); ExecuteOpcode(opHandle, packet);
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break; break;
case STATUS_LOGGEDIN_OR_RECENTLY_LOGGEDOUT: case STATUS_LOGGEDIN_OR_RECENTLY_LOGGEDOUT:
if(!_player && !m_playerRecentlyLogout) if (!_player && !m_playerRecentlyLogout)
{ {
LogUnexpectedOpcode(packet, "the player has not logged in yet and not recently logout"); LogUnexpectedOpcode(packet, "the player has not logged in yet and not recently logout");
} }
@ -238,16 +238,16 @@ bool WorldSession::Update(PacketFilter& updater)
ExecuteOpcode(opHandle, packet); ExecuteOpcode(opHandle, packet);
break; break;
case STATUS_TRANSFER: case STATUS_TRANSFER:
if(!_player) if (!_player)
LogUnexpectedOpcode(packet, "the player has not logged in yet"); LogUnexpectedOpcode(packet, "the player has not logged in yet");
else if(_player->IsInWorld()) else if (_player->IsInWorld())
LogUnexpectedOpcode(packet, "the player is still in world"); LogUnexpectedOpcode(packet, "the player is still in world");
else else
ExecuteOpcode(opHandle, packet); ExecuteOpcode(opHandle, packet);
break; break;
case STATUS_AUTHED: case STATUS_AUTHED:
// prevent cheating with skip queue wait // prevent cheating with skip queue wait
if(m_inQueue) if (m_inQueue)
{ {
LogUnexpectedOpcode(packet, "the player not pass queue yet"); LogUnexpectedOpcode(packet, "the player not pass queue yet");
break; break;
@ -261,26 +261,26 @@ bool WorldSession::Update(PacketFilter& updater)
ExecuteOpcode(opHandle, packet); ExecuteOpcode(opHandle, packet);
break; break;
case STATUS_NEVER: case STATUS_NEVER:
sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)", sLog.outError("SESSION: received not allowed opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()), LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode()); packet->GetOpcode());
break; break;
case STATUS_UNHANDLED: case STATUS_UNHANDLED:
DEBUG_LOG("SESSION: received not handled opcode %s (0x%.4X)", DEBUG_LOG("SESSION: received not handled opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()), LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode()); packet->GetOpcode());
break; break;
default: default:
sLog.outError("SESSION: received wrong-status-req opcode %s (0x%.4X)", sLog.outError("SESSION: received wrong-status-req opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()), LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode()); packet->GetOpcode());
break; break;
} }
} }
catch (ByteBufferException &) catch (ByteBufferException&)
{ {
sLog.outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i.", sLog.outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i.",
packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId()); packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG)) if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
{ {
DEBUG_LOG("Dumping error causing packet:"); DEBUG_LOG("Dumping error causing packet:");
@ -290,7 +290,7 @@ bool WorldSession::Update(PacketFilter& updater)
if (sWorld.getConfig(CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET)) if (sWorld.getConfig(CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET))
{ {
DETAIL_LOG("Disconnecting session [account id %u / address %s] for badly formatted packet.", DETAIL_LOG("Disconnecting session [account id %u / address %s] for badly formatted packet.",
GetAccountId(), GetRemoteAddress().c_str()); GetAccountId(), GetRemoteAddress().c_str());
KickPlayer(); KickPlayer();
} }
@ -300,15 +300,15 @@ bool WorldSession::Update(PacketFilter& updater)
} }
///- Cleanup socket pointer if need ///- Cleanup socket pointer if need
if (m_Socket && m_Socket->IsClosed ()) if (m_Socket && m_Socket->IsClosed())
{ {
m_Socket->RemoveReference (); m_Socket->RemoveReference();
m_Socket = NULL; m_Socket = NULL;
} }
//check if we are safe to proceed with logout //check if we are safe to proceed with logout
//logout procedure should happen only in World::UpdateSessions() method!!! //logout procedure should happen only in World::UpdateSessions() method!!!
if(updater.ProcessLogout()) if (updater.ProcessLogout())
{ {
///- If necessary, log the player out ///- If necessary, log the player out
time_t currTime = time(NULL); time_t currTime = time(NULL);
@ -326,7 +326,7 @@ bool WorldSession::Update(PacketFilter& updater)
void WorldSession::LogoutPlayer(bool Save) void WorldSession::LogoutPlayer(bool Save)
{ {
// finish pending transfers before starting the logout // finish pending transfers before starting the logout
while(_player && _player->IsBeingTeleportedFar()) while (_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode(); HandleMoveWorldportAckOpcode();
m_playerLogout = true; m_playerLogout = true;
@ -355,16 +355,15 @@ void WorldSession::LogoutPlayer(bool Save)
// build set of player who attack _player or who have pet attacking of _player // build set of player who attack _player or who have pet attacking of _player
std::set<Player*> aset; std::set<Player*> aset;
for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr) for (Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
{ {
Unit* owner = (*itr)->GetOwner(); // including player controlled case Unit* owner = (*itr)->GetOwner(); // including player controlled case
if(owner) if (owner)
{ {
if(owner->GetTypeId()==TYPEID_PLAYER) if (owner->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)owner); aset.insert((Player*)owner);
} }
else else if ((*itr)->GetTypeId()==TYPEID_PLAYER)
if((*itr)->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)(*itr)); aset.insert((Player*)(*itr));
} }
@ -374,16 +373,16 @@ void WorldSession::LogoutPlayer(bool Save)
_player->RepopAtGraveyard(); _player->RepopAtGraveyard();
// give honor to all attackers from set like group case // give honor to all attackers from set like group case
for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr) for (std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
(*itr)->RewardHonor(_player,aset.size()); (*itr)->RewardHonor(_player,aset.size());
// give bg rewards and update counters like kill by first from attackers // give bg rewards and update counters like kill by first from attackers
// this can't be called for all attackers. // this can't be called for all attackers.
if(!aset.empty()) if (!aset.empty())
if(BattleGround *bg = _player->GetBattleGround()) if (BattleGround* bg = _player->GetBattleGround())
bg->HandleKillPlayer(_player,*aset.begin()); bg->HandleKillPlayer(_player,*aset.begin());
} }
else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION)) else if (_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
{ {
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); _player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
@ -393,11 +392,11 @@ void WorldSession::LogoutPlayer(bool Save)
_player->RepopAtGraveyard(); _player->RepopAtGraveyard();
} }
//drop a flag if player is carrying it //drop a flag if player is carrying it
if(BattleGround *bg = _player->GetBattleGround()) if (BattleGround* bg = _player->GetBattleGround())
bg->EventPlayerLoggedOut(_player); bg->EventPlayerLoggedOut(_player);
///- Teleport to home if the player is in an invalid instance ///- Teleport to home if the player is in an invalid instance
if(!_player->m_InstanceValid && !_player->isGameMaster()) if (!_player->m_InstanceValid && !_player->isGameMaster())
{ {
_player->TeleportToHomebind(); _player->TeleportToHomebind();
//this is a bad place to call for far teleport because we need player to be in world for successful logout //this is a bad place to call for far teleport because we need player to be in world for successful logout
@ -406,12 +405,12 @@ void WorldSession::LogoutPlayer(bool Save)
// FG: finish pending transfers after starting the logout // FG: finish pending transfers after starting the logout
// this should fix players beeing able to logout and login back with full hp at death position // this should fix players beeing able to logout and login back with full hp at death position
while(_player->IsBeingTeleportedFar()) while (_player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode(); HandleMoveWorldportAckOpcode();
for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{ {
if(BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i)) if (BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i))
{ {
_player->RemoveBattleGroundQueueId(bgQueueTypeId); _player->RemoveBattleGroundQueueId(bgQueueTypeId);
sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetObjectGuid(), true); sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetObjectGuid(), true);
@ -443,7 +442,7 @@ void WorldSession::LogoutPlayer(bool Save)
///- empty buyback items and save the player in the database ///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc) // some save parts only correctly work in case player present in map/player_lists (pets, etc)
if(Save) if (Save)
_player->SaveToDB(); _player->SaveToDB();
///- Leave all channels before player delete... ///- Leave all channels before player delete...
@ -454,16 +453,16 @@ void WorldSession::LogoutPlayer(bool Save)
// remove player from the group if he is: // remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected) // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket) if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
_player->RemoveFromGroup(); _player->RemoveFromGroup();
///- Send update to group ///- Send update to group
if(_player->GetGroup()) if (_player->GetGroup())
_player->GetGroup()->SendUpdate(); _player->GetGroup()->SendUpdate();
///- Broadcast a logout message to the player's friends ///- Broadcast a logout message to the player's friends
sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetObjectGuid(), true); sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetObjectGuid(), true);
sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ()); sSocialMgr.RemovePlayerSocial(_player->GetGUIDLow());
///- Remove the player from the world ///- Remove the player from the world
// the player may not be in the world when logging out // the player may not be in the world when logging out
@ -483,8 +482,8 @@ void WorldSession::LogoutPlayer(bool Save)
SetPlayer(NULL); // deleted in Remove/DeleteFromWorld call SetPlayer(NULL); // deleted in Remove/DeleteFromWorld call
///- Send the 'logout complete' packet to the client ///- Send the 'logout complete' packet to the client
WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 ); WorldPacket data(SMSG_LOGOUT_COMPLETE, 0);
SendPacket( &data ); SendPacket(&data);
///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
//No SQL injection as AccountId is uint32 //No SQL injection as AccountId is uint32
@ -494,7 +493,7 @@ void WorldSession::LogoutPlayer(bool Save)
stmt = CharacterDatabase.CreateStatement(updChars, "UPDATE characters SET online = 0 WHERE account = ?"); stmt = CharacterDatabase.CreateStatement(updChars, "UPDATE characters SET online = 0 WHERE account = ?");
stmt.PExecute(GetAccountId()); stmt.PExecute(GetAccountId());
DEBUG_LOG( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" ); DEBUG_LOG("SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
} }
m_playerLogout = false; m_playerLogout = false;
@ -507,7 +506,7 @@ void WorldSession::LogoutPlayer(bool Save)
void WorldSession::KickPlayer() void WorldSession::KickPlayer()
{ {
if (m_Socket) if (m_Socket)
m_Socket->CloseSocket (); m_Socket->CloseSocket();
} }
/// Cancel channeling handler /// Cancel channeling handler
@ -519,7 +518,7 @@ void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
szStr[0] = '\0'; szStr[0] = '\0';
va_start(ap, Text); va_start(ap, Text);
vsnprintf( szStr, 1024, Text, ap ); vsnprintf(szStr, 1024, Text, ap);
va_end(ap); va_end(ap);
uint32 length = strlen(szStr)+1; uint32 length = strlen(szStr)+1;
@ -529,15 +528,15 @@ void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
SendPacket(&data); SendPacket(&data);
} }
void WorldSession::SendNotification(const char *format,...) void WorldSession::SendNotification(const char* format,...)
{ {
if(format) if (format)
{ {
va_list ap; va_list ap;
char szStr [1024]; char szStr [1024];
szStr[0] = '\0'; szStr[0] = '\0';
va_start(ap, format); va_start(ap, format);
vsnprintf( szStr, 1024, format, ap ); vsnprintf(szStr, 1024, format, ap);
va_end(ap); va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1)); WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
@ -549,13 +548,13 @@ void WorldSession::SendNotification(const char *format,...)
void WorldSession::SendNotification(int32 string_id,...) void WorldSession::SendNotification(int32 string_id,...)
{ {
char const* format = GetMangosString(string_id); char const* format = GetMangosString(string_id);
if(format) if (format)
{ {
va_list ap; va_list ap;
char szStr [1024]; char szStr [1024];
szStr[0] = '\0'; szStr[0] = '\0';
va_start(ap, string_id); va_start(ap, string_id);
vsnprintf( szStr, 1024, format, ap ); vsnprintf(szStr, 1024, format, ap);
va_end(ap); va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1)); WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
@ -571,50 +570,50 @@ void WorldSession::SendSetPhaseShift(uint32 PhaseShift)
SendPacket(&data); SendPacket(&data);
} }
const char * WorldSession::GetMangosString( int32 entry ) const const char* WorldSession::GetMangosString(int32 entry) const
{ {
return sObjectMgr.GetMangosString(entry,GetSessionDbLocaleIndex()); return sObjectMgr.GetMangosString(entry,GetSessionDbLocaleIndex());
} }
void WorldSession::Handle_NULL( WorldPacket& recvPacket ) void WorldSession::Handle_NULL(WorldPacket& recvPacket)
{ {
DEBUG_LOG("SESSION: received unimplemented opcode %s (0x%.4X)", DEBUG_LOG("SESSION: received unimplemented opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()), LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode()); recvPacket.GetOpcode());
} }
void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket ) void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
{ {
sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead", sLog.outError("SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
LookupOpcodeName(recvPacket.GetOpcode()), LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode()); recvPacket.GetOpcode());
} }
void WorldSession::Handle_ServerSide( WorldPacket& recvPacket ) void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
{ {
sLog.outError("SESSION: received server-side opcode %s (0x%.4X)", sLog.outError("SESSION: received server-side opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()), LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode()); recvPacket.GetOpcode());
} }
void WorldSession::Handle_Deprecated( WorldPacket& recvPacket ) void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
{ {
sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)", sLog.outError("SESSION: received deprecated opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()), LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode()); recvPacket.GetOpcode());
} }
void WorldSession::SendAuthWaitQue(uint32 position) void WorldSession::SendAuthWaitQue(uint32 position)
{ {
if(position == 0) if (position == 0)
{ {
WorldPacket packet( SMSG_AUTH_RESPONSE, 1 ); WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet << uint8( AUTH_OK ); packet << uint8(AUTH_OK);
SendPacket(&packet); SendPacket(&packet);
} }
else else
{ {
WorldPacket packet( SMSG_AUTH_RESPONSE, 1+4+1 ); WorldPacket packet(SMSG_AUTH_RESPONSE, 1+4+1);
packet << uint8(AUTH_WAIT_QUEUE); packet << uint8(AUTH_WAIT_QUEUE);
packet << uint32(position); packet << uint32(position);
packet << uint8(0); // unk 3.3.0 packet << uint8(0); // unk 3.3.0
@ -636,32 +635,33 @@ void WorldSession::LoadAccountData(QueryResult* result, uint32 mask)
if (mask & (1 << i)) if (mask & (1 << i))
m_accountData[i] = AccountData(); m_accountData[i] = AccountData();
if(!result) if (!result)
return; return;
do do
{ {
Field *fields = result->Fetch(); Field* fields = result->Fetch();
uint32 type = fields[0].GetUInt32(); uint32 type = fields[0].GetUInt32();
if (type >= NUM_ACCOUNT_DATA_TYPES) if (type >= NUM_ACCOUNT_DATA_TYPES)
{ {
sLog.outError("Table `%s` have invalid account data type (%u), ignore.", sLog.outError("Table `%s` have invalid account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type); mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue; continue;
} }
if ((mask & (1 << type))==0) if ((mask & (1 << type))==0)
{ {
sLog.outError("Table `%s` have non appropriate for table account data type (%u), ignore.", sLog.outError("Table `%s` have non appropriate for table account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type); mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue; continue;
} }
m_accountData[type].Time = time_t(fields[1].GetUInt64()); m_accountData[type].Time = time_t(fields[1].GetUInt64());
m_accountData[type].Data = fields[2].GetCppString(); m_accountData[type].Data = fields[2].GetCppString();
} while (result->NextRow()); }
while (result->NextRow());
delete result; delete result;
} }
@ -675,7 +675,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::strin
static SqlStatementID delId; static SqlStatementID delId;
static SqlStatementID insId; static SqlStatementID insId;
CharacterDatabase.BeginTransaction (); CharacterDatabase.BeginTransaction();
SqlStatement stmt = CharacterDatabase.CreateStatement(delId, "DELETE FROM account_data WHERE account=? AND type=?"); SqlStatement stmt = CharacterDatabase.CreateStatement(delId, "DELETE FROM account_data WHERE account=? AND type=?");
stmt.PExecute(acc, uint32(type)); stmt.PExecute(acc, uint32(type));
@ -683,18 +683,18 @@ void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::strin
stmt = CharacterDatabase.CreateStatement(insId, "INSERT INTO account_data VALUES (?,?,?,?)"); stmt = CharacterDatabase.CreateStatement(insId, "INSERT INTO account_data VALUES (?,?,?,?)");
stmt.PExecute(acc, uint32(type), uint64(time_), data.c_str()); stmt.PExecute(acc, uint32(type), uint64(time_), data.c_str());
CharacterDatabase.CommitTransaction (); CharacterDatabase.CommitTransaction();
} }
else else
{ {
// _player can be NULL and packet received after logout but m_GUID still store correct guid // _player can be NULL and packet received after logout but m_GUID still store correct guid
if(!m_GUIDLow) if (!m_GUIDLow)
return; return;
static SqlStatementID delId; static SqlStatementID delId;
static SqlStatementID insId; static SqlStatementID insId;
CharacterDatabase.BeginTransaction (); CharacterDatabase.BeginTransaction();
SqlStatement stmt = CharacterDatabase.CreateStatement(delId, "DELETE FROM character_account_data WHERE guid=? AND type=?"); SqlStatement stmt = CharacterDatabase.CreateStatement(delId, "DELETE FROM character_account_data WHERE guid=? AND type=?");
stmt.PExecute(m_GUIDLow, uint32(type)); stmt.PExecute(m_GUIDLow, uint32(type));
@ -702,7 +702,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::strin
stmt = CharacterDatabase.CreateStatement(insId, "INSERT INTO character_account_data VALUES (?,?,?,?)"); stmt = CharacterDatabase.CreateStatement(insId, "INSERT INTO character_account_data VALUES (?,?,?,?)");
stmt.PExecute(m_GUIDLow, uint32(type), uint64(time_), data.c_str()); stmt.PExecute(m_GUIDLow, uint32(type), uint64(time_), data.c_str());
CharacterDatabase.CommitTransaction (); CharacterDatabase.CommitTransaction();
} }
m_accountData[type].Time = time_; m_accountData[type].Time = time_;
@ -711,24 +711,24 @@ void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::strin
void WorldSession::SendAccountDataTimes(uint32 mask) void WorldSession::SendAccountDataTimes(uint32 mask)
{ {
WorldPacket data( SMSG_ACCOUNT_DATA_TIMES, 4+1+4+8*4 ); // changed in WotLK WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4+1+4+8*4); // changed in WotLK
data << uint32(time(NULL)); // unix time of something data << uint32(time(NULL)); // unix time of something
data << uint8(1); data << uint8(1);
data << uint32(mask); // type mask data << uint32(mask); // type mask
for(uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if(mask & (1 << i)) if (mask & (1 << i))
data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
SendPacket(&data); SendPacket(&data);
} }
void WorldSession::LoadTutorialsData() void WorldSession::LoadTutorialsData()
{ {
for ( int aX = 0 ; aX < 8 ; ++aX ) for (int aX = 0 ; aX < 8 ; ++aX)
m_Tutorials[ aX ] = 0; m_Tutorials[ aX ] = 0;
QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId()); QueryResult* result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId());
if(!result) if (!result)
{ {
m_tutorialState = TUTORIALDATA_NEW; m_tutorialState = TUTORIALDATA_NEW;
return; return;
@ -736,12 +736,12 @@ void WorldSession::LoadTutorialsData()
do do
{ {
Field *fields = result->Fetch(); Field* fields = result->Fetch();
for (int iI = 0; iI < 8; ++iI) for (int iI = 0; iI < 8; ++iI)
m_Tutorials[iI] = fields[iI].GetUInt32(); m_Tutorials[iI] = fields[iI].GetUInt32();
} }
while( result->NextRow() ); while (result->NextRow());
delete result; delete result;
@ -751,7 +751,7 @@ void WorldSession::LoadTutorialsData()
void WorldSession::SendTutorialsData() void WorldSession::SendTutorialsData()
{ {
WorldPacket data(SMSG_TUTORIAL_FLAGS, 4*8); WorldPacket data(SMSG_TUTORIAL_FLAGS, 4*8);
for(uint32 i = 0; i < 8; ++i) for (uint32 i = 0; i < 8; ++i)
data << m_Tutorials[i]; data << m_Tutorials[i];
SendPacket(&data); SendPacket(&data);
} }
@ -761,30 +761,30 @@ void WorldSession::SaveTutorialsData()
static SqlStatementID updTutorial ; static SqlStatementID updTutorial ;
static SqlStatementID insTutorial ; static SqlStatementID insTutorial ;
switch(m_tutorialState) switch (m_tutorialState)
{ {
case TUTORIALDATA_CHANGED: case TUTORIALDATA_CHANGED:
{ {
SqlStatement stmt = CharacterDatabase.CreateStatement(updTutorial, "UPDATE character_tutorial SET tut0=?, tut1=?, tut2=?, tut3=?, tut4=?, tut5=?, tut6=?, tut7=? WHERE account = ?"); SqlStatement stmt = CharacterDatabase.CreateStatement(updTutorial, "UPDATE character_tutorial SET tut0=?, tut1=?, tut2=?, tut3=?, tut4=?, tut5=?, tut6=?, tut7=? WHERE account = ?");
for (int i = 0; i < 8; ++i) for (int i = 0; i < 8; ++i)
stmt.addUInt32(m_Tutorials[i]); stmt.addUInt32(m_Tutorials[i]);
stmt.addUInt32(GetAccountId()); stmt.addUInt32(GetAccountId());
stmt.Execute(); stmt.Execute();
} }
break; break;
case TUTORIALDATA_NEW: case TUTORIALDATA_NEW:
{ {
SqlStatement stmt = CharacterDatabase.CreateStatement(insTutorial, "INSERT INTO character_tutorial (account,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); SqlStatement stmt = CharacterDatabase.CreateStatement(insTutorial, "INSERT INTO character_tutorial (account,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetAccountId()); stmt.addUInt32(GetAccountId());
for (int i = 0; i < 8; ++i) for (int i = 0; i < 8; ++i)
stmt.addUInt32(m_Tutorials[i]); stmt.addUInt32(m_Tutorials[i]);
stmt.Execute(); stmt.Execute();
} }
break; break;
case TUTORIALDATA_UNCHANGED: case TUTORIALDATA_UNCHANGED:
break; break;
} }
@ -792,17 +792,17 @@ void WorldSession::SaveTutorialsData()
m_tutorialState = TUTORIALDATA_UNCHANGED; m_tutorialState = TUTORIALDATA_UNCHANGED;
} }
void WorldSession::ReadAddonsInfo(WorldPacket &data) void WorldSession::ReadAddonsInfo(WorldPacket& data)
{ {
if (data.rpos() + 4 > data.size()) if (data.rpos() + 4 > data.size())
return; return;
uint32 size; uint32 size;
data >> size; data >> size;
if(!size) if (!size)
return; return;
if(size > 0xFFFFF) if (size > 0xFFFFF)
{ {
sLog.outError("WorldSession::ReadAddonsInfo addon info too big, size %u", size); sLog.outError("WorldSession::ReadAddonsInfo addon info too big, size %u", size);
return; return;
@ -820,14 +820,14 @@ void WorldSession::ReadAddonsInfo(WorldPacket &data)
uint32 addonsCount; uint32 addonsCount;
addonInfo >> addonsCount; // addons count addonInfo >> addonsCount; // addons count
for(uint32 i = 0; i < addonsCount; ++i) for (uint32 i = 0; i < addonsCount; ++i)
{ {
std::string addonName; std::string addonName;
uint8 enabled; uint8 enabled;
uint32 crc, unk1; uint32 crc, unk1;
// check next addon data format correctness // check next addon data format correctness
if(addonInfo.rpos()+1 > addonInfo.size()) if (addonInfo.rpos()+1 > addonInfo.size())
return; return;
addonInfo >> addonName; addonInfo >> addonName;
@ -842,7 +842,7 @@ void WorldSession::ReadAddonsInfo(WorldPacket &data)
uint32 unk2; uint32 unk2;
addonInfo >> unk2; addonInfo >> unk2;
if(addonInfo.rpos() != addonInfo.size()) if (addonInfo.rpos() != addonInfo.size())
DEBUG_LOG("packet under read!"); DEBUG_LOG("packet under read!");
} }
else else
@ -873,7 +873,7 @@ void WorldSession::SendAddonsInfo()
WorldPacket data(SMSG_ADDON_INFO, 4); WorldPacket data(SMSG_ADDON_INFO, 4);
for(AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr) for (AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
{ {
uint8 state = 2; // 2 is sent here uint8 state = 2; // 2 is sent here
data << uint8(state); data << uint8(state);
@ -916,12 +916,12 @@ void WorldSession::SendAddonsInfo()
SendPacket(&data); SendPacket(&data);
} }
void WorldSession::SetPlayer( Player *plr ) void WorldSession::SetPlayer(Player* plr)
{ {
_player = plr; _player = plr;
// set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset // set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
if(_player) if (_player)
m_GUIDLow = _player->GetGUIDLow(); m_GUIDLow = _player->GetGUIDLow();
} }
@ -944,7 +944,7 @@ void WorldSession::SendRedirectClient(std::string& ip, uint16 port)
SendPacket(&pkt); SendPacket(&pkt);
} }
void WorldSession::ExecuteOpcode( OpcodeHandler const& opHandle, WorldPacket* packet ) void WorldSession::ExecuteOpcode(OpcodeHandler const& opHandle, WorldPacket* packet)
{ {
// need prevent do internal far teleports in handlers because some handlers do lot steps // need prevent do internal far teleports in handlers because some handlers do lot steps
// or call code that can do far teleports in some conditions unexpectedly for generic way work code // or call code that can do far teleports in some conditions unexpectedly for generic way work code

View file

@ -190,24 +190,24 @@ enum TutorialDataState
class PacketFilter class PacketFilter
{ {
public: public:
explicit PacketFilter(WorldSession * pSession) : m_pSession(pSession) {} explicit PacketFilter(WorldSession* pSession) : m_pSession(pSession) {}
virtual ~PacketFilter() {} virtual ~PacketFilter() {}
virtual bool Process(WorldPacket * packet) { return true; } virtual bool Process(WorldPacket* packet) { return true; }
virtual bool ProcessLogout() const { return true; } virtual bool ProcessLogout() const { return true; }
protected: protected:
WorldSession * const m_pSession; WorldSession* const m_pSession;
}; };
//process only thread-safe packets in Map::Update() //process only thread-safe packets in Map::Update()
class MapSessionFilter : public PacketFilter class MapSessionFilter : public PacketFilter
{ {
public: public:
explicit MapSessionFilter(WorldSession * pSession) : PacketFilter(pSession) {} explicit MapSessionFilter(WorldSession* pSession) : PacketFilter(pSession) {}
~MapSessionFilter() {} ~MapSessionFilter() {}
virtual bool Process(WorldPacket * packet); virtual bool Process(WorldPacket* packet);
//in Map::Update() we do not process player logout! //in Map::Update() we do not process player logout!
virtual bool ProcessLogout() const { return false; } virtual bool ProcessLogout() const { return false; }
}; };
@ -217,7 +217,7 @@ class MapSessionFilter : public PacketFilter
class WorldSessionFilter : public PacketFilter class WorldSessionFilter : public PacketFilter
{ {
public: public:
explicit WorldSessionFilter(WorldSession * pSession) : PacketFilter(pSession) {} explicit WorldSessionFilter(WorldSession* pSession) : PacketFilter(pSession) {}
~WorldSessionFilter() {} ~WorldSessionFilter() {}
virtual bool Process(WorldPacket* packet); virtual bool Process(WorldPacket* packet);
@ -226,9 +226,9 @@ class WorldSessionFilter : public PacketFilter
/// Player session in the World /// Player session in the World
class MANGOS_DLL_SPEC WorldSession class MANGOS_DLL_SPEC WorldSession
{ {
friend class CharacterHandler; friend class CharacterHandler;
public: public:
WorldSession(uint32 id, WorldSocket *sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale); WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale);
~WorldSession(); ~WorldSession();
bool PlayerLoading() const { return m_playerLoading; } bool PlayerLoading() const { return m_playerLoading; }
@ -237,13 +237,13 @@ class MANGOS_DLL_SPEC WorldSession
void SizeError(WorldPacket const& packet, uint32 size) const; void SizeError(WorldPacket const& packet, uint32 size) const;
void ReadAddonsInfo(WorldPacket &data); void ReadAddonsInfo(WorldPacket& data);
void SendAddonsInfo(); void SendAddonsInfo();
void SendPacket(WorldPacket const* packet); void SendPacket(WorldPacket const* packet);
void SendNotification(const char *format,...) ATTR_PRINTF(2,3); void SendNotification(const char* format,...) ATTR_PRINTF(2,3);
void SendNotification(int32 string_id,...); void SendNotification(int32 string_id,...);
void SendPetNameInvalid(uint32 error, const std::string& name, DeclinedName *declinedName); void SendPetNameInvalid(uint32 error, const std::string& name, DeclinedName* declinedName);
void SendLfgSearchResults(LfgType type, uint32 entry); void SendLfgSearchResults(LfgType type, uint32 entry);
void SendLfgJoinResult(LfgJoinResult result); void SendLfgJoinResult(LfgJoinResult result);
void SendLfgUpdate(bool isGroup, LfgUpdateType updateType, uint32 id); void SendLfgUpdate(bool isGroup, LfgUpdateType updateType, uint32 id);
@ -259,7 +259,7 @@ class MANGOS_DLL_SPEC WorldSession
char const* GetPlayerName() const; char const* GetPlayerName() const;
void SetSecurity(AccountTypes security) { _security = security; } void SetSecurity(AccountTypes security) { _security = security; }
std::string const& GetRemoteAddress() { return m_Address; } std::string const& GetRemoteAddress() { return m_Address; }
void SetPlayer(Player *plr); void SetPlayer(Player* plr);
uint8 Expansion() const { return m_expansion; } uint8 Expansion() const { return m_expansion; }
/// Session in auth.queue currently /// Session in auth.queue currently
@ -292,10 +292,10 @@ class MANGOS_DLL_SPEC WorldSession
void SendNameQueryOpcode(Player* p); void SendNameQueryOpcode(Player* p);
void SendNameQueryOpcodeFromDB(ObjectGuid guid); void SendNameQueryOpcodeFromDB(ObjectGuid guid);
static void SendNameQueryOpcodeFromDBCallBack(QueryResult *result, uint32 accountId); static void SendNameQueryOpcodeFromDBCallBack(QueryResult* result, uint32 accountId);
void SendTrainerList(ObjectGuid guid); void SendTrainerList(ObjectGuid guid);
void SendTrainerList(ObjectGuid guid, const std::string& strTitle ); void SendTrainerList(ObjectGuid guid, const std::string& strTitle);
void SendListInventory(ObjectGuid guid); void SendListInventory(ObjectGuid guid);
bool CheckBanker(ObjectGuid guid); bool CheckBanker(ObjectGuid guid);
@ -305,8 +305,8 @@ class MANGOS_DLL_SPEC WorldSession
void SendTabardVendorActivate(ObjectGuid guid); void SendTabardVendorActivate(ObjectGuid guid);
void SendSpiritResurrect(); void SendSpiritResurrect();
void SendBindPoint(Creature* npc); void SendBindPoint(Creature* npc);
void SendGMTicketGetTicket(uint32 status, GMTicket *ticket = NULL); void SendGMTicketGetTicket(uint32 status, GMTicket* ticket = NULL);
void SendGMResponse(GMTicket *ticket); void SendGMResponse(GMTicket* ticket);
void SendAttackStop(Unit const* enemy); void SendAttackStop(Unit const* enemy);
@ -325,7 +325,7 @@ class MANGOS_DLL_SPEC WorldSession
bool CheckStableMaster(ObjectGuid guid); bool CheckStableMaster(ObjectGuid guid);
// Account Data // Account Data
AccountData *GetAccountData(AccountDataType type) { return &m_accountData[type]; } AccountData* GetAccountData(AccountDataType type) { return &m_accountData[type]; }
void SetAccountData(AccountDataType type, time_t time_, std::string data); void SetAccountData(AccountDataType type, time_t time_, std::string data);
void SendAccountDataTimes(uint32 mask); void SendAccountDataTimes(uint32 mask);
void LoadGlobalAccountData(); void LoadGlobalAccountData();
@ -333,33 +333,33 @@ class MANGOS_DLL_SPEC WorldSession
void LoadTutorialsData(); void LoadTutorialsData();
void SendTutorialsData(); void SendTutorialsData();
void SaveTutorialsData(); void SaveTutorialsData();
uint32 GetTutorialInt(uint32 intId ) uint32 GetTutorialInt(uint32 intId)
{ {
return m_Tutorials[intId]; return m_Tutorials[intId];
} }
void SetTutorialInt(uint32 intId, uint32 value) void SetTutorialInt(uint32 intId, uint32 value)
{ {
if(m_Tutorials[intId] != value) if (m_Tutorials[intId] != value)
{ {
m_Tutorials[intId] = value; m_Tutorials[intId] = value;
if(m_tutorialState == TUTORIALDATA_UNCHANGED) if (m_tutorialState == TUTORIALDATA_UNCHANGED)
m_tutorialState = TUTORIALDATA_CHANGED; m_tutorialState = TUTORIALDATA_CHANGED;
} }
} }
//used with item_page table //used with item_page table
bool SendItemInfo( uint32 itemid, WorldPacket data ); bool SendItemInfo(uint32 itemid, WorldPacket data);
//auction //auction
void SendAuctionHello(Unit *unit); void SendAuctionHello(Unit* unit);
void SendAuctionCommandResult(AuctionEntry *auc, AuctionAction Action, AuctionError ErrorCode, InventoryResult invError = EQUIP_ERR_OK); void SendAuctionCommandResult(AuctionEntry* auc, AuctionAction Action, AuctionError ErrorCode, InventoryResult invError = EQUIP_ERR_OK);
void SendAuctionBidderNotification(AuctionEntry *auction); void SendAuctionBidderNotification(AuctionEntry* auction);
void SendAuctionOwnerNotification(AuctionEntry *auction); void SendAuctionOwnerNotification(AuctionEntry* auction);
void SendAuctionRemovedNotification(AuctionEntry* auction); void SendAuctionRemovedNotification(AuctionEntry* auction);
static void SendAuctionOutbiddedMail(AuctionEntry *auction); static void SendAuctionOutbiddedMail(AuctionEntry* auction);
void SendAuctionCancelledToBidderMail(AuctionEntry *auction); void SendAuctionCancelledToBidderMail(AuctionEntry* auction);
void BuildListAuctionItems(std::vector<AuctionEntry*> const& auctions, WorldPacket& data, std::wstring const& searchedname, uint32 listfrom, uint32 levelmin, void BuildListAuctionItems(std::vector<AuctionEntry*> const& auctions, WorldPacket& data, std::wstring const& searchedname, uint32 listfrom, uint32 levelmin,
uint32 levelmax, uint32 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount, bool isFull); uint32 levelmax, uint32 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount, bool isFull);
AuctionHouseEntry const* GetCheckedAuctionHouseForAuctioneer(ObjectGuid guid); AuctionHouseEntry const* GetCheckedAuctionHouseForAuctioneer(ObjectGuid guid);
@ -369,18 +369,18 @@ class MANGOS_DLL_SPEC WorldSession
//Taxi //Taxi
void SendTaxiStatus(ObjectGuid guid); void SendTaxiStatus(ObjectGuid guid);
void SendTaxiMenu( Creature* unit ); void SendTaxiMenu(Creature* unit);
void SendDoFlight( uint32 mountDisplayId, uint32 path, uint32 pathNode = 0 ); void SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathNode = 0);
bool SendLearnNewTaxiNode( Creature* unit ); bool SendLearnNewTaxiNode(Creature* unit);
// Guild/Arena Team // Guild/Arena Team
void SendGuildCommandResult(uint32 typecmd, const std::string& str, uint32 cmdresult); void SendGuildCommandResult(uint32 typecmd, const std::string& str, uint32 cmdresult);
void SendArenaTeamCommandResult(uint32 team_action, const std::string& team, const std::string& player, uint32 error_id); void SendArenaTeamCommandResult(uint32 team_action, const std::string& team, const std::string& player, uint32 error_id);
void SendNotInArenaTeamPacket(uint8 type); void SendNotInArenaTeamPacket(uint8 type);
void SendPetitionShowList(ObjectGuid guid); void SendPetitionShowList(ObjectGuid guid);
void SendSaveGuildEmblem( uint32 msg ); void SendSaveGuildEmblem(uint32 msg);
void BuildPartyMemberStatsChangedPacket(Player *player, WorldPacket *data); void BuildPartyMemberStatsChangedPacket(Player* player, WorldPacket* data);
void DoLootRelease(ObjectGuid lguid); void DoLootRelease(ObjectGuid lguid);
@ -390,16 +390,16 @@ class MANGOS_DLL_SPEC WorldSession
// Locales // Locales
LocaleConstant GetSessionDbcLocale() const { return m_sessionDbcLocale; } LocaleConstant GetSessionDbcLocale() const { return m_sessionDbcLocale; }
int GetSessionDbLocaleIndex() const { return m_sessionDbLocaleIndex; } int GetSessionDbLocaleIndex() const { return m_sessionDbLocaleIndex; }
const char *GetMangosString(int32 entry) const; const char* GetMangosString(int32 entry) const;
uint32 GetLatency() const { return m_latency; } uint32 GetLatency() const { return m_latency; }
void SetLatency(uint32 latency) { m_latency = latency; } void SetLatency(uint32 latency) { m_latency = latency; }
uint32 getDialogStatus(Player *pPlayer, Object* questgiver, uint32 defstatus); uint32 getDialogStatus(Player* pPlayer, Object* questgiver, uint32 defstatus);
public: // opcodes handlers public: // opcodes handlers
void Handle_NULL(WorldPacket& recvPacket); // not used void Handle_NULL(WorldPacket& recvPacket); // not used
void Handle_EarlyProccess( WorldPacket& recvPacket);// just mark packets processed in WorldSocket::OnRead void Handle_EarlyProccess(WorldPacket& recvPacket); // just mark packets processed in WorldSocket::OnRead
void Handle_ServerSide(WorldPacket& recvPacket); // sever side only, can't be accepted from client void Handle_ServerSide(WorldPacket& recvPacket); // sever side only, can't be accepted from client
void Handle_Deprecated(WorldPacket& recvPacket); // never used anymore by client void Handle_Deprecated(WorldPacket& recvPacket); // never used anymore by client
@ -407,8 +407,8 @@ class MANGOS_DLL_SPEC WorldSession
void HandleCharDeleteOpcode(WorldPacket& recvPacket); void HandleCharDeleteOpcode(WorldPacket& recvPacket);
void HandleCharCreateOpcode(WorldPacket& recvPacket); void HandleCharCreateOpcode(WorldPacket& recvPacket);
void HandlePlayerLoginOpcode(WorldPacket& recvPacket); void HandlePlayerLoginOpcode(WorldPacket& recvPacket);
void HandleCharEnum(QueryResult * result); void HandleCharEnum(QueryResult* result);
void HandlePlayerLogin(LoginQueryHolder * holder); void HandlePlayerLogin(LoginQueryHolder* holder);
// played time // played time
void HandlePlayedTime(WorldPacket& recvPacket); void HandlePlayedTime(WorldPacket& recvPacket);
@ -424,11 +424,11 @@ class MANGOS_DLL_SPEC WorldSession
void HandleInspectHonorStatsOpcode(WorldPacket& recvPacket); void HandleInspectHonorStatsOpcode(WorldPacket& recvPacket);
void HandleMoveWaterWalkAck(WorldPacket& recvPacket); void HandleMoveWaterWalkAck(WorldPacket& recvPacket);
void HandleFeatherFallAck(WorldPacket &recv_data); void HandleFeatherFallAck(WorldPacket& recv_data);
void HandleMoveHoverAck( WorldPacket & recv_data ); void HandleMoveHoverAck(WorldPacket& recv_data);
void HandleMountSpecialAnimOpcode(WorldPacket &recvdata); void HandleMountSpecialAnimOpcode(WorldPacket& recvdata);
// character view // character view
void HandleShowingHelmOpcode(WorldPacket& recv_data); void HandleShowingHelmOpcode(WorldPacket& recv_data);
@ -441,7 +441,7 @@ class MANGOS_DLL_SPEC WorldSession
void HandleMoveKnockBackAck(WorldPacket& recvPacket); void HandleMoveKnockBackAck(WorldPacket& recvPacket);
void HandleMoveTeleportAckOpcode(WorldPacket& recvPacket); void HandleMoveTeleportAckOpcode(WorldPacket& recvPacket);
void HandleForceSpeedChangeAckOpcodes( WorldPacket & recv_data ); void HandleForceSpeedChangeAckOpcodes(WorldPacket& recv_data);
void HandlePingOpcode(WorldPacket& recvPacket); void HandlePingOpcode(WorldPacket& recvPacket);
void HandleAuthSessionOpcode(WorldPacket& recvPacket); void HandleAuthSessionOpcode(WorldPacket& recvPacket);
@ -474,10 +474,10 @@ class MANGOS_DLL_SPEC WorldSession
void HandleEmoteOpcode(WorldPacket& recvPacket); void HandleEmoteOpcode(WorldPacket& recvPacket);
void HandleContactListOpcode(WorldPacket& recvPacket); void HandleContactListOpcode(WorldPacket& recvPacket);
void HandleAddFriendOpcode(WorldPacket& recvPacket); void HandleAddFriendOpcode(WorldPacket& recvPacket);
static void HandleAddFriendOpcodeCallBack(QueryResult *result, uint32 accountId, std::string friendNote); static void HandleAddFriendOpcodeCallBack(QueryResult* result, uint32 accountId, std::string friendNote);
void HandleDelFriendOpcode(WorldPacket& recvPacket); void HandleDelFriendOpcode(WorldPacket& recvPacket);
void HandleAddIgnoreOpcode(WorldPacket& recvPacket); void HandleAddIgnoreOpcode(WorldPacket& recvPacket);
static void HandleAddIgnoreOpcodeCallBack(QueryResult *result, uint32 accountId); static void HandleAddIgnoreOpcodeCallBack(QueryResult* result, uint32 accountId);
void HandleDelIgnoreOpcode(WorldPacket& recvPacket); void HandleDelIgnoreOpcode(WorldPacket& recvPacket);
void HandleSetContactNotesOpcode(WorldPacket& recvPacket); void HandleSetContactNotesOpcode(WorldPacket& recvPacket);
void HandleBugOpcode(WorldPacket& recvPacket); void HandleBugOpcode(WorldPacket& recvPacket);
@ -486,9 +486,9 @@ class MANGOS_DLL_SPEC WorldSession
void HandleAreaTriggerOpcode(WorldPacket& recvPacket); void HandleAreaTriggerOpcode(WorldPacket& recvPacket);
void HandleSetFactionAtWarOpcode( WorldPacket & recv_data ); void HandleSetFactionAtWarOpcode(WorldPacket& recv_data);
void HandleSetWatchedFactionOpcode(WorldPacket & recv_data); void HandleSetWatchedFactionOpcode(WorldPacket& recv_data);
void HandleSetFactionInactiveOpcode(WorldPacket & recv_data); void HandleSetFactionInactiveOpcode(WorldPacket& recv_data);
void HandleUpdateAccountData(WorldPacket& recvPacket); void HandleUpdateAccountData(WorldPacket& recvPacket);
void HandleRequestAccountData(WorldPacket& recvPacket); void HandleRequestAccountData(WorldPacket& recvPacket);
@ -509,12 +509,12 @@ class MANGOS_DLL_SPEC WorldSession
void HandleMoveWorldportAckOpcode(); // for server-side calls void HandleMoveWorldportAckOpcode(); // for server-side calls
void HandleMovementOpcodes(WorldPacket& recvPacket); void HandleMovementOpcodes(WorldPacket& recvPacket);
void HandleSetActiveMoverOpcode(WorldPacket &recv_data); void HandleSetActiveMoverOpcode(WorldPacket& recv_data);
void HandleMoveNotActiveMoverOpcode(WorldPacket &recv_data); void HandleMoveNotActiveMoverOpcode(WorldPacket& recv_data);
void HandleDismissControlledVehicle(WorldPacket &recv_data); void HandleDismissControlledVehicle(WorldPacket& recv_data);
void HandleMoveTimeSkippedOpcode(WorldPacket &recv_data); void HandleMoveTimeSkippedOpcode(WorldPacket& recv_data);
void HandleRequestRaidInfoOpcode( WorldPacket & recv_data ); void HandleRequestRaidInfoOpcode(WorldPacket& recv_data);
void HandleGroupInviteOpcode(WorldPacket& recvPacket); void HandleGroupInviteOpcode(WorldPacket& recvPacket);
void HandleGroupAcceptOpcode(WorldPacket& recvPacket); void HandleGroupAcceptOpcode(WorldPacket& recvPacket);
@ -523,18 +523,18 @@ class MANGOS_DLL_SPEC WorldSession
void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket); void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket);
void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket); void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket);
void HandleGroupDisbandOpcode(WorldPacket& recvPacket); void HandleGroupDisbandOpcode(WorldPacket& recvPacket);
void HandleOptOutOfLootOpcode( WorldPacket &recv_data ); void HandleOptOutOfLootOpcode(WorldPacket& recv_data);
void HandleSetAllowLowLevelRaidOpcode( WorldPacket & recv_data ); void HandleSetAllowLowLevelRaidOpcode(WorldPacket& recv_data);
void HandleLootMethodOpcode(WorldPacket& recvPacket); void HandleLootMethodOpcode(WorldPacket& recvPacket);
void HandleLootRoll( WorldPacket &recv_data ); void HandleLootRoll(WorldPacket& recv_data);
void HandleRequestPartyMemberStatsOpcode( WorldPacket &recv_data ); void HandleRequestPartyMemberStatsOpcode(WorldPacket& recv_data);
void HandleRaidTargetUpdateOpcode( WorldPacket & recv_data ); void HandleRaidTargetUpdateOpcode(WorldPacket& recv_data);
void HandleRaidReadyCheckOpcode( WorldPacket & recv_data ); void HandleRaidReadyCheckOpcode(WorldPacket& recv_data);
void HandleRaidReadyCheckFinishedOpcode( WorldPacket & recv_data ); void HandleRaidReadyCheckFinishedOpcode(WorldPacket& recv_data);
void HandleGroupRaidConvertOpcode( WorldPacket & recv_data ); void HandleGroupRaidConvertOpcode(WorldPacket& recv_data);
void HandleGroupChangeSubGroupOpcode( WorldPacket & recv_data ); void HandleGroupChangeSubGroupOpcode(WorldPacket& recv_data);
void HandleGroupAssistantLeaderOpcode( WorldPacket & recv_data ); void HandleGroupAssistantLeaderOpcode(WorldPacket& recv_data);
void HandlePartyAssignmentOpcode( WorldPacket & recv_data ); void HandlePartyAssignmentOpcode(WorldPacket& recv_data);
void HandlePetitionBuyOpcode(WorldPacket& recv_data); void HandlePetitionBuyOpcode(WorldPacket& recv_data);
void HandlePetitionShowSignOpcode(WorldPacket& recv_data); void HandlePetitionShowSignOpcode(WorldPacket& recv_data);
@ -607,30 +607,30 @@ class MANGOS_DLL_SPEC WorldSession
void HandleUnacceptTradeOpcode(WorldPacket& recvPacket); void HandleUnacceptTradeOpcode(WorldPacket& recvPacket);
void HandleAuctionHelloOpcode(WorldPacket& recvPacket); void HandleAuctionHelloOpcode(WorldPacket& recvPacket);
void HandleAuctionListItems( WorldPacket & recv_data ); void HandleAuctionListItems(WorldPacket& recv_data);
void HandleAuctionListBidderItems( WorldPacket & recv_data ); void HandleAuctionListBidderItems(WorldPacket& recv_data);
void HandleAuctionSellItem( WorldPacket & recv_data ); void HandleAuctionSellItem(WorldPacket& recv_data);
void HandleAuctionRemoveItem( WorldPacket & recv_data ); void HandleAuctionRemoveItem(WorldPacket& recv_data);
void HandleAuctionListOwnerItems( WorldPacket & recv_data ); void HandleAuctionListOwnerItems(WorldPacket& recv_data);
void HandleAuctionPlaceBid( WorldPacket & recv_data ); void HandleAuctionPlaceBid(WorldPacket& recv_data);
void AuctionBind( uint32 price, AuctionEntry * auction, Player * pl, Player* auction_owner ); void AuctionBind(uint32 price, AuctionEntry* auction, Player* pl, Player* auction_owner);
void HandleAuctionListPendingSales( WorldPacket & recv_data ); void HandleAuctionListPendingSales(WorldPacket& recv_data);
void HandleGetMailList( WorldPacket & recv_data ); void HandleGetMailList(WorldPacket& recv_data);
void HandleSendMail( WorldPacket & recv_data ); void HandleSendMail(WorldPacket& recv_data);
void HandleMailTakeMoney( WorldPacket & recv_data ); void HandleMailTakeMoney(WorldPacket& recv_data);
void HandleMailTakeItem( WorldPacket & recv_data ); void HandleMailTakeItem(WorldPacket& recv_data);
void HandleMailMarkAsRead( WorldPacket & recv_data ); void HandleMailMarkAsRead(WorldPacket& recv_data);
void HandleMailReturnToSender( WorldPacket & recv_data ); void HandleMailReturnToSender(WorldPacket& recv_data);
void HandleMailDelete( WorldPacket & recv_data ); void HandleMailDelete(WorldPacket& recv_data);
void HandleItemTextQuery( WorldPacket & recv_data); void HandleItemTextQuery(WorldPacket& recv_data);
void HandleMailCreateTextItem(WorldPacket & recv_data ); void HandleMailCreateTextItem(WorldPacket& recv_data);
void HandleQueryNextMailTime(WorldPacket & recv_data ); void HandleQueryNextMailTime(WorldPacket& recv_data);
void HandleCancelChanneling(WorldPacket & recv_data ); void HandleCancelChanneling(WorldPacket& recv_data);
void SendItemPageInfo( ItemPrototype *itemProto ); void SendItemPageInfo(ItemPrototype* itemProto);
void HandleSplitItemOpcode(WorldPacket& recvPacket); void HandleSplitItemOpcode(WorldPacket& recvPacket);
void HandleSwapInvItemOpcode(WorldPacket& recvPacket); void HandleSwapInvItemOpcode(WorldPacket& recvPacket);
void HandleDestroyItemOpcode(WorldPacket& recvPacket); void HandleDestroyItemOpcode(WorldPacket& recvPacket);
@ -642,9 +642,9 @@ class MANGOS_DLL_SPEC WorldSession
void HandleListInventoryOpcode(WorldPacket& recvPacket); void HandleListInventoryOpcode(WorldPacket& recvPacket);
void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket); void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket);
void HandleReadItemOpcode(WorldPacket& recvPacket); void HandleReadItemOpcode(WorldPacket& recvPacket);
void HandleAutoEquipItemSlotOpcode(WorldPacket & recvPacket); void HandleAutoEquipItemSlotOpcode(WorldPacket& recvPacket);
void HandleSwapItem( WorldPacket & recvPacket); void HandleSwapItem(WorldPacket& recvPacket);
void HandleBuybackItem(WorldPacket & recvPacket); void HandleBuybackItem(WorldPacket& recvPacket);
void HandleAutoBankItemOpcode(WorldPacket& recvPacket); void HandleAutoBankItemOpcode(WorldPacket& recvPacket);
void HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket); void HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket);
void HandleWrapItemOpcode(WorldPacket& recvPacket); void HandleWrapItemOpcode(WorldPacket& recvPacket);
@ -674,8 +674,8 @@ class MANGOS_DLL_SPEC WorldSession
void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket); void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket);
void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket); void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket);
void HandleQuestQueryOpcode(WorldPacket& recvPacket); void HandleQuestQueryOpcode(WorldPacket& recvPacket);
void HandleQuestgiverCancel(WorldPacket& recv_data ); void HandleQuestgiverCancel(WorldPacket& recv_data);
void HandleQuestLogSwapQuest(WorldPacket& recv_data ); void HandleQuestLogSwapQuest(WorldPacket& recv_data);
void HandleQuestLogRemoveQuest(WorldPacket& recv_data); void HandleQuestLogRemoveQuest(WorldPacket& recv_data);
void HandleQuestConfirmAccept(WorldPacket& recv_data); void HandleQuestConfirmAccept(WorldPacket& recv_data);
void HandleQuestgiverCompleteQuest(WorldPacket& recv_data); void HandleQuestgiverCompleteQuest(WorldPacket& recv_data);
@ -694,9 +694,9 @@ class MANGOS_DLL_SPEC WorldSession
void HandleTextEmoteOpcode(WorldPacket& recvPacket); void HandleTextEmoteOpcode(WorldPacket& recvPacket);
void HandleChatIgnoredOpcode(WorldPacket& recvPacket); void HandleChatIgnoredOpcode(WorldPacket& recvPacket);
void HandleReclaimCorpseOpcode( WorldPacket& recvPacket ); void HandleReclaimCorpseOpcode(WorldPacket& recvPacket);
void HandleCorpseQueryOpcode( WorldPacket& recvPacket ); void HandleCorpseQueryOpcode(WorldPacket& recvPacket);
void HandleCorpseMapPositionQueryOpcode( WorldPacket& recvPacket ); void HandleCorpseMapPositionQueryOpcode(WorldPacket& recvPacket);
void HandleResurrectResponseOpcode(WorldPacket& recvPacket); void HandleResurrectResponseOpcode(WorldPacket& recvPacket);
void HandleSummonResponseOpcode(WorldPacket& recv_data); void HandleSummonResponseOpcode(WorldPacket& recv_data);
@ -726,43 +726,43 @@ class MANGOS_DLL_SPEC WorldSession
void HandlePageQuerySkippedOpcode(WorldPacket& recvPacket); void HandlePageQuerySkippedOpcode(WorldPacket& recvPacket);
void HandlePageTextQueryOpcode(WorldPacket& recvPacket); void HandlePageTextQueryOpcode(WorldPacket& recvPacket);
void HandleTutorialFlagOpcode ( WorldPacket & recv_data ); void HandleTutorialFlagOpcode(WorldPacket& recv_data);
void HandleTutorialClearOpcode( WorldPacket & recv_data ); void HandleTutorialClearOpcode(WorldPacket& recv_data);
void HandleTutorialResetOpcode( WorldPacket & recv_data ); void HandleTutorialResetOpcode(WorldPacket& recv_data);
//Pet //Pet
void HandlePetAction( WorldPacket & recv_data ); void HandlePetAction(WorldPacket& recv_data);
void HandlePetStopAttack(WorldPacket& recv_data); void HandlePetStopAttack(WorldPacket& recv_data);
void HandlePetNameQueryOpcode( WorldPacket & recv_data ); void HandlePetNameQueryOpcode(WorldPacket& recv_data);
void HandlePetSetAction( WorldPacket & recv_data ); void HandlePetSetAction(WorldPacket& recv_data);
void HandlePetAbandon( WorldPacket & recv_data ); void HandlePetAbandon(WorldPacket& recv_data);
void HandlePetRename( WorldPacket & recv_data ); void HandlePetRename(WorldPacket& recv_data);
void HandlePetCancelAuraOpcode( WorldPacket& recvPacket ); void HandlePetCancelAuraOpcode(WorldPacket& recvPacket);
void HandlePetUnlearnOpcode( WorldPacket& recvPacket ); void HandlePetUnlearnOpcode(WorldPacket& recvPacket);
void HandlePetSpellAutocastOpcode( WorldPacket& recvPacket ); void HandlePetSpellAutocastOpcode(WorldPacket& recvPacket);
void HandlePetCastSpellOpcode( WorldPacket& recvPacket ); void HandlePetCastSpellOpcode(WorldPacket& recvPacket);
void HandlePetLearnTalent( WorldPacket& recvPacket ); void HandlePetLearnTalent(WorldPacket& recvPacket);
void HandleLearnPreviewTalentsPet( WorldPacket& recvPacket ); void HandleLearnPreviewTalentsPet(WorldPacket& recvPacket);
void HandleSetActionBarTogglesOpcode(WorldPacket& recv_data); void HandleSetActionBarTogglesOpcode(WorldPacket& recv_data);
void HandleCharRenameOpcode(WorldPacket& recv_data); void HandleCharRenameOpcode(WorldPacket& recv_data);
static void HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname); static void HandleChangePlayerNameOpcodeCallBack(QueryResult* result, uint32 accountId, std::string newname);
void HandleSetPlayerDeclinedNamesOpcode(WorldPacket& recv_data); void HandleSetPlayerDeclinedNamesOpcode(WorldPacket& recv_data);
void HandleTotemDestroyed(WorldPacket& recv_data); void HandleTotemDestroyed(WorldPacket& recv_data);
//BattleGround //BattleGround
void HandleBattlemasterHelloOpcode(WorldPacket &recv_data); void HandleBattlemasterHelloOpcode(WorldPacket& recv_data);
void HandleBattlemasterJoinOpcode(WorldPacket &recv_data); void HandleBattlemasterJoinOpcode(WorldPacket& recv_data);
void HandleBattleGroundPlayerPositionsOpcode(WorldPacket& recv_data); void HandleBattleGroundPlayerPositionsOpcode(WorldPacket& recv_data);
void HandlePVPLogDataOpcode( WorldPacket &recv_data ); void HandlePVPLogDataOpcode(WorldPacket& recv_data);
void HandleBattlefieldStatusOpcode(WorldPacket &recv_data); void HandleBattlefieldStatusOpcode(WorldPacket& recv_data);
void HandleBattleFieldPortOpcode( WorldPacket &recv_data ); void HandleBattleFieldPortOpcode(WorldPacket& recv_data);
void HandleBattlefieldListOpcode( WorldPacket &recv_data ); void HandleBattlefieldListOpcode(WorldPacket& recv_data);
void HandleLeaveBattlefieldOpcode( WorldPacket &recv_data ); void HandleLeaveBattlefieldOpcode(WorldPacket& recv_data);
void HandleBattlemasterJoinArena( WorldPacket &recv_data ); void HandleBattlemasterJoinArena(WorldPacket& recv_data);
void HandleReportPvPAFK( WorldPacket &recv_data ); void HandleReportPvPAFK(WorldPacket& recv_data);
void HandleWardenDataOpcode(WorldPacket& recv_data); void HandleWardenDataOpcode(WorldPacket& recv_data);
void HandleWorldTeleportOpcode(WorldPacket& recv_data); void HandleWorldTeleportOpcode(WorldPacket& recv_data);
@ -782,7 +782,7 @@ class MANGOS_DLL_SPEC WorldSession
void HandleTimeSyncResp(WorldPacket& recv_data); void HandleTimeSyncResp(WorldPacket& recv_data);
void HandleWhoisOpcode(WorldPacket& recv_data); void HandleWhoisOpcode(WorldPacket& recv_data);
void HandleResetInstancesOpcode(WorldPacket& recv_data); void HandleResetInstancesOpcode(WorldPacket& recv_data);
void HandleHearthandResurrect(WorldPacket & recv_data); void HandleHearthandResurrect(WorldPacket& recv_data);
// Arena Team // Arena Team
void HandleInspectArenaTeamsOpcode(WorldPacket& recv_data); void HandleInspectArenaTeamsOpcode(WorldPacket& recv_data);
@ -809,7 +809,7 @@ class MANGOS_DLL_SPEC WorldSession
void HandleCancelTempEnchantmentOpcode(WorldPacket& recv_data); void HandleCancelTempEnchantmentOpcode(WorldPacket& recv_data);
void HandleItemRefundInfoRequest(WorldPacket& recv_data); void HandleItemRefundInfoRequest(WorldPacket& recv_data);
void HandleChannelVoiceOnOpcode(WorldPacket & recv_data); void HandleChannelVoiceOnOpcode(WorldPacket& recv_data);
void HandleVoiceSessionEnableOpcode(WorldPacket& recv_data); void HandleVoiceSessionEnableOpcode(WorldPacket& recv_data);
void HandleSetActiveVoiceChannel(WorldPacket& recv_data); void HandleSetActiveVoiceChannel(WorldPacket& recv_data);
void HandleSetTaxiBenchmarkOpcode(WorldPacket& recv_data); void HandleSetTaxiBenchmarkOpcode(WorldPacket& recv_data);
@ -864,15 +864,15 @@ class MANGOS_DLL_SPEC WorldSession
bool VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGuid const& guid) const; bool VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGuid const& guid) const;
void HandleMoverRelocation(MovementInfo& movementInfo); void HandleMoverRelocation(MovementInfo& movementInfo);
void ExecuteOpcode( OpcodeHandler const& opHandle, WorldPacket* packet ); void ExecuteOpcode(OpcodeHandler const& opHandle, WorldPacket* packet);
// logging helper // logging helper
void LogUnexpectedOpcode(WorldPacket *packet, const char * reason); void LogUnexpectedOpcode(WorldPacket* packet, const char* reason);
void LogUnprocessedTail(WorldPacket *packet); void LogUnprocessedTail(WorldPacket* packet);
uint32 m_GUIDLow; // set logged or recently logout player (while m_playerRecentlyLogout set) uint32 m_GUIDLow; // set logged or recently logout player (while m_playerRecentlyLogout set)
Player *_player; Player* _player;
WorldSocket *m_Socket; WorldSocket* m_Socket;
std::string m_Address; std::string m_Address;
AccountTypes _security; AccountTypes _security;

File diff suppressed because it is too large Load diff

View file

@ -103,75 +103,75 @@ class WorldSocket : protected WorldHandler
typedef ACE_Guard<LockType> GuardType; typedef ACE_Guard<LockType> GuardType;
/// Check if socket is closed. /// Check if socket is closed.
bool IsClosed (void) const; bool IsClosed(void) const;
/// Close the socket. /// Close the socket.
void CloseSocket (void); void CloseSocket(void);
/// Get address of connected peer. /// Get address of connected peer.
const std::string& GetRemoteAddress (void) const; const std::string& GetRemoteAddress(void) const;
/// Send A packet on the socket, this function is reentrant. /// Send A packet on the socket, this function is reentrant.
/// @param pct packet to send /// @param pct packet to send
/// @return -1 of failure /// @return -1 of failure
int SendPacket (const WorldPacket& pct); int SendPacket(const WorldPacket& pct);
/// Add reference to this object. /// Add reference to this object.
long AddReference (void); long AddReference(void);
/// Remove reference to this object. /// Remove reference to this object.
long RemoveReference (void); long RemoveReference(void);
/// Return the session key /// Return the session key
BigNumber& GetSessionKey() { return m_s; } BigNumber& GetSessionKey() { return m_s; }
protected: protected:
/// things called by ACE framework. /// things called by ACE framework.
WorldSocket (void); WorldSocket(void);
virtual ~WorldSocket (void); virtual ~WorldSocket(void);
/// Called on open ,the void* is the acceptor. /// Called on open ,the void* is the acceptor.
virtual int open (void *); virtual int open(void*);
/// Called on failures inside of the acceptor, don't call from your code. /// Called on failures inside of the acceptor, don't call from your code.
virtual int close (int); virtual int close(int);
/// Called when we can read from the socket. /// Called when we can read from the socket.
virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE); virtual int handle_input(ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when the socket can write. /// Called when the socket can write.
virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE); virtual int handle_output(ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when connection is closed or error happens. /// Called when connection is closed or error happens.
virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, virtual int handle_close(ACE_HANDLE = ACE_INVALID_HANDLE,
ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK);
/// Called by WorldSocketMgr/ReactorRunnable. /// Called by WorldSocketMgr/ReactorRunnable.
int Update (void); int Update(void);
private: private:
/// Helper functions for processing incoming data. /// Helper functions for processing incoming data.
int handle_input_header (void); int handle_input_header(void);
int handle_input_payload (void); int handle_input_payload(void);
int handle_input_missing_data (void); int handle_input_missing_data(void);
/// Help functions to mark/unmark the socket for output. /// Help functions to mark/unmark the socket for output.
/// @param g the guard is for m_OutBufferLock, the function will release it /// @param g the guard is for m_OutBufferLock, the function will release it
int cancel_wakeup_output (GuardType& g); int cancel_wakeup_output(GuardType& g);
int schedule_wakeup_output (GuardType& g); int schedule_wakeup_output(GuardType& g);
/// Drain the queue if its not empty. /// Drain the queue if its not empty.
int handle_output_queue (GuardType& g); int handle_output_queue(GuardType& g);
/// process one incoming packet. /// process one incoming packet.
/// @param new_pct received packet ,note that you need to delete it. /// @param new_pct received packet ,note that you need to delete it.
int ProcessIncoming (WorldPacket* new_pct); int ProcessIncoming(WorldPacket* new_pct);
/// Called by ProcessIncoming() on CMSG_AUTH_SESSION. /// Called by ProcessIncoming() on CMSG_AUTH_SESSION.
int HandleAuthSession (WorldPacket& recvPacket); int HandleAuthSession(WorldPacket& recvPacket);
/// Called by ProcessIncoming() on CMSG_PING. /// Called by ProcessIncoming() on CMSG_PING.
int HandlePing (WorldPacket& recvPacket); int HandlePing(WorldPacket& recvPacket);
private: private:
/// Time in which the last ping was received /// Time in which the last ping was received
@ -207,7 +207,7 @@ class WorldSocket : protected WorldHandler
LockType m_OutBufferLock; LockType m_OutBufferLock;
/// Buffer used for writing output. /// Buffer used for writing output.
ACE_Message_Block *m_OutBuffer; ACE_Message_Block* m_OutBuffer;
/// Size of the m_OutBuffer. /// Size of the m_OutBuffer.
size_t m_OutBufferSize; size_t m_OutBufferSize;

View file

@ -53,25 +53,25 @@ class ReactorRunnable : protected ACE_Task_Base
{ {
public: public:
ReactorRunnable() : ReactorRunnable() :
m_Reactor (0), m_Reactor(0),
m_Connections (0), m_Connections(0),
m_ThreadId (-1) m_ThreadId(-1)
{ {
ACE_Reactor_Impl* imp = 0; ACE_Reactor_Impl* imp = 0;
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) #if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
imp = new ACE_Dev_Poll_Reactor(); imp = new ACE_Dev_Poll_Reactor();
imp->max_notify_iterations(128); imp->max_notify_iterations(128);
imp->restart(1); imp->restart(1);
#else #else
imp = new ACE_TP_Reactor(); imp = new ACE_TP_Reactor();
imp->max_notify_iterations(128); imp->max_notify_iterations(128);
#endif #endif
m_Reactor = new ACE_Reactor(imp, 1); m_Reactor = new ACE_Reactor(imp, 1);
} }
@ -102,17 +102,17 @@ class ReactorRunnable : protected ACE_Task_Base
long Connections() long Connections()
{ {
return static_cast<long> (m_Connections.value()); return static_cast<long>(m_Connections.value());
} }
int AddSocket (WorldSocket* sock) int AddSocket(WorldSocket* sock)
{ {
ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, m_NewSockets_Lock, -1); ACE_GUARD_RETURN(ACE_Thread_Mutex, Guard, m_NewSockets_Lock, -1);
++m_Connections; ++m_Connections;
sock->AddReference(); sock->AddReference();
sock->reactor (m_Reactor); sock->reactor(m_Reactor);
m_NewSockets.insert (sock); m_NewSockets.insert(sock);
return 0; return 0;
} }
@ -125,7 +125,7 @@ class ReactorRunnable : protected ACE_Task_Base
protected: protected:
void AddNewSockets() void AddNewSockets()
{ {
ACE_GUARD (ACE_Thread_Mutex, Guard, m_NewSockets_Lock); ACE_GUARD(ACE_Thread_Mutex, Guard, m_NewSockets_Lock);
if (m_NewSockets.empty()) if (m_NewSockets.empty())
return; return;
@ -148,7 +148,7 @@ class ReactorRunnable : protected ACE_Task_Base
virtual int svc() virtual int svc()
{ {
DEBUG_LOG ("Network Thread Starting"); DEBUG_LOG("Network Thread Starting");
WorldDatabase.ThreadStart(); WorldDatabase.ThreadStart();
@ -160,9 +160,9 @@ class ReactorRunnable : protected ACE_Task_Base
{ {
// dont be too smart to move this outside the loop // dont be too smart to move this outside the loop
// the run_reactor_event_loop will modify interval // the run_reactor_event_loop will modify interval
ACE_Time_Value interval (0, 10000); ACE_Time_Value interval(0, 10000);
if (m_Reactor->run_reactor_event_loop (interval) == -1) if (m_Reactor->run_reactor_event_loop(interval) == -1)
break; break;
AddNewSockets(); AddNewSockets();
@ -185,7 +185,7 @@ class ReactorRunnable : protected ACE_Task_Base
WorldDatabase.ThreadEnd(); WorldDatabase.ThreadEnd();
DEBUG_LOG ("Network Thread Exitting"); DEBUG_LOG("Network Thread Exitting");
return 0; return 0;
} }
@ -219,23 +219,23 @@ WorldSocketMgr::~WorldSocketMgr()
if (m_NetThreads) if (m_NetThreads)
delete [] m_NetThreads; delete [] m_NetThreads;
if(m_Acceptor) if (m_Acceptor)
delete m_Acceptor; delete m_Acceptor;
} }
int WorldSocketMgr::StartReactiveIO (ACE_UINT16 port, const char* address) int WorldSocketMgr::StartReactiveIO(ACE_UINT16 port, const char* address)
{ {
m_UseNoDelay = sConfig.GetBoolDefault ("Network.TcpNodelay", true); m_UseNoDelay = sConfig.GetBoolDefault("Network.TcpNodelay", true);
int num_threads = sConfig.GetIntDefault ("Network.Threads", 1); int num_threads = sConfig.GetIntDefault("Network.Threads", 1);
if (num_threads <= 0) if (num_threads <= 0)
{ {
sLog.outError ("Network.Threads is wrong in your config file"); sLog.outError("Network.Threads is wrong in your config file");
return -1; return -1;
} }
m_NetThreadsCount = static_cast<size_t> (num_threads + 1); m_NetThreadsCount = static_cast<size_t>(num_threads + 1);
m_NetThreads = new ReactorRunnable[m_NetThreadsCount]; m_NetThreads = new ReactorRunnable[m_NetThreadsCount];
@ -248,18 +248,18 @@ int WorldSocketMgr::StartReactiveIO (ACE_UINT16 port, const char* address)
if (m_SockOutUBuff <= 0) if (m_SockOutUBuff <= 0)
{ {
sLog.outError ("Network.OutUBuff is wrong in your config file"); sLog.outError("Network.OutUBuff is wrong in your config file");
return -1; return -1;
} }
WorldSocket::Acceptor* acc = new WorldSocket::Acceptor; WorldSocket::Acceptor* acc = new WorldSocket::Acceptor;
m_Acceptor = acc; m_Acceptor = acc;
ACE_INET_Addr listen_addr (port, address); ACE_INET_Addr listen_addr(port, address);
if (acc->open (listen_addr, m_NetThreads[0].GetReactor(), ACE_NONBLOCK) == -1) if (acc->open(listen_addr, m_NetThreads[0].GetReactor(), ACE_NONBLOCK) == -1)
{ {
sLog.outError ("Failed to open acceptor, check if the port is free"); sLog.outError("Failed to open acceptor, check if the port is free");
return -1; return -1;
} }
@ -269,15 +269,15 @@ int WorldSocketMgr::StartReactiveIO (ACE_UINT16 port, const char* address)
return 0; return 0;
} }
int WorldSocketMgr::StartNetwork (ACE_UINT16 port, std::string& address) int WorldSocketMgr::StartNetwork(ACE_UINT16 port, std::string& address)
{ {
m_addr = address; m_addr = address;
m_port = port; m_port = port;
if (!sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG)) if (!sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
ACE_Log_Msg::instance()->priority_mask (LM_ERROR, ACE_Log_Msg::PROCESS); ACE_Log_Msg::instance()->priority_mask(LM_ERROR, ACE_Log_Msg::PROCESS);
if (StartReactiveIO (port, address.c_str()) == -1) if (StartReactiveIO(port, address.c_str()) == -1)
return -1; return -1;
return 0; return 0;
@ -318,7 +318,7 @@ int WorldSocketMgr::OnSocketOpen(WorldSocket* sock)
{ {
if (sock->peer().set_option(SOL_SOCKET, SO_SNDBUF, (void*)&m_SockOutKBuff, sizeof(int)) == -1 && errno != ENOTSUP) if (sock->peer().set_option(SOL_SOCKET, SO_SNDBUF, (void*)&m_SockOutKBuff, sizeof(int)) == -1 && errno != ENOTSUP)
{ {
sLog.outError ("WorldSocketMgr::OnSocketOpen set_option SO_SNDBUF"); sLog.outError("WorldSocketMgr::OnSocketOpen set_option SO_SNDBUF");
return -1; return -1;
} }
} }
@ -328,25 +328,25 @@ int WorldSocketMgr::OnSocketOpen(WorldSocket* sock)
// Set TCP_NODELAY. // Set TCP_NODELAY.
if (m_UseNoDelay) if (m_UseNoDelay)
{ {
if (sock->peer().set_option(ACE_IPPROTO_TCP, TCP_NODELAY, (void*)&ndoption, sizeof (int)) == -1) if (sock->peer().set_option(ACE_IPPROTO_TCP, TCP_NODELAY, (void*)&ndoption, sizeof(int)) == -1)
{ {
sLog.outError("WorldSocketMgr::OnSocketOpen: peer().set_option TCP_NODELAY errno = %s", ACE_OS::strerror(errno)); sLog.outError("WorldSocketMgr::OnSocketOpen: peer().set_option TCP_NODELAY errno = %s", ACE_OS::strerror(errno));
return -1; return -1;
} }
} }
sock->m_OutBufferSize = static_cast<size_t> (m_SockOutUBuff); sock->m_OutBufferSize = static_cast<size_t>(m_SockOutUBuff);
// we skip the Acceptor Thread // we skip the Acceptor Thread
size_t min = 1; size_t min = 1;
MANGOS_ASSERT (m_NetThreadsCount >= 1); MANGOS_ASSERT(m_NetThreadsCount >= 1);
for (size_t i = 1; i < m_NetThreadsCount; ++i) for (size_t i = 1; i < m_NetThreadsCount; ++i)
if (m_NetThreads[i].Connections() < m_NetThreads[min].Connections()) if (m_NetThreads[i].Connections() < m_NetThreads[min].Connections())
min = i; min = i;
return m_NetThreads[min].AddSocket (sock); return m_NetThreads[min].AddSocket(sock);
} }
WorldSocketMgr* WorldSocketMgr::Instance() WorldSocketMgr* WorldSocketMgr::Instance()