Phase system development continue.
[getmangos.git] / src / game / Map.cpp
blob9244b6d27f89b38a695df73c7e2efde0eddee007
1 /*
2 * Copyright (C) 2005-2009 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"
36 #include "MapRefManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "VMapFactory.h"
42 #define DEFAULT_GRID_EXPIRY 300
43 #define MAX_GRID_LOAD_TIME 50
45 // magic *.map header
46 const char MAP_MAGIC[] = "MAP_2.01";
48 GridState* si_GridStates[MAX_GRID_STATE];
50 Map::~Map()
52 UnloadAll(true);
55 bool Map::ExistMap(uint32 mapid,int x,int y)
57 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
58 char* tmp = new char[len];
59 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
61 FILE *pf=fopen(tmp,"rb");
63 if(!pf)
65 sLog.outError("Check existing of map file '%s': not exist!",tmp);
66 delete[] tmp;
67 return false;
70 char magic[8];
71 fread(magic,1,8,pf);
72 if(strncmp(MAP_MAGIC,magic,8))
74 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
75 delete [] tmp;
76 fclose(pf); //close file before return
77 return false;
80 delete [] tmp;
81 fclose(pf);
83 return true;
86 bool Map::ExistVMap(uint32 mapid,int x,int y)
88 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
90 if(vmgr->isMapLoadingEnabled())
92 // x and y are swapped !! => fixed now
93 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, x,y);
94 if(!exists)
96 std::string name = vmgr->getDirFileName(mapid,x,y);
97 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());
98 return false;
103 return true;
106 void Map::LoadVMap(int x,int y)
108 // x and y are swapped !!
109 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), x,y);
110 switch(vmapLoadResult)
112 case VMAP::VMAP_LOAD_RESULT_OK:
113 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
114 break;
115 case VMAP::VMAP_LOAD_RESULT_ERROR:
116 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);
117 break;
118 case VMAP::VMAP_LOAD_RESULT_IGNORED:
119 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
120 break;
124 void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
126 if( instanceid != 0 )
128 if(GridMaps[x][y])
129 return;
131 Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
133 // load gridmap for base map
134 if (!baseMap->GridMaps[x][y])
135 baseMap->EnsureGridCreated(GridPair(63-x,63-y));
137 //+++ if (!baseMap->GridMaps[x][y]) don't check for GridMaps[gx][gy], we need the management for vmaps
138 // return;
140 ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
141 baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
142 GridMaps[x][y] = baseMap->GridMaps[x][y];
143 return;
146 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
147 if(GridMaps[x][y])
149 sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
150 delete (GridMaps[x][y]);
151 GridMaps[x][y]=NULL;
154 // map file name
155 char *tmp=NULL;
156 // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
157 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
158 tmp = new char[len];
159 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
160 sLog.outDetail("Loading map %s",tmp);
161 // loading data
162 FILE *pf=fopen(tmp,"rb");
163 if(!pf)
165 delete [] tmp;
166 return;
169 char magic[8];
170 fread(magic,1,8,pf);
171 if(strncmp(MAP_MAGIC,magic,8))
173 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
174 delete [] tmp;
175 fclose(pf); //close file before return
176 return;
178 delete [] tmp;
180 GridMap * buf= new GridMap;
181 fread(buf,1,sizeof(GridMap),pf);
182 fclose(pf);
184 GridMaps[x][y] = buf;
187 void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
189 LoadMap(mapid,instanceid,x,y);
190 if(instanceid == 0)
191 LoadVMap(x, y); // Only load the data for the base map
194 void Map::InitStateMachine()
196 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
197 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
198 si_GridStates[GRID_STATE_IDLE] = new IdleState;
199 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
202 void Map::DeleteStateMachine()
204 delete si_GridStates[GRID_STATE_INVALID];
205 delete si_GridStates[GRID_STATE_ACTIVE];
206 delete si_GridStates[GRID_STATE_IDLE];
207 delete si_GridStates[GRID_STATE_REMOVAL];
210 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
211 : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
212 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
214 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
216 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
218 //z code
219 GridMaps[idx][j] =NULL;
220 setNGrid(NULL, idx, j);
225 // Template specialization of utility methods
226 template<class T>
227 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
229 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
232 template<>
233 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
235 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
238 template<>
239 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
241 // add to world object registry in grid
242 if(obj->GetType()!=CORPSE_BONES)
244 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246 // add to grid object store
247 else
249 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
253 template<>
254 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
256 // add to world object registry in grid
257 if(obj->isPet() || obj->isVehicle())
259 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
260 obj->SetCurrentCell(cell);
262 // add to grid object store
263 else
265 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
266 obj->SetCurrentCell(cell);
270 template<class T>
271 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
273 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
276 template<>
277 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
279 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
282 template<>
283 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
285 // remove from world object registry in grid
286 if(obj->GetType()!=CORPSE_BONES)
288 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290 // remove from grid object store
291 else
293 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
297 template<>
298 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
300 // remove from world object registry in grid
301 if(obj->isPet() || obj->isVehicle())
303 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
305 // remove from grid object store
306 else
308 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
312 template<class T>
313 void Map::DeleteFromWorld(T* obj)
315 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
316 delete obj;
319 template<class T>
320 void Map::AddNotifier(T* , Cell const& , CellPair const& )
324 template<>
325 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
327 PlayerRelocationNotify(obj,cell,cellpair);
330 template<>
331 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
333 CreatureRelocationNotify(obj,cell,cellpair);
336 void
337 Map::EnsureGridCreated(const GridPair &p)
339 if(!getNGrid(p.x_coord, p.y_coord))
341 Guard guard(*this);
342 if(!getNGrid(p.x_coord, p.y_coord))
344 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)),
345 p.x_coord, p.y_coord);
347 // build a linkage between this map and NGridType
348 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
350 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
352 //z coord
353 int gx=63-p.x_coord;
354 int gy=63-p.y_coord;
356 if(!GridMaps[gx][gy])
357 Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
362 void
363 Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
365 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
366 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
368 assert(grid != NULL);
369 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
371 if( player != NULL )
373 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
374 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);
376 else
378 DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
381 ObjectGridLoader loader(*grid, this, cell);
382 loader.LoadN();
383 setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
385 // Add resurrectable corpses to world object list in grid
386 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
388 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
389 grid->SetGridState(GRID_STATE_ACTIVE);
391 if( add_player && player != NULL )
392 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
394 else if( player && add_player )
395 AddToGrid(player,grid,cell);
398 void
399 Map::LoadGrid(const Cell& cell, bool no_unload)
401 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
402 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
404 assert(grid != NULL);
405 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
407 ObjectGridLoader loader(*grid, this, cell);
408 loader.LoadN();
410 // Add resurrectable corpses to world object list in grid
411 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
413 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
414 if(no_unload)
415 getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
417 LoadVMap(63-cell.GridX(),63-cell.GridY());
420 bool Map::Add(Player *player)
422 player->GetMapRef().link(this, player);
424 player->SetInstanceId(GetInstanceId());
426 // update player state for other player and visa-versa
427 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
428 Cell cell(p);
429 EnsureGridLoadedForPlayer(cell, player, true);
430 player->AddToWorld();
432 SendInitSelf(player);
433 SendInitTransports(player);
435 UpdatePlayerVisibility(player,cell,p);
436 UpdateObjectsVisibilityFor(player,cell,p);
438 AddNotifier(player,cell,p);
439 return true;
442 template<class T>
443 void
444 Map::Add(T *obj)
446 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
448 assert(obj);
450 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
452 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);
453 return;
456 Cell cell(p);
457 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
458 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
459 assert( grid != NULL );
461 AddToGrid(obj,grid,cell);
462 obj->AddToWorld();
464 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
466 UpdateObjectVisibility(obj,cell,p);
468 AddNotifier(obj,cell,p);
471 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
473 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
475 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
477 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);
478 return;
481 Cell cell(p);
482 cell.data.Part.reserved = ALL_DISTRICT;
484 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
485 return;
487 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
488 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
489 CellLock<ReadGuard> cell_lock(cell, p);
490 cell_lock->Visit(cell_lock, message, *this);
493 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
495 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
497 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
499 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);
500 return;
503 Cell cell(p);
504 cell.data.Part.reserved = ALL_DISTRICT;
505 cell.SetNoCreate();
507 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
508 return;
510 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
511 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
512 CellLock<ReadGuard> cell_lock(cell, p);
513 cell_lock->Visit(cell_lock, message, *this);
516 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
518 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
520 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
522 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);
523 return;
526 Cell cell(p);
527 cell.data.Part.reserved = ALL_DISTRICT;
529 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
530 return;
532 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
533 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
534 CellLock<ReadGuard> cell_lock(cell, p);
535 cell_lock->Visit(cell_lock, message, *this);
538 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
540 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
542 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
544 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);
545 return;
548 Cell cell(p);
549 cell.data.Part.reserved = ALL_DISTRICT;
550 cell.SetNoCreate();
552 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
553 return;
555 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
556 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
557 CellLock<ReadGuard> cell_lock(cell, p);
558 cell_lock->Visit(cell_lock, message, *this);
561 bool Map::loaded(const GridPair &p) const
563 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
566 void Map::Update(const uint32 &t_diff)
568 resetMarkedCells();
570 MaNGOS::ObjectUpdater updater(t_diff);
571 // for creature
572 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
573 // for pets
574 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
576 // the player iterator is stored in the map object
577 // to make sure calls to Map::Remove don't invalidate it
578 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
580 Player* plr = m_mapRefIter->getSource();
582 if(!plr->IsInWorld())
583 continue;
585 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
587 // Check for correctness of standing_cell, it also avoids problems with update_cell
588 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
589 continue;
591 // the overloaded operators handle range checking
592 // so ther's no need for range checking inside the loop
593 CellPair begin_cell(standing_cell), end_cell(standing_cell);
594 begin_cell << 1; begin_cell -= 1; // upper left
595 end_cell >> 1; end_cell += 1; // lower right
597 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
599 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
601 // marked cells are those that have been visited
602 // don't visit the same cell twice
603 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
604 if(!isCellMarked(cell_id))
606 markCell(cell_id);
607 CellPair pair(x,y);
608 Cell cell(pair);
609 cell.data.Part.reserved = CENTER_DISTRICT;
610 cell.SetNoCreate();
611 CellLock<NullGuard> cell_lock(cell, pair);
612 cell_lock->Visit(cell_lock, grid_object_update, *this);
613 cell_lock->Visit(cell_lock, world_object_update, *this);
619 // 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 !
620 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
621 if (IsBattleGroundOrArena())
622 return;
624 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
626 NGridType *grid = i->getSource();
627 GridInfo *info = i->getSource()->getGridInfoRef();
628 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
629 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
630 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
634 void Map::Remove(Player *player, bool remove)
636 // this may be called during Map::Update
637 // after decrement+unlink, ++m_mapRefIter will continue correctly
638 // when the first element of the list is being removed
639 // nocheck_prev will return the padding element of the RefManager
640 // instead of NULL in the case of prev
641 if(m_mapRefIter == player->GetMapRef())
642 m_mapRefIter = m_mapRefIter->nocheck_prev();
643 player->GetMapRef().unlink();
644 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
645 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
647 // invalid coordinates
648 player->RemoveFromWorld();
650 if( remove )
651 DeleteFromWorld(player);
653 return;
656 Cell cell(p);
658 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
660 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
661 return;
664 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
665 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
666 assert(grid != NULL);
668 player->RemoveFromWorld();
669 RemoveFromGrid(player,grid,cell);
671 SendRemoveTransports(player);
673 UpdateObjectsVisibilityFor(player,cell,p);
675 if( remove )
676 DeleteFromWorld(player);
679 bool Map::RemoveBones(uint64 guid, float x, float y)
681 if (IsRemovalGrid(x, y))
683 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
684 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
685 corpse->DeleteBonesFromWorld();
686 else
687 return false;
689 return true;
692 template<class T>
693 void
694 Map::Remove(T *obj, bool remove)
696 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
697 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
699 sLog.outError("Map::Remove: Object " I64FMT " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
700 return;
703 Cell cell(p);
704 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
705 return;
707 DEBUG_LOG("Remove object " I64FMT " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
708 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
709 assert( grid != NULL );
711 obj->RemoveFromWorld();
712 RemoveFromGrid(obj,grid,cell);
714 UpdateObjectVisibility(obj,cell,p);
716 if( remove )
718 // if option set then object already saved at this moment
719 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
720 obj->SaveRespawnTime();
721 DeleteFromWorld(obj);
725 void
726 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
728 assert(player);
730 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
731 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
733 Cell old_cell(old_val);
734 Cell new_cell(new_val);
735 new_cell |= old_cell;
736 bool same_cell = (new_cell == old_cell);
738 player->Relocate(x, y, z, orientation);
740 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
742 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());
744 // update player position for group at taxi flight
745 if(player->GetGroup() && player->isInFlight())
746 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
748 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
749 RemoveFromGrid(player, oldGrid,old_cell);
750 if( !old_cell.DiffGrid(new_cell) )
751 AddToGrid(player, oldGrid,new_cell);
753 if( old_cell.DiffGrid(new_cell) )
754 EnsureGridLoadedForPlayer(new_cell, player, true);
757 // if move then update what player see and who seen
758 UpdatePlayerVisibility(player,new_cell,new_val);
759 UpdateObjectsVisibilityFor(player,new_cell,new_val);
760 PlayerRelocationNotify(player,new_cell,new_val);
761 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
762 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
764 ResetGridExpiry(*newGrid, 0.1f);
765 newGrid->SetGridState(GRID_STATE_ACTIVE);
769 void
770 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
772 assert(CheckGridIntegrity(creature,false));
774 Cell old_cell = creature->GetCurrentCell();
776 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
777 Cell new_cell(new_val);
779 // delay creature move for grid/cell to grid/cell moves
780 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
782 #ifdef MANGOS_DEBUG
783 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
784 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());
785 #endif
786 AddCreatureToMoveList(creature,x,y,z,ang);
787 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
789 else
791 creature->Relocate(x, y, z, ang);
792 CreatureRelocationNotify(creature,new_cell,new_val);
794 assert(CheckGridIntegrity(creature,true));
797 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
799 if(!c)
800 return;
802 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
805 void Map::MoveAllCreaturesInMoveList()
807 while(!i_creaturesToMove.empty())
809 // get data and remove element;
810 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
811 Creature* c = iter->first;
812 CreatureMover cm = iter->second;
813 i_creaturesToMove.erase(iter);
815 // calculate cells
816 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
817 Cell new_cell(new_val);
819 // do move or do move to respawn or remove creature if previous all fail
820 if(CreatureCellRelocation(c,new_cell))
822 // update pos
823 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
824 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
826 else
828 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
829 // creature coordinates will be updated and notifiers send
830 if(!CreatureRespawnRelocation(c))
832 // ... or unload (if respawn grid also not loaded)
833 #ifdef MANGOS_DEBUG
834 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
835 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
836 #endif
837 c->CleanupsBeforeDelete();
838 AddObjectToRemoveList(c);
844 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
846 Cell const& old_cell = c->GetCurrentCell();
847 if(!old_cell.DiffGrid(new_cell) ) // in same grid
849 // if in same cell then none do
850 if(old_cell.DiffCell(new_cell))
852 #ifdef MANGOS_DEBUG
853 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
854 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());
855 #endif
857 if( !old_cell.DiffGrid(new_cell) )
859 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
860 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
861 c->SetCurrentCell(new_cell);
864 else
866 #ifdef MANGOS_DEBUG
867 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
868 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());
869 #endif
872 else // in diff. grids
873 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
875 #ifdef MANGOS_DEBUG
876 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
877 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());
878 #endif
880 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
882 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
883 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
886 else
888 #ifdef MANGOS_DEBUG
889 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
890 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());
891 #endif
892 return false;
895 return true;
898 bool Map::CreatureRespawnRelocation(Creature *c)
900 float resp_x, resp_y, resp_z, resp_o;
901 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
903 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
904 Cell resp_cell(resp_val);
906 c->CombatStop();
907 c->GetMotionMaster()->Clear();
909 #ifdef MANGOS_DEBUG
910 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
911 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());
912 #endif
914 // teleport it to respawn point (like normal respawn if player see)
915 if(CreatureCellRelocation(c,resp_cell))
917 c->Relocate(resp_x, resp_y, resp_z, resp_o);
918 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
919 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
920 return true;
922 else
923 return false;
926 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
928 NGridType *grid = getNGrid(x, y);
929 assert( grid != NULL);
932 if(!pForce && PlayersNearGrid(x, y) )
933 return false;
935 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
936 ObjectGridUnloader unloader(*grid);
938 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
939 // Must know real mob position before move
940 DoDelayedMovesAndRemoves();
942 // move creatures to respawn grids if this is diff.grid or to remove list
943 unloader.MoveToRespawnN();
945 // Finish creature moves, remove and delete all creatures with delayed remove before unload
946 DoDelayedMovesAndRemoves();
948 unloader.UnloadN();
949 delete getNGrid(x, y);
950 setNGrid(NULL, x, y);
952 int gx=63-x;
953 int gy=63-y;
955 // delete grid map, but don't delete if it is from parent map (and thus only reference)
956 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
958 if (i_InstanceId == 0)
960 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
961 // x and y are swapped
962 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
964 else
965 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
966 GridMaps[gx][gy] = NULL;
968 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
969 return true;
972 void Map::UnloadAll(bool pForce)
974 // clear all delayed moves, useless anyway do this moves before map unload.
975 i_creaturesToMove.clear();
977 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
979 NGridType &grid(*i->getSource());
980 ++i;
981 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
985 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
987 GridPair p = MaNGOS::ComputeGridPair(x, y);
989 // half opt method
990 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
991 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
993 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
994 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
996 // ensure GridMap is loaded
997 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
999 // find raw .map surface under Z coordinates
1000 float mapHeight;
1001 if(GridMap* gmap = GridMaps[gx][gy])
1003 int lx_int = (int)lx;
1004 int ly_int = (int)ly;
1006 float zi[4];
1007 // Probe 4 nearest points (except border cases)
1008 zi[0] = gmap->Z[lx_int][ly_int];
1009 zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
1010 zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
1011 zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
1012 // Recalculate them like if their x,y positions were in the range 0,1
1013 float b[4];
1014 b[0] = zi[0];
1015 b[1] = zi[1]-zi[0];
1016 b[2] = zi[2]-zi[0];
1017 b[3] = zi[0]-zi[1]-zi[2]+zi[3];
1018 // Normalize the dx and dy to be in range 0..1
1019 float fact_x = lx - lx_int;
1020 float fact_y = ly - ly_int;
1021 // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1022 float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1024 // look from a bit higher pos to find the floor, ignore under surface case
1025 if(z + 2.0f > _mapheight)
1026 mapHeight = _mapheight;
1027 else
1028 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1030 else
1031 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1033 float vmapHeight;
1034 if(pUseVmaps)
1036 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1037 if(vmgr->isHeightCalcEnabled())
1039 // look from a bit higher pos to find the floor
1040 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1042 else
1043 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1045 else
1046 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1048 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1049 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1051 if( vmapHeight > INVALID_HEIGHT )
1053 if( mapHeight > INVALID_HEIGHT )
1055 // we have mapheight and vmapheight and must select more appropriate
1057 // we are already under the surface or vmap height above map heigt
1058 // or if the distance of the vmap height is less the land height distance
1059 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1060 return vmapHeight;
1061 else
1062 return mapHeight; // better use .map surface height
1065 else
1066 return vmapHeight; // we have only vmapHeight (if have)
1068 else
1070 if(!pUseVmaps)
1071 return mapHeight; // explicitly use map data (if have)
1072 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1073 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1074 else
1075 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1079 uint16 Map::GetAreaFlag(float x, float y, float z) const
1081 //local x,y coords
1082 float lx,ly;
1083 int gx,gy;
1084 GridPair p = MaNGOS::ComputeGridPair(x, y);
1086 // half opt method
1087 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1088 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1090 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1091 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1092 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1094 // ensure GridMap is loaded
1095 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1097 uint16 areaflag;
1098 if(GridMaps[gx][gy])
1099 areaflag = GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1100 // this used while not all *.map files generated (instances)
1101 else
1102 areaflag = GetAreaFlagByMapId(i_id);
1104 //FIXME: some hacks for areas above or underground for ground area
1105 // required for area specific spells/etc, until map/vmap data
1106 // not provided correct areaflag with this hacks
1107 switch(areaflag)
1109 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1110 case 1984: // Plaguelands: The Scarlet Enclave
1111 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1112 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1113 if(z > 350.0f) areaflag = 2048; break;
1114 // Acherus: The Ebon Hold (Eastern Plaguelands)
1115 case 856: // The Noxious Glade (Eastern Plaguelands)
1116 case 2456: // Death's Breach (Eastern Plaguelands)
1117 if(z > 350.0f) areaflag = 1950; break;
1120 return areaflag;
1123 uint8 Map::GetTerrainType(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=16*(32 -x/SIZE_OF_GRIDS - gx);
1134 ly=16*(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]->terrain_type[(int)(lx)][(int)(ly)];
1141 else
1142 return 0;
1145 float Map::GetWaterLevel(float x, float y ) const
1147 //local x,y coords
1148 float lx,ly;
1149 int gx,gy;
1151 // half opt method
1152 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1153 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1155 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1156 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1158 // ensure GridMap is loaded
1159 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1161 if(GridMaps[gx][gy])
1162 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1163 else
1164 return 0;
1167 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1169 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1171 if (entry)
1172 return entry->ID;
1173 else
1174 return 0;
1177 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1179 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1181 if( entry )
1182 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1183 else
1184 return 0;
1187 bool Map::IsInWater(float x, float y, float pZ) const
1189 // This method is called too often to use vamps for that (4. parameter = false).
1190 // The pZ pos is taken anyway for future use
1191 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1193 // underground or instance without vmap
1194 if(z <= INVALID_HEIGHT)
1195 return false;
1197 float water_z = GetWaterLevel(x,y);
1198 uint8 flag = GetTerrainType(x,y);
1199 return (z < (water_z-2)) && (flag & 0x01);
1202 bool Map::IsUnderWater(float x, float y, float z) const
1204 float water_z = GetWaterLevel(x,y);
1205 uint8 flag = GetTerrainType(x,y);
1206 return (z < (water_z-2)) && (flag & 0x01);
1209 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1211 Cell const& cur_cell = c->GetCurrentCell();
1213 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1214 Cell xy_cell(xy_val);
1215 if(xy_cell != cur_cell)
1217 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]",
1218 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1219 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1220 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1221 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1222 return true; // not crash at error, just output error in debug mode
1225 return true;
1228 const char* Map::GetMapName() const
1230 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1233 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1235 cell.data.Part.reserved = ALL_DISTRICT;
1236 cell.SetNoCreate();
1237 MaNGOS::VisibleChangesNotifier notifier(*obj);
1238 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1239 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1240 cell_lock->Visit(cell_lock, player_notifier, *this);
1243 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1245 cell.data.Part.reserved = ALL_DISTRICT;
1247 MaNGOS::PlayerNotifier pl_notifier(*player);
1248 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1250 CellLock<ReadGuard> cell_lock(cell, cellpair);
1251 cell_lock->Visit(cell_lock, player_notifier, *this);
1254 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1256 MaNGOS::VisibleNotifier notifier(*player);
1258 cell.data.Part.reserved = ALL_DISTRICT;
1259 cell.SetNoCreate();
1260 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1261 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1262 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1263 cell_lock->Visit(cell_lock, world_notifier, *this);
1264 cell_lock->Visit(cell_lock, grid_notifier, *this);
1266 // send data
1267 notifier.Notify();
1270 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1272 CellLock<ReadGuard> cell_lock(cell, cellpair);
1273 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1274 cell.data.Part.reserved = ALL_DISTRICT;
1276 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1277 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1279 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1280 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1283 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1285 CellLock<ReadGuard> cell_lock(cell, cellpair);
1286 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1287 cell.data.Part.reserved = ALL_DISTRICT;
1288 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1290 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1291 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1293 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1294 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1297 void Map::SendInitSelf( Player * player )
1299 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1301 UpdateData data;
1303 bool hasTransport = false;
1305 // attach to player data current transport data
1306 if(Transport* transport = player->GetTransport())
1308 hasTransport = true;
1309 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1312 // build data for self presence in world at own client (one time for map)
1313 player->BuildCreateUpdateBlockForPlayer(&data, player);
1315 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1316 if(Transport* transport = player->GetTransport())
1318 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1320 if(player!=(*itr) && player->HaveAtClient(*itr))
1322 hasTransport = true;
1323 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1328 WorldPacket packet;
1329 data.BuildPacket(&packet, hasTransport);
1330 player->GetSession()->SendPacket(&packet);
1333 void Map::SendInitTransports( Player * player )
1335 // Hack to send out transports
1336 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1338 // no transports at map
1339 if (tmap.find(player->GetMapId()) == tmap.end())
1340 return;
1342 UpdateData transData;
1344 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1346 bool hasTransport = false;
1348 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1350 if((*i) != player->GetTransport()) // send data for current transport in other place
1352 hasTransport = true;
1353 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1357 WorldPacket packet;
1358 transData.BuildPacket(&packet, hasTransport);
1359 player->GetSession()->SendPacket(&packet);
1362 void Map::SendRemoveTransports( Player * player )
1364 // Hack to send out transports
1365 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1367 // no transports at map
1368 if (tmap.find(player->GetMapId()) == tmap.end())
1369 return;
1371 UpdateData transData;
1373 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1375 // except used transport
1376 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1377 if(player->GetTransport() != (*i))
1378 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1380 WorldPacket packet;
1381 transData.BuildPacket(&packet);
1382 player->GetSession()->SendPacket(&packet);
1385 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1387 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1389 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1390 assert(false);
1392 i_grids[x][y] = grid;
1395 void Map::DoDelayedMovesAndRemoves()
1397 MoveAllCreaturesInMoveList();
1398 RemoveAllObjectsInRemoveList();
1401 void Map::AddObjectToRemoveList(WorldObject *obj)
1403 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1405 i_objectsToRemove.insert(obj);
1406 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1409 void Map::RemoveAllObjectsInRemoveList()
1411 if(i_objectsToRemove.empty())
1412 return;
1414 //sLog.outDebug("Object remover 1 check.");
1415 while(!i_objectsToRemove.empty())
1417 WorldObject* obj = *i_objectsToRemove.begin();
1418 i_objectsToRemove.erase(i_objectsToRemove.begin());
1420 switch(obj->GetTypeId())
1422 case TYPEID_CORPSE:
1424 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1425 if (!corpse)
1426 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1427 else
1428 Remove(corpse,true);
1429 break;
1431 case TYPEID_DYNAMICOBJECT:
1432 Remove((DynamicObject*)obj,true);
1433 break;
1434 case TYPEID_GAMEOBJECT:
1435 Remove((GameObject*)obj,true);
1436 break;
1437 case TYPEID_UNIT:
1438 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1439 // make sure that like sources auras/etc removed before destructor start
1440 ((Creature*)obj)->CleanupsBeforeDelete ();
1441 Remove((Creature*)obj,true);
1442 break;
1443 default:
1444 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1445 break;
1448 //sLog.outDebug("Object remover 2 check.");
1451 uint32 Map::GetPlayersCountExceptGMs() const
1453 uint32 count = 0;
1454 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1455 if(!itr->getSource()->isGameMaster())
1456 ++count;
1457 return count;
1460 void Map::SendToPlayers(WorldPacket const* data) const
1462 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1463 itr->getSource()->GetSession()->SendPacket(data);
1466 bool Map::PlayersNearGrid(uint32 x, uint32 y) const
1468 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
1469 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
1470 cell_min << 2;
1471 cell_min -= 2;
1472 cell_max >> 2;
1473 cell_max += 2;
1475 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
1477 Player* plr = iter->getSource();
1479 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
1480 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1481 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1482 return true;
1485 return false;
1488 template void Map::Add(Corpse *);
1489 template void Map::Add(Creature *);
1490 template void Map::Add(GameObject *);
1491 template void Map::Add(DynamicObject *);
1493 template void Map::Remove(Corpse *,bool);
1494 template void Map::Remove(Creature *,bool);
1495 template void Map::Remove(GameObject *, bool);
1496 template void Map::Remove(DynamicObject *, bool);
1498 /* ******* Dungeon Instance Maps ******* */
1500 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1501 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1502 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1504 // the timer is started by default, and stopped when the first player joins
1505 // this make sure it gets unloaded if for some reason no player joins
1506 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1509 InstanceMap::~InstanceMap()
1511 if(i_data)
1513 delete i_data;
1514 i_data = NULL;
1519 Do map specific checks to see if the player can enter
1521 bool InstanceMap::CanEnter(Player *player)
1523 if(player->GetMapRef().getTarget() == this)
1525 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1526 assert(false);
1527 return false;
1530 // cannot enter if the instance is full (player cap), GMs don't count
1531 uint32 maxPlayers = GetMaxPlayers();
1532 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
1534 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
1535 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1536 return false;
1539 // cannot enter while players in the instance are in combat
1540 Group *pGroup = player->GetGroup();
1541 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1543 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1544 return false;
1547 return Map::CanEnter(player);
1551 Do map specific checks and add the player to the map if successful.
1553 bool InstanceMap::Add(Player *player)
1555 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1556 // GMs still can teleport player in instance.
1557 // Is it needed?
1560 Guard guard(*this);
1561 if(!CanEnter(player))
1562 return false;
1564 // get or create an instance save for the map
1565 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1566 if(!mapSave)
1568 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1569 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1572 // check for existing instance binds
1573 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1574 if(playerBind && playerBind->perm)
1576 // cannot enter other instances if bound permanently
1577 if(playerBind->save != mapSave)
1579 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());
1580 assert(false);
1583 else
1585 Group *pGroup = player->GetGroup();
1586 if(pGroup)
1588 // solo saves should be reset when entering a group
1589 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1590 if(playerBind)
1592 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());
1593 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());
1594 assert(false);
1596 // bind to the group or keep using the group save
1597 if(!groupBind)
1598 pGroup->BindToInstance(mapSave, false);
1599 else
1601 // cannot jump to a different instance without resetting it
1602 if(groupBind->save != mapSave)
1604 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());
1605 if(mapSave)
1606 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1607 else
1608 sLog.outError("MapSave NULL");
1609 if(groupBind->save)
1610 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1611 else
1612 sLog.outError("GroupBind save NULL");
1613 assert(false);
1615 // if the group/leader is permanently bound to the instance
1616 // players also become permanently bound when they enter
1617 if(groupBind->perm)
1619 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1620 data << uint32(0);
1621 player->GetSession()->SendPacket(&data);
1622 player->BindToInstance(mapSave, true);
1626 else
1628 // set up a solo bind or continue using it
1629 if(!playerBind)
1630 player->BindToInstance(mapSave, false);
1631 else
1632 // cannot jump to a different instance without resetting it
1633 assert(playerBind->save == mapSave);
1637 if(i_data) i_data->OnPlayerEnter(player);
1638 // for normal instances cancel the reset schedule when the
1639 // first player enters (no players yet)
1640 SetResetSchedule(false);
1642 player->SendInitWorldStates();
1643 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1644 // initialize unload state
1645 m_unloadTimer = 0;
1646 m_resetAfterUnload = false;
1647 m_unloadWhenEmpty = false;
1650 // this will acquire the same mutex so it cannot be in the previous block
1651 Map::Add(player);
1652 return true;
1655 void InstanceMap::Update(const uint32& t_diff)
1657 Map::Update(t_diff);
1659 if(i_data)
1660 i_data->Update(t_diff);
1663 void InstanceMap::Remove(Player *player, bool remove)
1665 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1666 //if last player set unload timer
1667 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
1668 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1669 Map::Remove(player, remove);
1670 // for normal instances schedule the reset after all players have left
1671 SetResetSchedule(true);
1674 void InstanceMap::CreateInstanceData(bool load)
1676 if(i_data != NULL)
1677 return;
1679 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1680 if (mInstance)
1682 i_script_id = mInstance->script_id;
1683 i_data = Script->CreateInstanceData(this);
1686 if(!i_data)
1687 return;
1689 if(load)
1691 // TODO: make a global storage for this
1692 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1693 if (result)
1695 Field* fields = result->Fetch();
1696 const char* data = fields[0].GetString();
1697 if(data)
1699 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
1700 i_data->Load(data);
1702 delete result;
1705 else
1707 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
1708 i_data->Initialize();
1713 Returns true if there are no players in the instance
1715 bool InstanceMap::Reset(uint8 method)
1717 // note: since the map may not be loaded when the instance needs to be reset
1718 // the instance must be deleted from the DB by InstanceSaveManager
1720 if(HavePlayers())
1722 if(method == INSTANCE_RESET_ALL)
1724 // notify the players to leave the instance so it can be reset
1725 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1726 itr->getSource()->SendResetFailedNotify(GetId());
1728 else
1730 if(method == INSTANCE_RESET_GLOBAL)
1732 // set the homebind timer for players inside (1 minute)
1733 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1734 itr->getSource()->m_InstanceValid = false;
1737 // the unload timer is not started
1738 // instead the map will unload immediately after the players have left
1739 m_unloadWhenEmpty = true;
1740 m_resetAfterUnload = true;
1743 else
1745 // unloaded at next update
1746 m_unloadTimer = MIN_UNLOAD_DELAY;
1747 m_resetAfterUnload = true;
1750 return m_mapRefManager.isEmpty();
1753 void InstanceMap::PermBindAllPlayers(Player *player)
1755 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1756 if(!save)
1758 sLog.outError("Cannot bind players, no instance save available for map!\n");
1759 return;
1762 Group *group = player->GetGroup();
1763 // group members outside the instance group don't get bound
1764 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1766 Player* plr = itr->getSource();
1767 // players inside an instance cannot be bound to other instances
1768 // some players may already be permanently bound, in this case nothing happens
1769 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1770 if(!bind || !bind->perm)
1772 plr->BindToInstance(save, true);
1773 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1774 data << uint32(0);
1775 plr->GetSession()->SendPacket(&data);
1778 // if the leader is not in the instance the group will not get a perm bind
1779 if(group && group->GetLeaderGUID() == plr->GetGUID())
1780 group->BindToInstance(save, true);
1784 time_t InstanceMap::GetResetTime()
1786 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1787 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1790 void InstanceMap::UnloadAll(bool pForce)
1792 if(HavePlayers())
1794 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1795 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1797 Player* plr = itr->getSource();
1798 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1802 if(m_resetAfterUnload == true)
1803 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1805 Map::UnloadAll(pForce);
1808 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
1810 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1811 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
1814 void InstanceMap::SetResetSchedule(bool on)
1816 // only for normal instances
1817 // the reset time is only scheduled when there are no payers inside
1818 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1819 if(!HavePlayers() && !IsRaid() && !IsHeroic())
1821 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1822 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1823 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1827 uint32 InstanceMap::GetMaxPlayers() const
1829 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1830 if(!iTemplate)
1831 return 0;
1832 return IsHeroic() ? iTemplate->maxPlayersHeroic : iTemplate->maxPlayers;
1835 /* ******* Battleground Instance Maps ******* */
1837 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1838 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1842 BattleGroundMap::~BattleGroundMap()
1846 bool BattleGroundMap::CanEnter(Player * player)
1848 if(player->GetMapRef().getTarget() == this)
1850 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1851 assert(false);
1852 return false;
1855 if(player->GetBattleGroundId() != GetInstanceId())
1856 return false;
1858 // player number limit is checked in bgmgr, no need to do it here
1860 return Map::CanEnter(player);
1863 bool BattleGroundMap::Add(Player * player)
1866 Guard guard(*this);
1867 if(!CanEnter(player))
1868 return false;
1869 // reset instance validity, battleground maps do not homebind
1870 player->m_InstanceValid = true;
1872 return Map::Add(player);
1875 void BattleGroundMap::Remove(Player *player, bool remove)
1877 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1878 Map::Remove(player, remove);
1881 void BattleGroundMap::SetUnload()
1883 m_unloadTimer = MIN_UNLOAD_DELAY;
1886 void BattleGroundMap::UnloadAll(bool pForce)
1888 while(HavePlayers())
1890 Player * plr = m_mapRefManager.getFirst()->getSource();
1891 if(plr) (plr)->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1892 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1893 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1894 // note that this remove is not needed if the code works well in other places
1895 plr->GetMapRef().unlink();
1898 Map::UnloadAll(pForce);