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

Revision 2, 52.2 kB (checked in by yumileroy, 17 years ago)

[svn] * Proper SVN structure

Original author: Neo2003
Date: 2008-10-02 16:23:55-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 "ObjectPosSelector.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            }
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
1169namespace MaNGOS
1170{
1171    class MessageChatLocaleCacheDo
1172    {
1173        public:
1174            MessageChatLocaleCacheDo(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID, float dist)
1175                : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), 
1176                i_targetGUID(targetGUID), i_dist(dist)
1177            {
1178            }
1179
1180            ~MessageChatLocaleCacheDo()
1181            {
1182                for(int i = 0; i < i_data_cache.size(); ++i)
1183                    delete i_data_cache[i];
1184            }
1185
1186            void operator()(Player* p)
1187            {
1188                // skip far away players
1189                if(p->GetDistance(&i_object) > i_dist)
1190                    return;
1191
1192                uint32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
1193                uint32 cache_idx = loc_idx+1;
1194                WorldPacket* data;
1195
1196                // create if not cached yet
1197                if(i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
1198                {
1199                    if(i_data_cache.size() < cache_idx+1)
1200                        i_data_cache.resize(cache_idx+1);
1201
1202                    char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1203
1204                    data = new WorldPacket(SMSG_MESSAGECHAT, 200);
1205
1206                    // TODO: i_object.GetName() also must be localized?
1207                    i_object.BuildMonsterChat(data,i_msgtype,text,i_language,i_object.GetName(),i_targetGUID);
1208
1209                    i_data_cache[cache_idx] = data;
1210                }
1211                else
1212                    data = i_data_cache[cache_idx];
1213
1214                p->SendDirectMessage(data);
1215            }
1216
1217        private:
1218            WorldObject const& i_object;
1219            ChatMsg i_msgtype;
1220            int32 i_textId;
1221            uint32 i_language;
1222            uint64 i_targetGUID;
1223            float i_dist;
1224            std::vector<WorldPacket*> i_data_cache;             // 0 = default, i => i-1 locale index
1225    };
1226}                                                           // namespace MaNGOS
1227
1228void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1229{
1230    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1231
1232    Cell cell(p);
1233    cell.data.Part.reserved = ALL_DISTRICT;
1234    cell.SetNoCreate();
1235
1236    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1237    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1238    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1239    CellLock<GridReadGuard> cell_lock(cell, p);
1240    cell_lock->Visit(cell_lock, message, *GetMap());
1241}
1242
1243void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1244{
1245    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1246
1247    Cell cell(p);
1248    cell.data.Part.reserved = ALL_DISTRICT;
1249    cell.SetNoCreate();
1250
1251    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL));
1252    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1253    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1254    CellLock<GridReadGuard> cell_lock(cell, p);
1255    cell_lock->Visit(cell_lock, message, *GetMap());
1256}
1257
1258void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1259{
1260    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1261
1262    Cell cell(p);
1263    cell.data.Part.reserved = ALL_DISTRICT;
1264    cell.SetNoCreate();
1265
1266    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));
1267    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1268    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1269    CellLock<GridReadGuard> cell_lock(cell, p);
1270    cell_lock->Visit(cell_lock, message, *GetMap());
1271}
1272
1273void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1274{
1275    Player *player = objmgr.GetPlayer(receiver);
1276    if(!player || !player->GetSession())
1277        return;
1278
1279    uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1280    char const* text = objmgr.GetMangosString(textId,loc_idx);
1281
1282    WorldPacket data(SMSG_MESSAGECHAT, 200);
1283    BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1284
1285    player->GetSession()->SendPacket(&data);
1286}
1287
1288void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1289{
1290    bool pre = (msgtype==CHAT_MSG_MONSTER_EMOTE || msgtype==CHAT_MSG_RAID_BOSS_EMOTE);
1291
1292    *data << (uint8)msgtype;
1293    *data << (uint32)language;
1294    *data << (uint64)GetGUID();
1295    *data << (uint32)0;                                     //2.1.0
1296    *data << (uint32)(strlen(name)+1);
1297    *data << name;
1298    *data << (uint64)targetGuid;                            //Unit Target
1299    if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1300    {
1301        *data << (uint32)1;                                 // target name length
1302        *data << (uint8)0;                                  // target name
1303    }
1304    *data << (uint32)(strlen(text)+1+(pre?3:0));
1305    if(pre)
1306        data->append("%s ",3);
1307    *data << text;
1308    *data << (uint8)0;                                      // ChatTag
1309}
1310
1311void WorldObject::BuildHeartBeatMsg(WorldPacket *data) const
1312{
1313    //Heartbeat message cannot be used for non-units
1314    if (!isType(TYPEMASK_UNIT))
1315        return;
1316
1317    data->Initialize(MSG_MOVE_HEARTBEAT, 32);
1318    data->append(GetPackGUID());
1319    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1320    *data << uint8(0);                                      // 2.3.0
1321    *data << getMSTime();                                   // time
1322    *data << m_positionX;
1323    *data << m_positionY;
1324    *data << m_positionZ;
1325    *data << m_orientation;
1326    *data << uint32(0);
1327}
1328
1329void WorldObject::BuildTeleportAckMsg(WorldPacket *data, float x, float y, float z, float ang) const
1330{
1331    //TeleportAck message cannot be used for non-units
1332    if (!isType(TYPEMASK_UNIT))
1333        return;
1334
1335    data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
1336    data->append(GetPackGUID());
1337    *data << uint32(0);                                     // this value increments every time
1338    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1339    *data << uint8(0);                                      // 2.3.0
1340    *data << getMSTime();                                   // time
1341    *data << x;
1342    *data << y;
1343    *data << z;
1344    *data << ang;
1345    *data << uint32(0);
1346}
1347
1348void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1349{
1350    MapManager::Instance().GetMap(m_mapId, this)->MessageBroadcast(this, data);
1351}
1352
1353void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1354{
1355    MapManager::Instance().GetMap(m_mapId, this)->MessageDistBroadcast(this, data, dist);
1356}
1357
1358void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1359{
1360    WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1361    data << guid;
1362    SendMessageToSet(&data, true);
1363}
1364
1365Map* WorldObject::GetMap() const
1366{
1367    return MapManager::Instance().GetMap(GetMapId(), this);
1368}
1369
1370Map const* WorldObject::GetBaseMap() const
1371{
1372    return MapManager::Instance().GetBaseMap(GetMapId());
1373}
1374
1375void WorldObject::AddObjectToRemoveList()
1376{
1377    Map* map = GetMap();
1378    if(!map)
1379    {
1380        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());
1381        return;
1382    }
1383
1384    map->AddObjectToRemoveList(this);
1385}
1386
1387Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1388{
1389    TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1390
1391    pCreature->SetInstanceId(GetInstanceId());
1392    uint32 team = 0;
1393    if (GetTypeId()==TYPEID_PLAYER)
1394        team = ((Player*)this)->GetTeam();
1395
1396    if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), id, team))
1397    {
1398        delete pCreature;
1399        return NULL;
1400    }
1401
1402    if (x == 0.0f && y == 0.0f && z == 0.0f)
1403        GetClosePoint(x, y, z, pCreature->GetObjectSize());
1404
1405    pCreature->Relocate(x, y, z, ang);
1406
1407    if(!pCreature->IsPositionValid())
1408    {
1409        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());
1410        delete pCreature;
1411        return NULL;
1412    }
1413
1414    pCreature->Summon(spwtype, despwtime);
1415
1416    if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1417        ((Creature*)this)->AI()->JustSummoned(pCreature);
1418
1419    //return the creature therewith the summoner has access to it
1420    return pCreature;
1421}
1422
1423namespace MaNGOS
1424{
1425    class NearUsedPosDo
1426    {
1427        public:
1428            NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1429                : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1430
1431            void operator()(Corpse*) const {}
1432            void operator()(DynamicObject*) const {}
1433
1434            void operator()(Creature* c) const
1435            {
1436                // skip self or target
1437                if(c==i_searcher || c==&i_object)
1438                    return;
1439
1440                float x,y,z;
1441
1442                if( !c->isAlive() || c->hasUnitState(UNIT_STAT_ROOT | UNIT_STAT_STUNDED | UNIT_STAT_DISTRACTED) ||
1443                    !c->GetMotionMaster()->GetDestination(x,y,z) )
1444                {
1445                    x = c->GetPositionX();
1446                    y = c->GetPositionY();
1447                }
1448
1449                add(c,x,y);
1450            }
1451
1452            template<class T>
1453                void operator()(T* u) const
1454            {
1455                // skip self or target
1456                if(u==i_searcher || u==&i_object)
1457                    return;
1458
1459                float x,y;
1460
1461                x = u->GetPositionX();
1462                y = u->GetPositionY();
1463
1464                add(u,x,y);
1465            }
1466
1467            // we must add used pos that can fill places around center
1468            void add(WorldObject* u, float x, float y) const
1469            {
1470                // dist include size of u
1471                float dist2d = i_object.GetDistance2d(x,y);
1472
1473                // u is too nearest to i_object
1474                if(dist2d + i_object.GetObjectSize() + u->GetObjectSize() < i_selector.m_dist - i_selector.m_size)
1475                    return;
1476
1477                // u is too far away from i_object
1478                if(dist2d + i_object.GetObjectSize() - u->GetObjectSize() > i_selector.m_dist + i_selector.m_size)
1479                    return;
1480
1481                float angle = i_object.GetAngle(u)-i_angle;
1482
1483                // move angle to range -pi ... +pi
1484                while( angle > M_PI)
1485                    angle -= 2.0f * M_PI;
1486                while(angle < -M_PI)
1487                    angle += 2.0f * M_PI;
1488
1489                i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1490            }
1491        private:
1492            WorldObject const& i_object;
1493            WorldObject const* i_searcher;
1494            float              i_angle;
1495            ObjectPosSelector& i_selector;
1496    };
1497}                                                           // namespace MaNGOS
1498
1499//===================================================================================================
1500
1501void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1502{
1503    x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1504    y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1505
1506    MaNGOS::NormalizeMapCoord(x);
1507    MaNGOS::NormalizeMapCoord(y);
1508}
1509
1510void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1511{
1512    GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1513    z = GetPositionZ();
1514
1515    // if detection disabled, return first point
1516    if(!sWorld.getConfig(CONFIG_DETECT_POS_COLLISION))
1517    {
1518        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1519        return;
1520    }
1521
1522    // or remember first point
1523    float first_x = x;
1524    float first_y = y;
1525    bool first_los_conflict = false;                        // first point LOS problems
1526
1527    // prepare selector for work
1528    ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1529
1530    // adding used positions around object
1531    {
1532        CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1533        Cell cell(p);
1534        cell.data.Part.reserved = ALL_DISTRICT;
1535        cell.SetNoCreate();
1536
1537        MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1538        MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(u_do);
1539
1540        TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer  > grid_obj_worker(worker);
1541        TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1542
1543        CellLock<GridReadGuard> cell_lock(cell, p);
1544        cell_lock->Visit(cell_lock, grid_obj_worker,  *MapManager::Instance().GetMap(GetMapId(), this));
1545        cell_lock->Visit(cell_lock, world_obj_worker, *MapManager::Instance().GetMap(GetMapId(), this));
1546    }
1547
1548    // maybe can just place in primary position
1549    if( selector.CheckOriginal() )
1550    {
1551        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1552
1553        if(IsWithinLOS(x,y,z))
1554            return;
1555
1556        first_los_conflict = true;                          // first point have LOS problems
1557    }
1558
1559    float angle;                                            // candidate of angle for free pos
1560
1561    // special case when one from list empty and then empty side preferred
1562    if(selector.FirstAngle(angle))
1563    {
1564        GetNearPoint2D(x,y,distance2d,absAngle+angle);
1565        z = GetPositionZ();
1566        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1567
1568        if(IsWithinLOS(x,y,z))
1569            return;
1570    }
1571
1572    // set first used pos in lists
1573    selector.InitializeAngle();
1574
1575    // select in positions after current nodes (selection one by one)
1576    while(selector.NextAngle(angle))                        // angle for free pos
1577    {
1578        GetNearPoint2D(x,y,distance2d,absAngle+angle);
1579        z = GetPositionZ();
1580        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1581
1582        if(IsWithinLOS(x,y,z))
1583            return;
1584    }
1585
1586    // BAD NEWS: not free pos (or used or have LOS problems)
1587    // Attempt find _used_ pos without LOS problem
1588
1589    if(!first_los_conflict)
1590    {
1591        x = first_x;
1592        y = first_y;
1593
1594        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1595        return;
1596    }
1597
1598    // special case when one from list empty and then empty side preferred
1599    if( selector.IsNonBalanced() )
1600    {
1601        if(!selector.FirstAngle(angle))                     // _used_ pos
1602        {
1603            GetNearPoint2D(x,y,distance2d,absAngle+angle);
1604            z = GetPositionZ();
1605            UpdateGroundPositionZ(x,y,z);                   // update to LOS height if available
1606
1607            if(IsWithinLOS(x,y,z))
1608                return;
1609        }
1610    }
1611
1612    // set first used pos in lists
1613    selector.InitializeAngle();
1614
1615    // select in positions after current nodes (selection one by one)
1616    while(selector.NextUsedAngle(angle))                    // angle for used pos but maybe without LOS problem
1617    {
1618        GetNearPoint2D(x,y,distance2d,absAngle+angle);
1619        z = GetPositionZ();
1620        UpdateGroundPositionZ(x,y,z);                       // update to LOS height if available
1621
1622        if(IsWithinLOS(x,y,z))
1623            return;
1624    }
1625
1626    // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1627    x = first_x;
1628    y = first_y;
1629
1630    UpdateGroundPositionZ(x,y,z);                           // update to LOS height if available
1631}
Note: See TracBrowser for help on using the browser.