[7123] Cleanup in using STD's containers erase method.
[getmangos.git] / src / game / MovementHandler.cpp
blobfcf5a4661577be3140671ccf1af87c6a116515cd
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "WorldPacket.h"
21 #include "WorldSession.h"
22 #include "Opcodes.h"
23 #include "Log.h"
24 #include "World.h"
25 #include "Corpse.h"
26 #include "Player.h"
27 #include "MapManager.h"
28 #include "Transports.h"
29 #include "BattleGround.h"
30 #include "WaypointMovementGenerator.h"
31 #include "InstanceSaveMgr.h"
33 void WorldSession::HandleMoveWorldportAckOpcode( WorldPacket & /*recv_data*/ )
35 sLog.outDebug( "WORLD: got MSG_MOVE_WORLDPORT_ACK." );
36 HandleMoveWorldportAckOpcode();
39 void WorldSession::HandleMoveWorldportAckOpcode()
41 // get the teleport destination
42 WorldLocation &loc = GetPlayer()->GetTeleportDest();
44 // possible errors in the coordinate validity check
45 if(!MapManager::IsValidMapCoord(loc.mapid,loc.x,loc.y,loc.z,loc.o))
47 LogoutPlayer(false);
48 return;
51 // get the destination map entry, not the current one, this will fix homebind and reset greeting
52 MapEntry const* mEntry = sMapStore.LookupEntry(loc.mapid);
53 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(loc.mapid);
55 // reset instance validity, except if going to an instance inside an instance
56 if(GetPlayer()->m_InstanceValid == false && !mInstance)
57 GetPlayer()->m_InstanceValid = true;
59 GetPlayer()->SetSemaphoreTeleport(false);
61 // relocate the player to the teleport destination
62 GetPlayer()->SetMapId(loc.mapid);
63 GetPlayer()->Relocate(loc.x, loc.y, loc.z, loc.o);
65 // since the MapId is set before the GetInstance call, the InstanceId must be set to 0
66 // to let GetInstance() determine the proper InstanceId based on the player's binds
67 GetPlayer()->SetInstanceId(0);
69 // check this before Map::Add(player), because that will create the instance save!
70 bool reset_notify = (GetPlayer()->GetBoundInstance(GetPlayer()->GetMapId(), GetPlayer()->GetDifficulty()) == NULL);
72 GetPlayer()->SendInitialPacketsBeforeAddToMap();
73 // the CanEnter checks are done in TeleporTo but conditions may change
74 // while the player is in transit, for example the map may get full
75 if(!GetPlayer()->GetMap()->Add(GetPlayer()))
77 sLog.outDebug("WORLD: teleport of player %s (%d) to location %d,%f,%f,%f,%f failed", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), loc.mapid, loc.x, loc.y, loc.z, loc.o);
78 // teleport the player home
79 GetPlayer()->SetDontMove(false);
80 if(!GetPlayer()->TeleportTo(GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation()))
82 // the player must always be able to teleport home
83 sLog.outError("WORLD: failed to teleport player %s (%d) to homebind location %d,%f,%f,%f,%f!", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation());
84 assert(false);
86 return;
88 GetPlayer()->SendInitialPacketsAfterAddToMap();
90 // flight fast teleport case
91 if(GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE)
93 if(!_player->InBattleGround())
95 // short preparations to continue flight
96 GetPlayer()->SetDontMove(false);
97 FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top());
98 flight->Initialize(*GetPlayer());
99 return;
102 // battleground state prepare, stop flight
103 GetPlayer()->GetMotionMaster()->MovementExpired();
104 GetPlayer()->m_taxi.ClearTaxiDestinations();
107 // resurrect character at enter into instance where his corpse exist after add to map
108 Corpse *corpse = GetPlayer()->GetCorpse();
109 if (corpse && corpse->GetType() != CORPSE_BONES && corpse->GetMapId() == GetPlayer()->GetMapId())
111 if( mEntry->IsDungeon() )
113 GetPlayer()->ResurrectPlayer(0.5f);
114 GetPlayer()->SpawnCorpseBones();
115 GetPlayer()->SaveToDB();
119 if(mEntry->IsRaid() && mInstance)
121 if(reset_notify)
123 uint32 timeleft = sInstanceSaveManager.GetResetTimeFor(GetPlayer()->GetMapId()) - time(NULL);
124 GetPlayer()->SendInstanceResetWarning(GetPlayer()->GetMapId(), timeleft); // greeting at the entrance of the resort raid instance
128 // mount allow check
129 if(!mEntry->IsMountAllowed())
130 _player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
132 // battleground state prepare
133 // only add to bg group and object, if the player was invited (else he entered through command)
134 if(_player->InBattleGround() && _player->IsInvitedForBattleGroundInstance(_player->GetBattleGroundId()))
136 BattleGround *bg = _player->GetBattleGround();
137 if(bg)
139 bg->AddPlayer(_player);
140 if(bg->GetMapId() == _player->GetMapId()) // we teleported to bg
142 // get the team this way, because arenas might 'override' the teams.
143 uint32 team = bg->GetPlayerTeam(_player->GetGUID());
144 if(!team)
145 team = _player->GetTeam();
146 if(!bg->GetBgRaid(team)) // first player joined
148 Group *group = new Group;
149 bg->SetBgRaid(team, group);
150 group->Create(_player->GetGUIDLow(), _player->GetName());
152 else // raid already exist
154 bg->GetBgRaid(team)->AddMember(_player->GetGUID(), _player->GetName());
160 // honorless target
161 if(GetPlayer()->pvpInfo.inHostileArea)
162 GetPlayer()->CastSpell(GetPlayer(), 2479, true);
164 // resummon pet
165 if(GetPlayer()->m_temporaryUnsummonedPetNumber)
167 Pet* NewPet = new Pet;
168 if(!NewPet->LoadPetFromDB(GetPlayer(), 0, GetPlayer()->m_temporaryUnsummonedPetNumber, true))
169 delete NewPet;
171 GetPlayer()->m_temporaryUnsummonedPetNumber = 0;
174 GetPlayer()->SetDontMove(false);
177 void WorldSession::HandleMovementOpcodes( WorldPacket & recv_data )
179 uint32 opcode = recv_data.GetOpcode();
180 sLog.outDebug("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(opcode), opcode, opcode);
182 if(GetPlayer()->GetDontMove())
183 return;
185 /* extract packet */
186 MovementInfo movementInfo;
187 ReadMovementInfo(recv_data, &movementInfo);
188 /*----------------*/
190 if(recv_data.size() != recv_data.rpos())
192 sLog.outError("MovementHandler: player %s (guid %d, account %u) sent a packet (opcode %u) that is %u bytes larger than it should be. Kicked as cheater.", _player->GetName(), _player->GetGUIDLow(), _player->GetSession()->GetAccountId(), recv_data.GetOpcode(), recv_data.size() - recv_data.rpos());
193 KickPlayer();
194 return;
197 if (!MaNGOS::IsValidMapCoord(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o))
198 return;
200 /* handle special cases */
201 if (movementInfo.flags & MOVEMENTFLAG_ONTRANSPORT)
203 // transports size limited
204 // (also received at zeppelin leave by some reason with t_* as absolute in continent coordinates, can be safely skipped)
205 if( movementInfo.t_x > 50 || movementInfo.t_y > 50 || movementInfo.t_z > 50 )
206 return;
208 if( !MaNGOS::IsValidMapCoord(movementInfo.x+movementInfo.t_x, movementInfo.y+movementInfo.t_y,
209 movementInfo.z+movementInfo.t_z, movementInfo.o+movementInfo.t_o) )
210 return;
212 // if we boarded a transport, add us to it
213 if (!GetPlayer()->m_transport)
215 // elevators also cause the client to send MOVEMENTFLAG_ONTRANSPORT - just unmount if the guid can be found in the transport list
216 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
218 if ((*iter)->GetGUID() == movementInfo.t_guid)
220 GetPlayer()->m_transport = (*iter);
221 (*iter)->AddPassenger(GetPlayer());
222 break;
227 else if (GetPlayer()->m_transport) // if we were on a transport, leave
229 GetPlayer()->m_transport->RemovePassenger(GetPlayer());
230 GetPlayer()->m_transport = NULL;
231 movementInfo.t_x = 0.0f;
232 movementInfo.t_y = 0.0f;
233 movementInfo.t_z = 0.0f;
234 movementInfo.t_o = 0.0f;
235 movementInfo.t_time = 0;
236 movementInfo.t_seat = -1;
239 // fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map).
240 if (opcode == MSG_MOVE_FALL_LAND && !GetPlayer()->isInFlight())
242 // calculate total z distance of the fall
243 float z_diff = GetPlayer()->m_lastFallZ - movementInfo.z;
244 sLog.outDebug("zDiff = %f", z_diff);
245 Player *target = GetPlayer();
247 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
248 // 14.57 can be calculated by resolving damageperc formular below to 0
249 if (z_diff >= 14.57f && !target->isDead() && !target->isGameMaster() &&
250 !target->HasAuraType(SPELL_AURA_HOVER) && !target->HasAuraType(SPELL_AURA_FEATHER_FALL) &&
251 !target->HasAuraType(SPELL_AURA_FLY) && !target->IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
253 //Safe fall, fall height reduction
254 int32 safe_fall = target->GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
256 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
258 if(damageperc >0 )
260 uint32 damage = (uint32)(damageperc * target->GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
262 float height = movementInfo.z;
263 target->UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
265 if (damage > 0)
267 //Prevent fall damage from being more than the player maximum health
268 if (damage > target->GetMaxHealth())
269 damage = target->GetMaxHealth();
271 // Gust of Wind
272 if (target->GetDummyAura(43621))
273 damage = target->GetMaxHealth()/2;
275 target->EnvironmentalDamage(target->GetGUID(), DAMAGE_FALL, damage);
277 // recheck alive, might have died of EnvironmentalDamage
278 if (target->isAlive())
279 target->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
282 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
283 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, target->GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
288 if(((movementInfo.flags & MOVEMENTFLAG_SWIMMING) != 0) != GetPlayer()->IsInWater())
290 // now client not include swimming flag in case jumping under water
291 GetPlayer()->SetInWater( !GetPlayer()->IsInWater() || GetPlayer()->GetBaseMap()->IsUnderWater(movementInfo.x, movementInfo.y, movementInfo.z) );
294 /*----------------------*/
296 /* process position-change */
297 Unit *mover = _player->m_mover;
298 recv_data.put<uint32>(6, getMSTime()); // fix time, offset flags(4) + unk(2)
299 WorldPacket data(recv_data.GetOpcode(), (mover->GetPackGUID().size()+recv_data.size()));
300 data.append(_player->m_mover->GetPackGUID()); // use mover guid
301 data.append(recv_data.contents(), recv_data.size());
302 GetPlayer()->SendMessageToSet(&data, false);
304 if(!_player->GetCharmGUID()) // nothing is charmed
306 _player->SetPosition(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
307 _player->m_movementInfo = movementInfo;
308 _player->SetUnitMovementFlags(movementInfo.flags);
310 else
312 if(mover->GetTypeId() != TYPEID_PLAYER) // unit, creature, pet, vehicle...
314 if(Map *map = mover->GetMap())
315 map->CreatureRelocation((Creature*)mover, movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
316 mover->SetUnitMovementFlags(movementInfo.flags);
318 else // player
320 ((Player*)mover)->SetPosition(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
321 ((Player*)mover)->m_movementInfo = movementInfo;
322 ((Player*)mover)->SetUnitMovementFlags(movementInfo.flags);
326 if (GetPlayer()->m_lastFallTime >= movementInfo.fallTime || GetPlayer()->m_lastFallZ <=movementInfo.z || recv_data.GetOpcode() == MSG_MOVE_FALL_LAND)
327 GetPlayer()->SetFallInformation(movementInfo.fallTime, movementInfo.z);
329 if(GetPlayer()->isMovingOrTurning())
330 GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
332 if(movementInfo.z < -500.0f)
334 if(GetPlayer()->InBattleGround()
335 && GetPlayer()->GetBattleGround()
336 && GetPlayer()->GetBattleGround()->HandlePlayerUnderMap(_player))
338 // do nothing, the handle already did if returned true
340 else
342 // NOTE: this is actually called many times while falling
343 // even after the player has been teleported away
344 // TODO: discard movement packets after the player is rooted
345 if(GetPlayer()->isAlive())
347 GetPlayer()->EnvironmentalDamage(GetPlayer()->GetGUID(),DAMAGE_FALL_TO_VOID, GetPlayer()->GetMaxHealth());
348 // change the death state to CORPSE to prevent the death timer from
349 // starting in the next player update
350 GetPlayer()->KillPlayer();
351 GetPlayer()->BuildPlayerRepop();
354 // cancel the death timer here if started
355 GetPlayer()->RepopAtGraveyard();
360 void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recv_data)
362 sLog.outDebug("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(recv_data.GetOpcode()), recv_data.GetOpcode(), recv_data.GetOpcode());
364 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+8+4);
366 /* extract packet */
367 uint64 guid;
368 uint32 unk1;
369 float newspeed;
371 recv_data >> guid;
373 // now can skip not our packet
374 if(_player->GetGUID() != guid)
375 return;
377 // continue parse packet
379 recv_data >> unk1; // counter or moveEvent
381 MovementInfo movementInfo;
382 ReadMovementInfo(recv_data, &movementInfo);
384 // recheck
385 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+4);
387 recv_data >> newspeed;
388 /*----------------*/
390 // client ACK send one packet for mounted/run case and need skip all except last from its
391 // in other cases anti-cheat check can be fail in false case
392 UnitMoveType move_type;
393 UnitMoveType force_move_type;
395 static char const* move_type_name[MAX_MOVE_TYPE] = { "Walk", "Run", "RunBack", "Swim", "SwimBack", "TurnRate", "Flight", "FlightBack", "PitchRate" };
397 uint16 opcode = recv_data.GetOpcode();
398 switch(opcode)
400 case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: move_type = MOVE_WALK; force_move_type = MOVE_WALK; break;
401 case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: move_type = MOVE_RUN; force_move_type = MOVE_RUN; break;
402 case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: move_type = MOVE_RUN_BACK; force_move_type = MOVE_RUN_BACK; break;
403 case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: move_type = MOVE_SWIM; force_move_type = MOVE_SWIM; break;
404 case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: move_type = MOVE_SWIM_BACK; force_move_type = MOVE_SWIM_BACK; break;
405 case CMSG_FORCE_TURN_RATE_CHANGE_ACK: move_type = MOVE_TURN_RATE; force_move_type = MOVE_TURN_RATE; break;
406 case CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT; force_move_type = MOVE_FLIGHT; break;
407 case CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT_BACK; force_move_type = MOVE_FLIGHT_BACK; break;
408 case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: move_type = MOVE_PITCH_RATE; force_move_type = MOVE_PITCH_RATE; break;
409 default:
410 sLog.outError("WorldSession::HandleForceSpeedChangeAck: Unknown move type opcode: %u", opcode);
411 return;
414 // skip all forced speed changes except last and unexpected
415 // in run/mounted case used one ACK and it must be skipped.m_forced_speed_changes[MOVE_RUN} store both.
416 if(_player->m_forced_speed_changes[force_move_type] > 0)
418 --_player->m_forced_speed_changes[force_move_type];
419 if(_player->m_forced_speed_changes[force_move_type] > 0)
420 return;
423 if (!_player->GetTransport() && fabs(_player->GetSpeed(move_type) - newspeed) > 0.01f)
425 if(_player->GetSpeed(move_type) > newspeed) // must be greater - just correct
427 sLog.outError("%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value",
428 move_type_name[move_type], _player->GetName(), _player->GetSpeed(move_type), newspeed);
429 _player->SetSpeed(move_type,_player->GetSpeedRate(move_type),true);
431 else // must be lesser - cheating
433 sLog.outBasic("Player %s from account id %u kicked for incorrect speed (must be %f instead %f)",
434 _player->GetName(),_player->GetSession()->GetAccountId(),_player->GetSpeed(move_type), newspeed);
435 _player->GetSession()->KickPlayer();
440 void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recv_data)
442 sLog.outDebug("WORLD: Recvd CMSG_SET_ACTIVE_MOVER");
443 recv_data.hexlike();
445 CHECK_PACKET_SIZE(recv_data, 8);
447 uint64 guid;
448 recv_data >> guid;
450 if(_player->m_mover->GetGUID() != guid)
452 sLog.outError("HandleSetActiveMoverOpcode: incorrect mover guid: mover is " I64FMT " and should be " I64FMT, _player->m_mover->GetGUID(), guid);
453 return;
457 void WorldSession::HandleMoveNotActiveMover(WorldPacket &recv_data)
459 sLog.outDebug("WORLD: Recvd CMSG_MOVE_NOT_ACTIVE_MOVER");
460 recv_data.hexlike();
462 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+8);
464 uint64 old_mover_guid;
465 recv_data >> old_mover_guid;
467 if(_player->m_mover->GetGUID() == old_mover_guid)
469 sLog.outError("HandleMoveNotActiveMover: incorrect mover guid: mover is " I64FMT " and should be " I64FMT " instead of " I64FMT, _player->m_mover->GetGUID(), _player->GetGUID(), old_mover_guid);
470 return;
473 MovementInfo mi;
474 ReadMovementInfo(recv_data, &mi);
475 _player->m_movementInfo = mi;
478 void WorldSession::HandleDismissControlledVehicle(WorldPacket &recv_data)
480 sLog.outDebug("WORLD: Recvd CMSG_DISMISS_CONTROLLED_VEHICLE");
481 recv_data.hexlike();
483 uint64 vehicleGUID = _player->GetCharmGUID();
485 if(!vehicleGUID) // something wrong here...
486 return;
488 MovementInfo mi;
489 ReadMovementInfo(recv_data, &mi);
490 _player->m_movementInfo = mi;
492 // using charm guid, because we don't have vehicle guid...
493 if(Vehicle *vehicle = ObjectAccessor::GetVehicle(vehicleGUID))
495 _player->ExitVehicle(vehicle);
496 vehicle->Dismiss();
500 void WorldSession::HandleMountSpecialAnimOpcode(WorldPacket& /*recvdata*/)
502 //sLog.outDebug("WORLD: Recvd CMSG_MOUNTSPECIAL_ANIM");
504 WorldPacket data(SMSG_MOUNTSPECIAL_ANIM, 8);
505 data << uint64(GetPlayer()->GetGUID());
507 GetPlayer()->SendMessageToSet(&data, false);
510 void WorldSession::HandleMoveKnockBackAck( WorldPacket & /*recv_data*/ )
512 // CHECK_PACKET_SIZE(recv_data,?);
513 sLog.outDebug("CMSG_MOVE_KNOCK_BACK_ACK");
514 // Currently not used but maybe use later for recheck final player position
515 // (must be at call same as into "recv_data >> x >> y >> z >> orientation;"
518 uint32 flags, time;
519 float x, y, z, orientation;
520 uint64 guid;
521 uint32 sequence;
522 uint32 ukn1;
523 float xdirection,ydirection,hspeed,vspeed;
525 recv_data >> guid;
526 recv_data >> sequence;
527 recv_data >> flags >> time;
528 recv_data >> x >> y >> z >> orientation;
529 recv_data >> ukn1; //unknown
530 recv_data >> vspeed >> xdirection >> ydirection >> hspeed;
532 // skip not personal message;
533 if(GetPlayer()->GetGUID()!=guid)
534 return;
536 // check code
540 void WorldSession::HandleMoveHoverAck( WorldPacket& /*recv_data*/ )
542 sLog.outDebug("CMSG_MOVE_HOVER_ACK");
545 void WorldSession::HandleMoveWaterWalkAck(WorldPacket& /*recv_data*/)
547 sLog.outDebug("CMSG_MOVE_WATER_WALK_ACK");
550 void WorldSession::HandleSummonResponseOpcode(WorldPacket& recv_data)
552 CHECK_PACKET_SIZE(recv_data,8+1);
554 if(!_player->isAlive() || _player->isInCombat() )
555 return;
557 uint64 summoner_guid;
558 bool agree;
559 recv_data >> summoner_guid;
560 recv_data >> agree;
562 _player->SummonIfPossible(agree);