[7827] dd support 2d version for WorldObject::GetDistanceOrder.
[getmangos.git] / src / game / Object.cpp
blob1478ff97157f65df59e8edb6035f48a8fa76bce1
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 "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 "Vehicle.h"
29 #include "ObjectMgr.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;
61 case HIGHGUID_VEHICLE: return TYPEID_UNIT;
63 return MAX_TYPEID; // unknown
66 Object::Object( )
68 m_objectTypeId = TYPEID_OBJECT;
69 m_objectType = TYPEMASK_OBJECT;
71 m_uint32Values = 0;
72 m_uint32Values_mirror = 0;
73 m_valuesCount = 0;
75 m_inWorld = false;
76 m_objectUpdated = false;
78 m_PackGUID.clear();
79 m_PackGUID.appendPackGUID(0);
82 Object::~Object( )
84 if(m_objectUpdated)
85 ObjectAccessor::Instance().RemoveUpdateObject(this);
87 if(m_uint32Values)
89 if(IsInWorld())
91 ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash
92 sLog.outError("Object::~Object - guid="I64FMTD", typeid=%d deleted but still in world!!", GetGUID(), GetTypeId());
93 //assert(0);
96 //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
97 delete [] m_uint32Values;
98 delete [] m_uint32Values_mirror;
99 //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
103 void Object::_InitValues()
105 m_uint32Values = new uint32[ m_valuesCount ];
106 memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
108 m_uint32Values_mirror = new uint32[ m_valuesCount ];
109 memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
111 m_objectUpdated = false;
114 void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
116 if(!m_uint32Values) _InitValues();
118 uint64 guid = MAKE_NEW_GUID(guidlow, entry, guidhigh); // required more changes to make it working
119 SetUInt64Value( OBJECT_FIELD_GUID, guid );
120 SetUInt32Value( OBJECT_FIELD_TYPE, m_objectType );
121 m_PackGUID.clear();
122 m_PackGUID.appendPackGUID(GetGUID());
125 void Object::BuildMovementUpdateBlock(UpdateData * data, uint32 flags ) const
127 ByteBuffer buf(500);
129 buf << uint8( UPDATETYPE_MOVEMENT );
130 buf << GetGUID();
132 _BuildMovementUpdate(&buf, flags, 0x00000000);
134 data->AddUpdateBlock(buf);
137 void Object::BuildCreateUpdateBlockForPlayer(UpdateData *data, Player *target) const
139 if(!target)
141 return;
144 uint8 updatetype = UPDATETYPE_CREATE_OBJECT;
145 uint8 flags = m_updateFlag;
146 uint32 flags2 = 0;
148 /** lower flag1 **/
149 if(target == this) // building packet for oneself
150 flags |= UPDATEFLAG_SELF;
152 if(flags & UPDATEFLAG_HAS_POSITION)
154 // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
155 if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
156 updatetype = UPDATETYPE_CREATE_OBJECT2;
158 // UPDATETYPE_CREATE_OBJECT2 for pets...
159 if(target->GetPetGUID() == GetGUID())
160 updatetype = UPDATETYPE_CREATE_OBJECT2;
162 // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
163 if(isType(TYPEMASK_GAMEOBJECT))
165 switch(((GameObject*)this)->GetGoType())
167 case GAMEOBJECT_TYPE_TRAP:
168 case GAMEOBJECT_TYPE_DUEL_ARBITER:
169 case GAMEOBJECT_TYPE_FLAGSTAND:
170 case GAMEOBJECT_TYPE_FLAGDROP:
171 updatetype = UPDATETYPE_CREATE_OBJECT2;
172 break;
173 case GAMEOBJECT_TYPE_TRANSPORT:
174 flags |= UPDATEFLAG_TRANSPORT;
175 break;
176 default:
177 break;
181 if(isType(TYPEMASK_UNIT))
183 if(((Unit*)this)->getVictim())
184 flags |= UPDATEFLAG_HAS_TARGET;
188 //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got flags: %X, flags2: %X", updatetype, m_objectTypeId, flags, flags2);
190 ByteBuffer buf(500);
191 buf << (uint8)updatetype;
192 //buf.append(GetPackGUID()); //client crashes when using this
193 buf << (uint8)0xFF << GetGUID();
194 buf << (uint8)m_objectTypeId;
196 _BuildMovementUpdate(&buf, flags, flags2);
198 UpdateMask updateMask;
199 updateMask.SetCount( m_valuesCount );
200 _SetCreateBits( &updateMask, target );
201 _BuildValuesUpdate(updatetype, &buf, &updateMask, target );
202 data->AddUpdateBlock(buf);
205 void Object::BuildUpdate(UpdateDataMapType &update_players)
207 ObjectAccessor::_buildUpdateObject(this,update_players);
208 ClearUpdateMask(true);
211 void Object::SendUpdateToPlayer(Player* player)
213 // send update to another players
214 SendUpdateObjectToAllExcept(player);
216 // send create update to player
217 UpdateData upd;
218 WorldPacket packet;
220 upd.Clear();
221 BuildCreateUpdateBlockForPlayer(&upd, player);
222 upd.BuildPacket(&packet);
223 player->GetSession()->SendPacket(&packet);
225 // now object updated/(create updated)
228 void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
230 ByteBuffer buf(500);
232 buf << (uint8) UPDATETYPE_VALUES;
233 //buf.append(GetPackGUID()); //client crashes when using this. but not have crash in debug mode
234 buf << (uint8)0xFF;
235 buf << GetGUID();
237 UpdateMask updateMask;
238 updateMask.SetCount( m_valuesCount );
240 _SetUpdateBits( &updateMask, target );
241 _BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target );
243 data->AddUpdateBlock(buf);
246 void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
248 data->AddOutOfRangeGUID(GetGUID());
251 void Object::DestroyForPlayer(Player *target) const
253 ASSERT(target);
255 WorldPacket data(SMSG_DESTROY_OBJECT, 8);
256 data << GetGUID();
257 data << uint8(0); // WotLK (bool)
258 target->GetSession()->SendPacket( &data );
261 void Object::_BuildMovementUpdate(ByteBuffer * data, uint8 flags, uint32 flags2) const
263 uint16 unk_flags = ((GetTypeId() == TYPEID_PLAYER) ? ((Player*)this)->m_movementInfo.unk1 : 0);
265 if(GetTypeId() == TYPEID_UNIT)
266 if(((Creature*)this)->isVehicle())
267 unk_flags |= 0x20; // always allow pitch
269 *data << (uint8)flags; // update flags
271 // 0x20
272 if (flags & UPDATEFLAG_LIVING)
274 switch(GetTypeId())
276 case TYPEID_UNIT:
278 flags2 = ((Unit*)this)->GetUnitMovementFlags();
280 break;
281 case TYPEID_PLAYER:
283 flags2 = ((Player*)this)->GetUnitMovementFlags();
285 if(((Player*)this)->GetTransport())
286 flags2 |= MOVEMENTFLAG_ONTRANSPORT;
287 else
288 flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
290 // remove unknown, unused etc flags for now
291 flags2 &= ~MOVEMENTFLAG_SPLINE2; // will be set manually
293 if(((Player*)this)->isInFlight())
295 WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
296 flags2 = (MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
299 break;
302 *data << uint32(flags2); // movement flags
303 *data << uint16(unk_flags); // unknown 2.3.0
304 *data << uint32(getMSTime()); // time (in milliseconds)
307 // 0x40
308 if (flags & UPDATEFLAG_HAS_POSITION)
310 // 0x02
311 if(flags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
313 *data << (float)0;
314 *data << (float)0;
315 *data << (float)0;
316 *data << ((WorldObject *)this)->GetOrientation();
318 else
320 *data << ((WorldObject *)this)->GetPositionX();
321 *data << ((WorldObject *)this)->GetPositionY();
322 *data << ((WorldObject *)this)->GetPositionZ();
323 *data << ((WorldObject *)this)->GetOrientation();
327 // 0x20
328 if(flags & UPDATEFLAG_LIVING)
330 // 0x00000200
331 if(flags2 & MOVEMENTFLAG_ONTRANSPORT)
333 if(GetTypeId() == TYPEID_PLAYER)
335 *data << (uint64)((Player*)this)->GetTransport()->GetGUID();
336 *data << (float)((Player*)this)->GetTransOffsetX();
337 *data << (float)((Player*)this)->GetTransOffsetY();
338 *data << (float)((Player*)this)->GetTransOffsetZ();
339 *data << (float)((Player*)this)->GetTransOffsetO();
340 *data << (uint32)((Player*)this)->GetTransTime();
341 *data << (int8)((Player*)this)->GetTransSeat();
343 //MaNGOS currently not have support for other than player on transport
346 // 0x02200000
347 if((flags2 & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2)) || (unk_flags & 0x20))
349 if(GetTypeId() == TYPEID_PLAYER)
350 *data << (float)((Player*)this)->m_movementInfo.s_pitch;
351 else
352 *data << (float)0; // is't part of movement packet, we must store and send it...
355 if(GetTypeId() == TYPEID_PLAYER)
356 *data << (uint32)((Player*)this)->m_movementInfo.fallTime;
357 else
358 *data << (uint32)0; // last fall time
360 // 0x00001000
361 if(flags2 & MOVEMENTFLAG_JUMPING)
363 if(GetTypeId() == TYPEID_PLAYER)
365 *data << (float)((Player*)this)->m_movementInfo.j_unk;
366 *data << (float)((Player*)this)->m_movementInfo.j_sinAngle;
367 *data << (float)((Player*)this)->m_movementInfo.j_cosAngle;
368 *data << (float)((Player*)this)->m_movementInfo.j_xyspeed;
370 else
372 *data << (float)0;
373 *data << (float)0;
374 *data << (float)0;
375 *data << (float)0;
379 // 0x04000000
380 if(flags2 & MOVEMENTFLAG_SPLINE)
382 if(GetTypeId() == TYPEID_PLAYER)
383 *data << (float)((Player*)this)->m_movementInfo.u_unk1;
384 else
385 *data << (float)0;
388 *data << ((Unit*)this)->GetSpeed( MOVE_WALK );
389 *data << ((Unit*)this)->GetSpeed( MOVE_RUN );
390 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM_BACK );
391 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM );
392 *data << ((Unit*)this)->GetSpeed( MOVE_RUN_BACK );
393 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT );
394 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT_BACK );
395 *data << ((Unit*)this)->GetSpeed( MOVE_TURN_RATE );
396 *data << ((Unit*)this)->GetSpeed( MOVE_PITCH_RATE );
398 // 0x08000000
399 if(flags2 & MOVEMENTFLAG_SPLINE2)
401 if(GetTypeId() != TYPEID_PLAYER)
403 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 for non-player");
404 return;
407 if(!((Player*)this)->isInFlight())
409 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 but not in flight");
410 return;
413 WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
415 FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(((Player*)this)->GetMotionMaster()->top());
417 uint32 flags3 = 0x00000300;
419 *data << uint32(flags3); // splines flag?
421 if(flags3 & 0x10000) // probably x,y,z coords there
423 *data << (float)0;
424 *data << (float)0;
425 *data << (float)0;
428 if(flags3 & 0x20000) // probably guid there
430 *data << uint64(0);
433 if(flags3 & 0x40000) // may be orientation
435 *data << (float)0;
438 Path &path = fmg->GetPath();
440 float x, y, z;
441 ((Player*)this)->GetPosition(x, y, z);
443 uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
444 uint32 traveltime = uint32(path.GetTotalLength() * 32);
446 *data << uint32(inflighttime); // passed move time?
447 *data << uint32(traveltime); // full move time?
448 *data << uint32(0); // ticks count?
450 uint32 poscount = uint32(path.Size());
452 *data << uint32(poscount); // points count
454 for(uint32 i = 0; i < poscount; ++i)
456 *data << path.GetNodes()[i].x;
457 *data << path.GetNodes()[i].y;
458 *data << path.GetNodes()[i].z;
461 *data << uint8(0); // added in 3.0.8
463 /*for(uint32 i = 0; i < poscount; i++)
465 // path points
466 *data << (float)0;
467 *data << (float)0;
468 *data << (float)0;
471 *data << path.GetNodes()[poscount-1].x;
472 *data << path.GetNodes()[poscount-1].y;
473 *data << path.GetNodes()[poscount-1].z;
475 // target position (path end)
476 /**data << ((Unit*)this)->GetPositionX();
477 *data << ((Unit*)this)->GetPositionY();
478 *data << ((Unit*)this)->GetPositionZ();*/
482 // 0x8
483 if(flags & UPDATEFLAG_LOWGUID)
485 switch(GetTypeId())
487 case TYPEID_OBJECT:
488 case TYPEID_ITEM:
489 case TYPEID_CONTAINER:
490 case TYPEID_GAMEOBJECT:
491 case TYPEID_DYNAMICOBJECT:
492 case TYPEID_CORPSE:
493 *data << uint32(GetGUIDLow()); // GetGUIDLow()
494 break;
495 case TYPEID_UNIT:
496 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
497 break;
498 case TYPEID_PLAYER:
499 if(flags & UPDATEFLAG_SELF)
500 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
501 else
502 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
503 break;
504 default:
505 *data << uint32(0x00000000); // unk
506 break;
510 // 0x10
511 if(flags & UPDATEFLAG_HIGHGUID)
513 switch(GetTypeId())
515 case TYPEID_OBJECT:
516 case TYPEID_ITEM:
517 case TYPEID_CONTAINER:
518 case TYPEID_GAMEOBJECT:
519 case TYPEID_DYNAMICOBJECT:
520 case TYPEID_CORPSE:
521 *data << uint32(GetGUIDHigh()); // GetGUIDHigh()
522 break;
523 case TYPEID_UNIT:
524 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
525 break;
526 case TYPEID_PLAYER:
527 if(flags & UPDATEFLAG_SELF)
528 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
529 else
530 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
531 break;
532 default:
533 *data << uint32(0x00000000); // unk
534 break;
538 // 0x4
539 if(flags & UPDATEFLAG_HAS_TARGET) // packed guid (current target guid)
541 if(Unit *victim = ((Unit*)this)->getVictim())
542 data->append(victim->GetPackGUID());
543 else
544 *data << uint8(0);
547 // 0x2
548 if(flags & UPDATEFLAG_TRANSPORT)
550 *data << uint32(getMSTime()); // ms time
553 // 0x80
554 if(flags & UPDATEFLAG_VEHICLE) // unused for now
556 *data << uint32(((Vehicle*)this)->GetVehicleId()); // vehicle id
557 *data << float(0); // facing adjustment
561 void Object::_BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
563 if(!target)
564 return;
566 bool IsActivateToQuest = false;
567 if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
569 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
571 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
573 IsActivateToQuest = true;
574 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
578 else //case UPDATETYPE_VALUES
580 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
582 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
584 IsActivateToQuest = true;
586 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
587 updateMask->SetBit(GAMEOBJECT_BYTES_1);
591 WPAssert(updateMask && updateMask->GetCount() == m_valuesCount);
593 *data << (uint8)updateMask->GetBlockCount();
594 data->append( updateMask->GetMask(), updateMask->GetLength() );
596 // 2 specialized loops for speed optimization in non-unit case
597 if(isType(TYPEMASK_UNIT)) // unit (creature/player) case
599 for( uint16 index = 0; index < m_valuesCount; index ++ )
601 if( updateMask->GetBit( index ) )
603 if( index == UNIT_NPC_FLAGS )
605 // remove custom flag before sending
606 uint32 appendValue = m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD;
608 if (GetTypeId() == TYPEID_UNIT && !target->canSeeSpellClickOn((Creature*)this))
609 appendValue &= ~UNIT_NPC_FLAG_SPELLCLICK;
611 *data << uint32(appendValue);
613 // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
614 else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
616 // convert from float to uint32 and send
617 *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
619 // there are some float values which may be negative or can't get negative due to other checks
620 else if ((index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4) ||
621 (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) ||
622 (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) ||
623 (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4))
625 *data << uint32(m_floatValues[ index ]);
627 // Gamemasters should be always able to select units - remove not selectable flag
628 else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
630 *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
632 // hide lootable animation for unallowed players
633 else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
635 if(!target->isAllowedToLoot((Creature*)this))
636 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
637 else
638 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_OTHER_TAGGER);
640 else
642 // send in current format (float as float, uint32 as uint32)
643 *data << m_uint32Values[ index ];
648 else if(isType(TYPEMASK_GAMEOBJECT)) // gameobject case
650 for( uint16 index = 0; index < m_valuesCount; index ++ )
652 if( updateMask->GetBit( index ) )
654 // send in current format (float as float, uint32 as uint32)
655 if ( index == GAMEOBJECT_DYNAMIC )
657 if(IsActivateToQuest )
659 switch(((GameObject*)this)->GetGoType())
661 case GAMEOBJECT_TYPE_CHEST:
662 *data << uint32(9); // enable quest object. Represent 9, but 1 for client before 2.3.0
663 break;
664 case GAMEOBJECT_TYPE_GOOBER:
665 *data << uint32(1);
666 break;
667 default:
668 *data << uint32(0); // unknown. not happen.
669 break;
672 else
673 *data << uint32(0); // disable quest object
675 else
676 *data << m_uint32Values[ index ]; // other cases
680 else // other objects case (no special index checks)
682 for( uint16 index = 0; index < m_valuesCount; index ++ )
684 if( updateMask->GetBit( index ) )
686 // send in current format (float as float, uint32 as uint32)
687 *data << m_uint32Values[ index ];
693 void Object::ClearUpdateMask(bool remove)
695 for( uint16 index = 0; index < m_valuesCount; index ++ )
697 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
698 m_uint32Values_mirror[index] = m_uint32Values[index];
700 if(m_objectUpdated)
702 if(remove)
703 ObjectAccessor::Instance().RemoveUpdateObject(this);
704 m_objectUpdated = false;
708 // Send current value fields changes to all viewers
709 void Object::SendUpdateObjectToAllExcept(Player* exceptPlayer)
711 // changes will be send in create packet
712 if(!IsInWorld())
713 return;
715 // nothing do
716 if(!m_objectUpdated)
717 return;
719 ObjectAccessor::UpdateObject(this,exceptPlayer);
722 bool Object::LoadValues(const char* data)
724 if(!m_uint32Values) _InitValues();
726 Tokens tokens = StrSplit(data, " ");
728 if(tokens.size() != m_valuesCount)
729 return false;
731 Tokens::iterator iter;
732 int index;
733 for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
735 m_uint32Values[index] = atol((*iter).c_str());
738 return true;
741 void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
743 for( uint16 index = 0; index < m_valuesCount; index ++ )
745 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
746 updateMask->SetBit(index);
750 void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
752 for( uint16 index = 0; index < m_valuesCount; index++ )
754 if(GetUInt32Value(index) != 0)
755 updateMask->SetBit(index);
759 void Object::SetInt32Value( uint16 index, int32 value )
761 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
763 if(m_int32Values[ index ] != value)
765 m_int32Values[ index ] = value;
767 if(m_inWorld)
769 if(!m_objectUpdated)
771 ObjectAccessor::Instance().AddUpdateObject(this);
772 m_objectUpdated = true;
778 void Object::SetUInt32Value( uint16 index, uint32 value )
780 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
782 if(m_uint32Values[ index ] != value)
784 m_uint32Values[ index ] = value;
786 if(m_inWorld)
788 if(!m_objectUpdated)
790 ObjectAccessor::Instance().AddUpdateObject(this);
791 m_objectUpdated = true;
797 void Object::SetUInt64Value( uint16 index, const uint64 &value )
799 ASSERT( index + 1 < m_valuesCount || PrintIndexError( index , true ) );
800 if(*((uint64*)&(m_uint32Values[ index ])) != value)
802 m_uint32Values[ index ] = *((uint32*)&value);
803 m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
805 if(m_inWorld)
807 if(!m_objectUpdated)
809 ObjectAccessor::Instance().AddUpdateObject(this);
810 m_objectUpdated = true;
816 void Object::SetFloatValue( uint16 index, float value )
818 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
820 if(m_floatValues[ index ] != value)
822 m_floatValues[ index ] = value;
824 if(m_inWorld)
826 if(!m_objectUpdated)
828 ObjectAccessor::Instance().AddUpdateObject(this);
829 m_objectUpdated = true;
835 void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
837 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
839 if(offset > 4)
841 sLog.outError("Object::SetByteValue: wrong offset %u", offset);
842 return;
845 if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
847 m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
848 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
850 if(m_inWorld)
852 if(!m_objectUpdated)
854 ObjectAccessor::Instance().AddUpdateObject(this);
855 m_objectUpdated = true;
861 void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
863 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
865 if(offset > 2)
867 sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
868 return;
871 if(uint8(m_uint32Values[ index ] >> (offset * 16)) != value)
873 m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
874 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
876 if(m_inWorld)
878 if(!m_objectUpdated)
880 ObjectAccessor::Instance().AddUpdateObject(this);
881 m_objectUpdated = true;
887 void Object::SetStatFloatValue( uint16 index, float value)
889 if(value < 0)
890 value = 0.0f;
892 SetFloatValue(index, value);
895 void Object::SetStatInt32Value( uint16 index, int32 value)
897 if(value < 0)
898 value = 0;
900 SetUInt32Value(index, uint32(value));
903 void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
905 int32 cur = GetUInt32Value(index);
906 cur += (apply ? val : -val);
907 if(cur < 0)
908 cur = 0;
909 SetUInt32Value(index,cur);
912 void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
914 int32 cur = GetInt32Value(index);
915 cur += (apply ? val : -val);
916 SetInt32Value(index,cur);
919 void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply)
921 float cur = GetFloatValue(index);
922 cur += (apply ? val : -val);
923 SetFloatValue(index,cur);
926 void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply)
928 float cur = GetFloatValue(index);
929 cur += (apply ? val : -val);
930 if(cur < 0)
931 cur = 0;
932 SetFloatValue(index,cur);
935 void Object::SetFlag( uint16 index, uint32 newFlag )
937 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
938 uint32 oldval = m_uint32Values[ index ];
939 uint32 newval = oldval | newFlag;
941 if(oldval != newval)
943 m_uint32Values[ index ] = newval;
945 if(m_inWorld)
947 if(!m_objectUpdated)
949 ObjectAccessor::Instance().AddUpdateObject(this);
950 m_objectUpdated = true;
956 void Object::RemoveFlag( uint16 index, uint32 oldFlag )
958 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
959 uint32 oldval = m_uint32Values[ index ];
960 uint32 newval = oldval & ~oldFlag;
962 if(oldval != newval)
964 m_uint32Values[ index ] = newval;
966 if(m_inWorld)
968 if(!m_objectUpdated)
970 ObjectAccessor::Instance().AddUpdateObject(this);
971 m_objectUpdated = true;
977 void Object::SetByteFlag( uint16 index, uint8 offset, uint8 newFlag )
979 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
981 if(offset > 4)
983 sLog.outError("Object::SetByteFlag: wrong offset %u", offset);
984 return;
987 if(!(uint8(m_uint32Values[ index ] >> (offset * 8)) & newFlag))
989 m_uint32Values[ index ] |= uint32(uint32(newFlag) << (offset * 8));
991 if(m_inWorld)
993 if(!m_objectUpdated)
995 ObjectAccessor::Instance().AddUpdateObject(this);
996 m_objectUpdated = true;
1002 void Object::RemoveByteFlag( uint16 index, uint8 offset, uint8 oldFlag )
1004 ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
1006 if(offset > 4)
1008 sLog.outError("Object::RemoveByteFlag: wrong offset %u", offset);
1009 return;
1012 if(uint8(m_uint32Values[ index ] >> (offset * 8)) & oldFlag)
1014 m_uint32Values[ index ] &= ~uint32(uint32(oldFlag) << (offset * 8));
1016 if(m_inWorld)
1018 if(!m_objectUpdated)
1020 ObjectAccessor::Instance().AddUpdateObject(this);
1021 m_objectUpdated = true;
1027 bool Object::PrintIndexError(uint32 index, bool set) const
1029 sLog.outError("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);
1031 // assert must fail after function call
1032 return false;
1035 WorldObject::WorldObject()
1036 : m_mapId(0), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL),
1037 m_positionX(0.0f), m_positionY(0.0f), m_positionZ(0.0f), m_orientation(0.0f)
1041 void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 mapid, uint32 phaseMask )
1043 Object::_Create(guidlow, 0, guidhigh);
1045 m_mapId = mapid;
1046 m_phaseMask = phaseMask;
1049 uint32 WorldObject::GetZoneId() const
1051 return MapManager::Instance().GetBaseMap(m_mapId)->GetZoneId(m_positionX,m_positionY,m_positionZ);
1054 uint32 WorldObject::GetAreaId() const
1056 return MapManager::Instance().GetBaseMap(m_mapId)->GetAreaId(m_positionX,m_positionY,m_positionZ);
1059 void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const
1061 MapManager::Instance().GetBaseMap(m_mapId)->GetZoneAndAreaId(zoneid,areaid,m_positionX,m_positionY,m_positionZ);
1064 InstanceData* WorldObject::GetInstanceData()
1066 Map *map = GetMap();
1067 return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
1070 //slow
1071 float WorldObject::GetDistance(const WorldObject* obj) const
1073 float dx = GetPositionX() - obj->GetPositionX();
1074 float dy = GetPositionY() - obj->GetPositionY();
1075 float dz = GetPositionZ() - obj->GetPositionZ();
1076 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1077 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1078 return ( dist > 0 ? dist : 0);
1081 float WorldObject::GetDistance2d(float x, float y) const
1083 float dx = GetPositionX() - x;
1084 float dy = GetPositionY() - y;
1085 float sizefactor = GetObjectSize();
1086 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1087 return ( dist > 0 ? dist : 0);
1090 float WorldObject::GetDistance(float x, float y, float z) const
1092 float dx = GetPositionX() - x;
1093 float dy = GetPositionY() - y;
1094 float dz = GetPositionZ() - z;
1095 float sizefactor = GetObjectSize();
1096 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1097 return ( dist > 0 ? dist : 0);
1100 float WorldObject::GetDistance2d(const WorldObject* obj) const
1102 float dx = GetPositionX() - obj->GetPositionX();
1103 float dy = GetPositionY() - obj->GetPositionY();
1104 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1105 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1106 return ( dist > 0 ? dist : 0);
1109 float WorldObject::GetDistanceZ(const WorldObject* obj) const
1111 float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1112 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1113 float dist = dz - sizefactor;
1114 return ( dist > 0 ? dist : 0);
1117 bool WorldObject::IsWithinDist(float x, float y, float z, float dist2compare, bool is3D) const
1119 float dx = GetPositionX() - x;
1120 float dy = GetPositionY() - y;
1121 float distsq = dx*dx + dy*dy;
1122 if(is3D)
1124 float dz = GetPositionZ() - z;
1125 distsq += dz*dz;
1127 float sizefactor = GetObjectSize();
1128 float maxdist = dist2compare + sizefactor;
1130 return distsq < maxdist * maxdist;
1133 bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const
1135 float dx = GetPositionX() - obj->GetPositionX();
1136 float dy = GetPositionY() - obj->GetPositionY();
1137 float distsq = dx*dx + dy*dy;
1138 if(is3D)
1140 float dz = GetPositionZ() - obj->GetPositionZ();
1141 distsq += dz*dz;
1143 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1144 float maxdist = dist2compare + sizefactor;
1146 return distsq < maxdist * maxdist;
1149 bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1151 if (!IsInMap(obj)) return false;
1152 float ox,oy,oz;
1153 obj->GetPosition(ox,oy,oz);
1154 return(IsWithinLOS(ox, oy, oz ));
1157 bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const
1159 float x,y,z;
1160 GetPosition(x,y,z);
1161 VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1162 return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1165 bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const
1167 float dx1 = GetPositionX() - obj1->GetPositionX();
1168 float dy1 = GetPositionY() - obj1->GetPositionY();
1169 float distsq1 = dx1*dx1 + dy1*dy1;
1170 if(is3D)
1172 float dz1 = GetPositionZ() - obj1->GetPositionZ();
1173 distsq1 += dz1*dz1;
1176 float dx2 = GetPositionX() - obj2->GetPositionX();
1177 float dy2 = GetPositionY() - obj2->GetPositionY();
1178 float distsq2 = dx2*dx2 + dy2*dy2;
1179 if(is3D)
1181 float dz2 = GetPositionZ() - obj2->GetPositionZ();
1182 distsq2 += dz2*dz2;
1185 return distsq1 < distsq2;
1188 bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange) const
1190 float dx = GetPositionX() - obj->GetPositionX();
1191 float dy = GetPositionY() - obj->GetPositionY();
1192 float dz = GetPositionZ() - obj->GetPositionZ();
1193 float distsq = dx*dx + dy*dy + dz*dz;
1195 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1197 float mindist = minRange + sizefactor;
1198 if(distsq < mindist * mindist)
1199 return false;
1201 float maxdist = maxRange + sizefactor;
1202 return distsq < maxdist * maxdist;
1205 bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const
1207 float dx = GetPositionX() - x;
1208 float dy = GetPositionY() - y;
1209 float distsq = dx*dx + dy*dy;
1211 float sizefactor = GetObjectSize();
1213 float mindist = minRange + sizefactor;
1214 if(distsq < mindist * mindist)
1215 return false;
1217 float maxdist = maxRange + sizefactor;
1218 return distsq < maxdist * maxdist;
1221 float WorldObject::GetAngle(const WorldObject* obj) const
1223 if(!obj) return 0;
1224 return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1227 // Return angle in range 0..2*pi
1228 float WorldObject::GetAngle( const float x, const float y ) const
1230 float dx = x - GetPositionX();
1231 float dy = y - GetPositionY();
1233 float ang = atan2(dy, dx);
1234 ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1235 return ang;
1238 bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1240 // always have self in arc
1241 if(obj == this)
1242 return true;
1244 float arc = arcangle;
1246 // move arc to range 0.. 2*pi
1247 while( arc >= 2.0f * M_PI )
1248 arc -= 2.0f * M_PI;
1249 while( arc < 0 )
1250 arc += 2.0f * M_PI;
1252 float angle = GetAngle( obj );
1253 angle -= m_orientation;
1255 // move angle to range -pi ... +pi
1256 while( angle > M_PI)
1257 angle -= 2.0f * M_PI;
1258 while(angle < -M_PI)
1259 angle += 2.0f * M_PI;
1261 float lborder = -1 * (arc/2.0f); // in range -pi..0
1262 float rborder = (arc/2.0f); // in range 0..pi
1263 return (( angle >= lborder ) && ( angle <= rborder ));
1266 void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1268 if(distance==0)
1270 rand_x = x;
1271 rand_y = y;
1272 rand_z = z;
1273 return;
1276 // angle to face `obj` to `this`
1277 float angle = rand_norm()*2*M_PI;
1278 float new_dist = rand_norm()*distance;
1280 rand_x = x + new_dist * cos(angle);
1281 rand_y = y + new_dist * sin(angle);
1282 rand_z = z;
1284 MaNGOS::NormalizeMapCoord(rand_x);
1285 MaNGOS::NormalizeMapCoord(rand_y);
1286 UpdateGroundPositionZ(rand_x,rand_y,rand_z); // update to LOS height if available
1289 void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1291 float new_z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(x,y,z,true);
1292 if(new_z > INVALID_HEIGHT)
1293 z = new_z+ 0.05f; // just to be sure that we are not a few pixel under the surface
1296 bool WorldObject::IsPositionValid() const
1298 return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1301 void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1303 WorldPacket data(SMSG_MESSAGECHAT, 200);
1304 BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1305 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1308 void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1310 WorldPacket data(SMSG_MESSAGECHAT, 200);
1311 BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1312 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1315 void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1317 WorldPacket data(SMSG_MESSAGECHAT, 200);
1318 BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1319 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1322 void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1324 Player *player = objmgr.GetPlayer(receiver);
1325 if(!player || !player->GetSession())
1326 return;
1328 WorldPacket data(SMSG_MESSAGECHAT, 200);
1329 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1331 player->GetSession()->SendPacket(&data);
1334 namespace MaNGOS
1336 class MonsterChatBuilder
1338 public:
1339 MonsterChatBuilder(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID)
1340 : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), i_targetGUID(targetGUID) {}
1341 void operator()(WorldPacket& data, int32 loc_idx)
1343 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1345 // TODO: i_object.GetName() also must be localized?
1346 i_object.BuildMonsterChat(&data,i_msgtype,text,i_language,i_object.GetNameForLocaleIdx(loc_idx),i_targetGUID);
1349 private:
1350 WorldObject const& i_object;
1351 ChatMsg i_msgtype;
1352 int32 i_textId;
1353 uint32 i_language;
1354 uint64 i_targetGUID;
1356 } // namespace MaNGOS
1358 void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1360 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1362 Cell cell(p);
1363 cell.data.Part.reserved = ALL_DISTRICT;
1364 cell.SetNoCreate();
1366 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid);
1367 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1368 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),say_do);
1369 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1370 CellLock<GridReadGuard> cell_lock(cell, p);
1371 cell_lock->Visit(cell_lock, message, *GetMap());
1374 void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1376 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1378 Cell cell(p);
1379 cell.data.Part.reserved = ALL_DISTRICT;
1380 cell.SetNoCreate();
1382 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1383 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1384 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),say_do);
1385 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1386 CellLock<GridReadGuard> cell_lock(cell, p);
1387 cell_lock->Visit(cell_lock, message, *GetMap());
1390 void WorldObject::MonsterYellToZone(int32 textId, uint32 language, uint64 TargetGuid)
1392 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1393 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1395 uint32 zoneid = GetZoneId();
1397 Map::PlayerList const& pList = GetMap()->GetPlayers();
1398 for(Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
1399 if(itr->getSource()->GetZoneId()==zoneid)
1400 say_do(itr->getSource());
1403 void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1405 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1407 Cell cell(p);
1408 cell.data.Part.reserved = ALL_DISTRICT;
1409 cell.SetNoCreate();
1411 MaNGOS::MonsterChatBuilder say_build(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid);
1412 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1413 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),say_do);
1414 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1415 CellLock<GridReadGuard> cell_lock(cell, p);
1416 cell_lock->Visit(cell_lock, message, *GetMap());
1419 void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1421 Player *player = objmgr.GetPlayer(receiver);
1422 if(!player || !player->GetSession())
1423 return;
1425 uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1426 char const* text = objmgr.GetMangosString(textId,loc_idx);
1428 WorldPacket data(SMSG_MESSAGECHAT, 200);
1429 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetNameForLocaleIdx(loc_idx),receiver);
1431 player->GetSession()->SendPacket(&data);
1434 void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1436 bool pre = (msgtype==CHAT_MSG_MONSTER_EMOTE || msgtype==CHAT_MSG_RAID_BOSS_EMOTE);
1438 *data << (uint8)msgtype;
1439 *data << (uint32)language;
1440 *data << (uint64)GetGUID();
1441 *data << (uint32)0; //2.1.0
1442 *data << (uint32)(strlen(name)+1);
1443 *data << name;
1444 *data << (uint64)targetGuid; //Unit Target
1445 if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1447 *data << (uint32)1; // target name length
1448 *data << (uint8)0; // target name
1450 *data << (uint32)(strlen(text)+1+(pre?3:0));
1451 if(pre)
1452 data->append("%s ",3);
1453 *data << text;
1454 *data << (uint8)0; // ChatTag
1457 void WorldObject::BuildHeartBeatMsg(WorldPacket *data) const
1459 //Heartbeat message cannot be used for non-units
1460 if (!isType(TYPEMASK_UNIT))
1461 return;
1463 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
1464 data->append(GetPackGUID());
1465 *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1466 *data << uint16(0); // 2.3.0
1467 *data << getMSTime(); // time
1468 *data << m_positionX;
1469 *data << m_positionY;
1470 *data << m_positionZ;
1471 *data << m_orientation;
1472 *data << uint32(0);
1475 void WorldObject::BuildTeleportAckMsg(WorldPacket *data, float x, float y, float z, float ang) const
1477 //TeleportAck message cannot be used for non-units
1478 if (!isType(TYPEMASK_UNIT))
1479 return;
1481 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
1482 data->append(GetPackGUID());
1483 *data << uint32(0); // this value increments every time
1484 *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1485 *data << uint16(0); // 2.3.0
1486 *data << getMSTime(); // time
1487 *data << x;
1488 *data << y;
1489 *data << z;
1490 *data << ang;
1491 *data << uint32(0);
1494 void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1496 GetMap()->MessageBroadcast(this, data);
1499 void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1501 GetMap()->MessageDistBroadcast(this, data, dist);
1504 void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1506 WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1507 data << guid;
1508 SendMessageToSet(&data, true);
1511 Map* WorldObject::GetMap() const
1513 return MapManager::Instance().GetMap(GetMapId(), this);
1516 Map const* WorldObject::GetBaseMap() const
1518 return MapManager::Instance().GetBaseMap(GetMapId());
1521 void WorldObject::AddObjectToRemoveList()
1523 Map* map = GetMap();
1524 if(!map)
1526 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());
1527 return;
1530 map->AddObjectToRemoveList(this);
1533 Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1535 TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1537 pCreature->SetInstanceId(GetInstanceId());
1538 uint32 team = 0;
1539 if (GetTypeId()==TYPEID_PLAYER)
1540 team = ((Player*)this)->GetTeam();
1542 if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), GetPhaseMask(), id, team))
1544 delete pCreature;
1545 return NULL;
1548 if (x == 0.0f && y == 0.0f && z == 0.0f)
1549 GetClosePoint(x, y, z, pCreature->GetObjectSize());
1551 pCreature->Relocate(x, y, z, ang);
1553 if(!pCreature->IsPositionValid())
1555 sLog.outError("Creature (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
1556 delete pCreature;
1557 return NULL;
1560 pCreature->Summon(spwtype, despwtime);
1562 if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1563 ((Creature*)this)->AI()->JustSummoned(pCreature);
1565 //return the creature therewith the summoner has access to it
1566 return pCreature;
1569 namespace MaNGOS
1571 class NearUsedPosDo
1573 public:
1574 NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1575 : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1577 void operator()(Corpse*) const {}
1578 void operator()(DynamicObject*) const {}
1580 void operator()(Creature* c) const
1582 // skip self or target
1583 if(c==i_searcher || c==&i_object)
1584 return;
1586 float x,y,z;
1588 if( !c->isAlive() || c->hasUnitState(UNIT_STAT_ROOT | UNIT_STAT_STUNNED | UNIT_STAT_DISTRACTED) ||
1589 !c->GetMotionMaster()->GetDestination(x,y,z) )
1591 x = c->GetPositionX();
1592 y = c->GetPositionY();
1595 add(c,x,y);
1598 template<class T>
1599 void operator()(T* u) const
1601 // skip self or target
1602 if(u==i_searcher || u==&i_object)
1603 return;
1605 float x,y;
1607 x = u->GetPositionX();
1608 y = u->GetPositionY();
1610 add(u,x,y);
1613 // we must add used pos that can fill places around center
1614 void add(WorldObject* u, float x, float y) const
1616 // u is too nearest/far away to i_object
1617 if(!i_object.IsInRange2d(x,y,i_selector.m_dist - i_selector.m_size,i_selector.m_dist + i_selector.m_size))
1618 return;
1620 float angle = i_object.GetAngle(u)-i_angle;
1622 // move angle to range -pi ... +pi
1623 while( angle > M_PI)
1624 angle -= 2.0f * M_PI;
1625 while(angle < -M_PI)
1626 angle += 2.0f * M_PI;
1628 // dist include size of u
1629 float dist2d = i_object.GetDistance2d(x,y);
1630 i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1632 private:
1633 WorldObject const& i_object;
1634 WorldObject const* i_searcher;
1635 float i_angle;
1636 ObjectPosSelector& i_selector;
1638 } // namespace MaNGOS
1640 //===================================================================================================
1642 void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1644 x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1645 y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1647 MaNGOS::NormalizeMapCoord(x);
1648 MaNGOS::NormalizeMapCoord(y);
1651 void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1653 GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1654 z = GetPositionZ();
1656 // if detection disabled, return first point
1657 if(!sWorld.getConfig(CONFIG_DETECT_POS_COLLISION))
1659 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1660 return;
1663 // or remember first point
1664 float first_x = x;
1665 float first_y = y;
1666 bool first_los_conflict = false; // first point LOS problems
1668 // prepare selector for work
1669 ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1671 // adding used positions around object
1673 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1674 Cell cell(p);
1675 cell.data.Part.reserved = ALL_DISTRICT;
1676 cell.SetNoCreate();
1678 MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1679 MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(this,u_do);
1681 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer > grid_obj_worker(worker);
1682 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1684 CellLock<GridReadGuard> cell_lock(cell, p);
1685 cell_lock->Visit(cell_lock, grid_obj_worker, *GetMap());
1686 cell_lock->Visit(cell_lock, world_obj_worker, *GetMap());
1689 // maybe can just place in primary position
1690 if( selector.CheckOriginal() )
1692 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1694 if(IsWithinLOS(x,y,z))
1695 return;
1697 first_los_conflict = true; // first point have LOS problems
1700 float angle; // candidate of angle for free pos
1702 // special case when one from list empty and then empty side preferred
1703 if(selector.FirstAngle(angle))
1705 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1706 z = GetPositionZ();
1707 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1709 if(IsWithinLOS(x,y,z))
1710 return;
1713 // set first used pos in lists
1714 selector.InitializeAngle();
1716 // select in positions after current nodes (selection one by one)
1717 while(selector.NextAngle(angle)) // angle for free pos
1719 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1720 z = GetPositionZ();
1721 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1723 if(IsWithinLOS(x,y,z))
1724 return;
1727 // BAD NEWS: not free pos (or used or have LOS problems)
1728 // Attempt find _used_ pos without LOS problem
1730 if(!first_los_conflict)
1732 x = first_x;
1733 y = first_y;
1735 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1736 return;
1739 // special case when one from list empty and then empty side preferred
1740 if( selector.IsNonBalanced() )
1742 if(!selector.FirstAngle(angle)) // _used_ pos
1744 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1745 z = GetPositionZ();
1746 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1748 if(IsWithinLOS(x,y,z))
1749 return;
1753 // set first used pos in lists
1754 selector.InitializeAngle();
1756 // select in positions after current nodes (selection one by one)
1757 while(selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem
1759 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1760 z = GetPositionZ();
1761 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1763 if(IsWithinLOS(x,y,z))
1764 return;
1767 // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1768 x = first_x;
1769 y = first_y;
1771 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1774 void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update)
1776 m_phaseMask = newPhaseMask;
1778 if(update && IsInWorld())
1779 ObjectAccessor::UpdateObjectVisibility(this);
1782 void WorldObject::PlayDistanceSound( uint32 sound_id, Player* target /*= NULL*/ )
1784 WorldPacket data(SMSG_PLAY_OBJECT_SOUND,4+8);
1785 data << uint32(sound_id);
1786 data << GetGUID();
1787 if (target)
1788 target->SendDirectMessage( &data );
1789 else
1790 SendMessageToSet( &data, true );
1793 void WorldObject::PlayDirectSound( uint32 sound_id, Player* target /*= NULL*/ )
1795 WorldPacket data(SMSG_PLAY_SOUND, 4);
1796 data << uint32(sound_id);
1797 if (target)
1798 target->SendDirectMessage( &data );
1799 else
1800 SendMessageToSet( &data, true );