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

Revision 260, 67.8 kB (checked in by yumileroy, 17 years ago)

*DB script table stucture change. Source Mangos. Also fix some bugs. Hopefully this rev will make program usable again.

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