Merge branch 'master' into 303
[getmangos.git] / src / game / Map.cpp
blob323cc23262937ff02da3e23753812317fe70e147
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "MapManager.h"
20 #include "Player.h"
21 #include "GridNotifiers.h"
22 #include "WorldSession.h"
23 #include "Log.h"
24 #include "GridStates.h"
25 #include "CellImpl.h"
26 #include "InstanceData.h"
27 #include "Map.h"
28 #include "GridNotifiersImpl.h"
29 #include "Config/ConfigEnv.h"
30 #include "Transports.h"
31 #include "ObjectAccessor.h"
32 #include "ObjectMgr.h"
33 #include "World.h"
34 #include "ScriptCalls.h"
35 #include "Group.h"
37 #include "MapInstanced.h"
38 #include "InstanceSaveMgr.h"
39 #include "VMapFactory.h"
41 #define DEFAULT_GRID_EXPIRY 300
42 #define MAX_GRID_LOAD_TIME 50
44 // magic *.map header
45 const char MAP_MAGIC[] = "MAP_2.01";
47 GridState* si_GridStates[MAX_GRID_STATE];
49 Map::~Map()
51 UnloadAll(true);
54 bool Map::ExistMap(uint32 mapid,int x,int y)
56 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
57 char* tmp = new char[len];
58 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
60 FILE *pf=fopen(tmp,"rb");
62 if(!pf)
64 sLog.outError("Check existing of map file '%s': not exist!",tmp);
65 delete[] tmp;
66 return false;
69 char magic[8];
70 fread(magic,1,8,pf);
71 if(strncmp(MAP_MAGIC,magic,8))
73 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
74 delete [] tmp;
75 fclose(pf); //close file before return
76 return false;
79 delete [] tmp;
80 fclose(pf);
82 return true;
85 bool Map::ExistVMap(uint32 mapid,int x,int y)
87 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
89 if(vmgr->isMapLoadingEnabled())
91 // x and y are swapped !! => fixed now
92 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, x,y);
93 if(!exists)
95 std::string name = vmgr->getDirFileName(mapid,x,y);
96 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());
97 return false;
102 return true;
105 void Map::LoadVMap(int x,int y)
107 // x and y are swapped !!
108 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), x,y);
109 switch(vmapLoadResult)
111 case VMAP::VMAP_LOAD_RESULT_OK:
112 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
113 break;
114 case VMAP::VMAP_LOAD_RESULT_ERROR:
115 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);
116 break;
117 case VMAP::VMAP_LOAD_RESULT_IGNORED:
118 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
119 break;
123 void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
125 if( instanceid != 0 )
127 if(GridMaps[x][y])
128 return;
130 Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
132 // load gridmap for base map
133 if (!baseMap->GridMaps[x][y])
134 baseMap->EnsureGridCreated(GridPair(63-x,63-y));
136 //+++ if (!baseMap->GridMaps[x][y]) don't check for GridMaps[gx][gy], we need the management for vmaps
137 // return;
139 ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
140 baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
141 GridMaps[x][y] = baseMap->GridMaps[x][y];
142 return;
145 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
146 if(GridMaps[x][y])
148 sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
149 delete (GridMaps[x][y]);
150 GridMaps[x][y]=NULL;
153 // map file name
154 char *tmp=NULL;
155 // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
156 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
157 tmp = new char[len];
158 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
159 sLog.outDetail("Loading map %s",tmp);
160 // loading data
161 FILE *pf=fopen(tmp,"rb");
162 if(!pf)
164 delete [] tmp;
165 return;
168 char magic[8];
169 fread(magic,1,8,pf);
170 if(strncmp(MAP_MAGIC,magic,8))
172 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
173 delete [] tmp;
174 fclose(pf); //close file before return
175 return;
177 delete [] tmp;
179 GridMap * buf= new GridMap;
180 fread(buf,1,sizeof(GridMap),pf);
181 fclose(pf);
183 GridMaps[x][y] = buf;
186 void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
188 LoadMap(mapid,instanceid,x,y);
189 if(instanceid == 0)
190 LoadVMap(x, y); // Only load the data for the base map
193 void Map::InitStateMachine()
195 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
196 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
197 si_GridStates[GRID_STATE_IDLE] = new IdleState;
198 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201 void Map::DeleteStateMachine()
203 delete si_GridStates[GRID_STATE_INVALID];
204 delete si_GridStates[GRID_STATE_ACTIVE];
205 delete si_GridStates[GRID_STATE_IDLE];
206 delete si_GridStates[GRID_STATE_REMOVAL];
209 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
210 : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
211 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
213 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
215 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
217 //z code
218 GridMaps[idx][j] =NULL;
219 setNGrid(NULL, idx, j);
224 // Template specialization of utility methods
225 template<class T>
226 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
228 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
231 template<>
232 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
234 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
237 template<>
238 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
240 // add to world object registry in grid
241 if(obj->GetType()!=CORPSE_BONES)
243 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
245 // add to grid object store
246 else
248 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
252 template<>
253 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
255 // add to world object registry in grid
256 if(obj->isPet() || obj->isVehicle())
258 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
259 obj->SetCurrentCell(cell);
261 // add to grid object store
262 else
264 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
265 obj->SetCurrentCell(cell);
269 template<class T>
270 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
272 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
275 template<>
276 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
278 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
281 template<>
282 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
284 // remove from world object registry in grid
285 if(obj->GetType()!=CORPSE_BONES)
287 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
289 // remove from grid object store
290 else
292 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
296 template<>
297 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
299 // remove from world object registry in grid
300 if(obj->isPet() || obj->isVehicle())
302 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
304 // remove from grid object store
305 else
307 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
311 template<class T>
312 void Map::DeleteFromWorld(T* obj)
314 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
315 delete obj;
318 template<class T>
319 void Map::AddNotifier(T* , Cell const& , CellPair const& )
323 template<>
324 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
326 PlayerRelocationNotify(obj,cell,cellpair);
329 template<>
330 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
332 CreatureRelocationNotify(obj,cell,cellpair);
335 void
336 Map::EnsureGridCreated(const GridPair &p)
338 if(!getNGrid(p.x_coord, p.y_coord))
340 Guard guard(*this);
341 if(!getNGrid(p.x_coord, p.y_coord))
343 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)),
344 p.x_coord, p.y_coord);
346 // build a linkage between this map and NGridType
347 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
349 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
351 //z coord
352 int gx=63-p.x_coord;
353 int gy=63-p.y_coord;
355 if(!GridMaps[gx][gy])
356 Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
361 void
362 Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
364 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
365 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
367 assert(grid != NULL);
368 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
370 if( player != NULL )
372 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
373 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);
375 else
377 DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
380 ObjectGridLoader loader(*grid, this, cell);
381 loader.LoadN();
382 setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
384 // Add resurrectable corpses to world object list in grid
385 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
387 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
388 grid->SetGridState(GRID_STATE_ACTIVE);
390 if( add_player && player != NULL )
391 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
393 else if( player && add_player )
394 AddToGrid(player,grid,cell);
397 void
398 Map::LoadGrid(const Cell& cell, bool no_unload)
400 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
401 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
403 assert(grid != NULL);
404 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
406 ObjectGridLoader loader(*grid, this, cell);
407 loader.LoadN();
409 // Add resurrectable corpses to world object list in grid
410 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
412 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
413 if(no_unload)
414 getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
416 LoadVMap(63-cell.GridX(),63-cell.GridY());
419 bool Map::Add(Player *player)
421 player->SetInstanceId(GetInstanceId());
423 // update player state for other player and visa-versa
424 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
425 Cell cell(p);
426 EnsureGridLoadedForPlayer(cell, player, true);
427 player->AddToWorld();
429 SendInitSelf(player);
430 SendInitTransports(player);
432 UpdatePlayerVisibility(player,cell,p);
433 UpdateObjectsVisibilityFor(player,cell,p);
435 AddNotifier(player,cell,p);
436 return true;
439 template<class T>
440 void
441 Map::Add(T *obj)
443 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
445 assert(obj);
447 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
449 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);
450 return;
453 Cell cell(p);
454 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
455 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
456 assert( grid != NULL );
458 AddToGrid(obj,grid,cell);
459 obj->AddToWorld();
461 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
463 UpdateObjectVisibility(obj,cell,p);
465 AddNotifier(obj,cell,p);
468 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
470 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
472 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
474 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);
475 return;
478 Cell cell(p);
479 cell.data.Part.reserved = ALL_DISTRICT;
481 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
482 return;
484 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
485 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
486 CellLock<ReadGuard> cell_lock(cell, p);
487 cell_lock->Visit(cell_lock, message, *this);
490 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
492 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
494 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
496 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);
497 return;
500 Cell cell(p);
501 cell.data.Part.reserved = ALL_DISTRICT;
502 cell.SetNoCreate();
504 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
505 return;
507 MaNGOS::ObjectMessageDeliverer post_man(msg);
508 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
509 CellLock<ReadGuard> cell_lock(cell, p);
510 cell_lock->Visit(cell_lock, message, *this);
513 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
515 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
517 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
519 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);
520 return;
523 Cell cell(p);
524 cell.data.Part.reserved = ALL_DISTRICT;
526 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
527 return;
529 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
530 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
531 CellLock<ReadGuard> cell_lock(cell, p);
532 cell_lock->Visit(cell_lock, message, *this);
535 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
537 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
539 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
541 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);
542 return;
545 Cell cell(p);
546 cell.data.Part.reserved = ALL_DISTRICT;
547 cell.SetNoCreate();
549 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
550 return;
552 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
553 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
554 CellLock<ReadGuard> cell_lock(cell, p);
555 cell_lock->Visit(cell_lock, message, *this);
558 bool Map::loaded(const GridPair &p) const
560 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
563 void Map::Update(const uint32 &t_diff)
565 resetMarkedCells();
567 MaNGOS::ObjectUpdater updater(t_diff);
568 // for creature
569 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
570 // for pets
571 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
573 //TODO: Player guard
574 HashMapHolder<Player>::MapType& playerMap = HashMapHolder<Player>::GetContainer();
575 for(HashMapHolder<Player>::MapType::iterator iter = playerMap.begin(); iter != playerMap.end(); ++iter)
577 WorldObject* obj = iter->second;
579 if(!obj->IsInWorld())
580 continue;
582 if(obj->GetMapId() != GetId())
583 continue;
585 if(obj->GetInstanceId() != GetInstanceId())
586 continue;
588 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
590 // Check for correctness of standing_cell, it also avoids problems with update_cell
591 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
592 continue;
594 // the overloaded operators handle range checking
595 // so ther's no need for range checking inside the loop
596 CellPair begin_cell(standing_cell), end_cell(standing_cell);
597 begin_cell << 1; begin_cell -= 1; // upper left
598 end_cell >> 1; end_cell += 1; // lower right
600 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
602 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
604 // marked cells are those that have been visited
605 // don't visit the same cell twice
606 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
607 if(!isCellMarked(cell_id))
609 markCell(cell_id);
610 CellPair pair(x,y);
611 Cell cell(pair);
612 cell.data.Part.reserved = CENTER_DISTRICT;
613 cell.SetNoCreate();
614 CellLock<NullGuard> cell_lock(cell, pair);
615 cell_lock->Visit(cell_lock, grid_object_update, *this);
616 cell_lock->Visit(cell_lock, world_object_update, *this);
623 // 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 !
624 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
625 if (IsBattleGroundOrArena())
626 return;
628 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
630 NGridType *grid = i->getSource();
631 GridInfo *info = i->getSource()->getGridInfoRef();
632 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
633 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
634 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
638 void Map::Remove(Player *player, bool remove)
640 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
641 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
643 // invalid coordinates
644 player->RemoveFromWorld();
646 if( remove )
647 DeleteFromWorld(player);
649 return;
652 Cell cell(p);
654 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
656 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
657 return;
660 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
661 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
662 assert(grid != NULL);
664 player->RemoveFromWorld();
665 RemoveFromGrid(player,grid,cell);
667 SendRemoveTransports(player);
669 UpdateObjectsVisibilityFor(player,cell,p);
671 if( remove )
672 DeleteFromWorld(player);
675 bool Map::RemoveBones(uint64 guid, float x, float y)
677 if (IsRemovalGrid(x, y))
679 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
680 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
681 corpse->DeleteBonesFromWorld();
682 else
683 return false;
685 return true;
688 template<class T>
689 void
690 Map::Remove(T *obj, bool remove)
692 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
693 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
695 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);
696 return;
699 Cell cell(p);
700 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
701 return;
703 DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
704 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
705 assert( grid != NULL );
707 obj->RemoveFromWorld();
708 RemoveFromGrid(obj,grid,cell);
710 UpdateObjectVisibility(obj,cell,p);
712 if( remove )
714 // if option set then object already saved at this moment
715 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
716 obj->SaveRespawnTime();
717 DeleteFromWorld(obj);
721 void
722 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
724 assert(player);
726 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
727 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
729 Cell old_cell(old_val);
730 Cell new_cell(new_val);
731 new_cell |= old_cell;
732 bool same_cell = (new_cell == old_cell);
734 player->Relocate(x, y, z, orientation);
736 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
738 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());
740 // update player position for group at taxi flight
741 if(player->GetGroup() && player->isInFlight())
742 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
744 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
745 RemoveFromGrid(player, oldGrid,old_cell);
746 if( !old_cell.DiffGrid(new_cell) )
747 AddToGrid(player, oldGrid,new_cell);
749 if( old_cell.DiffGrid(new_cell) )
750 EnsureGridLoadedForPlayer(new_cell, player, true);
753 // if move then update what player see and who seen
754 UpdatePlayerVisibility(player,new_cell,new_val);
755 UpdateObjectsVisibilityFor(player,new_cell,new_val);
756 PlayerRelocationNotify(player,new_cell,new_val);
757 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
758 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
760 ResetGridExpiry(*newGrid, 0.1f);
761 newGrid->SetGridState(GRID_STATE_ACTIVE);
765 void
766 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
768 assert(CheckGridIntegrity(creature,false));
770 Cell old_cell = creature->GetCurrentCell();
772 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
773 Cell new_cell(new_val);
775 // delay creature move for grid/cell to grid/cell moves
776 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
778 #ifdef MANGOS_DEBUG
779 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
780 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());
781 #endif
782 AddCreatureToMoveList(creature,x,y,z,ang);
783 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
785 else
787 creature->Relocate(x, y, z, ang);
788 CreatureRelocationNotify(creature,new_cell,new_val);
790 assert(CheckGridIntegrity(creature,true));
793 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
795 if(!c)
796 return;
798 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
801 void Map::MoveAllCreaturesInMoveList()
803 while(!i_creaturesToMove.empty())
805 // get data and remove element;
806 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
807 Creature* c = iter->first;
808 CreatureMover cm = iter->second;
809 i_creaturesToMove.erase(iter);
811 // calculate cells
812 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
813 Cell new_cell(new_val);
815 // do move or do move to respawn or remove creature if previous all fail
816 if(CreatureCellRelocation(c,new_cell))
818 // update pos
819 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
820 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
822 else
824 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
825 // creature coordinates will be updated and notifiers send
826 if(!CreatureRespawnRelocation(c))
828 // ... or unload (if respawn grid also not loaded)
829 #ifdef MANGOS_DEBUG
830 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
831 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
832 #endif
833 c->CleanupsBeforeDelete();
834 AddObjectToRemoveList(c);
840 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
842 Cell const& old_cell = c->GetCurrentCell();
843 if(!old_cell.DiffGrid(new_cell) ) // in same grid
845 // if in same cell then none do
846 if(old_cell.DiffCell(new_cell))
848 #ifdef MANGOS_DEBUG
849 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
850 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());
851 #endif
853 if( !old_cell.DiffGrid(new_cell) )
855 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
856 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
857 c->SetCurrentCell(new_cell);
860 else
862 #ifdef MANGOS_DEBUG
863 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
864 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());
865 #endif
868 else // in diff. grids
869 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
871 #ifdef MANGOS_DEBUG
872 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
873 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());
874 #endif
876 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
878 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
879 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
882 else
884 #ifdef MANGOS_DEBUG
885 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
886 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());
887 #endif
888 return false;
891 return true;
894 bool Map::CreatureRespawnRelocation(Creature *c)
896 float resp_x, resp_y, resp_z, resp_o;
897 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
899 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
900 Cell resp_cell(resp_val);
902 c->CombatStop();
903 c->GetMotionMaster()->Clear();
905 #ifdef MANGOS_DEBUG
906 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
907 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());
908 #endif
910 // teleport it to respawn point (like normal respawn if player see)
911 if(CreatureCellRelocation(c,resp_cell))
913 c->Relocate(resp_x, resp_y, resp_z, resp_o);
914 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
915 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
916 return true;
918 else
919 return false;
922 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
924 NGridType *grid = getNGrid(x, y);
925 assert( grid != NULL);
928 if(!pForce && ObjectAccessor::Instance().PlayersNearGrid(x, y, i_id, i_InstanceId) )
929 return false;
931 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
932 ObjectGridUnloader unloader(*grid);
934 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
935 // Must know real mob position before move
936 DoDelayedMovesAndRemoves();
938 // move creatures to respawn grids if this is diff.grid or to remove list
939 unloader.MoveToRespawnN();
941 // Finish creature moves, remove and delete all creatures with delayed remove before unload
942 DoDelayedMovesAndRemoves();
944 unloader.UnloadN();
945 delete getNGrid(x, y);
946 setNGrid(NULL, x, y);
948 int gx=63-x;
949 int gy=63-y;
951 // delete grid map, but don't delete if it is from parent map (and thus only reference)
952 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
954 if (i_InstanceId == 0)
956 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
957 // x and y are swaped
958 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
960 else
961 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
962 GridMaps[gx][gy] = NULL;
964 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
965 return true;
968 void Map::UnloadAll(bool pForce)
970 // clear all delayed moves, useless anyway do this moves before map unload.
971 i_creaturesToMove.clear();
973 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
975 NGridType &grid(*i->getSource());
976 ++i;
977 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
981 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
983 GridPair p = MaNGOS::ComputeGridPair(x, y);
985 // half opt method
986 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
987 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
989 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
990 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
992 // ensure GridMap is loaded
993 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
995 // find raw .map surface under Z coordinates
996 float mapHeight;
997 if(GridMap* gmap = GridMaps[gx][gy])
999 int lx_int = (int)lx;
1000 int ly_int = (int)ly;
1002 float zi[4];
1003 // Probe 4 nearest points (except border cases)
1004 zi[0] = gmap->Z[lx_int][ly_int];
1005 zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
1006 zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
1007 zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
1008 // Recalculate them like if their x,y positions were in the range 0,1
1009 float b[4];
1010 b[0] = zi[0];
1011 b[1] = zi[1]-zi[0];
1012 b[2] = zi[2]-zi[0];
1013 b[3] = zi[0]-zi[1]-zi[2]+zi[3];
1014 // Normalize the dx and dy to be in range 0..1
1015 float fact_x = lx - lx_int;
1016 float fact_y = ly - ly_int;
1017 // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1018 float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1020 // look from a bit higher pos to find the floor, ignore under surface case
1021 if(z + 2.0f > _mapheight)
1022 mapHeight = _mapheight;
1023 else
1024 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1026 else
1027 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1029 float vmapHeight;
1030 if(pUseVmaps)
1032 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1033 if(vmgr->isHeightCalcEnabled())
1035 // look from a bit higher pos to find the floor
1036 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1038 else
1039 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1041 else
1042 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1044 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1045 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1047 if( vmapHeight > INVALID_HEIGHT )
1049 if( mapHeight > INVALID_HEIGHT )
1051 // we have mapheight and vmapheight and must select more appropriate
1053 // we are already under the surface or vmap height above map heigt
1054 // or if the distance of the vmap height is less the land height distance
1055 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1056 return vmapHeight;
1057 else
1058 return mapHeight; // better use .map surface height
1061 else
1062 return vmapHeight; // we have only vmapHeight (if have)
1064 else
1066 if(!pUseVmaps)
1067 return mapHeight; // explicitly use map data (if have)
1068 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1069 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1070 else
1071 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1075 uint16 Map::GetAreaFlag(float x, float y ) const
1077 //local x,y coords
1078 float lx,ly;
1079 int gx,gy;
1080 GridPair p = MaNGOS::ComputeGridPair(x, y);
1082 // half opt method
1083 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1084 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1086 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1087 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1088 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1090 // ensure GridMap is loaded
1091 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1093 if(GridMaps[gx][gy])
1094 return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1095 // this used while not all *.map files generated (instances)
1096 else
1097 return GetAreaFlagByMapId(i_id);
1100 uint8 Map::GetTerrainType(float x, float y ) const
1102 //local x,y coords
1103 float lx,ly;
1104 int gx,gy;
1106 // half opt method
1107 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1108 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1110 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1111 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1113 // ensure GridMap is loaded
1114 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1116 if(GridMaps[gx][gy])
1117 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1118 else
1119 return 0;
1123 float Map::GetWaterLevel(float x, float y ) const
1125 //local x,y coords
1126 float lx,ly;
1127 int gx,gy;
1129 // half opt method
1130 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1131 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1133 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1134 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1136 // ensure GridMap is loaded
1137 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1139 if(GridMaps[gx][gy])
1140 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1141 else
1142 return 0;
1145 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1147 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1149 if (entry)
1150 return entry->ID;
1151 else
1152 return 0;
1155 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1157 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1159 if( entry )
1160 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1161 else
1162 return 0;
1165 bool Map::IsInWater(float x, float y, float pZ) const
1167 // This method is called too often to use vamps for that (4. parameter = false).
1168 // The pZ pos is taken anyway for future use
1169 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1171 // underground or instance without vmap
1172 if(z <= INVALID_HEIGHT)
1173 return false;
1175 float water_z = GetWaterLevel(x,y);
1176 uint8 flag = GetTerrainType(x,y);
1177 return (z < (water_z-2)) && (flag & 0x01);
1180 bool Map::IsUnderWater(float x, float y, float z) const
1182 float water_z = GetWaterLevel(x,y);
1183 uint8 flag = GetTerrainType(x,y);
1184 return (z < (water_z-2)) && (flag & 0x01);
1187 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1189 Cell const& cur_cell = c->GetCurrentCell();
1191 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1192 Cell xy_cell(xy_val);
1193 if(xy_cell != cur_cell)
1195 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]",
1196 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1197 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1198 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1199 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1200 return true; // not crash at error, just output error in debug mode
1203 return true;
1206 const char* Map::GetMapName() const
1208 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1211 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1213 cell.data.Part.reserved = ALL_DISTRICT;
1214 cell.SetNoCreate();
1215 MaNGOS::VisibleChangesNotifier notifier(*obj);
1216 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1217 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1218 cell_lock->Visit(cell_lock, player_notifier, *this);
1221 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1223 cell.data.Part.reserved = ALL_DISTRICT;
1225 MaNGOS::PlayerNotifier pl_notifier(*player);
1226 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1228 CellLock<ReadGuard> cell_lock(cell, cellpair);
1229 cell_lock->Visit(cell_lock, player_notifier, *this);
1232 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1234 MaNGOS::VisibleNotifier notifier(*player);
1236 cell.data.Part.reserved = ALL_DISTRICT;
1237 cell.SetNoCreate();
1238 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1239 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1240 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1241 cell_lock->Visit(cell_lock, world_notifier, *this);
1242 cell_lock->Visit(cell_lock, grid_notifier, *this);
1244 // send data
1245 notifier.Notify();
1248 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1250 CellLock<ReadGuard> cell_lock(cell, cellpair);
1251 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1252 cell.data.Part.reserved = ALL_DISTRICT;
1254 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1255 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1257 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1258 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1261 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1263 CellLock<ReadGuard> cell_lock(cell, cellpair);
1264 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1265 cell.data.Part.reserved = ALL_DISTRICT;
1266 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1268 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1269 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1271 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1272 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1275 void Map::SendInitSelf( Player * player )
1277 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1279 UpdateData data;
1281 bool hasTransport = false;
1283 // attach to player data current transport data
1284 if(Transport* transport = player->GetTransport())
1286 hasTransport = true;
1287 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1290 // build data for self presence in world at own client (one time for map)
1291 player->BuildCreateUpdateBlockForPlayer(&data, player);
1293 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1294 if(Transport* transport = player->GetTransport())
1296 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1298 if(player!=(*itr) && player->HaveAtClient(*itr))
1300 hasTransport = true;
1301 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1306 WorldPacket packet;
1307 data.BuildPacket(&packet, hasTransport);
1308 player->GetSession()->SendPacket(&packet);
1311 void Map::SendInitTransports( Player * player )
1313 // Hack to send out transports
1314 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1316 // no transports at map
1317 if (tmap.find(player->GetMapId()) == tmap.end())
1318 return;
1320 UpdateData transData;
1322 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1324 bool hasTransport = false;
1326 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1328 if((*i) != player->GetTransport()) // send data for current transport in other place
1330 hasTransport = true;
1331 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1335 WorldPacket packet;
1336 transData.BuildPacket(&packet, hasTransport);
1337 player->GetSession()->SendPacket(&packet);
1340 void Map::SendRemoveTransports( Player * player )
1342 // Hack to send out transports
1343 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1345 // no transports at map
1346 if (tmap.find(player->GetMapId()) == tmap.end())
1347 return;
1349 UpdateData transData;
1351 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1353 // except used transport
1354 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1355 if(player->GetTransport() != (*i))
1356 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1358 WorldPacket packet;
1359 transData.BuildPacket(&packet);
1360 player->GetSession()->SendPacket(&packet);
1363 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1365 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1367 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1368 assert(false);
1370 i_grids[x][y] = grid;
1373 void Map::DoDelayedMovesAndRemoves()
1375 MoveAllCreaturesInMoveList();
1376 RemoveAllObjectsInRemoveList();
1379 void Map::AddObjectToRemoveList(WorldObject *obj)
1381 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1383 i_objectsToRemove.insert(obj);
1384 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1387 void Map::RemoveAllObjectsInRemoveList()
1389 if(i_objectsToRemove.empty())
1390 return;
1392 //sLog.outDebug("Object remover 1 check.");
1393 while(!i_objectsToRemove.empty())
1395 WorldObject* obj = *i_objectsToRemove.begin();
1396 i_objectsToRemove.erase(i_objectsToRemove.begin());
1398 switch(obj->GetTypeId())
1400 case TYPEID_CORPSE:
1402 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1403 if (!corpse)
1404 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1405 else
1406 Remove(corpse,true);
1407 break;
1409 case TYPEID_DYNAMICOBJECT:
1410 Remove((DynamicObject*)obj,true);
1411 break;
1412 case TYPEID_GAMEOBJECT:
1413 Remove((GameObject*)obj,true);
1414 break;
1415 case TYPEID_UNIT:
1416 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1417 // make sure that like sources auras/etc removed before destructor start
1418 ((Creature*)obj)->CleanupsBeforeDelete ();
1419 Remove((Creature*)obj,true);
1420 break;
1421 default:
1422 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1423 break;
1426 //sLog.outDebug("Object remover 2 check.");
1429 bool Map::CanUnload(const uint32 &diff)
1431 if(!m_unloadTimer) return false;
1432 if(m_unloadTimer < diff) return true;
1433 m_unloadTimer -= diff;
1434 return false;
1437 template void Map::Add(Corpse *);
1438 template void Map::Add(Creature *);
1439 template void Map::Add(GameObject *);
1440 template void Map::Add(DynamicObject *);
1442 template void Map::Remove(Corpse *,bool);
1443 template void Map::Remove(Creature *,bool);
1444 template void Map::Remove(GameObject *, bool);
1445 template void Map::Remove(DynamicObject *, bool);
1447 /* ******* Dungeon Instance Maps ******* */
1449 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1450 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1451 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1453 // the timer is started by default, and stopped when the first player joins
1454 // this make sure it gets unloaded if for some reason no player joins
1455 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1458 InstanceMap::~InstanceMap()
1460 if(i_data)
1462 delete i_data;
1463 i_data = NULL;
1468 Do map specific checks to see if the player can enter
1470 bool InstanceMap::CanEnter(Player *player)
1472 if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1474 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1475 assert(false);
1476 return false;
1479 // cannot enter if the instance is full (player cap), GMs don't count
1480 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1481 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1483 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1484 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1485 return false;
1488 // cannot enter while players in the instance are in combat
1489 Group *pGroup = player->GetGroup();
1490 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1492 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1493 return false;
1496 return Map::CanEnter(player);
1500 Do map specific checks and add the player to the map if successful.
1502 bool InstanceMap::Add(Player *player)
1504 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1505 // GMs still can teleport player in instance.
1506 // Is it needed?
1509 Guard guard(*this);
1510 if(!CanEnter(player))
1511 return false;
1513 // get or create an instance save for the map
1514 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1515 if(!mapSave)
1517 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1518 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1521 // check for existing instance binds
1522 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1523 if(playerBind && playerBind->perm)
1525 // cannot enter other instances if bound permanently
1526 if(playerBind->save != mapSave)
1528 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());
1529 assert(false);
1532 else
1534 Group *pGroup = player->GetGroup();
1535 if(pGroup)
1537 // solo saves should be reset when entering a group
1538 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1539 if(playerBind)
1541 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());
1542 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());
1543 assert(false);
1545 // bind to the group or keep using the group save
1546 if(!groupBind)
1547 pGroup->BindToInstance(mapSave, false);
1548 else
1550 // cannot jump to a different instance without resetting it
1551 if(groupBind->save != mapSave)
1553 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());
1554 if(mapSave)
1555 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1556 else
1557 sLog.outError("MapSave NULL");
1558 if(groupBind->save)
1559 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1560 else
1561 sLog.outError("GroupBind save NULL");
1562 assert(false);
1564 // if the group/leader is permanently bound to the instance
1565 // players also become permanently bound when they enter
1566 if(groupBind->perm)
1568 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1569 data << uint32(0);
1570 player->GetSession()->SendPacket(&data);
1571 player->BindToInstance(mapSave, true);
1575 else
1577 // set up a solo bind or continue using it
1578 if(!playerBind)
1579 player->BindToInstance(mapSave, false);
1580 else
1581 // cannot jump to a different instance without resetting it
1582 assert(playerBind->save == mapSave);
1586 if(i_data) i_data->OnPlayerEnter(player);
1587 SetResetSchedule(false);
1589 i_Players.push_back(player);
1590 player->SendInitWorldStates();
1591 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1592 // initialize unload state
1593 m_unloadTimer = 0;
1594 m_resetAfterUnload = false;
1595 m_unloadWhenEmpty = false;
1598 // this will acquire the same mutex so it cannot be in the previous block
1599 Map::Add(player);
1600 return true;
1603 void InstanceMap::Update(const uint32& t_diff)
1605 Map::Update(t_diff);
1607 if(i_data)
1608 i_data->Update(t_diff);
1611 void InstanceMap::Remove(Player *player, bool remove)
1613 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1614 i_Players.remove(player);
1615 SetResetSchedule(true);
1616 if(!m_unloadTimer && i_Players.empty())
1617 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1618 Map::Remove(player, remove);
1621 void InstanceMap::CreateInstanceData(bool load)
1623 if(i_data != NULL)
1624 return;
1626 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1627 if (mInstance)
1629 i_script = mInstance->script;
1630 i_data = Script->CreateInstanceData(this);
1633 if(!i_data)
1634 return;
1636 if(load)
1638 // TODO: make a global storage for this
1639 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1640 if (result)
1642 Field* fields = result->Fetch();
1643 const char* data = fields[0].GetString();
1644 if(data)
1646 sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1647 i_data->Load(data);
1649 delete result;
1652 else
1654 sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1655 i_data->Initialize();
1660 Returns true if there are no players in the instance
1662 bool InstanceMap::Reset(uint8 method)
1664 // note: since the map may not be loaded when the instance needs to be reset
1665 // the instance must be deleted from the DB by InstanceSaveManager
1667 if(!i_Players.empty())
1669 if(method == INSTANCE_RESET_ALL)
1671 // notify the players to leave the instance so it can be reset
1672 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1673 (*itr)->SendResetFailedNotify(GetId());
1675 else
1677 if(method == INSTANCE_RESET_GLOBAL)
1679 // set the homebind timer for players inside (1 minute)
1680 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1681 (*itr)->m_InstanceValid = false;
1684 // the unload timer is not started
1685 // instead the map will unload immediately after the players have left
1686 m_unloadWhenEmpty = true;
1687 m_resetAfterUnload = true;
1690 else
1692 // unloaded at next update
1693 m_unloadTimer = MIN_UNLOAD_DELAY;
1694 m_resetAfterUnload = true;
1697 return i_Players.empty();
1700 uint32 InstanceMap::GetPlayersCountExceptGMs() const
1702 uint32 count = 0;
1703 for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1704 if(!(*itr)->isGameMaster())
1705 ++count;
1706 return count;
1709 void InstanceMap::PermBindAllPlayers(Player *player)
1711 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1712 if(!save)
1714 sLog.outError("Cannot bind players, no instance save available for map!\n");
1715 return;
1718 Group *group = player->GetGroup();
1719 // group members outside the instance group don't get bound
1720 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1722 if(*itr)
1724 // players inside an instance cannot be bound to other instances
1725 // some players may already be permanently bound, in this case nothing happens
1726 InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1727 if(!bind || !bind->perm)
1729 (*itr)->BindToInstance(save, true);
1730 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1731 data << uint32(0);
1732 (*itr)->GetSession()->SendPacket(&data);
1735 // if the leader is not in the instance the group will not get a perm bind
1736 if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1737 group->BindToInstance(save, true);
1742 time_t InstanceMap::GetResetTime()
1744 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1745 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1748 void InstanceMap::UnloadAll(bool pForce)
1750 if(!i_Players.empty())
1752 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1753 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1754 if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1757 if(m_resetAfterUnload == true)
1758 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1760 Map::UnloadAll(pForce);
1763 void InstanceMap::SendResetWarnings(uint32 timeLeft)
1765 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1766 (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1769 void InstanceMap::SetResetSchedule(bool on)
1771 // only for normal instances
1772 // the reset time is only scheduled when there are no payers inside
1773 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1774 if(i_Players.empty() && !IsRaid() && !IsHeroic())
1776 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1777 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1778 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1782 void InstanceMap::SendToPlayers(WorldPacket const* data) const
1784 for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1785 (*itr)->GetSession()->SendPacket(data);
1788 /* ******* Battleground Instance Maps ******* */
1790 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1791 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1795 BattleGroundMap::~BattleGroundMap()
1799 bool BattleGroundMap::CanEnter(Player * player)
1801 if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1803 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1804 assert(false);
1805 return false;
1808 if(player->GetBattleGroundId() != GetInstanceId())
1809 return false;
1811 // player number limit is checked in bgmgr, no need to do it here
1813 return Map::CanEnter(player);
1816 bool BattleGroundMap::Add(Player * player)
1819 Guard guard(*this);
1820 if(!CanEnter(player))
1821 return false;
1822 i_Players.push_back(player);
1823 // reset instance validity, battleground maps do not homebind
1824 player->m_InstanceValid = true;
1826 return Map::Add(player);
1829 void BattleGroundMap::Remove(Player *player, bool remove)
1831 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1832 i_Players.remove(player);
1833 Map::Remove(player, remove);
1836 void BattleGroundMap::SetUnload()
1838 m_unloadTimer = MIN_UNLOAD_DELAY;
1841 void BattleGroundMap::UnloadAll(bool pForce)
1843 while(!i_Players.empty())
1845 PlayerList::iterator itr = i_Players.begin();
1846 Player * plr = *itr;
1847 if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1848 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1849 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1850 // note that this remove is not needed if the code works well in other places
1851 i_Players.remove(plr);
1854 Map::UnloadAll(pForce);