root/trunk/src/game/Map.cpp @ 174

Revision 174, 65.1 kB (checked in by yumileroy, 17 years ago)

[svn] Implemented player on player and player on creature possession:
* Implemented packet and vision forwarding through possessed units
* Added new OnPossess? script call alerting scripts on when possession is applied/removed
* Moved fall damage and fall under map calculations into the Player class
* Added new PossessedAI that is applied only while possession on creature is active
* Implemented summon possessed spell effect
* Fixed Eyes of the Beast

Original author: gvcoman
Date: 2008-11-05 20:51:05-06:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.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 "MapManager.h"
22#include "Player.h"
23#include "GridNotifiers.h"
24#include "WorldSession.h"
25#include "Log.h"
26#include "GridStates.h"
27#include "CellImpl.h"
28#include "InstanceData.h"
29#include "Map.h"
30#include "GridNotifiersImpl.h"
31#include "Config/ConfigEnv.h"
32#include "Transports.h"
33#include "ObjectAccessor.h"
34#include "ObjectMgr.h"
35#include "World.h"
36#include "ScriptCalls.h"
37#include "Group.h"
38
39#include "MapInstanced.h"
40#include "InstanceSaveMgr.h"
41#include "VMapFactory.h"
42
43#define DEFAULT_GRID_EXPIRY     300
44#define MAX_GRID_LOAD_TIME      50
45
46// magic *.map header
47const char MAP_MAGIC[] = "MAP_2.00";
48
49GridState* si_GridStates[MAX_GRID_STATE];
50
51Map::~Map()
52{
53    UnloadAll(true);
54}
55
56bool Map::ExistMap(uint32 mapid,int x,int y)
57{
58    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
59    char* tmp = new char[len];
60    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
61
62    FILE *pf=fopen(tmp,"rb");
63
64    if(!pf)
65    {
66        sLog.outError("Check existing of map file '%s': not exist!",tmp);
67        delete[] tmp;
68        return false;
69    }
70
71    char magic[8];
72    fread(magic,1,8,pf);
73    if(strncmp(MAP_MAGIC,magic,8))
74    {
75        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
76        delete [] tmp;
77        fclose(pf);                                         //close file before return
78        return false;
79    }
80
81    delete [] tmp;
82    fclose(pf);
83
84    return true;
85}
86
87bool Map::ExistVMap(uint32 mapid,int x,int y)
88{
89    if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
90    {
91        if(vmgr->isMapLoadingEnabled())
92        {
93                                                            // x and y are swaped !! => fixed now
94            bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(),  mapid, x,y);
95            if(!exists)
96            {
97                std::string name = vmgr->getDirFileName(mapid,x,y);
98                sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
99                return false;
100            }
101        }
102    }
103
104    return true;
105}
106
107void Map::LoadVMap(int x,int y)
108{
109                                                            // x and y are swaped !!
110    int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(),  GetId(), x,y);
111    switch(vmapLoadResult)
112    {
113        case VMAP::VMAP_LOAD_RESULT_OK:
114            sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
115            break;
116        case VMAP::VMAP_LOAD_RESULT_ERROR:
117            sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
118            break;
119        case VMAP::VMAP_LOAD_RESULT_IGNORED:
120            DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
121            break;
122    }
123}
124
125void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
126{
127    if( instanceid != 0 )
128    {
129        if(GridMaps[x][y])
130            return;
131
132        Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
133
134        // load gridmap for base map
135        if (!baseMap->GridMaps[x][y])
136            baseMap->EnsureGridCreated(GridPair(63-x,63-y));
137
138//+++        if (!baseMap->GridMaps[x][y])  don't check for GridMaps[gx][gy], we need the management for vmaps
139//            return;
140
141        ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
142        baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
143        GridMaps[x][y] = baseMap->GridMaps[x][y];
144        return;
145    }
146
147    //map already load, delete it before reloading (Is it neccessary? Do we really need the abilty the reload maps during runtime?)
148    if(GridMaps[x][y])
149    {
150        sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
151        delete (GridMaps[x][y]);
152        GridMaps[x][y]=NULL;
153    }
154
155    // map file name
156    char *tmp=NULL;
157    // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
158    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
159    tmp = new char[len];
160    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
161    sLog.outDetail("Loading map %s",tmp);
162    // loading data
163    FILE *pf=fopen(tmp,"rb");
164    if(!pf)
165    {
166        delete [] tmp;
167        return;
168    }
169
170    char magic[8];
171    fread(magic,1,8,pf);
172    if(strncmp(MAP_MAGIC,magic,8))
173    {
174        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
175        delete [] tmp;
176        fclose(pf);                                         //close file before return
177        return;
178    }
179    delete []  tmp;
180
181    GridMap * buf= new GridMap;
182    fread(buf,1,sizeof(GridMap),pf);
183    fclose(pf);
184
185    GridMaps[x][y] = buf;
186}
187
188void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
189{
190    LoadMap(mapid,instanceid,x,y);
191    if(instanceid == 0)
192        LoadVMap(x, y);                                     // Only load the data for the base map
193}
194
195void Map::InitStateMachine()
196{
197    si_GridStates[GRID_STATE_INVALID] = new InvalidState;
198    si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
199    si_GridStates[GRID_STATE_IDLE] = new IdleState;
200    si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201}
202
203void Map::DeleteStateMachine()
204{
205    delete si_GridStates[GRID_STATE_INVALID];
206    delete si_GridStates[GRID_STATE_ACTIVE];
207    delete si_GridStates[GRID_STATE_IDLE];
208    delete si_GridStates[GRID_STATE_REMOVAL];
209}
210
211Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
212  : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
213 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
214{
215    for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
216    {
217        for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
218        {
219            //z code
220            GridMaps[idx][j] =NULL;
221            setNGrid(NULL, idx, j);
222        }
223    }
224}
225
226// Template specialization of utility methods
227template<class T>
228void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
229{
230    (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
231}
232
233template<>
234void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
235{
236    (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
237}
238
239template<>
240void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
241{
242    // add to world object registry in grid
243    if(obj->GetType()!=CORPSE_BONES)
244    {
245        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246    }
247    // add to grid object store
248    else
249    {
250        (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
251    }
252}
253
254template<>
255void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
256{
257    // add to world object registry in grid
258    if(obj->isPet() || obj->isPossessedByPlayer())
259    {
260        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
261        obj->SetCurrentCell(cell);
262    }
263    // add to grid object store
264    else
265    {
266        (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
267        obj->SetCurrentCell(cell);
268    }
269}
270
271template<class T>
272void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
273{
274    (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
275}
276
277template<>
278void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
279{
280    (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
281}
282
283template<>
284void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
285{
286    // remove from world object registry in grid
287    if(obj->GetType()!=CORPSE_BONES)
288    {
289        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290    }
291    // remove from grid object store
292    else
293    {
294        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
295    }
296}
297
298template<>
299void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
300{
301    // remove from world object registry in grid
302    if(obj->isPet() || obj->isPossessedByPlayer())
303    {
304        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
305    }
306    // remove from grid object store
307    else
308    {
309        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
310    }
311}
312
313template<class T>
314void Map::SwitchGridContainers(T* obj, bool active)
315{
316    CellPair pair = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
317    Cell cell(pair);
318    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
319
320    if (active)
321    {
322        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<T>(obj, obj->GetGUID());
323        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<T>(obj, obj->GetGUID());
324    } else
325    {
326        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<T>(obj, obj->GetGUID());
327        (*grid)(cell.CellX(), cell.CellY()).AddGridObject<T>(obj, obj->GetGUID());
328    }
329}
330
331template void Map::SwitchGridContainers(Creature *, bool);
332template void Map::SwitchGridContainers(Corpse *, bool);
333
334template<class T>
335void Map::DeleteFromWorld(T* obj)
336{
337    // Note: In case resurrectable corpse and pet its removed from gloabal lists in own destructors
338    delete obj;
339}
340
341template<class T>
342void Map::AddNotifier(T* , Cell const& , CellPair const& )
343{
344}
345
346template<>
347void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
348{
349    PlayerRelocationNotify(obj,cell,cellpair);
350}
351
352template<>
353void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
354{
355    CreatureRelocationNotify(obj,cell,cellpair);
356}
357
358void
359Map::EnsureGridCreated(const GridPair &p)
360{
361    if(!getNGrid(p.x_coord, p.y_coord))
362    {
363        Guard guard(*this);
364        if(!getNGrid(p.x_coord, p.y_coord))
365        {
366            setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_GRID_UNLOAD)),
367                p.x_coord, p.y_coord);
368
369            // build a linkage between this map and NGridType
370            buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
371
372            getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
373
374            //z coord
375            int gx=63-p.x_coord;
376            int gy=63-p.y_coord;
377
378            if(!GridMaps[gx][gy])
379                Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
380        }
381    }
382}
383
384void
385Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
386{
387    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
388    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
389
390    assert(grid != NULL);
391    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
392    {
393        if( player != NULL )
394        {
395            player->SendDelayResponse(MAX_GRID_LOAD_TIME);
396            DEBUG_LOG("Player %s enter cell[%u,%u] triggers of loading grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), i_id);
397        }
398        else
399        {
400            DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
401        }
402
403        ObjectGridLoader loader(*grid, this, cell);
404        loader.LoadN();
405        setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
406
407        // Add resurrectable corpses to world object list in grid
408        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
409
410        ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
411        grid->SetGridState(GRID_STATE_ACTIVE);
412
413        if( add_player && player != NULL )
414            (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
415    }
416    else if( player && add_player )
417        AddToGrid(player,grid,cell);
418}
419
420void
421Map::LoadGrid(const Cell& cell, bool no_unload)
422{
423    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
424    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
425
426    assert(grid != NULL);
427    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
428    {
429        ObjectGridLoader loader(*grid, this, cell);
430        loader.LoadN();
431
432        // Add resurrectable corpses to world object list in grid
433        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
434
435        setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
436        if(no_unload)
437            getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
438    }
439    LoadVMap(63-cell.GridX(),63-cell.GridY());
440}
441
442bool Map::Add(Player *player)
443{
444    player->SetInstanceId(this->GetInstanceId());
445
446    // update player state for other player and visa-versa
447    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
448    Cell cell(p);
449    EnsureGridLoadedForPlayer(cell, player, true);
450    player->AddToWorld();
451
452    SendInitSelf(player);
453    SendInitTransports(player);
454
455    UpdatePlayerVisibility(player,cell,p);
456    UpdateObjectsVisibilityFor(player,cell,p);
457
458    AddNotifier(player,cell,p);
459    return true;
460}
461
462template<class T>
463void
464Map::Add(T *obj)
465{
466    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
467
468    assert(obj);
469
470    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
471    {
472        sLog.outError("Map::Add: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
473        return;
474    }
475
476    Cell cell(p);
477    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
478    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
479    assert( grid != NULL );
480
481    AddToGrid(obj,grid,cell);
482    obj->AddToWorld();
483
484    DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
485
486    UpdateObjectVisibility(obj,cell,p);
487
488    AddNotifier(obj,cell,p);
489}
490
491void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self, bool to_possessor)
492{
493    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
494
495    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
496    {
497        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
498        return;
499    }
500
501    Cell cell(p);
502    cell.data.Part.reserved = ALL_DISTRICT;
503
504    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
505        return;
506
507    Trinity::MessageDeliverer post_man(*player, msg, to_possessor, to_self);
508    TypeContainerVisitor<Trinity::MessageDeliverer, WorldTypeMapContainer > message(post_man);
509    CellLock<ReadGuard> cell_lock(cell, p);
510    cell_lock->Visit(cell_lock, message, *this);
511}
512
513void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg, bool to_possessor)
514{
515    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
516
517    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
518    {
519        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
520        return;
521    }
522
523    Cell cell(p);
524    cell.data.Part.reserved = ALL_DISTRICT;
525    cell.SetNoCreate();
526
527    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
528        return;
529
530    Trinity::ObjectMessageDeliverer post_man(*obj, msg, to_possessor);
531    TypeContainerVisitor<Trinity::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
532    CellLock<ReadGuard> cell_lock(cell, p);
533    cell_lock->Visit(cell_lock, message, *this);
534}
535
536void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only, bool to_possessor)
537{
538    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
539
540    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
541    {
542        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
543        return;
544    }
545
546    Cell cell(p);
547    cell.data.Part.reserved = ALL_DISTRICT;
548
549    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
550        return;
551
552    Trinity::MessageDistDeliverer post_man(*player, msg, to_possessor, dist, to_self, own_team_only);
553    TypeContainerVisitor<Trinity::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
554    CellLock<ReadGuard> cell_lock(cell, p);
555    cell_lock->Visit(cell_lock, message, *this);
556}
557
558void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist, bool to_possessor)
559{
560    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
561
562    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
563    {
564        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
565        return;
566    }
567
568    Cell cell(p);
569    cell.data.Part.reserved = ALL_DISTRICT;
570    cell.SetNoCreate();
571
572    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
573        return;
574
575    Trinity::ObjectMessageDistDeliverer post_man(*obj, msg, to_possessor, dist);
576    TypeContainerVisitor<Trinity::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
577    CellLock<ReadGuard> cell_lock(cell, p);
578    cell_lock->Visit(cell_lock, message, *this);
579}
580
581bool Map::loaded(const GridPair &p) const
582{
583    return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
584}
585
586void Map::Update(const uint32 &t_diff)
587{
588    // Don't unload grids if it's battleground, since we may have manually added GOs,creatures, those doesn't load from DB at grid re-load !
589    // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
590    if (IsBattleGroundOrArena())
591        return;
592
593    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
594    {
595        NGridType *grid = i->getSource();
596        GridInfo *info = i->getSource()->getGridInfoRef();
597        ++i;                                                // The update might delete the map and we need the next map before the iterator gets invalid
598        assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
599        si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
600    }
601}
602
603void Map::Remove(Player *player, bool remove)
604{
605    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
606    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
607    {
608        // invalid coordinates
609        player->RemoveFromWorld();
610
611        if( remove )
612            DeleteFromWorld(player);
613
614        return;
615    }
616
617    Cell cell(p);
618
619    if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
620    {
621        sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
622        return;
623    }
624
625    DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
626    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
627    assert(grid != NULL);
628
629    player->RemoveFromWorld();
630    RemoveFromGrid(player,grid,cell);
631
632    SendRemoveTransports(player);
633
634    UpdateObjectsVisibilityFor(player,cell,p);
635
636    if( remove )
637        DeleteFromWorld(player);
638}
639
640bool Map::RemoveBones(uint64 guid, float x, float y)
641{
642    if (IsRemovalGrid(x, y))
643    {
644        Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
645        if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
646            corpse->DeleteBonesFromWorld();
647        else
648            return false;
649    }
650    return true;
651}
652
653template<class T>
654void
655Map::Remove(T *obj, bool remove)
656{
657    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
658    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
659    {
660        sLog.outError("Map::Remove: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
661        return;
662    }
663
664    Cell cell(p);
665    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
666        return;
667
668    DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
669    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
670    assert( grid != NULL );
671
672    obj->RemoveFromWorld();
673
674    RemoveFromGrid(obj,grid,cell);
675
676    UpdateObjectVisibility(obj,cell,p);
677
678    if( remove )
679    {
680        // if option set then object already saved at this moment
681        if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
682            obj->SaveRespawnTime();
683        DeleteFromWorld(obj);
684    }
685}
686
687void
688Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
689{
690    assert(player);
691
692    CellPair old_val = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
693    CellPair new_val = Trinity::ComputeCellPair(x, y);
694
695    Cell old_cell(old_val);
696    Cell new_cell(new_val);
697    new_cell |= old_cell;
698    bool same_cell = (new_cell == old_cell);
699
700    player->Relocate(x, y, z, orientation);
701
702    if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
703    {
704        DEBUG_LOG("Player %s relocation grid[%u,%u]cell[%u,%u]->grid[%u,%u]cell[%u,%u]", player->GetName(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
705
706        // update player position for group at taxi flight
707        if(player->GetGroup() && player->isInFlight())
708            player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
709
710        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
711        RemoveFromGrid(player, oldGrid,old_cell);
712        if( !old_cell.DiffGrid(new_cell) )
713            AddToGrid(player, oldGrid,new_cell);
714
715        if( old_cell.DiffGrid(new_cell) )
716            EnsureGridLoadedForPlayer(new_cell, player, true);
717    }
718
719    // if move then update what player see and who seen
720    UpdatePlayerVisibility(player,new_cell,new_val);
721    UpdateObjectsVisibilityFor(player,new_cell,new_val);
722
723    // also update what possessing player sees
724    if(player->isPossessedByPlayer())
725        UpdateObjectsVisibilityFor((Player*)player->GetCharmer(), new_cell, new_val);
726
727    PlayerRelocationNotify(player,new_cell,new_val);
728    NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
729    if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
730    {
731        ResetGridExpiry(*newGrid, 0.1f);
732        newGrid->SetGridState(GRID_STATE_ACTIVE);
733    }
734}
735
736void
737Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
738{
739    assert(CheckGridIntegrity(creature,false));
740
741    Cell old_cell = creature->GetCurrentCell();
742
743    CellPair new_val = Trinity::ComputeCellPair(x, y);
744    Cell new_cell(new_val);
745
746    // delay creature move for grid/cell to grid/cell moves
747    if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
748    {
749        #ifdef TRINITY_DEBUG
750        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
751            sLog.outDebug("Creature (GUID: %u Entry: %u) added to moving list from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", creature->GetGUIDLow(), creature->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
752        #endif
753        AddCreatureToMoveList(creature,x,y,z,ang);
754        // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
755        if(creature->isPossessedByPlayer())
756            EnsureGridLoadedForPlayer(new_cell, (Player*)creature->GetCharmer(), false);
757    }
758    else
759    {
760        creature->Relocate(x, y, z, ang);
761        // Update visibility back to player who is controlling the creature
762        if(creature->isPossessedByPlayer())
763            UpdateObjectsVisibilityFor((Player*)creature->GetCharmer(), new_cell, new_val);
764
765        CreatureRelocationNotify(creature,new_cell,new_val);
766    }
767    assert(CheckGridIntegrity(creature,true));
768}
769
770void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
771{
772    if(!c)
773        return;
774
775    i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
776}
777
778void Map::MoveAllCreaturesInMoveList()
779{
780    while(!i_creaturesToMove.empty())
781    {
782        // get data and remove element;
783        CreatureMoveList::iterator iter = i_creaturesToMove.begin();
784        Creature* c = iter->first;
785        CreatureMover cm = iter->second;
786        i_creaturesToMove.erase(iter);
787
788        // calculate cells
789        CellPair new_val = Trinity::ComputeCellPair(cm.x, cm.y);
790        Cell new_cell(new_val);
791
792        // do move or do move to respawn or remove creature if previous all fail
793        if(CreatureCellRelocation(c,new_cell))
794        {
795            // update pos
796            c->Relocate(cm.x, cm.y, cm.z, cm.ang);
797            CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
798        }
799        else
800        {
801            // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
802            // creature coordinates will be updated and notifiers send
803            if(!CreatureRespawnRelocation(c))
804            {
805                // ... or unload (if respawn grid also not loaded)
806                #ifdef TRINITY_DEBUG
807                if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
808                    sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
809                #endif
810                c->CleanupsBeforeDelete();
811                AddObjectToRemoveList(c);
812            }
813        }
814    }
815}
816
817bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
818{
819    Cell const& old_cell = c->GetCurrentCell();
820    if(!old_cell.DiffGrid(new_cell) )                       // in same grid
821    {
822        // if in same cell then none do
823        if(old_cell.DiffCell(new_cell))
824        {
825            #ifdef TRINITY_DEBUG
826            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
827                sLog.outDebug("Creature (GUID: %u Entry: %u) moved in grid[%u,%u] from cell[%u,%u] to cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
828            #endif
829
830            if( !old_cell.DiffGrid(new_cell) )
831            {
832                RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
833                AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
834                c->SetCurrentCell(new_cell);
835            }
836        }
837        else
838        {
839            #ifdef TRINITY_DEBUG
840            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
841                sLog.outDebug("Creature (GUID: %u Entry: %u) move in same grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
842            #endif
843        }
844    }
845    else                                                    // in diff. grids
846    if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
847    {
848        #ifdef TRINITY_DEBUG
849        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
850            sLog.outDebug("Creature (GUID: %u Entry: %u) moved from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
851        #endif
852
853        RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
854        {
855            EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
856            AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
857        }
858    }
859    else
860    {
861        #ifdef TRINITY_DEBUG
862        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
863            sLog.outDebug("Creature (GUID: %u Entry: %u) attempt move from grid[%u,%u]cell[%u,%u] to unloaded grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
864        #endif
865        return false;
866    }
867
868    return true;
869}
870
871bool Map::CreatureRespawnRelocation(Creature *c)
872{
873    float resp_x, resp_y, resp_z, resp_o;
874    c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
875
876    CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
877    Cell resp_cell(resp_val);
878
879    c->CombatStop();
880    c->GetMotionMaster()->Clear();
881
882    #ifdef TRINITY_DEBUG
883    if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
884        sLog.outDebug("Creature (GUID: %u Entry: %u) will moved from grid[%u,%u]cell[%u,%u] to respawn grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), c->GetCurrentCell().GridX(), c->GetCurrentCell().GridY(), c->GetCurrentCell().CellX(), c->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
885    #endif
886
887    // teleport it to respawn point (like normal respawn if player see)
888    if(CreatureCellRelocation(c,resp_cell))
889    {
890        c->Relocate(resp_x, resp_y, resp_z, resp_o);
891        c->GetMotionMaster()->Initialize();                 // prevent possible problems with default move generators
892        CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
893        return true;
894    }
895    else
896        return false;
897}
898
899bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
900{
901    NGridType *grid = getNGrid(x, y);
902    assert( grid != NULL);
903
904    {
905        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
906            return false;
907
908        DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
909        ObjectGridUnloader unloader(*grid);
910
911        // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
912        // Must know real mob position before move
913        DoDelayedMovesAndRemoves();
914
915        // move creatures to respawn grids if this is diff.grid or to remove list
916        unloader.MoveToRespawnN();
917
918        // Finish creature moves, remove and delete all creatures with delayed remove before unload
919        DoDelayedMovesAndRemoves();
920
921        unloader.UnloadN();
922        delete getNGrid(x, y);
923        setNGrid(NULL, x, y);
924    }
925    int gx=63-x;
926    int gy=63-y;
927
928    // delete grid map, but don't delete if it is from parent map (and thus only reference)
929    //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
930    {
931        if (i_InstanceId == 0)
932        {
933            if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
934            // x and y are swaped
935            VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
936        }
937        else
938            ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
939        GridMaps[gx][gy] = NULL;
940    }
941    DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
942    return true;
943}
944
945void Map::UnloadAll(bool pForce)
946{
947    // clear all delayed moves, useless anyway do this moves before map unload.
948    i_creaturesToMove.clear();
949
950    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
951    {
952        NGridType &grid(*i->getSource());
953        ++i;
954        UnloadGrid(grid.getX(), grid.getY(), pForce);       // deletes the grid and removes it from the GridRefManager
955    }
956}
957
958float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
959{
960    GridPair p = Trinity::ComputeGridPair(x, y);
961
962    // half opt method
963    int gx=(int)(32-x/SIZE_OF_GRIDS);                       //grid x
964    int gy=(int)(32-y/SIZE_OF_GRIDS);                       //grid y
965
966    float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
967    float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
968
969    // ensure GridMap is loaded
970    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
971
972    // find raw .map surface under Z coordinates
973    float mapHeight;
974    if(GridMap* gmap = GridMaps[gx][gy])
975    {
976        int lx_int = (int)lx;
977        int ly_int = (int)ly;
978
979        float zi[4];
980        // Probe 4 nearest points (except border cases)
981        zi[0] = gmap->Z[lx_int][ly_int];
982        zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
983        zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
984        zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
985        // Recalculate them like if their x,y positions were in the range 0,1
986        float b[4];
987        b[0] = zi[0];
988        b[1] = zi[1]-zi[0];
989        b[2] = zi[2]-zi[0];
990        b[3] = zi[0]-zi[1]-zi[2]+zi[3];
991        // Normalize the dx and dy to be in range 0..1
992        float fact_x = lx - lx_int;
993        float fact_y = ly - ly_int;
994        // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
995        float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
996
997        // look from a bit higher pos to find the floor, ignore under surface case
998        if(z + 2.0f > _mapheight)
999            mapHeight = _mapheight;
1000        else
1001            mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1002    }
1003    else
1004        mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1005
1006    float vmapHeight;
1007    if(pUseVmaps)
1008    {
1009        VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1010        if(vmgr->isHeightCalcEnabled())
1011        {
1012            // look from a bit higher pos to find the floor
1013            vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1014        }
1015        else
1016            vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1017    }
1018    else
1019        vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1020
1021    // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1022    // vmapheight set for any under Z value or <= INVALID_HEIGHT
1023
1024    if( vmapHeight > INVALID_HEIGHT )
1025    {
1026        if( mapHeight > INVALID_HEIGHT )
1027        {
1028            // we have mapheight and vmapheight and must select more appropriate
1029
1030            // we are already under the surface or vmap height above map heigt
1031            // or if the distance of the vmap height is less the land height distance
1032            if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1033                return vmapHeight;
1034            else
1035                return mapHeight;                           // better use .map surface height
1036
1037        }
1038        else
1039            return vmapHeight;                              // we have only vmapHeight (if have)
1040    }
1041    else
1042    {
1043        if(!pUseVmaps)
1044            return mapHeight;                               // explicitly use map data (if have)
1045        else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1046            return mapHeight;                               // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1047        else
1048            return VMAP_INVALID_HEIGHT_VALUE;               // we not have any height
1049    }
1050}
1051
1052uint16 Map::GetAreaFlag(float x, float y ) const
1053{
1054    //local x,y coords
1055    float lx,ly;
1056    int gx,gy;
1057    GridPair p = Trinity::ComputeGridPair(x, y);
1058
1059    // half opt method
1060    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1061    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1062
1063    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1064    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1065    //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1066
1067    // ensure GridMap is loaded
1068    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1069
1070    if(GridMaps[gx][gy])
1071        return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1072    // this used while not all *.map files generated (instances)
1073    else
1074        return GetAreaFlagByMapId(i_id);
1075}
1076
1077uint8 Map::GetTerrainType(float x, float y ) const
1078{
1079    //local x,y coords
1080    float lx,ly;
1081    int gx,gy;
1082
1083    // half opt method
1084    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1085    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1086
1087    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1088    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1089
1090    // ensure GridMap is loaded
1091    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1092
1093    if(GridMaps[gx][gy])
1094        return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1095    else
1096        return 0;
1097
1098}
1099
1100float Map::GetWaterLevel(float x, float y ) const
1101{
1102    //local x,y coords
1103    float lx,ly;
1104    int gx,gy;
1105
1106    // half opt method
1107    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1108    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1109
1110    lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1111    ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1112
1113    // ensure GridMap is loaded
1114    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1115
1116    if(GridMaps[gx][gy])
1117        return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1118    else
1119        return 0;
1120}
1121
1122uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1123{
1124    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1125
1126    if (entry)
1127        return entry->ID;
1128    else
1129        return 0;
1130}
1131
1132uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1133{
1134    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1135
1136    if( entry )
1137        return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1138    else
1139        return 0;
1140}
1141
1142bool Map::IsInWater(float x, float y, float pZ) const
1143{
1144    // This method is called too often to use vamps for that (4. parameter = false).
1145    // The pZ pos is taken anyway for future use
1146    float z = GetHeight(x,y,pZ,false);                      // use .map base surface height
1147
1148    // underground or instance without vmap
1149    if(z <= INVALID_HEIGHT)
1150        return false;
1151
1152    float water_z = GetWaterLevel(x,y);
1153    uint8 flag = GetTerrainType(x,y);
1154    return (z < (water_z-2)) && (flag & 0x01);
1155}
1156
1157bool Map::IsUnderWater(float x, float y, float z) const
1158{
1159    float water_z = GetWaterLevel(x,y);
1160    uint8 flag = GetTerrainType(x,y);
1161    return (z < (water_z-2)) && (flag & 0x01);
1162}
1163
1164bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1165{
1166    Cell const& cur_cell = c->GetCurrentCell();
1167
1168    CellPair xy_val = Trinity::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1169    Cell xy_cell(xy_val);
1170    if(xy_cell != cur_cell)
1171    {
1172        sLog.outError("ERROR: %s (GUID: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1173            (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1174            c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1175            cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1176            xy_cell.GridX(),  xy_cell.GridY(),  xy_cell.CellX(),  xy_cell.CellY());
1177        return true;                                        // not crash at error, just output error in debug mode
1178    }
1179
1180    return true;
1181}
1182
1183const char* Map::GetMapName() const
1184{
1185    return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1186}
1187
1188void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1189{
1190    cell.data.Part.reserved = ALL_DISTRICT;
1191    cell.SetNoCreate();
1192    Trinity::VisibleChangesNotifier notifier(*obj);
1193    TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1194    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1195    cell_lock->Visit(cell_lock, player_notifier, *this);
1196}
1197
1198void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1199{
1200    cell.data.Part.reserved = ALL_DISTRICT;
1201
1202    Trinity::PlayerNotifier pl_notifier(*player);
1203    TypeContainerVisitor<Trinity::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1204
1205    CellLock<ReadGuard> cell_lock(cell, cellpair);
1206    cell_lock->Visit(cell_lock, player_notifier, *this);
1207}
1208
1209void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1210{
1211    Trinity::VisibleNotifier notifier(*player);
1212
1213    cell.data.Part.reserved = ALL_DISTRICT;
1214    cell.SetNoCreate();
1215    TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1216    TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer  > grid_notifier(notifier);
1217    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1218    cell_lock->Visit(cell_lock, world_notifier, *this);
1219    cell_lock->Visit(cell_lock, grid_notifier,  *this);
1220
1221    // send data
1222    notifier.Notify();
1223}
1224
1225void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1226{
1227    CellLock<ReadGuard> cell_lock(cell, cellpair);
1228    Trinity::PlayerRelocationNotifier relocationNotifier(*player);
1229    cell.data.Part.reserved = ALL_DISTRICT;
1230
1231    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, GridTypeMapContainer >  p2grid_relocation(relocationNotifier);
1232    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1233
1234    cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1235    cell_lock->Visit(cell_lock, p2world_relocation, *this);
1236}
1237
1238void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1239{
1240    CellLock<ReadGuard> cell_lock(cell, cellpair);
1241    Trinity::CreatureRelocationNotifier relocationNotifier(*creature);
1242    cell.data.Part.reserved = ALL_DISTRICT;
1243    cell.SetNoCreate();                                     // not trigger load unloaded grids at notifier call
1244
1245    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1246    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, GridTypeMapContainer >  c2grid_relocation(relocationNotifier);
1247
1248    cell_lock->Visit(cell_lock, c2world_relocation, *this);
1249    cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1250}
1251
1252void Map::SendInitSelf( Player * player )
1253{
1254    sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1255
1256    UpdateData data;
1257
1258    bool hasTransport = false;
1259
1260    // attach to player data current transport data
1261    if(Transport* transport = player->GetTransport())
1262    {
1263        hasTransport = true;
1264        transport->BuildCreateUpdateBlockForPlayer(&data, player);
1265    }
1266
1267    // build data for self presence in world at own client (one time for map)
1268    player->BuildCreateUpdateBlockForPlayer(&data, player);
1269
1270    // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1271    if(Transport* transport = player->GetTransport())
1272    {
1273        for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1274        {
1275            if(player!=(*itr) && player->HaveAtClient(*itr))
1276            {
1277                hasTransport = true;
1278                (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1279            }
1280        }
1281    }
1282
1283    WorldPacket packet;
1284    data.BuildPacket(&packet, hasTransport);
1285    player->GetSession()->SendPacket(&packet);
1286}
1287
1288void Map::SendInitTransports( Player * player )
1289{
1290    // Hack to send out transports
1291    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1292
1293    // no transports at map
1294    if (tmap.find(player->GetMapId()) == tmap.end())
1295        return;
1296
1297    UpdateData transData;
1298
1299    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1300
1301    bool hasTransport = false;
1302
1303    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1304    {
1305        if((*i) != player->GetTransport())                  // send data for current transport in other place
1306        {
1307            hasTransport = true;
1308            (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1309        }
1310    }
1311
1312    WorldPacket packet;
1313    transData.BuildPacket(&packet, hasTransport);
1314    player->GetSession()->SendPacket(&packet);
1315}
1316
1317void Map::SendRemoveTransports( Player * player )
1318{
1319    // Hack to send out transports
1320    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1321
1322    // no transports at map
1323    if (tmap.find(player->GetMapId()) == tmap.end())
1324        return;
1325
1326    UpdateData transData;
1327
1328    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1329
1330    // except used transport
1331    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1332        if(player->GetTransport() != (*i))
1333            (*i)->BuildOutOfRangeUpdateBlock(&transData);
1334
1335    WorldPacket packet;
1336    transData.BuildPacket(&packet);
1337    player->GetSession()->SendPacket(&packet);
1338}
1339
1340inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1341{
1342    if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1343    {
1344        sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1345        assert(false);
1346    }
1347    i_grids[x][y] = grid;
1348}
1349
1350void Map::DoDelayedMovesAndRemoves()
1351{
1352    MoveAllCreaturesInMoveList();
1353    RemoveAllObjectsInRemoveList();
1354}
1355
1356void Map::AddObjectToRemoveList(WorldObject *obj)
1357{
1358    assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1359
1360    i_objectsToRemove.insert(obj);
1361    //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1362}
1363
1364void Map::RemoveAllObjectsInRemoveList()
1365{
1366    if(i_objectsToRemove.empty())
1367        return;
1368
1369    //sLog.outDebug("Object remover 1 check.");
1370    while(!i_objectsToRemove.empty())
1371    {
1372        WorldObject* obj = *i_objectsToRemove.begin();
1373        i_objectsToRemove.erase(i_objectsToRemove.begin());
1374
1375        switch(obj->GetTypeId())
1376        {
1377            case TYPEID_CORPSE:
1378            {
1379                Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1380                if (!corpse)
1381                    sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1382                else
1383                    Remove(corpse,true);
1384                break;
1385            }
1386        case TYPEID_DYNAMICOBJECT:
1387            Remove((DynamicObject*)obj,true);
1388            break;
1389        case TYPEID_GAMEOBJECT:
1390            Remove((GameObject*)obj,true);
1391            break;
1392        case TYPEID_UNIT:
1393            // in case triggred sequence some spell can continue casting after prev CleanupsBeforeDelete call
1394            // make sure that like sources auras/etc removed before destructor start
1395            ((Creature*)obj)->CleanupsBeforeDelete ();
1396            Remove((Creature*)obj,true);
1397            break;
1398        default:
1399            sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1400            break;
1401        }
1402    }
1403    //sLog.outDebug("Object remover 2 check.");
1404}
1405
1406bool Map::CanUnload(const uint32 &diff)
1407{
1408    if(!m_unloadTimer) return false;
1409    if(m_unloadTimer < diff) return true;
1410    m_unloadTimer -= diff;
1411    return false;
1412}
1413
1414template void Map::Add(Corpse *);
1415template void Map::Add(Creature *);
1416template void Map::Add(GameObject *);
1417template void Map::Add(DynamicObject *);
1418
1419template void Map::Remove(Corpse *,bool);
1420template void Map::Remove(Creature *,bool);
1421template void Map::Remove(GameObject *, bool);
1422template void Map::Remove(DynamicObject *, bool);
1423
1424/* ******* Dungeon Instance Maps ******* */
1425
1426InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1427  : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1428    m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1429{
1430    // the timer is started by default, and stopped when the first player joins
1431    // this make sure it gets unloaded if for some reason no player joins
1432    m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1433}
1434
1435InstanceMap::~InstanceMap()
1436{
1437    if(i_data)
1438    {
1439        delete i_data;
1440        i_data = NULL;
1441    }
1442}
1443
1444/*
1445    Do map specific checks to see if the player can enter
1446*/
1447bool InstanceMap::CanEnter(Player *player)
1448{
1449    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1450    {
1451        sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1452        assert(false);
1453        return false;
1454    }
1455
1456    // cannot enter if the instance is full (player cap), GMs don't count
1457    InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1458    if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1459    {
1460        sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1461        player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1462        return false;
1463    }
1464
1465    // cannot enter while players in the instance are in combat
1466    Group *pGroup = player->GetGroup();
1467    if(!player->isGameMaster() && pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1468    {
1469        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1470        return false;
1471    }
1472
1473    /*if(!player->isGameMaster() && i_data && i_data->IsEncounterInProgress())
1474    {
1475        sLog.outDebug("InstanceMap::CanEnter - Player '%s' can't enter instance '%s' while an encounter is in progress.", player->GetName(), GetMapName());
1476        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1477        return false;
1478    }*/
1479
1480    return Map::CanEnter(player);
1481}
1482
1483/*
1484    Do map specific checks and add the player to the map if successful.
1485*/
1486bool InstanceMap::Add(Player *player)
1487{
1488    // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1489    // GMs still can teleport player in instance.
1490    // Is it needed?
1491
1492    {
1493        Guard guard(*this);
1494        if(!CanEnter(player))
1495            return false;
1496
1497        // get or create an instance save for the map
1498        InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1499        if(!mapSave)
1500        {
1501            sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1502            mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1503        }
1504
1505        // check for existing instance binds
1506        InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1507        if(playerBind && playerBind->perm)
1508        {
1509            // cannot enter other instances if bound permanently
1510            if(playerBind->save != mapSave)
1511            {
1512                sLog.outError("InstanceMap::Add: player %s(%d) is permanently bound to instance %d,%d,%d,%d,%d,%d but he is being put in instance %d,%d,%d,%d,%d,%d", player->GetName(), player->GetGUIDLow(), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset());
1513                assert(false);
1514            }
1515        }
1516        else
1517        {
1518            Group *pGroup = player->GetGroup();
1519            if(pGroup)
1520            {
1521                // solo saves should be reset when entering a group
1522                InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1523                if(playerBind)
1524                {
1525                    sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d,%d,%d,%d but he is in group %d and is bound to instance %d,%d,%d,%d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset(), GUID_LOPART(pGroup->GetLeaderGUID()), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset());
1526                    if(groupBind) sLog.outError("InstanceMap::Add: the group is bound to instance %d,%d,%d,%d,%d,%d", groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty(), groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount(), groupBind->save->CanReset());
1527                    assert(false);
1528                }
1529                // bind to the group or keep using the group save
1530                if(!groupBind)
1531                    pGroup->BindToInstance(mapSave, false);
1532                else
1533                {
1534                    // cannot jump to a different instance without resetting it
1535                    if(groupBind->save != mapSave)
1536                    {
1537                        sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d but he is in group %d which is bound to instance %d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), GUID_LOPART(pGroup->GetLeaderGUID()), groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty());
1538                        if(mapSave)
1539                            sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1540                        else
1541                            sLog.outError("MapSave NULL");
1542                        if(groupBind->save)
1543                            sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1544                        else
1545                            sLog.outError("GroupBind save NULL");
1546                        assert(false);
1547                    }
1548                    // if the group/leader is permanently bound to the instance
1549                    // players also become permanently bound when they enter
1550                    if(groupBind->perm)
1551                    {
1552                        WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1553                        data << uint32(0);
1554                        player->GetSession()->SendPacket(&data);
1555                        player->BindToInstance(mapSave, true);
1556                    }
1557                }
1558            }
1559            else
1560            {
1561                // set up a solo bind or continue using it
1562                if(!playerBind)
1563                    player->BindToInstance(mapSave, false);
1564                else
1565                    // cannot jump to a different instance without resetting it
1566                    assert(playerBind->save == mapSave);
1567            }
1568        }
1569
1570        if(i_data) i_data->OnPlayerEnter(player);
1571        SetResetSchedule(false);
1572
1573        i_Players.push_back(player);
1574        player->SendInitWorldStates();
1575        sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1576        // initialize unload state
1577        m_unloadTimer = 0;
1578        m_resetAfterUnload = false;
1579        m_unloadWhenEmpty = false;
1580    }
1581
1582    // this will acquire the same mutex so it cannot be in the previous block
1583    Map::Add(player);
1584    return true;
1585}
1586
1587void InstanceMap::Update(const uint32& t_diff)
1588{
1589        Map::Update(t_diff);
1590
1591        if(i_data)
1592                i_data->Update(t_diff);
1593}
1594
1595void InstanceMap::Remove(Player *player, bool remove)
1596{
1597    sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1598    i_Players.remove(player);
1599    SetResetSchedule(true);
1600    if(!m_unloadTimer && i_Players.empty())
1601        m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1602    Map::Remove(player, remove);
1603}
1604
1605Creature * Map::GetCreatureInMap(uint64 guid)
1606{
1607    Creature * obj = HashMapHolder<Creature>::Find(guid);
1608    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1609    return obj;
1610}
1611
1612GameObject * Map::GetGameObjectInMap(uint64 guid)
1613{
1614    GameObject * obj = HashMapHolder<GameObject>::Find(guid);
1615    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1616    return obj;
1617}
1618
1619void InstanceMap::CreateInstanceData(bool load)
1620{
1621    if(i_data != NULL)
1622        return;
1623
1624    InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1625    if (mInstance)
1626    {
1627        i_script = mInstance->script;
1628        i_data = Script->CreateInstanceData(this);
1629    }
1630
1631    if(!i_data)
1632        return;
1633
1634    if(load)
1635    {
1636        // TODO: make a global storage for this
1637        QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1638        if (result)
1639        {
1640            Field* fields = result->Fetch();
1641            const char* data = fields[0].GetString();
1642            if(data)
1643            {
1644                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1645                i_data->Load(data);
1646            }
1647            delete result;
1648        }
1649    }
1650    else
1651    {
1652        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1653        i_data->Initialize();
1654    }
1655}
1656
1657/*
1658    Returns true if there are no players in the instance
1659*/
1660bool InstanceMap::Reset(uint8 method)
1661{
1662    // note: since the map may not be loaded when the instance needs to be reset
1663    // the instance must be deleted from the DB by InstanceSaveManager
1664
1665    if(!i_Players.empty())
1666    {
1667        if(method == INSTANCE_RESET_ALL)
1668        {
1669            // notify the players to leave the instance so it can be reset
1670            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1671                (*itr)->SendResetFailedNotify(GetId());
1672        }
1673        else
1674        {
1675            if(method == INSTANCE_RESET_GLOBAL)
1676            {
1677                // set the homebind timer for players inside (1 minute)
1678                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1679                    (*itr)->m_InstanceValid = false;
1680            }
1681
1682            // the unload timer is not started
1683            // instead the map will unload immediately after the players have left
1684            m_unloadWhenEmpty = true;
1685            m_resetAfterUnload = true;
1686        }
1687    }
1688    else
1689    {
1690        // unloaded at next update
1691        m_unloadTimer = MIN_UNLOAD_DELAY;
1692        m_resetAfterUnload = true;
1693    }
1694
1695    return i_Players.empty();
1696}
1697
1698uint32 InstanceMap::GetPlayersCountExceptGMs() const
1699{
1700    uint32 count = 0;
1701    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1702        if(!(*itr)->isGameMaster())
1703            ++count;
1704    return count;
1705}
1706
1707void InstanceMap::PermBindAllPlayers(Player *player)
1708{
1709    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1710    if(!save)
1711    {
1712        sLog.outError("Cannot bind players, no instance save available for map!\n");
1713        return;
1714    }
1715
1716    Group *group = player->GetGroup();
1717    // group members outside the instance group don't get bound
1718    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1719    {
1720        if(*itr)
1721        {
1722            // players inside an instance cannot be bound to other instances
1723            // some players may already be permanently bound, in this case nothing happens
1724            InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1725            if(!bind || !bind->perm)
1726            {
1727                (*itr)->BindToInstance(save, true);
1728                WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1729                data << uint32(0);
1730                (*itr)->GetSession()->SendPacket(&data);
1731            }
1732
1733            // if the leader is not in the instance the group will not get a perm bind
1734            if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1735                group->BindToInstance(save, true);
1736        }
1737    }
1738}
1739
1740time_t InstanceMap::GetResetTime()
1741{
1742    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1743    return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1744}
1745
1746void InstanceMap::UnloadAll(bool pForce)
1747{
1748    if(!i_Players.empty())
1749    {
1750        sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1751        for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1752            if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1753    }
1754
1755    if(m_resetAfterUnload == true)
1756        objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1757
1758    Map::UnloadAll(pForce);
1759}
1760
1761void InstanceMap::SendResetWarnings(uint32 timeLeft)
1762{
1763    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1764        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1765}
1766
1767void InstanceMap::SetResetSchedule(bool on)
1768{
1769    // only for normal instances
1770    // the reset time is only scheduled when there are no payers inside
1771    // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1772    if(i_Players.empty() && !IsRaid() && !IsHeroic())
1773    {
1774        InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1775        if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1776        else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1777    }
1778}
1779
1780void InstanceMap::SendToPlayers(WorldPacket const* data) const
1781{
1782    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1783        (*itr)->GetSession()->SendPacket(data);
1784}
1785
1786/* ******* Battleground Instance Maps ******* */
1787
1788BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1789  : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1790{
1791}
1792
1793BattleGroundMap::~BattleGroundMap()
1794{
1795}
1796
1797bool BattleGroundMap::CanEnter(Player * player)
1798{
1799    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1800    {
1801        sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1802        assert(false);
1803        return false;
1804    }
1805
1806    if(player->GetBattleGroundId() != GetInstanceId())
1807        return false;
1808
1809    // player number limit is checked in bgmgr, no need to do it here
1810
1811    return Map::CanEnter(player);
1812}
1813
1814bool BattleGroundMap::Add(Player * player)
1815{
1816    {
1817        Guard guard(*this);
1818        if(!CanEnter(player))
1819            return false;
1820        i_Players.push_back(player);
1821        // reset instance validity, battleground maps do not homebind
1822        player->m_InstanceValid = true;
1823    }
1824    return Map::Add(player);
1825}
1826
1827void BattleGroundMap::Remove(Player *player, bool remove)
1828{
1829    sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1830    i_Players.remove(player);
1831    Map::Remove(player, remove);
1832}
1833
1834void BattleGroundMap::SetUnload()
1835{
1836    m_unloadTimer = MIN_UNLOAD_DELAY;
1837}
1838
1839void BattleGroundMap::UnloadAll(bool pForce)
1840{
1841    while(!i_Players.empty())
1842    {
1843        PlayerList::iterator itr = i_Players.begin();
1844        Player * plr = *itr;
1845        if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1846        // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1847        // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1848        // note that this remove is not needed if the code works well in other places
1849        i_Players.remove(plr);
1850    }
1851
1852    Map::UnloadAll(pForce);
1853}
Note: See TracBrowser for help on using the browser.