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

Revision 281, 69.5 kB (checked in by yumileroy, 17 years ago)

Merge with 273 (aab191f73e46).

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