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

Revision 229, 64.8 kB (checked in by yumileroy, 17 years ago)

[svn] *** Source: MaNGOS ***
* Fixed build extractor at Windows Vista. Author: Vladimir
* Fixed comment text and code indentifiers spelling. Author: Vladimir & Paradox.
* Access cached member lists in guild handlers instead of querying the DB. Author: Hunuza
* Small fixes in send/received packet and simple code cleanup also. Author: Vladimir
* Not output error at loading empty character_ticket table. Author: Vladimir
* Not reset display model at shapeshift aura remove if it not set at apply. Author: Arthorius
* Applied props to few files.

Original author: visagalis
Date: 2008-11-14 16:28:45-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 swapped !! => 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 swapped !!
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 necessary? Do we really need the ability 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 global lists in own destructor
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(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 to_possessor, bool own_team_only)
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    RemoveFromGrid(obj,grid,cell);
674
675    UpdateObjectVisibility(obj,cell,p);
676
677    if( remove )
678    {
679        // if option set then object already saved at this moment
680        if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
681            obj->SaveRespawnTime();
682        DeleteFromWorld(obj);
683    }
684}
685
686void
687Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
688{
689    assert(player);
690
691    CellPair old_val = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
692    CellPair new_val = Trinity::ComputeCellPair(x, y);
693
694    Cell old_cell(old_val);
695    Cell new_cell(new_val);
696    new_cell |= old_cell;
697    bool same_cell = (new_cell == old_cell);
698
699    player->Relocate(x, y, z, orientation);
700
701    if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
702    {
703        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());
704
705        // update player position for group at taxi flight
706        if(player->GetGroup() && player->isInFlight())
707            player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
708
709        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
710        RemoveFromGrid(player, oldGrid,old_cell);
711        if( !old_cell.DiffGrid(new_cell) )
712            AddToGrid(player, oldGrid,new_cell);
713
714        if( old_cell.DiffGrid(new_cell) )
715            EnsureGridLoadedForPlayer(new_cell, player, true);
716    }
717
718    // if move then update what player see and who seen
719    UpdatePlayerVisibility(player,new_cell,new_val);
720    UpdateObjectsVisibilityFor(player,new_cell,new_val);
721
722    // also update what possessing player sees
723    if(player->isPossessedByPlayer())
724        UpdateObjectsVisibilityFor((Player*)player->GetCharmer(), new_cell, new_val);
725
726    PlayerRelocationNotify(player,new_cell,new_val);
727    NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
728    if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
729    {
730        ResetGridExpiry(*newGrid, 0.1f);
731        newGrid->SetGridState(GRID_STATE_ACTIVE);
732    }
733}
734
735void
736Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
737{
738    assert(CheckGridIntegrity(creature,false));
739
740    Cell old_cell = creature->GetCurrentCell();
741
742    CellPair new_val = Trinity::ComputeCellPair(x, y);
743    Cell new_cell(new_val);
744
745    // delay creature move for grid/cell to grid/cell moves
746    if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
747    {
748        #ifdef TRINITY_DEBUG
749        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
750            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());
751        #endif
752        AddCreatureToMoveList(creature,x,y,z,ang);
753        // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
754        if(creature->isPossessedByPlayer())
755            EnsureGridLoadedForPlayer(new_cell, (Player*)creature->GetCharmer(), false);
756    }
757    else
758    {
759        creature->Relocate(x, y, z, ang);
760        // Update visibility back to player who is controlling the creature
761        if(creature->isPossessedByPlayer())
762            UpdateObjectsVisibilityFor((Player*)creature->GetCharmer(), new_cell, new_val);
763
764        CreatureRelocationNotify(creature,new_cell,new_val);
765    }
766    assert(CheckGridIntegrity(creature,true));
767}
768
769void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
770{
771    if(!c)
772        return;
773
774    i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
775}
776
777void Map::MoveAllCreaturesInMoveList()
778{
779    while(!i_creaturesToMove.empty())
780    {
781        // get data and remove element;
782        CreatureMoveList::iterator iter = i_creaturesToMove.begin();
783        Creature* c = iter->first;
784        CreatureMover cm = iter->second;
785        i_creaturesToMove.erase(iter);
786
787        // calculate cells
788        CellPair new_val = Trinity::ComputeCellPair(cm.x, cm.y);
789        Cell new_cell(new_val);
790
791        // do move or do move to respawn or remove creature if previous all fail
792        if(CreatureCellRelocation(c,new_cell))
793        {
794            // update pos
795            c->Relocate(cm.x, cm.y, cm.z, cm.ang);
796            CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
797        }
798        else
799        {
800            // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
801            // creature coordinates will be updated and notifiers send
802            if(!CreatureRespawnRelocation(c))
803            {
804                // ... or unload (if respawn grid also not loaded)
805                #ifdef TRINITY_DEBUG
806                if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
807                    sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
808                #endif
809                c->CleanupsBeforeDelete();
810                AddObjectToRemoveList(c);
811            }
812        }
813    }
814}
815
816bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
817{
818    Cell const& old_cell = c->GetCurrentCell();
819    if(!old_cell.DiffGrid(new_cell) )                       // in same grid
820    {
821        // if in same cell then none do
822        if(old_cell.DiffCell(new_cell))
823        {
824            #ifdef TRINITY_DEBUG
825            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
826                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());
827            #endif
828
829            if( !old_cell.DiffGrid(new_cell) )
830            {
831                RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
832                AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
833                c->SetCurrentCell(new_cell);
834            }
835        }
836        else
837        {
838            #ifdef TRINITY_DEBUG
839            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
840                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());
841            #endif
842        }
843    }
844    else                                                    // in diff. grids
845    if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
846    {
847        #ifdef TRINITY_DEBUG
848        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
849            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());
850        #endif
851
852        RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
853        {
854            EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
855            AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
856        }
857    }
858    else
859    {
860        #ifdef TRINITY_DEBUG
861        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
862            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());
863        #endif
864        return false;
865    }
866
867    return true;
868}
869
870bool Map::CreatureRespawnRelocation(Creature *c)
871{
872    float resp_x, resp_y, resp_z, resp_o;
873    c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
874
875    CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
876    Cell resp_cell(resp_val);
877
878    c->CombatStop();
879    c->GetMotionMaster()->Clear();
880
881    #ifdef TRINITY_DEBUG
882    if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
883        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());
884    #endif
885
886    // teleport it to respawn point (like normal respawn if player see)
887    if(CreatureCellRelocation(c,resp_cell))
888    {
889        c->Relocate(resp_x, resp_y, resp_z, resp_o);
890        c->GetMotionMaster()->Initialize();                 // prevent possible problems with default move generators
891        CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
892        return true;
893    }
894    else
895        return false;
896}
897
898bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
899{
900    NGridType *grid = getNGrid(x, y);
901    assert( grid != NULL);
902
903    {
904        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
905            return false;
906
907        DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
908        ObjectGridUnloader unloader(*grid);
909
910        // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
911        // Must know real mob position before move
912        DoDelayedMovesAndRemoves();
913
914        // move creatures to respawn grids if this is diff.grid or to remove list
915        unloader.MoveToRespawnN();
916
917        // Finish creature moves, remove and delete all creatures with delayed remove before unload
918        DoDelayedMovesAndRemoves();
919
920        unloader.UnloadN();
921        delete getNGrid(x, y);
922        setNGrid(NULL, x, y);
923    }
924    int gx=63-x;
925    int gy=63-y;
926
927    // delete grid map, but don't delete if it is from parent map (and thus only reference)
928    //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
929    {
930        if (i_InstanceId == 0)
931        {
932            if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
933            // x and y are swaped
934            VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
935        }
936        else
937            ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
938        GridMaps[gx][gy] = NULL;
939    }
940    DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
941    return true;
942}
943
944void Map::UnloadAll(bool pForce)
945{
946    // clear all delayed moves, useless anyway do this moves before map unload.
947    i_creaturesToMove.clear();
948
949    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
950    {
951        NGridType &grid(*i->getSource());
952        ++i;
953        UnloadGrid(grid.getX(), grid.getY(), pForce);       // deletes the grid and removes it from the GridRefManager
954    }
955}
956
957float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
958{
959    GridPair p = Trinity::ComputeGridPair(x, y);
960
961    // half opt method
962    int gx=(int)(32-x/SIZE_OF_GRIDS);                       //grid x
963    int gy=(int)(32-y/SIZE_OF_GRIDS);                       //grid y
964
965    float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
966    float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
967
968    // ensure GridMap is loaded
969    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
970
971    // find raw .map surface under Z coordinates
972    float mapHeight;
973    if(GridMap* gmap = GridMaps[gx][gy])
974    {
975        int lx_int = (int)lx;
976        int ly_int = (int)ly;
977
978        float zi[4];
979        // Probe 4 nearest points (except border cases)
980        zi[0] = gmap->Z[lx_int][ly_int];
981        zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
982        zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
983        zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
984        // Recalculate them like if their x,y positions were in the range 0,1
985        float b[4];
986        b[0] = zi[0];
987        b[1] = zi[1]-zi[0];
988        b[2] = zi[2]-zi[0];
989        b[3] = zi[0]-zi[1]-zi[2]+zi[3];
990        // Normalize the dx and dy to be in range 0..1
991        float fact_x = lx - lx_int;
992        float fact_y = ly - ly_int;
993        // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
994        float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
995
996        // look from a bit higher pos to find the floor, ignore under surface case
997        if(z + 2.0f > _mapheight)
998            mapHeight = _mapheight;
999        else
1000            mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1001    }
1002    else
1003        mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1004
1005    float vmapHeight;
1006    if(pUseVmaps)
1007    {
1008        VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1009        if(vmgr->isHeightCalcEnabled())
1010        {
1011            // look from a bit higher pos to find the floor
1012            vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1013        }
1014        else
1015            vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1016    }
1017    else
1018        vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1019
1020    // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1021    // vmapheight set for any under Z value or <= INVALID_HEIGHT
1022
1023    if( vmapHeight > INVALID_HEIGHT )
1024    {
1025        if( mapHeight > INVALID_HEIGHT )
1026        {
1027            // we have mapheight and vmapheight and must select more appropriate
1028
1029            // we are already under the surface or vmap height above map heigt
1030            // or if the distance of the vmap height is less the land height distance
1031            if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1032                return vmapHeight;
1033            else
1034                return mapHeight;                           // better use .map surface height
1035
1036        }
1037        else
1038            return vmapHeight;                              // we have only vmapHeight (if have)
1039    }
1040    else
1041    {
1042        if(!pUseVmaps)
1043            return mapHeight;                               // explicitly use map data (if have)
1044        else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1045            return mapHeight;                               // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1046        else
1047            return VMAP_INVALID_HEIGHT_VALUE;               // we not have any height
1048    }
1049}
1050
1051uint16 Map::GetAreaFlag(float x, float y ) const
1052{
1053    //local x,y coords
1054    float lx,ly;
1055    int gx,gy;
1056    GridPair p = Trinity::ComputeGridPair(x, y);
1057
1058    // half opt method
1059    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1060    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1061
1062    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1063    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1064    //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1065
1066    // ensure GridMap is loaded
1067    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1068
1069    if(GridMaps[gx][gy])
1070        return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1071    // this used while not all *.map files generated (instances)
1072    else
1073        return GetAreaFlagByMapId(i_id);
1074}
1075
1076uint8 Map::GetTerrainType(float x, float y ) const
1077{
1078    //local x,y coords
1079    float lx,ly;
1080    int gx,gy;
1081
1082    // half opt method
1083    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1084    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1085
1086    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1087    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1088
1089    // ensure GridMap is loaded
1090    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1091
1092    if(GridMaps[gx][gy])
1093        return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1094    else
1095        return 0;
1096
1097}
1098
1099float Map::GetWaterLevel(float x, float y ) const
1100{
1101    //local x,y coords
1102    float lx,ly;
1103    int gx,gy;
1104
1105    // half opt method
1106    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1107    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1108
1109    lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1110    ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1111
1112    // ensure GridMap is loaded
1113    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1114
1115    if(GridMaps[gx][gy])
1116        return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1117    else
1118        return 0;
1119}
1120
1121uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1122{
1123    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1124
1125    if (entry)
1126        return entry->ID;
1127    else
1128        return 0;
1129}
1130
1131uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1132{
1133    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1134
1135    if( entry )
1136        return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1137    else
1138        return 0;
1139}
1140
1141bool Map::IsInWater(float x, float y, float pZ) const
1142{
1143    // This method is called too often to use vamps for that (4. parameter = false).
1144    // The pZ pos is taken anyway for future use
1145    float z = GetHeight(x,y,pZ,false);                      // use .map base surface height
1146
1147    // underground or instance without vmap
1148    if(z <= INVALID_HEIGHT)
1149        return false;
1150
1151    float water_z = GetWaterLevel(x,y);
1152    uint8 flag = GetTerrainType(x,y);
1153    return (z < (water_z-2)) && (flag & 0x01);
1154}
1155
1156bool Map::IsUnderWater(float x, float y, float z) const
1157{
1158    float water_z = GetWaterLevel(x,y);
1159    uint8 flag = GetTerrainType(x,y);
1160    return (z < (water_z-2)) && (flag & 0x01);
1161}
1162
1163bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1164{
1165    Cell const& cur_cell = c->GetCurrentCell();
1166
1167    CellPair xy_val = Trinity::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1168    Cell xy_cell(xy_val);
1169    if(xy_cell != cur_cell)
1170    {
1171        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]",
1172            (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1173            c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1174            cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1175            xy_cell.GridX(),  xy_cell.GridY(),  xy_cell.CellX(),  xy_cell.CellY());
1176        return true;                                        // not crash at error, just output error in debug mode
1177    }
1178
1179    return true;
1180}
1181
1182const char* Map::GetMapName() const
1183{
1184    return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1185}
1186
1187void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1188{
1189    cell.data.Part.reserved = ALL_DISTRICT;
1190    cell.SetNoCreate();
1191    Trinity::VisibleChangesNotifier notifier(*obj);
1192    TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1193    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1194    cell_lock->Visit(cell_lock, player_notifier, *this);
1195}
1196
1197void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1198{
1199    cell.data.Part.reserved = ALL_DISTRICT;
1200
1201    Trinity::PlayerNotifier pl_notifier(*player);
1202    TypeContainerVisitor<Trinity::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1203
1204    CellLock<ReadGuard> cell_lock(cell, cellpair);
1205    cell_lock->Visit(cell_lock, player_notifier, *this);
1206}
1207
1208void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1209{
1210    Trinity::VisibleNotifier notifier(*player);
1211
1212    cell.data.Part.reserved = ALL_DISTRICT;
1213    cell.SetNoCreate();
1214    TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1215    TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer  > grid_notifier(notifier);
1216    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1217    cell_lock->Visit(cell_lock, world_notifier, *this);
1218    cell_lock->Visit(cell_lock, grid_notifier,  *this);
1219
1220    // send data
1221    notifier.Notify();
1222}
1223
1224void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1225{
1226    CellLock<ReadGuard> cell_lock(cell, cellpair);
1227    Trinity::PlayerRelocationNotifier relocationNotifier(*player);
1228    cell.data.Part.reserved = ALL_DISTRICT;
1229
1230    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, GridTypeMapContainer >  p2grid_relocation(relocationNotifier);
1231    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1232
1233    cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1234    cell_lock->Visit(cell_lock, p2world_relocation, *this);
1235}
1236
1237void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1238{
1239    CellLock<ReadGuard> cell_lock(cell, cellpair);
1240    Trinity::CreatureRelocationNotifier relocationNotifier(*creature);
1241    cell.data.Part.reserved = ALL_DISTRICT;
1242    cell.SetNoCreate();                                     // not trigger load unloaded grids at notifier call
1243
1244    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1245    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, GridTypeMapContainer >  c2grid_relocation(relocationNotifier);
1246
1247    cell_lock->Visit(cell_lock, c2world_relocation, *this);
1248    cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1249}
1250
1251void Map::SendInitSelf( Player * player )
1252{
1253    sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1254
1255    UpdateData data;
1256
1257    bool hasTransport = false;
1258
1259    // attach to player data current transport data
1260    if(Transport* transport = player->GetTransport())
1261    {
1262        hasTransport = true;
1263        transport->BuildCreateUpdateBlockForPlayer(&data, player);
1264    }
1265
1266    // build data for self presence in world at own client (one time for map)
1267    player->BuildCreateUpdateBlockForPlayer(&data, player);
1268
1269    // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1270    if(Transport* transport = player->GetTransport())
1271    {
1272        for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1273        {
1274            if(player!=(*itr) && player->HaveAtClient(*itr))
1275            {
1276                hasTransport = true;
1277                (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1278            }
1279        }
1280    }
1281
1282    WorldPacket packet;
1283    data.BuildPacket(&packet, hasTransport);
1284    player->GetSession()->SendPacket(&packet);
1285}
1286
1287void Map::SendInitTransports( Player * player )
1288{
1289    // Hack to send out transports
1290    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1291
1292    // no transports at map
1293    if (tmap.find(player->GetMapId()) == tmap.end())
1294        return;
1295
1296    UpdateData transData;
1297
1298    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1299
1300    bool hasTransport = false;
1301
1302    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1303    {
1304        if((*i) != player->GetTransport())                  // send data for current transport in other place
1305        {
1306            hasTransport = true;
1307            (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1308        }
1309    }
1310
1311    WorldPacket packet;
1312    transData.BuildPacket(&packet, hasTransport);
1313    player->GetSession()->SendPacket(&packet);
1314}
1315
1316void Map::SendRemoveTransports( Player * player )
1317{
1318    // Hack to send out transports
1319    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1320
1321    // no transports at map
1322    if (tmap.find(player->GetMapId()) == tmap.end())
1323        return;
1324
1325    UpdateData transData;
1326
1327    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1328
1329    // except used transport
1330    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1331        if(player->GetTransport() != (*i))
1332            (*i)->BuildOutOfRangeUpdateBlock(&transData);
1333
1334    WorldPacket packet;
1335    transData.BuildPacket(&packet);
1336    player->GetSession()->SendPacket(&packet);
1337}
1338
1339inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1340{
1341    if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1342    {
1343        sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1344        assert(false);
1345    }
1346    i_grids[x][y] = grid;
1347}
1348
1349void Map::DoDelayedMovesAndRemoves()
1350{
1351    MoveAllCreaturesInMoveList();
1352    RemoveAllObjectsInRemoveList();
1353}
1354
1355void Map::AddObjectToRemoveList(WorldObject *obj)
1356{
1357    assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1358
1359    i_objectsToRemove.insert(obj);
1360    //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1361}
1362
1363void Map::RemoveAllObjectsInRemoveList()
1364{
1365    if(i_objectsToRemove.empty())
1366        return;
1367
1368    //sLog.outDebug("Object remover 1 check.");
1369    while(!i_objectsToRemove.empty())
1370    {
1371        WorldObject* obj = *i_objectsToRemove.begin();
1372        i_objectsToRemove.erase(i_objectsToRemove.begin());
1373
1374        switch(obj->GetTypeId())
1375        {
1376            case TYPEID_CORPSE:
1377            {
1378                Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1379                if (!corpse)
1380                    sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1381                else
1382                    Remove(corpse,true);
1383                break;
1384            }
1385        case TYPEID_DYNAMICOBJECT:
1386            Remove((DynamicObject*)obj,true);
1387            break;
1388        case TYPEID_GAMEOBJECT:
1389            Remove((GameObject*)obj,true);
1390            break;
1391        case TYPEID_UNIT:
1392            // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1393            // make sure that like sources auras/etc removed before destructor start
1394            ((Creature*)obj)->CleanupsBeforeDelete ();
1395            Remove((Creature*)obj,true);
1396            break;
1397        default:
1398            sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1399            break;
1400        }
1401    }
1402    //sLog.outDebug("Object remover 2 check.");
1403}
1404
1405bool Map::CanUnload(const uint32 &diff)
1406{
1407    if(!m_unloadTimer) return false;
1408    if(m_unloadTimer < diff) return true;
1409    m_unloadTimer -= diff;
1410    return false;
1411}
1412
1413template void Map::Add(Corpse *);
1414template void Map::Add(Creature *);
1415template void Map::Add(GameObject *);
1416template void Map::Add(DynamicObject *);
1417
1418template void Map::Remove(Corpse *,bool);
1419template void Map::Remove(Creature *,bool);
1420template void Map::Remove(GameObject *, bool);
1421template void Map::Remove(DynamicObject *, bool);
1422
1423/* ******* Dungeon Instance Maps ******* */
1424
1425InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1426  : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1427    m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1428{
1429    // the timer is started by default, and stopped when the first player joins
1430    // this make sure it gets unloaded if for some reason no player joins
1431    m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1432}
1433
1434InstanceMap::~InstanceMap()
1435{
1436    if(i_data)
1437    {
1438        delete i_data;
1439        i_data = NULL;
1440    }
1441}
1442
1443/*
1444    Do map specific checks to see if the player can enter
1445*/
1446bool InstanceMap::CanEnter(Player *player)
1447{
1448    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1449    {
1450        sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1451        assert(false);
1452        return false;
1453    }
1454
1455    // cannot enter if the instance is full (player cap), GMs don't count
1456    InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1457    if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1458    {
1459        sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1460        player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1461        return false;
1462    }
1463
1464    // cannot enter while players in the instance are in combat
1465    Group *pGroup = player->GetGroup();
1466    if(!player->isGameMaster() && pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1467    {
1468        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1469        return false;
1470    }
1471
1472    return Map::CanEnter(player);
1473}
1474
1475/*
1476    Do map specific checks and add the player to the map if successful.
1477*/
1478bool InstanceMap::Add(Player *player)
1479{
1480    // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1481    // GMs still can teleport player in instance.
1482    // Is it needed?
1483
1484    {
1485        Guard guard(*this);
1486        if(!CanEnter(player))
1487            return false;
1488
1489        // get or create an instance save for the map
1490        InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1491        if(!mapSave)
1492        {
1493            sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1494            mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1495        }
1496
1497        // check for existing instance binds
1498        InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1499        if(playerBind && playerBind->perm)
1500        {
1501            // cannot enter other instances if bound permanently
1502            if(playerBind->save != mapSave)
1503            {
1504                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());
1505                assert(false);
1506            }
1507        }
1508        else
1509        {
1510            Group *pGroup = player->GetGroup();
1511            if(pGroup)
1512            {
1513                // solo saves should be reset when entering a group
1514                InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1515                if(playerBind)
1516                {
1517                    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());
1518                    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());
1519                    assert(false);
1520                }
1521                // bind to the group or keep using the group save
1522                if(!groupBind)
1523                    pGroup->BindToInstance(mapSave, false);
1524                else
1525                {
1526                    // cannot jump to a different instance without resetting it
1527                    if(groupBind->save != mapSave)
1528                    {
1529                        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());
1530                        if(mapSave)
1531                            sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1532                        else
1533                            sLog.outError("MapSave NULL");
1534                        if(groupBind->save)
1535                            sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1536                        else
1537                            sLog.outError("GroupBind save NULL");
1538                        assert(false);
1539                    }
1540                    // if the group/leader is permanently bound to the instance
1541                    // players also become permanently bound when they enter
1542                    if(groupBind->perm)
1543                    {
1544                        WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1545                        data << uint32(0);
1546                        player->GetSession()->SendPacket(&data);
1547                        player->BindToInstance(mapSave, true);
1548                    }
1549                }
1550            }
1551            else
1552            {
1553                // set up a solo bind or continue using it
1554                if(!playerBind)
1555                    player->BindToInstance(mapSave, false);
1556                else
1557                    // cannot jump to a different instance without resetting it
1558                    assert(playerBind->save == mapSave);
1559            }
1560        }
1561
1562        if(i_data) i_data->OnPlayerEnter(player);
1563        SetResetSchedule(false);
1564
1565        i_Players.push_back(player);
1566        player->SendInitWorldStates();
1567        sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1568        // initialize unload state
1569        m_unloadTimer = 0;
1570        m_resetAfterUnload = false;
1571        m_unloadWhenEmpty = false;
1572    }
1573
1574    // this will acquire the same mutex so it cannot be in the previous block
1575    Map::Add(player);
1576    return true;
1577}
1578
1579void InstanceMap::Update(const uint32& t_diff)
1580{
1581    Map::Update(t_diff);
1582
1583    if(i_data)
1584        i_data->Update(t_diff);
1585}
1586
1587void InstanceMap::Remove(Player *player, bool remove)
1588{
1589    sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1590    i_Players.remove(player);
1591    SetResetSchedule(true);
1592    if(!m_unloadTimer && i_Players.empty())
1593        m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1594    Map::Remove(player, remove);
1595}
1596
1597Creature * Map::GetCreatureInMap(uint64 guid)
1598{
1599    Creature * obj = HashMapHolder<Creature>::Find(guid);
1600    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1601    return obj;
1602}
1603
1604GameObject * Map::GetGameObjectInMap(uint64 guid)
1605{
1606    GameObject * obj = HashMapHolder<GameObject>::Find(guid);
1607    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1608    return obj;
1609}
1610
1611void InstanceMap::CreateInstanceData(bool load)
1612{
1613    if(i_data != NULL)
1614        return;
1615
1616    InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1617    if (mInstance)
1618    {
1619        i_script = mInstance->script;
1620        i_data = Script->CreateInstanceData(this);
1621    }
1622
1623    if(!i_data)
1624        return;
1625
1626    if(load)
1627    {
1628        // TODO: make a global storage for this
1629        QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1630        if (result)
1631        {
1632            Field* fields = result->Fetch();
1633            const char* data = fields[0].GetString();
1634            if(data)
1635            {
1636                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1637                i_data->Load(data);
1638            }
1639            delete result;
1640        }
1641    }
1642    else
1643    {
1644        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1645        i_data->Initialize();
1646    }
1647}
1648
1649/*
1650    Returns true if there are no players in the instance
1651*/
1652bool InstanceMap::Reset(uint8 method)
1653{
1654    // note: since the map may not be loaded when the instance needs to be reset
1655    // the instance must be deleted from the DB by InstanceSaveManager
1656
1657    if(!i_Players.empty())
1658    {
1659        if(method == INSTANCE_RESET_ALL)
1660        {
1661            // notify the players to leave the instance so it can be reset
1662            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1663                (*itr)->SendResetFailedNotify(GetId());
1664        }
1665        else
1666        {
1667            if(method == INSTANCE_RESET_GLOBAL)
1668            {
1669                // set the homebind timer for players inside (1 minute)
1670                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1671                    (*itr)->m_InstanceValid = false;
1672            }
1673
1674            // the unload timer is not started
1675            // instead the map will unload immediately after the players have left
1676            m_unloadWhenEmpty = true;
1677            m_resetAfterUnload = true;
1678        }
1679    }
1680    else
1681    {
1682        // unloaded at next update
1683        m_unloadTimer = MIN_UNLOAD_DELAY;
1684        m_resetAfterUnload = true;
1685    }
1686
1687    return i_Players.empty();
1688}
1689
1690uint32 InstanceMap::GetPlayersCountExceptGMs() const
1691{
1692    uint32 count = 0;
1693    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1694        if(!(*itr)->isGameMaster())
1695            ++count;
1696    return count;
1697}
1698
1699void InstanceMap::PermBindAllPlayers(Player *player)
1700{
1701    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1702    if(!save)
1703    {
1704        sLog.outError("Cannot bind players, no instance save available for map!\n");
1705        return;
1706    }
1707
1708    Group *group = player->GetGroup();
1709    // group members outside the instance group don't get bound
1710    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1711    {
1712        if(*itr)
1713        {
1714            // players inside an instance cannot be bound to other instances
1715            // some players may already be permanently bound, in this case nothing happens
1716            InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1717            if(!bind || !bind->perm)
1718            {
1719                (*itr)->BindToInstance(save, true);
1720                WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1721                data << uint32(0);
1722                (*itr)->GetSession()->SendPacket(&data);
1723            }
1724
1725            // if the leader is not in the instance the group will not get a perm bind
1726            if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1727                group->BindToInstance(save, true);
1728        }
1729    }
1730}
1731
1732time_t InstanceMap::GetResetTime()
1733{
1734    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1735    return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1736}
1737
1738void InstanceMap::UnloadAll(bool pForce)
1739{
1740    if(!i_Players.empty())
1741    {
1742        sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1743        for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1744            if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1745    }
1746
1747    if(m_resetAfterUnload == true)
1748        objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1749
1750    Map::UnloadAll(pForce);
1751}
1752
1753void InstanceMap::SendResetWarnings(uint32 timeLeft)
1754{
1755    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1756        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1757}
1758
1759void InstanceMap::SetResetSchedule(bool on)
1760{
1761    // only for normal instances
1762    // the reset time is only scheduled when there are no payers inside
1763    // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1764    if(i_Players.empty() && !IsRaid() && !IsHeroic())
1765    {
1766        InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1767        if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1768        else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1769    }
1770}
1771
1772void InstanceMap::SendToPlayers(WorldPacket const* data) const
1773{
1774    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1775        (*itr)->GetSession()->SendPacket(data);
1776}
1777
1778/* ******* Battleground Instance Maps ******* */
1779
1780BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1781  : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1782{
1783}
1784
1785BattleGroundMap::~BattleGroundMap()
1786{
1787}
1788
1789bool BattleGroundMap::CanEnter(Player * player)
1790{
1791    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1792    {
1793        sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1794        assert(false);
1795        return false;
1796    }
1797
1798    if(player->GetBattleGroundId() != GetInstanceId())
1799        return false;
1800
1801    // player number limit is checked in bgmgr, no need to do it here
1802
1803    return Map::CanEnter(player);
1804}
1805
1806bool BattleGroundMap::Add(Player * player)
1807{
1808    {
1809        Guard guard(*this);
1810        if(!CanEnter(player))
1811            return false;
1812        i_Players.push_back(player);
1813        // reset instance validity, battleground maps do not homebind
1814        player->m_InstanceValid = true;
1815    }
1816    return Map::Add(player);
1817}
1818
1819void BattleGroundMap::Remove(Player *player, bool remove)
1820{
1821    sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1822    i_Players.remove(player);
1823    Map::Remove(player, remove);
1824}
1825
1826void BattleGroundMap::SetUnload()
1827{
1828    m_unloadTimer = MIN_UNLOAD_DELAY;
1829}
1830
1831void BattleGroundMap::UnloadAll(bool pForce)
1832{
1833    while(!i_Players.empty())
1834    {
1835        PlayerList::iterator itr = i_Players.begin();
1836        Player * plr = *itr;
1837        if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1838        // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1839        // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1840        // note that this remove is not needed if the code works well in other places
1841        i_Players.remove(plr);
1842    }
1843
1844    Map::UnloadAll(pForce);
1845}
Note: See TracBrowser for help on using the browser.