root/trunk/src/game/Object.cpp @ 42

Revision 42, 45.9 kB (checked in by yumileroy, 17 years ago)

[svn] * Send ShutdownMsg? to console using outstring_log.
* Prevent Client Crashes when MOVEMENTFLAG_ONTRANSPORT and MOVEMENTFLAG_SPLINE2 is set on creatures.
* Implement four new SEC_ADMINISTRATOR commands:

  • Group (.group [leader]/[disband]/[remove]) commands.
  • GameObject? State (.gobject state <guid> <state>) command.

Original author: Seline
Date: 2008-10-12 18:26:26-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
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"
43
44#include "TemporarySummon.h"
45
46uint32 GuidHigh2TypeId(uint32 guid_hi)
47{
48    switch(guid_hi)
49    {
50        case HIGHGUID_ITEM:         return TYPEID_ITEM;
51        //case HIGHGUID_CONTAINER:    return TYPEID_CONTAINER; HIGHGUID_CONTAINER==HIGHGUID_ITEM currently
52        case HIGHGUID_UNIT:         return TYPEID_UNIT;
53        case HIGHGUID_PET:          return TYPEID_UNIT;
54        case HIGHGUID_PLAYER:       return TYPEID_PLAYER;
55        case HIGHGUID_GAMEOBJECT:   return TYPEID_GAMEOBJECT;
56        case HIGHGUID_DYNAMICOBJECT:return TYPEID_DYNAMICOBJECT;
57        case HIGHGUID_CORPSE:       return TYPEID_CORPSE;
58        case HIGHGUID_MO_TRANSPORT: return TYPEID_GAMEOBJECT;
59    }
60    return 10;                                              // unknown
61}
62
63Object::Object( )
64{
65    m_objectTypeId      = TYPEID_OBJECT;
66    m_objectType        = TYPEMASK_OBJECT;
67
68    m_uint32Values      = 0;
69    m_uint32Values_mirror = 0;
70    m_valuesCount       = 0;
71
72    m_inWorld           = false;
73    m_objectUpdated     = false;
74
75    m_PackGUID.clear();
76    m_PackGUID.appendPackGUID(0);
77}
78
79Object::~Object( )
80{
81    if(m_objectUpdated)
82        ObjectAccessor::Instance().RemoveUpdateObject(this);
83
84    if(m_uint32Values)
85    {
86        if(IsInWorld())
87        {
88            ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash
89            sLog.outError("Object::~Object - guid="I64FMTD", typeid=%d deleted but still in world!!", GetGUID(), GetTypeId());
90            //assert(0);
91        }
92
93        //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
94        delete [] m_uint32Values;
95        delete [] m_uint32Values_mirror;
96        //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
97    }
98}
99
100void Object::_InitValues()
101{
102    m_uint32Values = new uint32[ m_valuesCount ];
103    memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
104
105    m_uint32Values_mirror = new uint32[ m_valuesCount ];
106    memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
107
108    m_objectUpdated = false;
109}
110
111void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
112{
113    if(!m_uint32Values) _InitValues();
114
115    uint64 guid = MAKE_NEW_GUID(guidlow, entry, guidhigh);  // required more changes to make it working
116    SetUInt64Value( OBJECT_FIELD_GUID, guid );
117    SetUInt32Value( OBJECT_FIELD_TYPE, m_objectType );
118    m_PackGUID.clear();
119    m_PackGUID.appendPackGUID(GetGUID());
120}
121
122void Object::BuildMovementUpdateBlock(UpdateData * data, uint32 flags ) const
123{
124    ByteBuffer buf(500);
125
126    buf << uint8( UPDATETYPE_MOVEMENT );
127    buf << GetGUID();
128
129    _BuildMovementUpdate(&buf, flags, 0x00000000);
130
131    data->AddUpdateBlock(buf);
132}
133
134void Object::BuildCreateUpdateBlockForPlayer(UpdateData *data, Player *target) const
135{
136    if(!target)
137    {
138        return;
139    }
140
141    uint8  updatetype = UPDATETYPE_CREATE_OBJECT;
142    uint8  flags      = m_updateFlag;
143    uint32 flags2     = 0;
144
145    /** lower flag1 **/
146    if(target == this)                                      // building packet for oneself
147    {
148        flags |= UPDATEFLAG_SELF;
149
150        /*** temporary reverted - until real source of stack corruption will not found
151        updatetype = UPDATETYPE_CREATE_OBJECT2;
152        ****/
153    }
154
155    if(flags & UPDATEFLAG_HASPOSITION)
156    {
157        // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
158        if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
159            updatetype = UPDATETYPE_CREATE_OBJECT2;
160
161        // UPDATETYPE_CREATE_OBJECT2 for pets...
162        if(target->GetPetGUID() == GetGUID())
163            updatetype = UPDATETYPE_CREATE_OBJECT2;
164
165        // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
166        if(isType(TYPEMASK_GAMEOBJECT))
167        {
168            switch(((GameObject*)this)->GetGoType())
169            {
170                case GAMEOBJECT_TYPE_TRAP:
171                case GAMEOBJECT_TYPE_DUEL_ARBITER:
172                case GAMEOBJECT_TYPE_FLAGSTAND:
173                case GAMEOBJECT_TYPE_FLAGDROP:
174                    updatetype = UPDATETYPE_CREATE_OBJECT2;
175                    break;
176                case GAMEOBJECT_TYPE_TRANSPORT:
177                    flags |= UPDATEFLAG_TRANSPORT;
178                    break;
179            }
180        }
181    }
182
183    //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got flags: %X, flags2: %X", updatetype, m_objectTypeId, flags, flags2);
184
185    ByteBuffer buf(500);
186    buf << (uint8)updatetype;
187    //buf.append(GetPackGUID());    //client crashes when using this
188    buf << (uint8)0xFF << GetGUID();
189    buf << (uint8)m_objectTypeId;
190
191    _BuildMovementUpdate(&buf, flags, flags2);
192
193    UpdateMask updateMask;
194    updateMask.SetCount( m_valuesCount );
195    _SetCreateBits( &updateMask, target );
196    _BuildValuesUpdate(updatetype, &buf, &updateMask, target );
197    data->AddUpdateBlock(buf);
198}
199
200void Object::BuildUpdate(UpdateDataMapType &update_players)
201{
202    ObjectAccessor::_buildUpdateObject(this,update_players);
203    ClearUpdateMask(true);
204}
205
206void Object::SendUpdateToPlayer(Player* player)
207{
208    // send update to another players
209    SendUpdateObjectToAllExcept(player);
210
211    // send create update to player
212    UpdateData upd;
213    WorldPacket packet;
214
215    upd.Clear();
216    BuildCreateUpdateBlockForPlayer(&upd, player);
217    upd.BuildPacket(&packet);
218    player->GetSession()->SendPacket(&packet);
219
220    // now object updated/(create updated)
221}
222
223void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
224{
225    ByteBuffer buf(500);
226
227    buf << (uint8) UPDATETYPE_VALUES;
228    //buf.append(GetPackGUID());    //client crashes when using this. but not have crash in debug mode
229    buf << (uint8)0xFF;
230    buf << GetGUID();
231
232    UpdateMask updateMask;
233    updateMask.SetCount( m_valuesCount );
234
235    _SetUpdateBits( &updateMask, target );
236    _BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target );
237
238    data->AddUpdateBlock(buf);
239}
240
241void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
242{
243    data->AddOutOfRangeGUID(GetGUID());
244}
245
246void Object::DestroyForPlayer(Player *target) const
247{
248    ASSERT(target);
249
250    WorldPacket data(SMSG_DESTROY_OBJECT, 8);
251    data << GetGUID();
252    target->GetSession()->SendPacket( &data );
253}
254
255void Object::_BuildMovementUpdate(ByteBuffer * data, uint8 flags, uint32 flags2 ) const
256{
257    *data << (uint8)flags;                                  // update flags
258
259    // 0x20
260    if (flags & UPDATEFLAG_LIVING)
261    {
262        switch(GetTypeId())
263        {
264            case TYPEID_UNIT:
265            {
266                flags2 = ((Unit*)this)->GetUnitMovementFlags();
267                flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
268                flags2 &= ~MOVEMENTFLAG_SPLINE2;
269            }
270            break;
271            case TYPEID_PLAYER:
272            {
273                flags2 = ((Player*)this)->GetUnitMovementFlags();
274
275                if(((Player*)this)->GetTransport())
276                    flags2 |= MOVEMENTFLAG_ONTRANSPORT;
277                else
278                    flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
279
280                // remove unknown, unused etc flags for now
281                flags2 &= ~MOVEMENTFLAG_SPLINE2;            // will be set manually
282
283                if(((Player*)this)->isInFlight())
284                {
285                    WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
286                    flags2 = (MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
287                }
288            }
289            break;
290        }
291
292        *data << uint32(flags2);                            // movement flags
293        *data << uint8(0);                                  // unk 2.3.0
294        *data << uint32(getMSTime());                       // time (in milliseconds)
295    }
296
297    // 0x40
298    if (flags & UPDATEFLAG_HASPOSITION)
299    {
300        // 0x02
301        if(flags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
302        {
303            *data << (float)0;
304            *data << (float)0;
305            *data << (float)0;
306            *data << ((WorldObject *)this)->GetOrientation();
307        }
308        else
309        {
310            *data << ((WorldObject *)this)->GetPositionX();
311            *data << ((WorldObject *)this)->GetPositionY();
312            *data << ((WorldObject *)this)->GetPositionZ();
313            *data << ((WorldObject *)this)->GetOrientation();
314        }
315    }
316
317    // 0x20
318    if(flags & UPDATEFLAG_LIVING)
319    {
320        // 0x00000200
321        if(flags2 & MOVEMENTFLAG_ONTRANSPORT)
322        {
323            if(GetTypeId() == TYPEID_PLAYER)
324            {
325                *data << (uint64)((Player*)this)->GetTransport()->GetGUID();
326                *data << (float)((Player*)this)->GetTransOffsetX();
327                *data << (float)((Player*)this)->GetTransOffsetY();
328                *data << (float)((Player*)this)->GetTransOffsetZ();
329                *data << (float)((Player*)this)->GetTransOffsetO();
330                *data << (uint32)((Player*)this)->GetTransTime();
331            }
332            //MaNGOS currently not have support for other than player on transport
333        }
334
335        // 0x02200000
336        if(flags2 & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2))
337        {
338            if(GetTypeId() == TYPEID_PLAYER)
339                *data << (float)((Player*)this)->m_movementInfo.s_pitch;
340            else
341                *data << (float)0;                          // is't part of movement packet, we must store and send it...
342        }
343
344        if(GetTypeId() == TYPEID_PLAYER)
345            *data << (uint32)((Player*)this)->m_movementInfo.fallTime;
346        else
347            *data << (uint32)0;                             // last fall time
348
349        // 0x00001000
350        if(flags2 & MOVEMENTFLAG_JUMPING)
351        {
352            if(GetTypeId() == TYPEID_PLAYER)
353            {
354                *data << (float)((Player*)this)->m_movementInfo.j_unk;
355                *data << (float)((Player*)this)->m_movementInfo.j_sinAngle;
356                *data << (float)((Player*)this)->m_movementInfo.j_cosAngle;
357                *data << (float)((Player*)this)->m_movementInfo.j_xyspeed;
358            }
359            else
360            {
361                *data << (float)0;
362                *data << (float)0;
363                *data << (float)0;
364                *data << (float)0;
365            }
366        }
367
368        // 0x04000000
369        if(flags2 & MOVEMENTFLAG_SPLINE)
370        {
371            if(GetTypeId() == TYPEID_PLAYER)
372                *data << (float)((Player*)this)->m_movementInfo.u_unk1;
373            else
374                *data << (float)0;
375        }
376
377        *data << ((Unit*)this)->GetSpeed( MOVE_WALK );
378        *data << ((Unit*)this)->GetSpeed( MOVE_RUN );
379        *data << ((Unit*)this)->GetSpeed( MOVE_SWIMBACK );
380        *data << ((Unit*)this)->GetSpeed( MOVE_SWIM );
381        *data << ((Unit*)this)->GetSpeed( MOVE_WALKBACK );
382        *data << ((Unit*)this)->GetSpeed( MOVE_FLY );
383        *data << ((Unit*)this)->GetSpeed( MOVE_FLYBACK );
384        *data << ((Unit*)this)->GetSpeed( MOVE_TURN );
385
386        // 0x08000000
387        if(flags2 & MOVEMENTFLAG_SPLINE2)
388        {
389            if(GetTypeId() != TYPEID_PLAYER)
390            {
391                sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 for non-player");
392                return;
393            }
394
395            if(!((Player*)this)->isInFlight())
396            {
397                sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 but not in flight");
398                return;
399            }
400
401            WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
402
403            FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(((Player*)this)->GetMotionMaster()->top());
404
405            uint32 flags3 = 0x00000300;
406
407            *data << uint32(flags3);                        // splines flag?
408
409            if(flags3 & 0x10000)                            // probably x,y,z coords there
410            {
411                *data << (float)0;
412                *data << (float)0;
413                *data << (float)0;
414            }
415
416            if(flags3 & 0x20000)                            // probably guid there
417            {
418                *data << uint64(0);
419            }
420
421            if(flags3 & 0x40000)                            // may be orientation
422            {
423                *data << (float)0;
424            }
425
426            Path &path = fmg->GetPath();
427
428            float x, y, z;
429            ((Player*)this)->GetPosition(x, y, z);
430
431            uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
432            uint32 traveltime = uint32(path.GetTotalLength() * 32);
433
434            *data << uint32(inflighttime);                  // passed move time?
435            *data << uint32(traveltime);                    // full move time?
436            *data << uint32(0);                             // ticks count?
437
438            uint32 poscount = uint32(path.Size());
439
440            *data << uint32(poscount);                      // points count
441
442            for(uint32 i = 0; i < poscount; ++i)
443            {
444                *data << path.GetNodes()[i].x;
445                *data << path.GetNodes()[i].y;
446                *data << path.GetNodes()[i].z;
447            }
448
449            /*for(uint32 i = 0; i < poscount; i++)
450            {
451                // path points
452                *data << (float)0;
453                *data << (float)0;
454                *data << (float)0;
455            }*/
456
457            *data << path.GetNodes()[poscount-1].x;
458            *data << path.GetNodes()[poscount-1].y;
459            *data << path.GetNodes()[poscount-1].z;
460
461            // target position (path end)
462            /**data << ((Unit*)this)->GetPositionX();
463             *data << ((Unit*)this)->GetPositionY();
464             *data << ((Unit*)this)->GetPositionZ();*/
465        }
466    }
467
468    // 0x8
469    if(flags & UPDATEFLAG_LOWGUID)
470    {
471        switch(GetTypeId())
472        {
473            case TYPEID_OBJECT:
474            case TYPEID_ITEM:
475            case TYPEID_CONTAINER:
476            case TYPEID_GAMEOBJECT:
477            case TYPEID_DYNAMICOBJECT:
478            case TYPEID_CORPSE:
479                *data << uint32(GetGUIDLow());              // GetGUIDLow()
480                break;
481            case TYPEID_UNIT:
482                *data << uint32(0x0000000B);                // unk, can be 0xB or 0xC
483                break;
484            case TYPEID_PLAYER:
485                if(flags & UPDATEFLAG_SELF)
486                    *data << uint32(0x00000015);            // unk, can be 0x15 or 0x22
487                else
488                    *data << uint32(0x00000008);            // unk, can be 0x7 or 0x8
489                break;
490            default:
491                *data << uint32(0x00000000);                // unk
492                break;
493        }
494    }
495
496    // 0x10
497    if(flags & UPDATEFLAG_HIGHGUID)
498    {
499        switch(GetTypeId())
500        {
501            case TYPEID_OBJECT:
502            case TYPEID_ITEM:
503            case TYPEID_CONTAINER:
504            case TYPEID_GAMEOBJECT:
505            case TYPEID_DYNAMICOBJECT:
506            case TYPEID_CORPSE:
507                *data << uint32(GetGUIDHigh());             // GetGUIDHigh()
508                break;
509            default:
510                *data << uint32(0x00000000);                // unk
511                break;
512        }
513    }
514
515    // 0x4
516    if(flags & UPDATEFLAG_FULLGUID)
517    {
518        *data << uint8(0);                                  // packed guid (probably target guid)
519    }
520
521    // 0x2
522    if(flags & UPDATEFLAG_TRANSPORT)
523    {
524        *data << uint32(getMSTime());                       // ms time
525    }
526}
527
528void Object::_BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
529{
530    if(!target)
531        return;
532
533    bool IsActivateToQuest = false;
534    if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
535    {
536        if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
537        {
538            if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
539            {
540                IsActivateToQuest = true;
541                updateMask->SetBit(GAMEOBJECT_DYN_FLAGS);
542            }
543        }
544    }
545    else                                                    //case UPDATETYPE_VALUES
546    {
547        if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
548        {
549            if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
550            {
551                IsActivateToQuest = true;
552            }
553            updateMask->SetBit(GAMEOBJECT_DYN_FLAGS);
554            updateMask->SetBit(GAMEOBJECT_ANIMPROGRESS);
555        }
556    }
557
558    WPAssert(updateMask && updateMask->GetCount() == m_valuesCount);
559
560    *data << (uint8)updateMask->GetBlockCount();
561    data->append( updateMask->GetMask(), updateMask->GetLength() );
562
563    // 2 specialized loops for speed optimization in non-unit case
564    if(isType(TYPEMASK_UNIT))                               // unit (creature/player) case
565    {
566        for( uint16 index = 0; index < m_valuesCount; index ++ )
567        {
568            if( updateMask->GetBit( index ) )
569            {
570                // remove custom flag before send
571                if( index == UNIT_NPC_FLAGS )
572                    *data << uint32(m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD);
573                // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
574                else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
575                {
576                    // convert from float to uint32 and send
577                    *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
578                }
579                // there are some float values which may be negative or can't get negative due to other checks
580                else if(index >= UNIT_FIELD_NEGSTAT0   && index <= UNIT_FIELD_NEGSTAT4 ||
581                    index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE  && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6) ||
582                    index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE  && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6) ||
583                    index >= UNIT_FIELD_POSSTAT0   && index <= UNIT_FIELD_POSSTAT4)
584                {
585                    *data << uint32(m_floatValues[ index ]);
586                }
587                // Gamemasters should be always able to select units - remove not selectable flag
588                else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
589                {
590                    *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
591                }
592                // hide lootable animation for unallowed players
593                else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
594                {
595                    if(!target->isAllowedToLoot((Creature*)this))
596                        *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
597                    else
598                        *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_OTHER_TAGGER);
599                }
600                else
601                {
602                    // send in current format (float as float, uint32 as uint32)
603                    *data << m_uint32Values[ index ];
604                }
605            }
606        }
607    }
608    else if(isType(TYPEMASK_GAMEOBJECT))                    // gameobject case
609    {
610        for( uint16 index = 0; index < m_valuesCount; index ++ )
611        {
612            if( updateMask->GetBit( index ) )
613            {
614                // send in current format (float as float, uint32 as uint32)
615                if ( index == GAMEOBJECT_DYN_FLAGS )
616                {
617                    if(IsActivateToQuest )
618                    {
619                        switch(((GameObject*)this)->GetGoType())
620                        {
621                            case GAMEOBJECT_TYPE_CHEST:
622                                *data << uint32(9);         // enable quest object. Represent 9, but 1 for client before 2.3.0
623                                break;
624                            case GAMEOBJECT_TYPE_GOOBER:
625                                *data << uint32(1);
626                                break;
627                            default:
628                                *data << uint32(0);         //unknown. not happen.
629                                break;
630                        }
631                    }
632                    else
633                        *data << uint32(0);                 // disable quest object
634                }
635                else
636                    *data << m_uint32Values[ index ];       // other cases
637            }
638        }
639    }
640    else                                                    // other objects case (no special index checks)
641    {
642        for( uint16 index = 0; index < m_valuesCount; index ++ )
643        {
644            if( updateMask->GetBit( index ) )
645            {
646                // send in current format (float as float, uint32 as uint32)
647                *data << m_uint32Values[ index ];
648            }
649        }
650    }
651}
652
653void Object::ClearUpdateMask(bool remove)
654{
655    for( uint16 index = 0; index < m_valuesCount; index ++ )
656    {
657        if(m_uint32Values_mirror[index]!= m_uint32Values[index])
658            m_uint32Values_mirror[index] = m_uint32Values[index];
659    }
660    if(m_objectUpdated)
661    {
662        if(remove)
663            ObjectAccessor::Instance().RemoveUpdateObject(this);
664        m_objectUpdated = false;
665    }
666}
667
668// Send current value fields changes to all viewers
669void Object::SendUpdateObjectToAllExcept(Player* exceptPlayer)
670{
671    // changes will be send in create packet
672    if(!IsInWorld())
673        return;
674
675    // nothing do
676    if(!m_objectUpdated)
677        return;
678
679    ObjectAccessor::UpdateObject(this,exceptPlayer);
680}
681
682bool Object::LoadValues(const char* data)
683{
684    if(!m_uint32Values) _InitValues();
685
686    Tokens tokens = StrSplit(data, " ");
687
688    if(tokens.size() != m_valuesCount)
689        return false;
690
691    Tokens::iterator iter;
692    int index;
693    for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
694    {
695        m_uint32Values[index] = atol((*iter).c_str());
696    }
697
698    return true;
699}
700
701void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
702{
703    for( uint16 index = 0; index < m_valuesCount; index ++ )
704    {
705        if(m_uint32Values_mirror[index]!= m_uint32Values[index])
706            updateMask->SetBit(index);
707    }
708}
709
710void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
711{
712    for( uint16 index = 0; index < m_valuesCount; index++ )
713    {
714        if(GetUInt32Value(index) != 0)
715            updateMask->SetBit(index);
716    }
717}
718
719void Object::SetInt32Value( uint16 index, int32 value )
720{
721    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
722
723    if(m_int32Values[ index ] != value)
724    {
725        m_int32Values[ index ] = value;
726
727        if(m_inWorld)
728        {
729            if(!m_objectUpdated)
730            {
731                ObjectAccessor::Instance().AddUpdateObject(this);
732                m_objectUpdated = true;
733            }
734        }
735    }
736}
737
738void Object::SetUInt32Value( uint16 index, uint32 value )
739{
740    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
741
742    if(m_uint32Values[ index ] != value)
743    {
744        m_uint32Values[ index ] = value;
745
746        if(m_inWorld)
747        {
748            if(!m_objectUpdated)
749            {
750                ObjectAccessor::Instance().AddUpdateObject(this);
751                m_objectUpdated = true;
752            }
753        }
754    }
755}
756
757void Object::SetUInt64Value( uint16 index, const uint64 &value )
758{
759    ASSERT( index + 1 < m_valuesCount || PrintIndexError( index , true ) );
760    if(*((uint64*)&(m_uint32Values[ index ])) != value)
761    {
762        m_uint32Values[ index ] = *((uint32*)&value);
763        m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
764
765        if(m_inWorld)
766        {
767            if(!m_objectUpdated)
768            {
769                ObjectAccessor::Instance().AddUpdateObject(this);
770                m_objectUpdated = true;
771            }
772        }
773    }
774}
775
776void Object::SetFloatValue( uint16 index, float value )
777{
778    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
779
780    if(m_floatValues[ index ] != value)
781    {
782        m_floatValues[ index ] = value;
783
784        if(m_inWorld)
785        {
786            if(!m_objectUpdated)
787            {
788                ObjectAccessor::Instance().AddUpdateObject(this);
789                m_objectUpdated = true;
790            }
791        }
792    }
793}
794
795void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
796{
797    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
798
799    if(offset > 4)
800    {
801        sLog.outError("Object::SetByteValue: wrong offset %u", offset);
802        return;
803    }
804
805    if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
806    {
807        m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
808        m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
809
810        if(m_inWorld)
811        {
812            if(!m_objectUpdated)
813            {
814                ObjectAccessor::Instance().AddUpdateObject(this);
815                m_objectUpdated = true;
816            }
817        }
818    }
819}
820
821void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
822{
823    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
824
825    if(offset > 2)
826    {
827        sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
828        return;
829    }
830
831    if(uint8(m_uint32Values[ index ] >> (offset * 16)) != value)
832    {
833        m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
834        m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
835
836        if(m_inWorld)
837        {
838            if(!m_objectUpdated)
839            {
840                ObjectAccessor::Instance().AddUpdateObject(this);
841                m_objectUpdated = true;
842            }
843        }
844    }
845}
846
847void Object::SetStatFloatValue( uint16 index, float value)
848{
849    if(value < 0)
850        value = 0.0f;
851
852    SetFloatValue(index, value);
853}
854
855void Object::SetStatInt32Value( uint16 index, int32 value)
856{
857    if(value < 0)
858        value = 0;
859
860    SetUInt32Value(index, uint32(value));
861}
862
863void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
864{
865    int32 cur = GetUInt32Value(index);
866    cur += (apply ? val : -val);
867    if(cur < 0)
868        cur = 0;
869    SetUInt32Value(index,cur);
870}
871
872void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
873{
874    int32 cur = GetInt32Value(index);
875    cur += (apply ? val : -val);
876    SetInt32Value(index,cur);
877}
878
879void Object::ApplyModSignedFloatValue(uint16 index, float  val, bool apply)
880{
881    float cur = GetFloatValue(index);
882    cur += (apply ? val : -val);
883    SetFloatValue(index,cur);
884}
885
886void Object::ApplyModPositiveFloatValue(uint16 index, float  val, bool apply)
887{
888    float cur = GetFloatValue(index);
889    cur += (apply ? val : -val);
890    if(cur < 0)
891        cur = 0;
892    SetFloatValue(index,cur);
893}
894
895void Object::SetFlag( uint16 index, uint32 newFlag )
896{
897    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
898    uint32 oldval = m_uint32Values[ index ];
899    uint32 newval = oldval | newFlag;
900
901    if(oldval != newval)
902    {
903        m_uint32Values[ index ] = newval;
904
905        if(m_inWorld)
906        {
907            if(!m_objectUpdated)
908            {
909                ObjectAccessor::Instance().AddUpdateObject(this);
910                m_objectUpdated = true;
911            }
912        }
913    }
914}
915
916void Object::RemoveFlag( uint16 index, uint32 oldFlag )
917{
918    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
919    uint32 oldval = m_uint32Values[ index ];
920    uint32 newval = oldval & ~oldFlag;
921
922    if(oldval != newval)
923    {
924        m_uint32Values[ index ] = newval;
925
926        if(m_inWorld)
927        {
928            if(!m_objectUpdated)
929            {
930                ObjectAccessor::Instance().AddUpdateObject(this);
931                m_objectUpdated = true;
932            }
933        }
934    }
935}
936
937bool Object::PrintIndexError(uint32 index, bool set) const
938{
939    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);
940
941    // assert must fail after function call
942    return false;
943}
944
945WorldObject::WorldObject()
946{
947    m_positionX         = 0.0f;
948    m_positionY         = 0.0f;
949    m_positionZ         = 0.0f;
950    m_orientation       = 0.0f;
951
952    m_mapId             = 0;
953    m_InstanceId        = 0;
954
955    m_name = "";
956
957    mSemaphoreTeleport  = false;
958}
959
960void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 mapid )
961{
962    Object::_Create(guidlow, 0, guidhigh);
963
964    m_mapId = mapid;
965}
966
967uint32 WorldObject::GetZoneId() const
968{
969    return MapManager::Instance().GetBaseMap(m_mapId)->GetZoneId(m_positionX,m_positionY);
970}
971
972uint32 WorldObject::GetAreaId() const
973{
974    return MapManager::Instance().GetBaseMap(m_mapId)->GetAreaId(m_positionX,m_positionY);
975}
976
977InstanceData* WorldObject::GetInstanceData()
978{
979    Map *map = MapManager::Instance().GetMap(m_mapId, this);
980    return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
981}
982
983                                                            //slow
984float WorldObject::GetDistance(const WorldObject* obj) const
985{
986    float dx = GetPositionX() - obj->GetPositionX();
987    float dy = GetPositionY() - obj->GetPositionY();
988    float dz = GetPositionZ() - obj->GetPositionZ();
989    float sizefactor = GetObjectSize() + obj->GetObjectSize();
990    float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
991    return ( dist > 0 ? dist : 0);
992}
993
994float WorldObject::GetDistance2d(float x, float y) const
995{
996    float dx = GetPositionX() - x;
997    float dy = GetPositionY() - y;
998    float sizefactor = GetObjectSize();
999    float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1000    return ( dist > 0 ? dist : 0);
1001}
1002
1003float WorldObject::GetDistance(const float x, const float y, const float z) const
1004{
1005    float dx = GetPositionX() - x;
1006    float dy = GetPositionY() - y;
1007    float dz = GetPositionZ() - z;
1008    float sizefactor = GetObjectSize();
1009    float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1010    return ( dist > 0 ? dist : 0);
1011}
1012
1013float WorldObject::GetDistance2d(const WorldObject* obj) const
1014{
1015    float dx = GetPositionX() - obj->GetPositionX();
1016    float dy = GetPositionY() - obj->GetPositionY();
1017    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1018    float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1019    return ( dist > 0 ? dist : 0);
1020}
1021
1022float WorldObject::GetDistanceZ(const WorldObject* obj) const
1023{
1024    float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1025    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1026    float dist = dz - sizefactor;
1027    return ( dist > 0 ? dist : 0);
1028}
1029
1030bool WorldObject::IsWithinDistInMap(const WorldObject* obj, const float dist2compare) const
1031{
1032    if (!obj || !IsInMap(obj)) return false;
1033
1034    float dx = GetPositionX() - obj->GetPositionX();
1035    float dy = GetPositionY() - obj->GetPositionY();
1036    float dz = GetPositionZ() - obj->GetPositionZ();
1037    float distsq = dx*dx + dy*dy + dz*dz;
1038    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1039    float maxdist = dist2compare + sizefactor;
1040
1041    return distsq < maxdist * maxdist;
1042}
1043
1044bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1045{
1046    if (!IsInMap(obj)) return false;
1047    float ox,oy,oz;
1048    obj->GetPosition(ox,oy,oz);
1049    return(IsWithinLOS(ox, oy, oz ));
1050}
1051
1052bool WorldObject::IsWithinLOS(const float ox, const float oy, const float oz ) const
1053{
1054    float x,y,z;
1055    GetPosition(x,y,z);
1056    VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1057    return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1058}
1059
1060float WorldObject::GetAngle(const WorldObject* obj) const
1061{
1062    if(!obj) return 0;
1063    return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1064}
1065
1066// Return angle in range 0..2*pi
1067float WorldObject::GetAngle( const float x, const float y ) const
1068{
1069    float dx = x - GetPositionX();
1070    float dy = y - GetPositionY();
1071
1072    float ang = atan2(dy, dx);
1073    ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1074    return ang;
1075}
1076
1077bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1078{
1079    float arc = arcangle;
1080
1081    // move arc to range 0.. 2*pi
1082    while( arc >= 2.0f * M_PI )
1083        arc -=  2.0f * M_PI;
1084    while( arc < 0 )
1085        arc +=  2.0f * M_PI;
1086
1087    float angle = GetAngle( obj );
1088    angle -= m_orientation;
1089
1090    // move angle to range -pi ... +pi
1091    while( angle > M_PI)
1092        angle -= 2.0f * M_PI;
1093    while(angle < -M_PI)
1094        angle += 2.0f * M_PI;
1095
1096    float lborder =  -1 * (arc/2.0f);                       // in range -pi..0
1097    float rborder = (arc/2.0f);                             // in range 0..pi
1098    return (( angle >= lborder ) && ( angle <= rborder ));
1099}
1100
1101void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1102{
1103    if(distance==0)
1104    {
1105        rand_x = x;
1106        rand_y = y;
1107        rand_z = z;
1108        return;
1109    }
1110
1111    // angle to face `obj` to `this`
1112    float angle = rand_norm()*2*M_PI;
1113    float new_dist = rand_norm()*distance;
1114
1115    rand_x = x + new_dist * cos(angle);
1116    rand_y = y + new_dist * sin(angle);
1117    rand_z = z;
1118
1119    MaNGOS::NormalizeMapCoord(rand_x);
1120    MaNGOS::NormalizeMapCoord(rand_y);
1121    UpdateGroundPositionZ(rand_x,rand_y,rand_z);            // update to LOS height if available
1122}
1123
1124void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1125{
1126    float new_z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(x,y,z,true);
1127    if(new_z > INVALID_HEIGHT)
1128        z = new_z+ 0.05f;                                   // just to be sure that we are not a few pixel under the surface
1129}
1130
1131bool WorldObject::IsPositionValid() const
1132{
1133    return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1134}
1135
1136void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1137{
1138    WorldPacket data(SMSG_MESSAGECHAT, 200);
1139    BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1140    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1141}
1142
1143void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1144{
1145    WorldPacket data(SMSG_MESSAGECHAT, 200);
1146    BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1147    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1148}
1149
1150void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1151{
1152    WorldPacket data(SMSG_MESSAGECHAT, 200);
1153    BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1154    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1155}
1156
1157void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1158{
1159    Player *player = objmgr.GetPlayer(receiver);
1160    if(!player || !player->GetSession())
1161        return;
1162
1163    WorldPacket data(SMSG_MESSAGECHAT, 200);
1164    BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1165
1166    player->GetSession()->SendPacket(&data);
1167}
1168
1169void WorldObject::SendPlaySound(uint32 Sound, bool OnlySelf)
1170{
1171    WorldPacket data(SMSG_PLAY_SOUND, 4);
1172    data << Sound;
1173    if (OnlySelf && GetTypeId() == TYPEID_PLAYER )
1174        ((Player*)this)->GetSession()->SendPacket( &data );
1175    else
1176        SendMessageToSet( &data, true ); // ToSelf ignored in this case
1177}
1178
1179namespace MaNGOS
1180{
1181    class MessageChatLocaleCacheDo
1182    {
1183        public:
1184            MessageChatLocaleCacheDo(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID, float dist)
1185                : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), 
1186                i_targetGUID(targetGUID), i_dist(dist)
1187            {
1188            }
1189
1190            ~MessageChatLocaleCacheDo()
1191            {
1192                for(int i = 0; i < i_data_cache.size(); ++i)
1193                    delete i_data_cache[i];
1194            }
1195
1196            void operator()(Player* p)
1197            {
1198                // skip far away players
1199                if(p->GetDistance(&i_object) > i_dist)
1200                    return;
1201
1202                uint32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
1203                uint32 cache_idx = loc_idx+1;
1204                WorldPacket* data;
1205
1206                // create if not cached yet
1207                if(i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
1208                {
1209                    if(i_data_cache.size() < cache_idx+1)
1210                        i_data_cache.resize(cache_idx+1);
1211
1212                    char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1213
1214                    data = new WorldPacket(SMSG_MESSAGECHAT, 200);
1215
1216                    // TODO: i_object.GetName() also must be localized?
1217                    i_object.BuildMonsterChat(data,i_msgtype,text,i_language,i_object.GetName(),i_targetGUID);
1218
1219                    i_data_cache[cache_idx] = data;
1220                }
1221                else
1222                    data = i_data_cache[cache_idx];
1223
1224                p->SendDirectMessage(data);
1225            }
1226
1227        private:
1228            WorldObject const& i_object;
1229            ChatMsg i_msgtype;
1230            int32 i_textId;
1231            uint32 i_language;
1232            uint64 i_targetGUID;
1233            float i_dist;
1234            std::vector<WorldPacket*> i_data_cache;             // 0 = default, i => i-1 locale index
1235    };
1236}                                                           // namespace MaNGOS
1237
1238void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1239{
1240    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1241
1242    Cell cell(p);
1243    cell.data.Part.reserved = ALL_DISTRICT;
1244    cell.SetNoCreate();
1245
1246    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1247    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1248    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1249    CellLock<GridReadGuard> cell_lock(cell, p);
1250    cell_lock->Visit(cell_lock, message, *GetMap());
1251}
1252
1253void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1254{
1255    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1256
1257    Cell cell(p);
1258    cell.data.Part.reserved = ALL_DISTRICT;
1259    cell.SetNoCreate();
1260
1261    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL));
1262    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1263    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1264    CellLock<GridReadGuard> cell_lock(cell, p);
1265    cell_lock->Visit(cell_lock, message, *GetMap());
1266}
1267
1268void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1269{
1270    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1271
1272    Cell cell(p);
1273    cell.data.Part.reserved = ALL_DISTRICT;
1274    cell.SetNoCreate();
1275
1276    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));
1277    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1278    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1279    CellLock<GridReadGuard> cell_lock(cell, p);
1280    cell_lock->Visit(cell_lock, message, *GetMap());
1281}
1282
1283void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1284{
1285    Player *player = objmgr.GetPlayer(receiver);
1286    if(!player || !player->GetSession())
1287        return;
1288
1289    uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1290    char const* text = objmgr.GetMangosString(textId,loc_idx);
1291
1292    WorldPacket data(SMSG_MESSAGECHAT, 200);
1293    BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1294
1295    player->GetSession()->SendPacket(&data);
1296}
1297
1298void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1299{
1300    bool pre = (msgtype==CHAT_MSG_MONSTER_EMOTE || msgtype==CHAT_MSG_RAID_BOSS_EMOTE);
1301
1302    *data << (uint8)msgtype;
1303    *data << (uint32)language;
1304    *data << (uint64)GetGUID();
1305    *data << (uint32)0;                                     //2.1.0
1306    *data << (uint32)(strlen(name)+1);
1307    *data << name;
1308    *data << (uint64)targetGuid;                            //Unit Target
1309    if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1310    {
1311        *data << (uint32)1;                                 // target name length
1312        *data << (uint8)0;                                  // target name
1313    }
1314    *data << (uint32)(strlen(text)+1+(pre?3:0));
1315    if(pre)
1316        data->append("%s ",3);
1317    *data << text;
1318    *data << (uint8)0;                                      // ChatTag
1319}
1320
1321void WorldObject::BuildHeartBeatMsg(WorldPacket *data) const
1322{
1323    //Heartbeat message cannot be used for non-units
1324    if (!isType(TYPEMASK_UNIT))
1325        return;
1326
1327    data->Initialize(MSG_MOVE_HEARTBEAT, 32);
1328    data->append(GetPackGUID());
1329    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1330    *data << uint8(0);                                      // 2.3.0
1331    *data << getMSTime();                                   // time
1332    *data << m_positionX;
1333    *data << m_positionY;
1334    *data << m_positionZ;
1335    *data << m_orientation;
1336    *data << uint32(0);
1337}
1338
1339void WorldObject::BuildTeleportAckMsg(WorldPacket *data, float x, float y, float z, float ang) const
1340{
1341    //TeleportAck message cannot be used for non-units
1342    if (!isType(TYPEMASK_UNIT))
1343        return;
1344
1345    data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
1346    data->append(GetPackGUID());
1347    *data << uint32(0);                                     // this value increments every time
1348    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1349    *data << uint8(0);                                      // 2.3.0
1350    *data << getMSTime();                                   // time
1351    *data << x;
1352    *data << y;
1353    *data << z;
1354    *data << ang;
1355    *data << uint32(0);
1356}
1357
1358void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1359{
1360    MapManager::Instance().GetMap(m_mapId, this)->MessageBroadcast(this, data);
1361}
1362
1363void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1364{
1365    MapManager::Instance().GetMap(m_mapId, this)->MessageDistBroadcast(this, data, dist);
1366}
1367
1368void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1369{
1370    WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1371    data << guid;
1372    SendMessageToSet(&data, true);
1373}
1374
1375Map* WorldObject::GetMap() const
1376{
1377    return MapManager::Instance().GetMap(GetMapId(), this);
1378}
1379
1380Map const* WorldObject::GetBaseMap() const
1381{
1382    return MapManager::Instance().GetBaseMap(GetMapId());
1383}
1384
1385void WorldObject::AddObjectToRemoveList()
1386{
1387    Map* map = GetMap();
1388    if(!map)
1389    {
1390        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());
1391        return;
1392    }
1393
1394    map->AddObjectToRemoveList(this);
1395}
1396
1397Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1398{
1399    TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1400
1401    pCreature->SetInstanceId(GetInstanceId());
1402    uint32 team = 0;
1403    if (GetTypeId()==TYPEID_PLAYER)
1404        team = ((Player*)this)->GetTeam();
1405
1406    if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), id, team))
1407    {
1408        delete pCreature;
1409        return NULL;
1410    }
1411
1412    if (x == 0.0f && y == 0.0f && z == 0.0f)
1413        GetClosePoint(x, y, z, pCreature->GetObjectSize());
1414
1415    pCreature->Relocate(x, y, z, ang);
1416
1417    if(!pCreature->IsPositionValid())
1418    {
1419        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());
1420        delete pCreature;
1421        return NULL;
1422    }
1423
1424    pCreature->Summon(spwtype, despwtime);
1425
1426    if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1427        ((Creature*)this)->AI()->JustSummoned(pCreature);
1428
1429    //return the creature therewith the summoner has access to it
1430    return pCreature;
1431}
1432
1433void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1434{
1435    x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1436    y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1437
1438    MaNGOS::NormalizeMapCoord(x);
1439    MaNGOS::NormalizeMapCoord(y);
1440}
1441
1442void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1443{
1444    GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1445   
1446    z = GetPositionZ();
1447   
1448    UpdateGroundPositionZ(x,y,z);
1449}
Note: See TracBrowser for help on using the browser.