Fixed possible crash
[getmangos.git] / src / game / Object.cpp
blob1c8ad7bed4715758435a414ea8fd887b9e1c5070
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "SharedDefines.h"
21 #include "WorldPacket.h"
22 #include "Opcodes.h"
23 #include "Log.h"
24 #include "World.h"
25 #include "Object.h"
26 #include "Creature.h"
27 #include "Player.h"
28 #include "ObjectMgr.h"
29 #include "WorldSession.h"
30 #include "UpdateData.h"
31 #include "UpdateMask.h"
32 #include "Util.h"
33 #include "MapManager.h"
34 #include "ObjectAccessor.h"
35 #include "Log.h"
36 #include "Transports.h"
37 #include "TargetedMovementGenerator.h"
38 #include "WaypointMovementGenerator.h"
39 #include "VMapFactory.h"
40 #include "CellImpl.h"
41 #include "GridNotifiers.h"
42 #include "GridNotifiersImpl.h"
44 #include "ObjectPosSelector.h"
46 #include "TemporarySummon.h"
48 uint32 GuidHigh2TypeId(uint32 guid_hi)
50 switch(guid_hi)
52 case HIGHGUID_ITEM: return TYPEID_ITEM;
53 //case HIGHGUID_CONTAINER: return TYPEID_CONTAINER; HIGHGUID_CONTAINER==HIGHGUID_ITEM currently
54 case HIGHGUID_UNIT: return TYPEID_UNIT;
55 case HIGHGUID_PET: return TYPEID_UNIT;
56 case HIGHGUID_PLAYER: return TYPEID_PLAYER;
57 case HIGHGUID_GAMEOBJECT: return TYPEID_GAMEOBJECT;
58 case HIGHGUID_DYNAMICOBJECT:return TYPEID_DYNAMICOBJECT;
59 case HIGHGUID_CORPSE: return TYPEID_CORPSE;
60 case HIGHGUID_MO_TRANSPORT: return TYPEID_GAMEOBJECT;
62 return 10; // unknown
65 Object::Object( )
67 m_objectTypeId = TYPEID_OBJECT;
68 m_objectType = TYPEMASK_OBJECT;
70 m_uint32Values = 0;
71 m_uint32Values_mirror = 0;
72 m_valuesCount = 0;
74 m_inWorld = false;
75 m_objectUpdated = false;
77 m_PackGUID.clear();
78 m_PackGUID.appendPackGUID(0);
81 Object::~Object( )
83 if(m_objectUpdated)
84 ObjectAccessor::Instance().RemoveUpdateObject(this);
86 if(m_uint32Values)
88 if(IsInWorld())
90 ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash
91 sLog.outError("Object::~Object - guid="I64FMTD", typeid=%d deleted but still in world!!", GetGUID(), GetTypeId());
92 //assert(0);
95 //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
96 delete [] m_uint32Values;
97 delete [] m_uint32Values_mirror;
98 //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
102 void Object::_InitValues()
104 m_uint32Values = new uint32[ m_valuesCount ];
105 memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
107 m_uint32Values_mirror = new uint32[ m_valuesCount ];
108 memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
110 m_objectUpdated = false;
113 void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
115 if(!m_uint32Values) _InitValues();
117 uint64 guid = MAKE_NEW_GUID(guidlow, entry, guidhigh); // required more changes to make it working
118 SetUInt64Value( OBJECT_FIELD_GUID, guid );
119 SetUInt32Value( OBJECT_FIELD_TYPE, m_objectType );
120 m_PackGUID.clear();
121 m_PackGUID.appendPackGUID(GetGUID());
124 void Object::BuildMovementUpdateBlock(UpdateData * data, uint32 flags ) const
126 ByteBuffer buf(500);
128 buf << uint8( UPDATETYPE_MOVEMENT );
129 buf << GetGUID();
131 _BuildMovementUpdate(&buf, flags, 0x00000000);
133 data->AddUpdateBlock(buf);
136 void Object::BuildCreateUpdateBlockForPlayer(UpdateData *data, Player *target) const
138 if(!target)
140 return;
143 uint8 updatetype = UPDATETYPE_CREATE_OBJECT;
144 uint8 flags = m_updateFlag;
145 uint32 flags2 = 0;
147 /** lower flag1 **/
148 if(target == this) // building packet for oneself
149 flags |= UPDATEFLAG_SELF;
151 if(flags & UPDATEFLAG_HAS_POSITION)
153 // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
154 if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
155 updatetype = UPDATETYPE_CREATE_OBJECT2;
157 // UPDATETYPE_CREATE_OBJECT2 for pets...
158 if(target->GetPetGUID() == GetGUID())
159 updatetype = UPDATETYPE_CREATE_OBJECT2;
161 // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
162 if(isType(TYPEMASK_GAMEOBJECT))
164 switch(((GameObject*)this)->GetGoType())
166 case GAMEOBJECT_TYPE_TRAP:
167 case GAMEOBJECT_TYPE_DUEL_ARBITER:
168 case GAMEOBJECT_TYPE_FLAGSTAND:
169 case GAMEOBJECT_TYPE_FLAGDROP:
170 updatetype = UPDATETYPE_CREATE_OBJECT2;
171 break;
172 case GAMEOBJECT_TYPE_TRANSPORT:
173 flags |= UPDATEFLAG_TRANSPORT;
174 break;
178 if(isType(TYPEMASK_UNIT))
180 if(((Unit*)this)->getVictim())
181 flags |= UPDATEFLAG_HAS_TARGET;
185 //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got flags: %X, flags2: %X", updatetype, m_objectTypeId, flags, flags2);
187 ByteBuffer buf(500);
188 buf << (uint8)updatetype;
189 //buf.append(GetPackGUID()); //client crashes when using this
190 buf << (uint8)0xFF << GetGUID();
191 buf << (uint8)m_objectTypeId;
193 _BuildMovementUpdate(&buf, flags, flags2);
195 UpdateMask updateMask;
196 updateMask.SetCount( m_valuesCount );
197 _SetCreateBits( &updateMask, target );
198 _BuildValuesUpdate(updatetype, &buf, &updateMask, target );
199 data->AddUpdateBlock(buf);
202 void Object::BuildUpdate(UpdateDataMapType &update_players)
204 ObjectAccessor::_buildUpdateObject(this,update_players);
205 ClearUpdateMask(true);
208 void Object::SendUpdateToPlayer(Player* player)
210 // send update to another players
211 SendUpdateObjectToAllExcept(player);
213 // send create update to player
214 UpdateData upd;
215 WorldPacket packet;
217 upd.Clear();
218 BuildCreateUpdateBlockForPlayer(&upd, player);
219 upd.BuildPacket(&packet);
220 player->GetSession()->SendPacket(&packet);
222 // now object updated/(create updated)
225 void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
227 ByteBuffer buf(500);
229 buf << (uint8) UPDATETYPE_VALUES;
230 //buf.append(GetPackGUID()); //client crashes when using this. but not have crash in debug mode
231 buf << (uint8)0xFF;
232 buf << GetGUID();
234 UpdateMask updateMask;
235 updateMask.SetCount( m_valuesCount );
237 _SetUpdateBits( &updateMask, target );
238 _BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target );
240 data->AddUpdateBlock(buf);
243 void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
245 data->AddOutOfRangeGUID(GetGUID());
248 void Object::DestroyForPlayer(Player *target) const
250 ASSERT(target);
252 WorldPacket data(SMSG_DESTROY_OBJECT, 8);
253 data << GetGUID();
254 data << uint8(0); // WotLK (bool)
255 target->GetSession()->SendPacket( &data );
258 void Object::_BuildMovementUpdate(ByteBuffer * data, uint8 flags, uint32 flags2) const
260 uint16 unk_flags = ((GetTypeId() == TYPEID_PLAYER) ? ((Player*)this)->m_movementInfo.unk1 : 0);
262 if(GetTypeId() == TYPEID_UNIT)
263 if(((Creature*)this)->isVehicle())
264 unk_flags |= 0x20; // always allow pitch
266 *data << (uint8)flags; // update flags
268 // 0x20
269 if (flags & UPDATEFLAG_LIVING)
271 switch(GetTypeId())
273 case TYPEID_UNIT:
275 flags2 = ((Unit*)this)->GetUnitMovementFlags();
277 break;
278 case TYPEID_PLAYER:
280 flags2 = ((Player*)this)->GetUnitMovementFlags();
282 if(((Player*)this)->GetTransport())
283 flags2 |= MOVEMENTFLAG_ONTRANSPORT;
284 else
285 flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
287 // remove unknown, unused etc flags for now
288 flags2 &= ~MOVEMENTFLAG_SPLINE2; // will be set manually
290 if(((Player*)this)->isInFlight())
292 WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
293 flags2 = (MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
296 break;
299 *data << uint32(flags2); // movement flags
300 *data << uint16(unk_flags); // unknown 2.3.0
301 *data << uint32(getMSTime()); // time (in milliseconds)
304 // 0x40
305 if (flags & UPDATEFLAG_HAS_POSITION)
307 // 0x02
308 if(flags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
310 *data << (float)0;
311 *data << (float)0;
312 *data << (float)0;
313 *data << ((WorldObject *)this)->GetOrientation();
315 else
317 *data << ((WorldObject *)this)->GetPositionX();
318 *data << ((WorldObject *)this)->GetPositionY();
319 *data << ((WorldObject *)this)->GetPositionZ();
320 *data << ((WorldObject *)this)->GetOrientation();
324 // 0x20
325 if(flags & UPDATEFLAG_LIVING)
327 // 0x00000200
328 if(flags2 & MOVEMENTFLAG_ONTRANSPORT)
330 if(GetTypeId() == TYPEID_PLAYER)
332 *data << (uint64)((Player*)this)->GetTransport()->GetGUID();
333 *data << (float)((Player*)this)->GetTransOffsetX();
334 *data << (float)((Player*)this)->GetTransOffsetY();
335 *data << (float)((Player*)this)->GetTransOffsetZ();
336 *data << (float)((Player*)this)->GetTransOffsetO();
337 *data << (uint32)((Player*)this)->GetTransTime();
338 *data << (int8)((Player*)this)->GetTransSeat();
340 //MaNGOS currently not have support for other than player on transport
343 // 0x02200000
344 if((flags2 & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2)) || (unk_flags & 0x20))
346 if(GetTypeId() == TYPEID_PLAYER)
347 *data << (float)((Player*)this)->m_movementInfo.s_pitch;
348 else
349 *data << (float)0; // is't part of movement packet, we must store and send it...
352 if(GetTypeId() == TYPEID_PLAYER)
353 *data << (uint32)((Player*)this)->m_movementInfo.fallTime;
354 else
355 *data << (uint32)0; // last fall time
357 // 0x00001000
358 if(flags2 & MOVEMENTFLAG_JUMPING)
360 if(GetTypeId() == TYPEID_PLAYER)
362 *data << (float)((Player*)this)->m_movementInfo.j_unk;
363 *data << (float)((Player*)this)->m_movementInfo.j_sinAngle;
364 *data << (float)((Player*)this)->m_movementInfo.j_cosAngle;
365 *data << (float)((Player*)this)->m_movementInfo.j_xyspeed;
367 else
369 *data << (float)0;
370 *data << (float)0;
371 *data << (float)0;
372 *data << (float)0;
376 // 0x04000000
377 if(flags2 & MOVEMENTFLAG_SPLINE)
379 if(GetTypeId() == TYPEID_PLAYER)
380 *data << (float)((Player*)this)->m_movementInfo.u_unk1;
381 else
382 *data << (float)0;
385 *data << ((Unit*)this)->GetSpeed( MOVE_WALK );
386 *data << ((Unit*)this)->GetSpeed( MOVE_RUN );
387 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM_BACK );
388 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM );
389 *data << ((Unit*)this)->GetSpeed( MOVE_RUN_BACK );
390 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT );
391 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT_BACK );
392 *data << ((Unit*)this)->GetSpeed( MOVE_TURN_RATE );
393 *data << ((Unit*)this)->GetSpeed( MOVE_PITCH_RATE );
395 // 0x08000000
396 if(flags2 & MOVEMENTFLAG_SPLINE2)
398 if(GetTypeId() != TYPEID_PLAYER)
400 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 for non-player");
401 return;
404 if(!((Player*)this)->isInFlight())
406 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 but not in flight");
407 return;
410 WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
412 FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(((Player*)this)->GetMotionMaster()->top());
414 uint32 flags3 = 0x00000300;
416 *data << uint32(flags3); // splines flag?
418 if(flags3 & 0x10000) // probably x,y,z coords there
420 *data << (float)0;
421 *data << (float)0;
422 *data << (float)0;
425 if(flags3 & 0x20000) // probably guid there
427 *data << uint64(0);
430 if(flags3 & 0x40000) // may be orientation
432 *data << (float)0;
435 Path &path = fmg->GetPath();
437 float x, y, z;
438 ((Player*)this)->GetPosition(x, y, z);
440 uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
441 uint32 traveltime = uint32(path.GetTotalLength() * 32);
443 *data << uint32(inflighttime); // passed move time?
444 *data << uint32(traveltime); // full move time?
445 *data << uint32(0); // ticks count?
447 uint32 poscount = uint32(path.Size());
449 *data << uint32(poscount); // points count
451 for(uint32 i = 0; i < poscount; ++i)
453 *data << path.GetNodes()[i].x;
454 *data << path.GetNodes()[i].y;
455 *data << path.GetNodes()[i].z;
458 /*for(uint32 i = 0; i < poscount; i++)
460 // path points
461 *data << (float)0;
462 *data << (float)0;
463 *data << (float)0;
466 *data << path.GetNodes()[poscount-1].x;
467 *data << path.GetNodes()[poscount-1].y;
468 *data << path.GetNodes()[poscount-1].z;
470 // target position (path end)
471 /**data << ((Unit*)this)->GetPositionX();
472 *data << ((Unit*)this)->GetPositionY();
473 *data << ((Unit*)this)->GetPositionZ();*/
477 // 0x8
478 if(flags & UPDATEFLAG_LOWGUID)
480 switch(GetTypeId())
482 case TYPEID_OBJECT:
483 case TYPEID_ITEM:
484 case TYPEID_CONTAINER:
485 case TYPEID_GAMEOBJECT:
486 case TYPEID_DYNAMICOBJECT:
487 case TYPEID_CORPSE:
488 *data << uint32(GetGUIDLow()); // GetGUIDLow()
489 break;
490 case TYPEID_UNIT:
491 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
492 break;
493 case TYPEID_PLAYER:
494 if(flags & UPDATEFLAG_SELF)
495 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
496 else
497 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
498 break;
499 default:
500 *data << uint32(0x00000000); // unk
501 break;
505 // 0x10
506 if(flags & UPDATEFLAG_HIGHGUID)
508 switch(GetTypeId())
510 case TYPEID_OBJECT:
511 case TYPEID_ITEM:
512 case TYPEID_CONTAINER:
513 case TYPEID_GAMEOBJECT:
514 case TYPEID_DYNAMICOBJECT:
515 case TYPEID_CORPSE:
516 *data << uint32(GetGUIDHigh()); // GetGUIDHigh()
517 break;
518 case TYPEID_UNIT:
519 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
520 break;
521 case TYPEID_PLAYER:
522 if(flags & UPDATEFLAG_SELF)
523 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
524 else
525 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
526 break;
527 default:
528 *data << uint32(0x00000000); // unk
529 break;
533 // 0x4
534 if(flags & UPDATEFLAG_HAS_TARGET) // packed guid (current target guid)
536 if(Unit *victim = ((Unit*)this)->getVictim())
537 data->append(victim->GetPackGUID());
538 else
539 *data << uint8(0);
542 // 0x2
543 if(flags & UPDATEFLAG_TRANSPORT)
545 *data << uint32(getMSTime()); // ms time
548 // 0x80
549 if(flags & UPDATEFLAG_VEHICLE) // unused for now
551 *data << uint32(((Vehicle*)this)->GetVehicleId()); // vehicle id
552 *data << float(0); // facing adjustment
556 void Object::_BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
558 if(!target)
559 return;
561 bool IsActivateToQuest = false;
562 if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
564 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
566 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
568 IsActivateToQuest = true;
569 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
573 else //case UPDATETYPE_VALUES
575 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
577 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
579 IsActivateToQuest = true;
581 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
582 updateMask->SetBit(GAMEOBJECT_BYTES_1);
586 WPAssert(updateMask && updateMask->GetCount() == m_valuesCount);
588 *data << (uint8)updateMask->GetBlockCount();
589 data->append( updateMask->GetMask(), updateMask->GetLength() );
591 // 2 specialized loops for speed optimization in non-unit case
592 if(isType(TYPEMASK_UNIT)) // unit (creature/player) case
594 for( uint16 index = 0; index < m_valuesCount; index ++ )
596 if( updateMask->GetBit( index ) )
598 // remove custom flag before send
599 if( index == UNIT_NPC_FLAGS )
600 *data << uint32(m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD);
601 // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
602 else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
604 // convert from float to uint32 and send
605 *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
607 // there are some float values which may be negative or can't get negative due to other checks
608 else if(index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4 ||
609 index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6) ||
610 index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6) ||
611 index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4)
613 *data << uint32(m_floatValues[ index ]);
615 // Gamemasters should be always able to select units - remove not selectable flag
616 else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
618 *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
620 // hide lootable animation for unallowed players
621 else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
623 if(!target->isAllowedToLoot((Creature*)this))
624 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
625 else
626 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_OTHER_TAGGER);
628 else
630 // send in current format (float as float, uint32 as uint32)
631 *data << m_uint32Values[ index ];
636 else if(isType(TYPEMASK_GAMEOBJECT)) // gameobject case
638 for( uint16 index = 0; index < m_valuesCount; index ++ )
640 if( updateMask->GetBit( index ) )
642 // send in current format (float as float, uint32 as uint32)
643 if ( index == GAMEOBJECT_DYNAMIC )
645 if(IsActivateToQuest )
647 switch(((GameObject*)this)->GetGoType())
649 case GAMEOBJECT_TYPE_CHEST:
650 *data << uint32(9); // enable quest object. Represent 9, but 1 for client before 2.3.0
651 break;
652 case GAMEOBJECT_TYPE_GOOBER:
653 *data << uint32(1);
654 break;
655 default:
656 *data << uint32(0); // unknown. not happen.
657 break;
660 else
661 *data << uint32(0); // disable quest object
663 else
664 *data << m_uint32Values[ index ]; // other cases
668 else // other objects case (no special index checks)
670 for( uint16 index = 0; index < m_valuesCount; index ++ )
672 if( updateMask->GetBit( index ) )
674 // send in current format (float as float, uint32 as uint32)
675 *data << m_uint32Values[ index ];
681 void Object::ClearUpdateMask(bool remove)
683 for( uint16 index = 0; index < m_valuesCount; index ++ )
685 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
686 m_uint32Values_mirror[index] = m_uint32Values[index];
688 if(m_objectUpdated)
690 if(remove)
691 ObjectAccessor::Instance().RemoveUpdateObject(this);
692 m_objectUpdated = false;
696 // Send current value fields changes to all viewers
697 void Object::SendUpdateObjectToAllExcept(Player* exceptPlayer)
699 // changes will be send in create packet
700 if(!IsInWorld())
701 return;
703 // nothing do
704 if(!m_objectUpdated)
705 return;
707 ObjectAccessor::UpdateObject(this,exceptPlayer);
710 bool Object::LoadValues(const char* data)
712 if(!m_uint32Values) _InitValues();
714 Tokens tokens = StrSplit(data, " ");
716 if(tokens.size() != m_valuesCount)
717 return false;
719 Tokens::iterator iter;
720 int index;
721 for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
723 m_uint32Values[index] = atol((*iter).c_str());
726 return true;
729 void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
731 for( uint16 index = 0; index < m_valuesCount; index ++ )
733 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
734 updateMask->SetBit(index);
738 void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
740 for( uint16 index = 0; index < m_valuesCount; index++ )
742 if(GetUInt32Value(index) != 0)
743 updateMask->SetBit(index);
747 void Object::SetInt32Value( uint16 index, int32 value )
749 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
751 if(m_int32Values[ index ] != value)
753 m_int32Values[ index ] = value;
755 if(m_inWorld)
757 if(!m_objectUpdated)
759 ObjectAccessor::Instance().AddUpdateObject(this);
760 m_objectUpdated = true;
766 void Object::SetUInt32Value( uint16 index, uint32 value )
768 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
770 if(m_uint32Values[ index ] != value)
772 m_uint32Values[ index ] = value;
774 if(m_inWorld)
776 if(!m_objectUpdated)
778 ObjectAccessor::Instance().AddUpdateObject(this);
779 m_objectUpdated = true;
785 void Object::SetUInt64Value( uint16 index, const uint64 &value )
787 ASSERT( index + 1 < m_valuesCount || PrintIndexError( index , true ) );
788 if(*((uint64*)&(m_uint32Values[ index ])) != value)
790 m_uint32Values[ index ] = *((uint32*)&value);
791 m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
793 if(m_inWorld)
795 if(!m_objectUpdated)
797 ObjectAccessor::Instance().AddUpdateObject(this);
798 m_objectUpdated = true;
804 void Object::SetFloatValue( uint16 index, float value )
806 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
808 if(m_floatValues[ index ] != value)
810 m_floatValues[ index ] = value;
812 if(m_inWorld)
814 if(!m_objectUpdated)
816 ObjectAccessor::Instance().AddUpdateObject(this);
817 m_objectUpdated = true;
823 void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
825 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
827 if(offset > 4)
829 sLog.outError("Object::SetByteValue: wrong offset %u", offset);
830 return;
833 if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
835 m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
836 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
838 if(m_inWorld)
840 if(!m_objectUpdated)
842 ObjectAccessor::Instance().AddUpdateObject(this);
843 m_objectUpdated = true;
849 void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
851 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
853 if(offset > 2)
855 sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
856 return;
859 if(uint8(m_uint32Values[ index ] >> (offset * 16)) != value)
861 m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
862 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
864 if(m_inWorld)
866 if(!m_objectUpdated)
868 ObjectAccessor::Instance().AddUpdateObject(this);
869 m_objectUpdated = true;
875 void Object::SetStatFloatValue( uint16 index, float value)
877 if(value < 0)
878 value = 0.0f;
880 SetFloatValue(index, value);
883 void Object::SetStatInt32Value( uint16 index, int32 value)
885 if(value < 0)
886 value = 0;
888 SetUInt32Value(index, uint32(value));
891 void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
893 int32 cur = GetUInt32Value(index);
894 cur += (apply ? val : -val);
895 if(cur < 0)
896 cur = 0;
897 SetUInt32Value(index,cur);
900 void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
902 int32 cur = GetInt32Value(index);
903 cur += (apply ? val : -val);
904 SetInt32Value(index,cur);
907 void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply)
909 float cur = GetFloatValue(index);
910 cur += (apply ? val : -val);
911 SetFloatValue(index,cur);
914 void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply)
916 float cur = GetFloatValue(index);
917 cur += (apply ? val : -val);
918 if(cur < 0)
919 cur = 0;
920 SetFloatValue(index,cur);
923 void Object::SetFlag( uint16 index, uint32 newFlag )
925 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
926 uint32 oldval = m_uint32Values[ index ];
927 uint32 newval = oldval | newFlag;
929 if(oldval != newval)
931 m_uint32Values[ index ] = newval;
933 if(m_inWorld)
935 if(!m_objectUpdated)
937 ObjectAccessor::Instance().AddUpdateObject(this);
938 m_objectUpdated = true;
944 void Object::RemoveFlag( uint16 index, uint32 oldFlag )
946 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
947 uint32 oldval = m_uint32Values[ index ];
948 uint32 newval = oldval & ~oldFlag;
950 if(oldval != newval)
952 m_uint32Values[ index ] = newval;
954 if(m_inWorld)
956 if(!m_objectUpdated)
958 ObjectAccessor::Instance().AddUpdateObject(this);
959 m_objectUpdated = true;
965 void Object::SetByteFlag( uint16 index, uint8 offset, uint8 newFlag )
967 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
969 if(offset > 4)
971 sLog.outError("Object::SetByteFlag: wrong offset %u", offset);
972 return;
975 if(!(uint8(m_uint32Values[ index ] >> (offset * 8)) & newFlag))
977 m_uint32Values[ index ] |= uint32(uint32(newFlag) << (offset * 8));
979 if(m_inWorld)
981 if(!m_objectUpdated)
983 ObjectAccessor::Instance().AddUpdateObject(this);
984 m_objectUpdated = true;
990 void Object::RemoveByteFlag( uint16 index, uint8 offset, uint8 oldFlag )
992 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
994 if(offset > 4)
996 sLog.outError("Object::RemoveByteFlag: wrong offset %u", offset);
997 return;
1000 if(uint8(m_uint32Values[ index ] >> (offset * 8)) & oldFlag)
1002 m_uint32Values[ index ] &= ~uint32(uint32(oldFlag) << (offset * 8));
1004 if(m_inWorld)
1006 if(!m_objectUpdated)
1008 ObjectAccessor::Instance().AddUpdateObject(this);
1009 m_objectUpdated = true;
1015 bool Object::PrintIndexError(uint32 index, bool set) const
1017 sLog.outError("ERROR: Attempt %s non-existed value field: %u (count: %u) for object typeid: %u type mask: %u",(set ? "set value to" : "get value from"),index,m_valuesCount,GetTypeId(),m_objectType);
1019 // assert must fail after function call
1020 return false;
1023 WorldObject::WorldObject()
1025 m_positionX = 0.0f;
1026 m_positionY = 0.0f;
1027 m_positionZ = 0.0f;
1028 m_orientation = 0.0f;
1030 m_mapId = 0;
1031 m_InstanceId = 0;
1033 m_name = "";
1035 mSemaphoreTeleport = false;
1038 void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 mapid )
1040 Object::_Create(guidlow, 0, guidhigh);
1042 m_mapId = mapid;
1045 uint32 WorldObject::GetZoneId() const
1047 return MapManager::Instance().GetBaseMap(m_mapId)->GetZoneId(m_positionX,m_positionY);
1050 uint32 WorldObject::GetAreaId() const
1052 return MapManager::Instance().GetBaseMap(m_mapId)->GetAreaId(m_positionX,m_positionY);
1055 InstanceData* WorldObject::GetInstanceData()
1057 Map *map = GetMap();
1058 return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
1061 //slow
1062 float WorldObject::GetDistance(const WorldObject* obj) const
1064 float dx = GetPositionX() - obj->GetPositionX();
1065 float dy = GetPositionY() - obj->GetPositionY();
1066 float dz = GetPositionZ() - obj->GetPositionZ();
1067 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1068 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1069 return ( dist > 0 ? dist : 0);
1072 float WorldObject::GetDistance2d(float x, float y) const
1074 float dx = GetPositionX() - x;
1075 float dy = GetPositionY() - y;
1076 float sizefactor = GetObjectSize();
1077 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1078 return ( dist > 0 ? dist : 0);
1081 float WorldObject::GetDistance(const float x, const float y, const float z) const
1083 float dx = GetPositionX() - x;
1084 float dy = GetPositionY() - y;
1085 float dz = GetPositionZ() - z;
1086 float sizefactor = GetObjectSize();
1087 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1088 return ( dist > 0 ? dist : 0);
1091 float WorldObject::GetDistance2d(const WorldObject* obj) const
1093 float dx = GetPositionX() - obj->GetPositionX();
1094 float dy = GetPositionY() - obj->GetPositionY();
1095 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1096 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1097 return ( dist > 0 ? dist : 0);
1100 float WorldObject::GetDistanceZ(const WorldObject* obj) const
1102 float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1103 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1104 float dist = dz - sizefactor;
1105 return ( dist > 0 ? dist : 0);
1108 bool WorldObject::IsWithinDistInMap(const WorldObject* obj, const float dist2compare) const
1110 if (!obj || !IsInMap(obj)) return false;
1112 float dx = GetPositionX() - obj->GetPositionX();
1113 float dy = GetPositionY() - obj->GetPositionY();
1114 float dz = GetPositionZ() - obj->GetPositionZ();
1115 float distsq = dx*dx + dy*dy + dz*dz;
1116 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1117 float maxdist = dist2compare + sizefactor;
1119 return distsq < maxdist * maxdist;
1122 bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1124 if (!IsInMap(obj)) return false;
1125 float ox,oy,oz;
1126 obj->GetPosition(ox,oy,oz);
1127 return(IsWithinLOS(ox, oy, oz ));
1130 bool WorldObject::IsWithinLOS(const float ox, const float oy, const float oz ) const
1132 float x,y,z;
1133 GetPosition(x,y,z);
1134 VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1135 return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1138 float WorldObject::GetAngle(const WorldObject* obj) const
1140 if(!obj) return 0;
1141 return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1144 // Return angle in range 0..2*pi
1145 float WorldObject::GetAngle( const float x, const float y ) const
1147 float dx = x - GetPositionX();
1148 float dy = y - GetPositionY();
1150 float ang = atan2(dy, dx);
1151 ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1152 return ang;
1155 bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1157 float arc = arcangle;
1159 // move arc to range 0.. 2*pi
1160 while( arc >= 2.0f * M_PI )
1161 arc -= 2.0f * M_PI;
1162 while( arc < 0 )
1163 arc += 2.0f * M_PI;
1165 float angle = GetAngle( obj );
1166 angle -= m_orientation;
1168 // move angle to range -pi ... +pi
1169 while( angle > M_PI)
1170 angle -= 2.0f * M_PI;
1171 while(angle < -M_PI)
1172 angle += 2.0f * M_PI;
1174 float lborder = -1 * (arc/2.0f); // in range -pi..0
1175 float rborder = (arc/2.0f); // in range 0..pi
1176 return (( angle >= lborder ) && ( angle <= rborder ));
1179 void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1181 if(distance==0)
1183 rand_x = x;
1184 rand_y = y;
1185 rand_z = z;
1186 return;
1189 // angle to face `obj` to `this`
1190 float angle = rand_norm()*2*M_PI;
1191 float new_dist = rand_norm()*distance;
1193 rand_x = x + new_dist * cos(angle);
1194 rand_y = y + new_dist * sin(angle);
1195 rand_z = z;
1197 MaNGOS::NormalizeMapCoord(rand_x);
1198 MaNGOS::NormalizeMapCoord(rand_y);
1199 UpdateGroundPositionZ(rand_x,rand_y,rand_z); // update to LOS height if available
1202 void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1204 float new_z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(x,y,z,true);
1205 if(new_z > INVALID_HEIGHT)
1206 z = new_z+ 0.05f; // just to be sure that we are not a few pixel under the surface
1209 bool WorldObject::IsPositionValid() const
1211 return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1214 void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1216 WorldPacket data(SMSG_MESSAGECHAT, 200);
1217 BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1218 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1221 void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1223 WorldPacket data(SMSG_MESSAGECHAT, 200);
1224 BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1225 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1228 void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1230 WorldPacket data(SMSG_MESSAGECHAT, 200);
1231 BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1232 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1235 void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1237 Player *player = objmgr.GetPlayer(receiver);
1238 if(!player || !player->GetSession())
1239 return;
1241 WorldPacket data(SMSG_MESSAGECHAT, 200);
1242 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1244 player->GetSession()->SendPacket(&data);
1247 namespace MaNGOS
1249 class MessageChatLocaleCacheDo
1251 public:
1252 MessageChatLocaleCacheDo(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID, float dist)
1253 : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language),
1254 i_targetGUID(targetGUID), i_dist(dist)
1258 ~MessageChatLocaleCacheDo()
1260 for(int i = 0; i < i_data_cache.size(); ++i)
1261 delete i_data_cache[i];
1264 void operator()(Player* p)
1266 // skip far away players
1267 if(p->GetDistance(&i_object) > i_dist)
1268 return;
1270 uint32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
1271 uint32 cache_idx = loc_idx+1;
1272 WorldPacket* data;
1274 // create if not cached yet
1275 if(i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
1277 if(i_data_cache.size() < cache_idx+1)
1278 i_data_cache.resize(cache_idx+1);
1280 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1282 data = new WorldPacket(SMSG_MESSAGECHAT, 200);
1284 // TODO: i_object.GetName() also must be localized?
1285 i_object.BuildMonsterChat(data,i_msgtype,text,i_language,i_object.GetNameForLocaleIdx(loc_idx),i_targetGUID);
1287 i_data_cache[cache_idx] = data;
1289 else
1290 data = i_data_cache[cache_idx];
1292 p->SendDirectMessage(data);
1295 private:
1296 WorldObject const& i_object;
1297 ChatMsg i_msgtype;
1298 int32 i_textId;
1299 uint32 i_language;
1300 uint64 i_targetGUID;
1301 float i_dist;
1302 std::vector<WorldPacket*> i_data_cache; // 0 = default, i => i-1 locale index
1304 } // namespace MaNGOS
1306 void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1308 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1310 Cell cell(p);
1311 cell.data.Part.reserved = ALL_DISTRICT;
1312 cell.SetNoCreate();
1314 MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1315 MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1316 TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1317 CellLock<GridReadGuard> cell_lock(cell, p);
1318 cell_lock->Visit(cell_lock, message, *GetMap());
1321 void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1323 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1325 Cell cell(p);
1326 cell.data.Part.reserved = ALL_DISTRICT;
1327 cell.SetNoCreate();
1329 MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL));
1330 MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1331 TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1332 CellLock<GridReadGuard> cell_lock(cell, p);
1333 cell_lock->Visit(cell_lock, message, *GetMap());
1336 void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1338 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1340 Cell cell(p);
1341 cell.data.Part.reserved = ALL_DISTRICT;
1342 cell.SetNoCreate();
1344 MaNGOS::MessageChatLocaleCacheDo say_do(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE));
1345 MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1346 TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1347 CellLock<GridReadGuard> cell_lock(cell, p);
1348 cell_lock->Visit(cell_lock, message, *GetMap());
1351 void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1353 Player *player = objmgr.GetPlayer(receiver);
1354 if(!player || !player->GetSession())
1355 return;
1357 uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1358 char const* text = objmgr.GetMangosString(textId,loc_idx);
1360 WorldPacket data(SMSG_MESSAGECHAT, 200);
1361 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1363 player->GetSession()->SendPacket(&data);
1366 void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1368 bool pre = (msgtype==CHAT_MSG_MONSTER_EMOTE || msgtype==CHAT_MSG_RAID_BOSS_EMOTE);
1370 *data << (uint8)msgtype;
1371 *data << (uint32)language;
1372 *data << (uint64)GetGUID();
1373 *data << (uint32)0; //2.1.0
1374 *data << (uint32)(strlen(name)+1);
1375 *data << name;
1376 *data << (uint64)targetGuid; //Unit Target
1377 if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1379 *data << (uint32)1; // target name length
1380 *data << (uint8)0; // target name
1382 *data << (uint32)(strlen(text)+1+(pre?3:0));
1383 if(pre)
1384 data->append("%s ",3);
1385 *data << text;
1386 *data << (uint8)0; // ChatTag
1389 void WorldObject::BuildHeartBeatMsg(WorldPacket *data) const
1391 //Heartbeat message cannot be used for non-units
1392 if (!isType(TYPEMASK_UNIT))
1393 return;
1395 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
1396 data->append(GetPackGUID());
1397 *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1398 *data << uint16(0); // 2.3.0
1399 *data << getMSTime(); // time
1400 *data << m_positionX;
1401 *data << m_positionY;
1402 *data << m_positionZ;
1403 *data << m_orientation;
1404 *data << uint32(0);
1407 void WorldObject::BuildTeleportAckMsg(WorldPacket *data, float x, float y, float z, float ang) const
1409 //TeleportAck message cannot be used for non-units
1410 if (!isType(TYPEMASK_UNIT))
1411 return;
1413 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
1414 data->append(GetPackGUID());
1415 *data << uint32(0); // this value increments every time
1416 *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1417 *data << uint16(0); // 2.3.0
1418 *data << getMSTime(); // time
1419 *data << x;
1420 *data << y;
1421 *data << z;
1422 *data << ang;
1423 *data << uint32(0);
1426 void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1428 GetMap()->MessageBroadcast(this, data);
1431 void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1433 GetMap()->MessageDistBroadcast(this, data, dist);
1436 void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1438 WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1439 data << guid;
1440 SendMessageToSet(&data, true);
1443 Map* WorldObject::GetMap() const
1445 return MapManager::Instance().GetMap(GetMapId(), this);
1448 Map const* WorldObject::GetBaseMap() const
1450 return MapManager::Instance().GetBaseMap(GetMapId());
1453 void WorldObject::AddObjectToRemoveList()
1455 Map* map = GetMap();
1456 if(!map)
1458 sLog.outError("Object (TypeId: %u Entry: %u GUID: %u) at attempt add to move list not have valid map (Id: %u).",GetTypeId(),GetEntry(),GetGUIDLow(),GetMapId());
1459 return;
1462 map->AddObjectToRemoveList(this);
1465 Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1467 TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1469 pCreature->SetInstanceId(GetInstanceId());
1470 uint32 team = 0;
1471 if (GetTypeId()==TYPEID_PLAYER)
1472 team = ((Player*)this)->GetTeam();
1474 if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), id, team))
1476 delete pCreature;
1477 return NULL;
1480 if (x == 0.0f && y == 0.0f && z == 0.0f)
1481 GetClosePoint(x, y, z, pCreature->GetObjectSize());
1483 pCreature->Relocate(x, y, z, ang);
1485 if(!pCreature->IsPositionValid())
1487 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
1488 delete pCreature;
1489 return NULL;
1492 pCreature->Summon(spwtype, despwtime);
1494 if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1495 ((Creature*)this)->AI()->JustSummoned(pCreature);
1497 //return the creature therewith the summoner has access to it
1498 return pCreature;
1501 namespace MaNGOS
1503 class NearUsedPosDo
1505 public:
1506 NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1507 : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1509 void operator()(Corpse*) const {}
1510 void operator()(DynamicObject*) const {}
1512 void operator()(Creature* c) const
1514 // skip self or target
1515 if(c==i_searcher || c==&i_object)
1516 return;
1518 float x,y,z;
1520 if( !c->isAlive() || c->hasUnitState(UNIT_STAT_ROOT | UNIT_STAT_STUNNED | UNIT_STAT_DISTRACTED) ||
1521 !c->GetMotionMaster()->GetDestination(x,y,z) )
1523 x = c->GetPositionX();
1524 y = c->GetPositionY();
1527 add(c,x,y);
1530 template<class T>
1531 void operator()(T* u) const
1533 // skip self or target
1534 if(u==i_searcher || u==&i_object)
1535 return;
1537 float x,y;
1539 x = u->GetPositionX();
1540 y = u->GetPositionY();
1542 add(u,x,y);
1545 // we must add used pos that can fill places around center
1546 void add(WorldObject* u, float x, float y) const
1548 // dist include size of u
1549 float dist2d = i_object.GetDistance2d(x,y);
1551 // u is too nearest to i_object
1552 if(dist2d + i_object.GetObjectSize() + u->GetObjectSize() < i_selector.m_dist - i_selector.m_size)
1553 return;
1555 // u is too far away from i_object
1556 if(dist2d + i_object.GetObjectSize() - u->GetObjectSize() > i_selector.m_dist + i_selector.m_size)
1557 return;
1559 float angle = i_object.GetAngle(u)-i_angle;
1561 // move angle to range -pi ... +pi
1562 while( angle > M_PI)
1563 angle -= 2.0f * M_PI;
1564 while(angle < -M_PI)
1565 angle += 2.0f * M_PI;
1567 i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1569 private:
1570 WorldObject const& i_object;
1571 WorldObject const* i_searcher;
1572 float i_angle;
1573 ObjectPosSelector& i_selector;
1575 } // namespace MaNGOS
1577 //===================================================================================================
1579 void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1581 x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1582 y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1584 MaNGOS::NormalizeMapCoord(x);
1585 MaNGOS::NormalizeMapCoord(y);
1588 void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1590 GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1591 z = GetPositionZ();
1593 // if detection disabled, return first point
1594 if(!sWorld.getConfig(CONFIG_DETECT_POS_COLLISION))
1596 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1597 return;
1600 // or remember first point
1601 float first_x = x;
1602 float first_y = y;
1603 bool first_los_conflict = false; // first point LOS problems
1605 // prepare selector for work
1606 ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1608 // adding used positions around object
1610 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1611 Cell cell(p);
1612 cell.data.Part.reserved = ALL_DISTRICT;
1613 cell.SetNoCreate();
1615 MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1616 MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(u_do);
1618 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer > grid_obj_worker(worker);
1619 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1621 CellLock<GridReadGuard> cell_lock(cell, p);
1622 cell_lock->Visit(cell_lock, grid_obj_worker, *GetMap());
1623 cell_lock->Visit(cell_lock, world_obj_worker, *GetMap());
1626 // maybe can just place in primary position
1627 if( selector.CheckOriginal() )
1629 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1631 if(IsWithinLOS(x,y,z))
1632 return;
1634 first_los_conflict = true; // first point have LOS problems
1637 float angle; // candidate of angle for free pos
1639 // special case when one from list empty and then empty side preferred
1640 if(selector.FirstAngle(angle))
1642 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1643 z = GetPositionZ();
1644 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1646 if(IsWithinLOS(x,y,z))
1647 return;
1650 // set first used pos in lists
1651 selector.InitializeAngle();
1653 // select in positions after current nodes (selection one by one)
1654 while(selector.NextAngle(angle)) // angle for free pos
1656 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1657 z = GetPositionZ();
1658 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1660 if(IsWithinLOS(x,y,z))
1661 return;
1664 // BAD NEWS: not free pos (or used or have LOS problems)
1665 // Attempt find _used_ pos without LOS problem
1667 if(!first_los_conflict)
1669 x = first_x;
1670 y = first_y;
1672 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1673 return;
1676 // special case when one from list empty and then empty side preferred
1677 if( selector.IsNonBalanced() )
1679 if(!selector.FirstAngle(angle)) // _used_ pos
1681 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1682 z = GetPositionZ();
1683 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1685 if(IsWithinLOS(x,y,z))
1686 return;
1690 // set first used pos in lists
1691 selector.InitializeAngle();
1693 // select in positions after current nodes (selection one by one)
1694 while(selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem
1696 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1697 z = GetPositionZ();
1698 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1700 if(IsWithinLOS(x,y,z))
1701 return;
1704 // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1705 x = first_x;
1706 y = first_y;
1708 UpdateGroundPositionZ(x,y,z); // update to LOS height if available