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

Revision 52, 47.0 kB (checked in by yumileroy, 17 years ago)

[svn] Added a function for WorldObjects? to summon GameObjects?. Original patch provided by streetrat. Please refer to the patch thread for usage instructions.

Original author: w12x
Date: 2008-10-17 18:13:04-05:00

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