[7721] Fixed possible source crash at rogue stealth lost in some special cases.
[AHbot.git] / src / game / Map.cpp
blob7de4dfa3fd3508fb2513e46748bc934fa967330f
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 "Log.h"
23 #include "GridStates.h"
24 #include "CellImpl.h"
25 #include "InstanceData.h"
26 #include "Map.h"
27 #include "GridNotifiersImpl.h"
28 #include "Config/ConfigEnv.h"
29 #include "Transports.h"
30 #include "ObjectAccessor.h"
31 #include "ObjectMgr.h"
32 #include "World.h"
33 #include "ScriptCalls.h"
34 #include "Group.h"
35 #include "MapRefManager.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 GridState* si_GridStates[MAX_GRID_STATE];
46 Map::~Map()
48 UnloadAll(true);
51 bool Map::ExistMap(uint32 mapid,int gx,int gy)
53 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
54 char* tmp = new char[len];
55 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
57 FILE *pf=fopen(tmp,"rb");
59 if(!pf)
61 sLog.outError("Check existing of map file '%s': not exist!",tmp);
62 delete[] tmp;
63 return false;
66 map_fileheader header;
67 fread(&header, sizeof(header), 1, pf);
68 if (header.mapMagic != uint32(MAP_MAGIC) ||
69 header.versionMagic != uint32(MAP_VERSION_MAGIC))
71 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
72 delete [] tmp;
73 fclose(pf); //close file before return
74 return false;
77 delete [] tmp;
78 fclose(pf);
79 return true;
82 bool Map::ExistVMap(uint32 mapid,int gx,int gy)
84 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
86 if(vmgr->isMapLoadingEnabled())
88 // x and y are swapped !! => fixed now
89 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
90 if(!exists)
92 std::string name = vmgr->getDirFileName(mapid,gx,gy);
93 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());
94 return false;
99 return true;
102 void Map::LoadVMap(int gx,int gy)
104 // x and y are swapped !!
105 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
106 switch(vmapLoadResult)
108 case VMAP::VMAP_LOAD_RESULT_OK:
109 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
110 break;
111 case VMAP::VMAP_LOAD_RESULT_ERROR:
112 sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
113 break;
114 case VMAP::VMAP_LOAD_RESULT_IGNORED:
115 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
116 break;
120 void Map::LoadMap(int gx,int gy)
122 if( i_InstanceId != 0 )
124 if(GridMaps[gx][gy])
125 return;
127 Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(i_id));
129 // load grid map for base map
130 if (!baseMap->GridMaps[gx][gy])
131 baseMap->EnsureGridCreated(GridPair(63-gx,63-gy));
133 ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(gx,gy));
134 GridMaps[gx][gy] = baseMap->GridMaps[gx][gy];
135 return;
138 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
139 if(GridMaps[gx][gy])
141 sLog.outDetail("Unloading already loaded map %u before reloading.",i_id);
142 delete (GridMaps[gx][gy]);
143 GridMaps[gx][gy]=NULL;
146 // map file name
147 char *tmp=NULL;
148 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
149 tmp = new char[len];
150 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),i_id,gx,gy);
151 sLog.outDetail("Loading map %s",tmp);
152 // loading data
153 GridMaps[gx][gy] = new GridMap();
154 if (!GridMaps[gx][gy]->loadData(tmp))
156 sLog.outError("Error load map file: \n %s\n", tmp);
158 delete [] tmp;
161 void Map::LoadMapAndVMap(int gx,int gy)
163 LoadMap(gx,gy);
164 if(i_InstanceId == 0)
165 LoadVMap(gx, gy); // Only load the data for the base map
168 void Map::InitStateMachine()
170 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
171 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
172 si_GridStates[GRID_STATE_IDLE] = new IdleState;
173 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
176 void Map::DeleteStateMachine()
178 delete si_GridStates[GRID_STATE_INVALID];
179 delete si_GridStates[GRID_STATE_ACTIVE];
180 delete si_GridStates[GRID_STATE_IDLE];
181 delete si_GridStates[GRID_STATE_REMOVAL];
184 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
185 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
186 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0), i_gridExpiry(expiry),
187 m_activeNonPlayersIter(m_activeNonPlayers.end())
189 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
191 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
193 //z code
194 GridMaps[idx][j] =NULL;
195 setNGrid(NULL, idx, j);
200 // Template specialization of utility methods
201 template<class T>
202 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
204 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
207 template<>
208 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
210 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
213 template<>
214 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
216 // add to world object registry in grid
217 if(obj->GetType()!=CORPSE_BONES)
219 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
221 // add to grid object store
222 else
224 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
228 template<>
229 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
231 // add to world object registry in grid
232 if(obj->isPet() || obj->isVehicle())
234 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
235 obj->SetCurrentCell(cell);
237 // add to grid object store
238 else
240 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
241 obj->SetCurrentCell(cell);
245 template<class T>
246 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
248 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
251 template<>
252 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
254 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
257 template<>
258 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
260 // remove from world object registry in grid
261 if(obj->GetType()!=CORPSE_BONES)
263 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
265 // remove from grid object store
266 else
268 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
272 template<>
273 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
275 // remove from world object registry in grid
276 if(obj->isPet() || obj->isVehicle())
278 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
280 // remove from grid object store
281 else
283 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
287 template<class T>
288 void Map::DeleteFromWorld(T* obj)
290 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
291 delete obj;
294 template<class T>
295 void Map::AddNotifier(T* , Cell const& , CellPair const& )
299 template<>
300 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
302 PlayerRelocationNotify(obj,cell,cellpair);
305 template<>
306 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
308 CreatureRelocationNotify(obj,cell,cellpair);
311 void
312 Map::EnsureGridCreated(const GridPair &p)
314 if(!getNGrid(p.x_coord, p.y_coord))
316 Guard guard(*this);
317 if(!getNGrid(p.x_coord, p.y_coord))
319 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)),
320 p.x_coord, p.y_coord);
322 // build a linkage between this map and NGridType
323 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
325 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
327 //z coord
328 int gx=63-p.x_coord;
329 int gy=63-p.y_coord;
331 if(!GridMaps[gx][gy])
332 LoadMapAndVMap(gx,gy);
337 void
338 Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
340 NGridType *grid;
342 if(EnsureGridLoaded(cell))
344 grid = getNGrid(cell.GridX(), cell.GridY());
346 if (player)
348 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
349 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);
351 else
353 DEBUG_LOG("Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
356 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
357 grid->SetGridState(GRID_STATE_ACTIVE);
359 else
360 grid = getNGrid(cell.GridX(), cell.GridY());
362 if (player)
363 AddToGrid(player,grid,cell);
366 bool Map::EnsureGridLoaded(const Cell &cell)
368 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
369 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
371 assert(grid != NULL);
372 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
374 ObjectGridLoader loader(*grid, this, cell);
375 loader.LoadN();
377 // Add resurrectable corpses to world object list in grid
378 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
380 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
381 return true;
384 return false;
387 void Map::LoadGrid(const Cell& cell, bool no_unload)
389 EnsureGridLoaded(cell);
391 if(no_unload)
392 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
395 bool Map::Add(Player *player)
397 player->GetMapRef().link(this, player);
399 player->SetInstanceId(GetInstanceId());
401 // update player state for other player and visa-versa
402 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
403 Cell cell(p);
404 EnsureGridLoadedAtEnter(cell, player);
405 player->AddToWorld();
407 SendInitSelf(player);
408 SendInitTransports(player);
410 UpdatePlayerVisibility(player,cell,p);
411 UpdateObjectsVisibilityFor(player,cell,p);
413 AddNotifier(player,cell,p);
414 return true;
417 template<class T>
418 void
419 Map::Add(T *obj)
421 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
423 assert(obj);
425 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
427 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);
428 return;
431 Cell cell(p);
432 if(obj->isActiveObject())
433 EnsureGridLoadedAtEnter(cell);
434 else
435 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
437 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
438 assert( grid != NULL );
440 AddToGrid(obj,grid,cell);
441 obj->AddToWorld();
443 if(obj->isActiveObject())
444 AddToActive(obj);
446 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
448 UpdateObjectVisibility(obj,cell,p);
450 AddNotifier(obj,cell,p);
453 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
455 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
457 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
459 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);
460 return;
463 Cell cell(p);
464 cell.data.Part.reserved = ALL_DISTRICT;
466 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
467 return;
469 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
470 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
471 CellLock<ReadGuard> cell_lock(cell, p);
472 cell_lock->Visit(cell_lock, message, *this);
475 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
477 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
479 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
481 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);
482 return;
485 Cell cell(p);
486 cell.data.Part.reserved = ALL_DISTRICT;
487 cell.SetNoCreate();
489 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
490 return;
492 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
493 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
494 CellLock<ReadGuard> cell_lock(cell, p);
495 cell_lock->Visit(cell_lock, message, *this);
498 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
500 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
502 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
504 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);
505 return;
508 Cell cell(p);
509 cell.data.Part.reserved = ALL_DISTRICT;
511 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
512 return;
514 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
515 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
516 CellLock<ReadGuard> cell_lock(cell, p);
517 cell_lock->Visit(cell_lock, message, *this);
520 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
522 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
524 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
526 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);
527 return;
530 Cell cell(p);
531 cell.data.Part.reserved = ALL_DISTRICT;
532 cell.SetNoCreate();
534 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
535 return;
537 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
538 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
539 CellLock<ReadGuard> cell_lock(cell, p);
540 cell_lock->Visit(cell_lock, message, *this);
543 bool Map::loaded(const GridPair &p) const
545 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
548 void Map::Update(const uint32 &t_diff)
550 resetMarkedCells();
552 MaNGOS::ObjectUpdater updater(t_diff);
553 // for creature
554 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
555 // for pets
556 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
558 // the player iterator is stored in the map object
559 // to make sure calls to Map::Remove don't invalidate it
560 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
562 Player* plr = m_mapRefIter->getSource();
564 if(!plr->IsInWorld())
565 continue;
567 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
569 // Check for correctness of standing_cell, it also avoids problems with update_cell
570 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
571 continue;
573 // the overloaded operators handle range checking
574 // so ther's no need for range checking inside the loop
575 CellPair begin_cell(standing_cell), end_cell(standing_cell);
576 begin_cell << 1; begin_cell -= 1; // upper left
577 end_cell >> 1; end_cell += 1; // lower right
579 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
581 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
583 // marked cells are those that have been visited
584 // don't visit the same cell twice
585 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
586 if(!isCellMarked(cell_id))
588 markCell(cell_id);
589 CellPair pair(x,y);
590 Cell cell(pair);
591 cell.data.Part.reserved = CENTER_DISTRICT;
592 cell.SetNoCreate();
593 CellLock<NullGuard> cell_lock(cell, pair);
594 cell_lock->Visit(cell_lock, grid_object_update, *this);
595 cell_lock->Visit(cell_lock, world_object_update, *this);
601 // non-player active objects
602 if(!m_activeNonPlayers.empty())
604 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
606 // skip not in world
607 WorldObject* obj = *m_activeNonPlayersIter;
609 // step before processing, in this case if Map::Remove remove next object we correctly
610 // step to next-next, and if we step to end() then newly added objects can wait next update.
611 ++m_activeNonPlayersIter;
613 if(!obj->IsInWorld())
614 continue;
616 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
618 // Check for correctness of standing_cell, it also avoids problems with update_cell
619 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
620 continue;
622 // the overloaded operators handle range checking
623 // so ther's no need for range checking inside the loop
624 CellPair begin_cell(standing_cell), end_cell(standing_cell);
625 begin_cell << 1; begin_cell -= 1; // upper left
626 end_cell >> 1; end_cell += 1; // lower right
628 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
630 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
632 // marked cells are those that have been visited
633 // don't visit the same cell twice
634 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
635 if(!isCellMarked(cell_id))
637 markCell(cell_id);
638 CellPair pair(x,y);
639 Cell cell(pair);
640 cell.data.Part.reserved = CENTER_DISTRICT;
641 cell.SetNoCreate();
642 CellLock<NullGuard> cell_lock(cell, pair);
643 cell_lock->Visit(cell_lock, grid_object_update, *this);
644 cell_lock->Visit(cell_lock, world_object_update, *this);
651 // 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 !
652 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
653 if (IsBattleGroundOrArena())
654 return;
656 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
658 NGridType *grid = i->getSource();
659 GridInfo *info = i->getSource()->getGridInfoRef();
660 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
661 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
662 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
666 void Map::Remove(Player *player, bool remove)
668 // this may be called during Map::Update
669 // after decrement+unlink, ++m_mapRefIter will continue correctly
670 // when the first element of the list is being removed
671 // nocheck_prev will return the padding element of the RefManager
672 // instead of NULL in the case of prev
673 if(m_mapRefIter == player->GetMapRef())
674 m_mapRefIter = m_mapRefIter->nocheck_prev();
675 player->GetMapRef().unlink();
676 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
677 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
679 // invalid coordinates
680 player->RemoveFromWorld();
682 if( remove )
683 DeleteFromWorld(player);
685 return;
688 Cell cell(p);
690 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
692 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
693 return;
696 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
697 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
698 assert(grid != NULL);
700 player->RemoveFromWorld();
701 RemoveFromGrid(player,grid,cell);
703 SendRemoveTransports(player);
705 UpdateObjectsVisibilityFor(player,cell,p);
707 if( remove )
708 DeleteFromWorld(player);
711 bool Map::RemoveBones(uint64 guid, float x, float y)
713 if (IsRemovalGrid(x, y))
715 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
716 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
717 corpse->DeleteBonesFromWorld();
718 else
719 return false;
721 return true;
724 template<class T>
725 void
726 Map::Remove(T *obj, bool remove)
728 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
729 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
731 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);
732 return;
735 Cell cell(p);
736 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
737 return;
739 DEBUG_LOG("Remove object " I64FMT " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
740 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
741 assert( grid != NULL );
743 if(obj->isActiveObject())
744 RemoveFromActive(obj);
746 obj->RemoveFromWorld();
747 RemoveFromGrid(obj,grid,cell);
749 UpdateObjectVisibility(obj,cell,p);
751 if( remove )
753 // if option set then object already saved at this moment
754 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
755 obj->SaveRespawnTime();
756 DeleteFromWorld(obj);
760 void
761 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
763 assert(player);
765 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
766 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
768 Cell old_cell(old_val);
769 Cell new_cell(new_val);
770 new_cell |= old_cell;
771 bool same_cell = (new_cell == old_cell);
773 player->Relocate(x, y, z, orientation);
775 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
777 DEBUG_LOG("Player %s relocation grid[%u,%u]cell[%u,%u]->grid[%u,%u]cell[%u,%u]", player->GetName(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
779 // update player position for group at taxi flight
780 if(player->GetGroup() && player->isInFlight())
781 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
783 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
784 RemoveFromGrid(player, oldGrid,old_cell);
785 if( !old_cell.DiffGrid(new_cell) )
786 AddToGrid(player, oldGrid,new_cell);
787 else
788 EnsureGridLoadedAtEnter(new_cell, player);
791 // if move then update what player see and who seen
792 UpdatePlayerVisibility(player,new_cell,new_val);
793 UpdateObjectsVisibilityFor(player,new_cell,new_val);
794 PlayerRelocationNotify(player,new_cell,new_val);
795 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
796 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
798 ResetGridExpiry(*newGrid, 0.1f);
799 newGrid->SetGridState(GRID_STATE_ACTIVE);
803 void
804 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
806 assert(CheckGridIntegrity(creature,false));
808 Cell old_cell = creature->GetCurrentCell();
810 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
811 Cell new_cell(new_val);
813 // delay creature move for grid/cell to grid/cell moves
814 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
816 #ifdef MANGOS_DEBUG
817 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
818 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());
819 #endif
820 AddCreatureToMoveList(creature,x,y,z,ang);
821 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
823 else
825 creature->Relocate(x, y, z, ang);
826 CreatureRelocationNotify(creature,new_cell,new_val);
828 assert(CheckGridIntegrity(creature,true));
831 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
833 if(!c)
834 return;
836 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
839 void Map::MoveAllCreaturesInMoveList()
841 while(!i_creaturesToMove.empty())
843 // get data and remove element;
844 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
845 Creature* c = iter->first;
846 CreatureMover cm = iter->second;
847 i_creaturesToMove.erase(iter);
849 // calculate cells
850 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
851 Cell new_cell(new_val);
853 // do move or do move to respawn or remove creature if previous all fail
854 if(CreatureCellRelocation(c,new_cell))
856 // update pos
857 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
858 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
860 else
862 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
863 // creature coordinates will be updated and notifiers send
864 if(!CreatureRespawnRelocation(c))
866 // ... or unload (if respawn grid also not loaded)
867 #ifdef MANGOS_DEBUG
868 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
869 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
870 #endif
871 c->CleanupsBeforeDelete();
872 AddObjectToRemoveList(c);
878 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
880 Cell const& old_cell = c->GetCurrentCell();
881 if(!old_cell.DiffGrid(new_cell) ) // in same grid
883 // if in same cell then none do
884 if(old_cell.DiffCell(new_cell))
886 #ifdef MANGOS_DEBUG
887 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
888 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());
889 #endif
891 if( !old_cell.DiffGrid(new_cell) )
893 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
894 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
895 c->SetCurrentCell(new_cell);
898 else
900 #ifdef MANGOS_DEBUG
901 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
902 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());
903 #endif
906 return true;
909 // in diff. grids but active creature
910 if(c->isActiveObject())
912 EnsureGridLoadedAtEnter(new_cell);
914 #ifdef MANGOS_DEBUG
915 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
916 sLog.outDebug("Active 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());
917 #endif
919 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
920 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
922 return true;
925 // in diff. loaded grid normal creature
926 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
928 #ifdef MANGOS_DEBUG
929 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
930 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());
931 #endif
933 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
935 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
936 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
939 return true;
942 // fail to move: normal creature attempt move to unloaded grid
943 #ifdef MANGOS_DEBUG
944 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
945 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());
946 #endif
947 return false;
950 bool Map::CreatureRespawnRelocation(Creature *c)
952 float resp_x, resp_y, resp_z, resp_o;
953 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
955 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
956 Cell resp_cell(resp_val);
958 c->CombatStop();
959 c->GetMotionMaster()->Clear();
961 #ifdef MANGOS_DEBUG
962 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
963 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());
964 #endif
966 // teleport it to respawn point (like normal respawn if player see)
967 if(CreatureCellRelocation(c,resp_cell))
969 c->Relocate(resp_x, resp_y, resp_z, resp_o);
970 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
971 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
972 return true;
974 else
975 return false;
978 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
980 NGridType *grid = getNGrid(x, y);
981 assert( grid != NULL);
984 if(!pForce && ActiveObjectsNearGrid(x, y) )
985 return false;
987 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
988 ObjectGridUnloader unloader(*grid);
990 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
991 // Must know real mob position before move
992 DoDelayedMovesAndRemoves();
994 // move creatures to respawn grids if this is diff.grid or to remove list
995 unloader.MoveToRespawnN();
997 // Finish creature moves, remove and delete all creatures with delayed remove before unload
998 DoDelayedMovesAndRemoves();
1000 unloader.UnloadN();
1001 delete getNGrid(x, y);
1002 setNGrid(NULL, x, y);
1004 int gx=63-x;
1005 int gy=63-y;
1007 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1008 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1010 if (i_InstanceId == 0)
1012 if(GridMaps[gx][gy])
1014 GridMaps[gx][gy]->unloadData();
1015 delete GridMaps[gx][gy];
1017 // x and y are swapped
1018 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
1020 else
1021 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
1022 GridMaps[gx][gy] = NULL;
1024 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1025 return true;
1028 void Map::UnloadAll(bool pForce)
1030 // clear all delayed moves, useless anyway do this moves before map unload.
1031 i_creaturesToMove.clear();
1033 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1035 NGridType &grid(*i->getSource());
1036 ++i;
1037 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1041 //*****************************
1042 // Grid function
1043 //*****************************
1044 GridMap::GridMap()
1046 m_flags = 0;
1047 // Area data
1048 m_gridArea = 0;
1049 m_area_map = NULL;
1050 // Height level data
1051 m_gridHeight = INVALID_HEIGHT;
1052 m_gridGetHeight = &GridMap::getHeightFromFlat;
1053 m_V9 = NULL;
1054 m_V8 = NULL;
1055 // Liquid data
1056 m_liquidType = 0;
1057 m_liquid_offX = 0;
1058 m_liquid_offY = 0;
1059 m_liquid_width = 0;
1060 m_liquid_height = 0;
1061 m_liquidLevel = INVALID_HEIGHT;
1062 m_liquid_type = NULL;
1063 m_liquid_map = NULL;
1066 GridMap::~GridMap()
1068 unloadData();
1071 bool GridMap::loadData(char *filename)
1073 // Unload old data if exist
1074 unloadData();
1076 map_fileheader header;
1077 // Not return error if file not found
1078 FILE *in = fopen(filename, "rb");
1079 if (!in)
1080 return true;
1081 fread(&header, sizeof(header),1,in);
1082 if (header.mapMagic == uint32(MAP_MAGIC) &&
1083 header.versionMagic == uint32(MAP_VERSION_MAGIC))
1085 // loadup area data
1086 if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
1088 sLog.outError("Error loading map area data\n");
1089 fclose(in);
1090 return false;
1092 // loadup height data
1093 if (header.heightMapOffset && !loadHeihgtData(in, header.heightMapOffset, header.heightMapSize))
1095 sLog.outError("Error loading map height data\n");
1096 fclose(in);
1097 return false;
1099 // loadup liquid data
1100 if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
1102 sLog.outError("Error loading map liquids data\n");
1103 fclose(in);
1104 return false;
1106 fclose(in);
1107 return true;
1109 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
1110 fclose(in);
1111 return false;
1114 void GridMap::unloadData()
1116 if (m_area_map) delete[] m_area_map;
1117 if (m_V9) delete[] m_V9;
1118 if (m_V8) delete[] m_V8;
1119 if (m_liquid_type) delete[] m_liquid_type;
1120 if (m_liquid_map) delete[] m_liquid_map;
1121 m_area_map = NULL;
1122 m_V9 = NULL;
1123 m_V8 = NULL;
1124 m_liquid_type = NULL;
1125 m_liquid_map = NULL;
1126 m_gridGetHeight = &GridMap::getHeightFromFlat;
1129 bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 size)
1131 map_areaHeader header;
1132 fseek(in, offset, SEEK_SET);
1133 fread(&header, sizeof(header), 1, in);
1134 if (header.fourcc != uint32(MAP_AREA_MAGIC))
1135 return false;
1137 m_gridArea = header.gridArea;
1138 if (!(header.flags & MAP_AREA_NO_AREA))
1140 m_area_map = new uint16 [16*16];
1141 fread(m_area_map, sizeof(uint16), 16*16, in);
1143 return true;
1146 bool GridMap::loadHeihgtData(FILE *in, uint32 offset, uint32 size)
1148 map_heightHeader header;
1149 fseek(in, offset, SEEK_SET);
1150 fread(&header, sizeof(header), 1, in);
1151 if (header.fourcc != uint32(MAP_HEIGTH_MAGIC))
1152 return false;
1154 m_gridHeight = header.gridHeight;
1155 if (!(header.flags & MAP_HEIGHT_NO_HIGHT))
1157 if ((header.flags & MAP_HEIGHT_AS_INT16))
1159 m_uint16_V9 = new uint16 [129*129];
1160 m_uint16_V8 = new uint16 [128*128];
1161 fread(m_uint16_V9, sizeof(uint16), 129*129, in);
1162 fread(m_uint16_V8, sizeof(uint16), 128*128, in);
1163 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
1164 m_gridGetHeight = &GridMap::getHeightFromUint16;
1166 else if ((header.flags & MAP_HEIGHT_AS_INT8))
1168 m_uint8_V9 = new uint8 [129*129];
1169 m_uint8_V8 = new uint8 [128*128];
1170 fread(m_uint8_V9, sizeof(uint8), 129*129, in);
1171 fread(m_uint8_V8, sizeof(uint8), 128*128, in);
1172 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
1173 m_gridGetHeight = &GridMap::getHeightFromUint8;
1175 else
1177 m_V9 = new float [129*129];
1178 m_V8 = new float [128*128];
1179 fread(m_V9, sizeof(float), 129*129, in);
1180 fread(m_V8, sizeof(float), 128*128, in);
1181 m_gridGetHeight = &GridMap::getHeightFromFloat;
1184 else
1185 m_gridGetHeight = &GridMap::getHeightFromFlat;
1186 return true;
1189 bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 size)
1191 map_liquidHeader header;
1192 fseek(in, offset, SEEK_SET);
1193 fread(&header, sizeof(header), 1, in);
1194 if (header.fourcc != uint32(MAP_LIQUID_MAGIC))
1195 return false;
1197 m_liquidType = header.liquidType;
1198 m_liquid_offX = header.offsetX;
1199 m_liquid_offY = header.offsetY;
1200 m_liquid_width = header.width;
1201 m_liquid_height= header.height;
1202 m_liquidLevel = header.liquidLevel;
1204 if (!(header.flags&MAP_LIQUID_NO_TYPE))
1206 m_liquid_type = new uint8 [16*16];
1207 fread(m_liquid_type, sizeof(uint8), 16*16, in);
1209 if (!(header.flags&MAP_LIQUID_NO_HIGHT))
1211 m_liquid_map = new float [m_liquid_width*m_liquid_height];
1212 fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
1214 return true;
1217 uint16 GridMap::getArea(float x, float y)
1219 if (!m_area_map)
1220 return m_gridArea;
1222 x = 16 * (32 - x/SIZE_OF_GRIDS);
1223 y = 16 * (32 - y/SIZE_OF_GRIDS);
1224 int lx = (int)x & 15;
1225 int ly = (int)y & 15;
1226 return m_area_map[lx*16 + ly];
1229 float GridMap::getHeightFromFlat(float x, float y) const
1231 return m_gridHeight;
1234 float GridMap::getHeightFromFloat(float x, float y) const
1236 if (!m_V8 || !m_V9)
1237 return m_gridHeight;
1239 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1240 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1242 int x_int = (int)x;
1243 int y_int = (int)y;
1244 x -= x_int;
1245 y -= y_int;
1246 x_int&=(MAP_RESOLUTION - 1);
1247 y_int&=(MAP_RESOLUTION - 1);
1249 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1250 // +--------------> X
1251 // | h1-------h2 Coordinates is:
1252 // | | \ 1 / | h1 0,0
1253 // | | \ / | h2 0,1
1254 // | | 2 h5 3 | h3 1,0
1255 // | | / \ | h4 1,1
1256 // | | / 4 \ | h5 1/2,1/2
1257 // | h3-------h4
1258 // V Y
1259 // For find height need
1260 // 1 - detect triangle
1261 // 2 - solve linear equation from triangle points
1262 // Calculate coefficients for solve h = a*x + b*y + c
1264 float a,b,c;
1265 // Select triangle:
1266 if (x+y < 1)
1268 if (x > y)
1270 // 1 triangle (h1, h2, h5 points)
1271 float h1 = m_V9[(x_int )*129 + y_int];
1272 float h2 = m_V9[(x_int+1)*129 + y_int];
1273 float h5 = 2 * m_V8[x_int*128 + y_int];
1274 a = h2-h1;
1275 b = h5-h1-h2;
1276 c = h1;
1278 else
1280 // 2 triangle (h1, h3, h5 points)
1281 float h1 = m_V9[x_int*129 + y_int ];
1282 float h3 = m_V9[x_int*129 + y_int+1];
1283 float h5 = 2 * m_V8[x_int*128 + y_int];
1284 a = h5 - h1 - h3;
1285 b = h3 - h1;
1286 c = h1;
1289 else
1291 if (x > y)
1293 // 3 triangle (h2, h4, h5 points)
1294 float h2 = m_V9[(x_int+1)*129 + y_int ];
1295 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1296 float h5 = 2 * m_V8[x_int*128 + y_int];
1297 a = h2 + h4 - h5;
1298 b = h4 - h2;
1299 c = h5 - h4;
1301 else
1303 // 4 triangle (h3, h4, h5 points)
1304 float h3 = m_V9[(x_int )*129 + y_int+1];
1305 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1306 float h5 = 2 * m_V8[x_int*128 + y_int];
1307 a = h4 - h3;
1308 b = h3 + h4 - h5;
1309 c = h5 - h4;
1312 // Calculate height
1313 return a * x + b * y + c;
1316 float GridMap::getHeightFromUint8(float x, float y) const
1318 if (!m_uint8_V8 || !m_uint8_V9)
1319 return m_gridHeight;
1321 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1322 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1324 int x_int = (int)x;
1325 int y_int = (int)y;
1326 x -= x_int;
1327 y -= y_int;
1328 x_int&=(MAP_RESOLUTION - 1);
1329 y_int&=(MAP_RESOLUTION - 1);
1331 int32 a, b, c;
1332 uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
1333 if (x+y < 1)
1335 if (x > y)
1337 // 1 triangle (h1, h2, h5 points)
1338 int32 h1 = V9_h1_ptr[ 0];
1339 int32 h2 = V9_h1_ptr[129];
1340 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1341 a = h2-h1;
1342 b = h5-h1-h2;
1343 c = h1;
1345 else
1347 // 2 triangle (h1, h3, h5 points)
1348 int32 h1 = V9_h1_ptr[0];
1349 int32 h3 = V9_h1_ptr[1];
1350 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1351 a = h5 - h1 - h3;
1352 b = h3 - h1;
1353 c = h1;
1356 else
1358 if (x > y)
1360 // 3 triangle (h2, h4, h5 points)
1361 int32 h2 = V9_h1_ptr[129];
1362 int32 h4 = V9_h1_ptr[130];
1363 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1364 a = h2 + h4 - h5;
1365 b = h4 - h2;
1366 c = h5 - h4;
1368 else
1370 // 4 triangle (h3, h4, h5 points)
1371 int32 h3 = V9_h1_ptr[ 1];
1372 int32 h4 = V9_h1_ptr[130];
1373 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1374 a = h4 - h3;
1375 b = h3 + h4 - h5;
1376 c = h5 - h4;
1379 // Calculate height
1380 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1383 float GridMap::getHeightFromUint16(float x, float y) const
1385 if (!m_uint16_V8 || !m_uint16_V9)
1386 return m_gridHeight;
1388 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1389 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1391 int x_int = (int)x;
1392 int y_int = (int)y;
1393 x -= x_int;
1394 y -= y_int;
1395 x_int&=(MAP_RESOLUTION - 1);
1396 y_int&=(MAP_RESOLUTION - 1);
1398 int32 a, b, c;
1399 uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
1400 if (x+y < 1)
1402 if (x > y)
1404 // 1 triangle (h1, h2, h5 points)
1405 int32 h1 = V9_h1_ptr[ 0];
1406 int32 h2 = V9_h1_ptr[129];
1407 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1408 a = h2-h1;
1409 b = h5-h1-h2;
1410 c = h1;
1412 else
1414 // 2 triangle (h1, h3, h5 points)
1415 int32 h1 = V9_h1_ptr[0];
1416 int32 h3 = V9_h1_ptr[1];
1417 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1418 a = h5 - h1 - h3;
1419 b = h3 - h1;
1420 c = h1;
1423 else
1425 if (x > y)
1427 // 3 triangle (h2, h4, h5 points)
1428 int32 h2 = V9_h1_ptr[129];
1429 int32 h4 = V9_h1_ptr[130];
1430 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1431 a = h2 + h4 - h5;
1432 b = h4 - h2;
1433 c = h5 - h4;
1435 else
1437 // 4 triangle (h3, h4, h5 points)
1438 int32 h3 = V9_h1_ptr[ 1];
1439 int32 h4 = V9_h1_ptr[130];
1440 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1441 a = h4 - h3;
1442 b = h3 + h4 - h5;
1443 c = h5 - h4;
1446 // Calculate height
1447 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1450 float GridMap::getLiquidLevel(float x, float y)
1452 if (!m_liquid_map)
1453 return m_liquidLevel;
1455 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1456 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1458 int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
1459 int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
1461 if (cx_int < 0 || cx_int >=m_liquid_height)
1462 return INVALID_HEIGHT;
1463 if (cy_int < 0 || cy_int >=m_liquid_width )
1464 return INVALID_HEIGHT;
1466 return m_liquid_map[cx_int*m_liquid_width + cy_int];
1469 uint8 GridMap::getTerrainType(float x, float y)
1471 if (!m_liquid_type)
1472 return m_liquidType;
1474 x = 16 * (32 - x/SIZE_OF_GRIDS);
1475 y = 16 * (32 - y/SIZE_OF_GRIDS);
1476 int lx = (int)x & 15;
1477 int ly = (int)y & 15;
1478 return m_liquid_type[lx*16 + ly];
1481 // Get water state on map
1482 inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
1484 // Check water type (if no water return)
1485 if (!m_liquid_type && !m_liquidType)
1486 return LIQUID_MAP_NO_WATER;
1488 // Get cell
1489 float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1490 float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1492 int x_int = (int)cx & (MAP_RESOLUTION-1);
1493 int y_int = (int)cy & (MAP_RESOLUTION-1);
1495 // Check water type in cell
1496 uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
1497 if (type == 0)
1498 return LIQUID_MAP_NO_WATER;
1500 // Check req liquid type mask
1501 if (ReqLiquidType && !(ReqLiquidType&type))
1502 return LIQUID_MAP_NO_WATER;
1504 // Check water level:
1505 // Check water height map
1506 int lx_int = x_int - m_liquid_offY;
1507 int ly_int = y_int - m_liquid_offX;
1508 if (lx_int < 0 || lx_int >=m_liquid_height)
1509 return LIQUID_MAP_NO_WATER;
1510 if (ly_int < 0 || ly_int >=m_liquid_width )
1511 return LIQUID_MAP_NO_WATER;
1513 // Get water level
1514 float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
1515 // Get ground level (sub 0.2 for fix some errors)
1516 float ground_level = getHeight(x, y);
1518 // Check water level and ground level
1519 if (liquid_level < ground_level || z < ground_level - 2)
1520 return LIQUID_MAP_NO_WATER;
1522 // All ok in water -> store data
1523 if (data)
1525 data->type = type;
1526 data->level = liquid_level;
1527 data->depth_level = ground_level;
1530 // For speed check as int values
1531 int delta = int((liquid_level - z) * 10);
1533 // Get position delta
1534 if (delta > 20) // Under water
1535 return LIQUID_MAP_UNDER_WATER;
1536 if (delta > 0 ) // In water
1537 return LIQUID_MAP_IN_WATER;
1538 if (delta > -1) // Walk on water
1539 return LIQUID_MAP_WATER_WALK;
1540 // Above water
1541 return LIQUID_MAP_ABOVE_WATER;
1544 inline GridMap *Map::GetGrid(float x, float y)
1546 // half opt method
1547 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1548 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1550 // ensure GridMap is loaded
1551 EnsureGridCreated(GridPair(63-gx,63-gy));
1553 return GridMaps[gx][gy];
1556 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1558 // find raw .map surface under Z coordinates
1559 float mapHeight;
1560 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1562 float _mapheight = gmap->getHeight(x,y);
1564 // look from a bit higher pos to find the floor, ignore under surface case
1565 if(z + 2.0f > _mapheight)
1566 mapHeight = _mapheight;
1567 else
1568 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1570 else
1571 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1573 float vmapHeight;
1574 if(pUseVmaps)
1576 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1577 if(vmgr->isHeightCalcEnabled())
1579 // look from a bit higher pos to find the floor
1580 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1582 else
1583 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1585 else
1586 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1588 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1589 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1591 if( vmapHeight > INVALID_HEIGHT )
1593 if( mapHeight > INVALID_HEIGHT )
1595 // we have mapheight and vmapheight and must select more appropriate
1597 // we are already under the surface or vmap height above map heigt
1598 // or if the distance of the vmap height is less the land height distance
1599 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1600 return vmapHeight;
1601 else
1602 return mapHeight; // better use .map surface height
1605 else
1606 return vmapHeight; // we have only vmapHeight (if have)
1608 else
1610 if(!pUseVmaps)
1611 return mapHeight; // explicitly use map data (if have)
1612 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1613 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1614 else
1615 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1619 uint16 Map::GetAreaFlag(float x, float y, float z) const
1621 uint16 areaflag;
1622 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1623 areaflag = gmap->getArea(x, y);
1624 // this used while not all *.map files generated (instances)
1625 else
1626 areaflag = GetAreaFlagByMapId(i_id);
1628 //FIXME: some hacks for areas above or underground for ground area
1629 // required for area specific spells/etc, until map/vmap data
1630 // not provided correct areaflag with this hacks
1631 switch(areaflag)
1633 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1634 case 1984: // Plaguelands: The Scarlet Enclave
1635 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1636 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1637 if(z > 350.0f) areaflag = 2048; break;
1638 // Acherus: The Ebon Hold (Eastern Plaguelands)
1639 case 856: // The Noxious Glade (Eastern Plaguelands)
1640 case 2456: // Death's Breach (Eastern Plaguelands)
1641 if(z > 350.0f) areaflag = 1950; break;
1642 // Dalaran
1643 case 1593: // Crystalsong Forest
1644 case 2484: // The Twilight Rivulet (Crystalsong Forest)
1645 case 2492: // Forlorn Woods (Crystalsong Forest)
1646 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f) areaflag = 2153; break;
1647 // Maw of Neltharion (cave)
1648 case 164: // Dragonblight
1649 case 1797: // Obsidian Dragonshrine (Dragonblight)
1650 case 1827: // Wintergrasp
1651 case 2591: // The Cauldron of Flames (Wintergrasp)
1652 if (x > 4364.0f && x < 4632.0f && y > 1545.0f && y < 1886.0f && z < 200.0f) areaflag = 1853; break;
1653 // Undercity (sewers enter and path)
1654 case 179: // Tirisfal Glades
1655 if (x > 1595.0f && x < 1699.0f && y > 535.0f && y < 643.5f && z < 30.5f) areaflag = 685; break;
1656 // Undercity (Royal Quarter)
1657 case 210: // Silverpine Forest
1658 case 316: // The Shining Strand (Silverpine Forest)
1659 case 438: // Lordamere Lake (Silverpine Forest)
1660 if (x > 1237.0f && x < 1401.0f && y > 284.0f && y < 440.0f && z < -40.0f) areaflag = 685; break;
1661 // Undercity (cave and ground zone, part of royal quarter)
1662 case 607: // Ruins of Lordaeron (Tirisfal Glades)
1663 // ground and near to ground (by city walls)
1664 if(z > 0.0f)
1666 if (x > 1510.0f && x < 1839.0f && y > 29.77f && y < 433.0f) areaflag = 685;
1668 // more wide underground, part of royal quarter
1669 else
1671 if (x > 1299.0f && x < 1839.0f && y > 10.0f && y < 440.0f) areaflag = 685;
1673 break;
1674 // The Makers' Perch (ground) and Makers' Overlook (ground and cave)
1675 case 1335: // Sholazar Basin
1676 // The Makers' Perch ground (fast box)
1677 if (x > 6100.0f && x < 6250.0f && y > 5650.0f && y < 5800.0f)
1679 // nice slow circle
1680 if ((x-6183.0f)*(x-6183.0f)+(y-5717.0f)*(y-5717.0f) < 2500.0f)
1681 areaflag = 2189;
1683 // Makers' Overlook (ground and cave)
1684 else if (x > 5634.48f && x < 5774.53f && y < 3475.0f && z > 300.0f)
1686 if(y > 3380.26f || y > 3265.0f && z < 360.0f) areaflag = 2187;
1688 break;
1689 // The Makers' Perch (underground)
1690 case 2147: // The Stormwright's Shelf (Sholazar Basin)
1691 if (x > 6199.0f && x < 6283.0f && y > 5705.0f && y < 5817.0f && z < 38.0f) areaflag = 2189; break;
1692 // Makers' Overlook (deep cave)
1693 case 267: // Icecrown
1694 if (x > 5684.0f && x < 5798.0f && y > 3035.0f && y < 3367.0f && z < 358.0f) areaflag = 2187; break;
1695 // Wyrmrest Temple (Dragonblight)
1696 case 1814: // Path of the Titans (Dragonblight)
1697 case 1897: // The Dragon Wastes (Dragonblight)
1698 // fast box
1699 if (x > 3400.0f && x < 3700.0f && y > 130.0f && y < 420.0f)
1701 // nice slow circle
1702 if ((x-3546.87f)*(x-3546.87f)+(y-272.71f)*(y-272.71f) < 19600.0f) areaflag = 1791;
1704 break;
1707 return areaflag;
1710 uint8 Map::GetTerrainType(float x, float y ) const
1712 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1713 return gmap->getTerrainType(x, y);
1714 else
1715 return 0;
1718 ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
1720 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1721 return gmap->getLiquidStatus(x, y, z, ReqLiquidType, data);
1722 else
1723 return LIQUID_MAP_NO_WATER;
1726 float Map::GetWaterLevel(float x, float y ) const
1728 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1729 return gmap->getLiquidLevel(x, y);
1730 else
1731 return 0;
1734 uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
1736 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1738 if (entry)
1739 return entry->ID;
1740 else
1741 return 0;
1744 uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
1746 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1748 if( entry )
1749 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1750 else
1751 return 0;
1754 void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
1756 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1758 areaid = entry ? entry->ID : 0;
1759 zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
1762 bool Map::IsInWater(float x, float y, float pZ) const
1764 // Check surface in x, y point for liquid
1765 if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1767 LiquidData liquid_status;
1768 if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, &liquid_status))
1770 if (liquid_status.level - liquid_status.depth_level > 2)
1771 return true;
1774 return false;
1777 bool Map::IsUnderWater(float x, float y, float z) const
1779 if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1781 if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
1782 return true;
1784 return false;
1787 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1789 Cell const& cur_cell = c->GetCurrentCell();
1791 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1792 Cell xy_cell(xy_val);
1793 if(xy_cell != cur_cell)
1795 sLog.outError("Creature (GUIDLow: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1796 c->GetGUIDLow(),
1797 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1798 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1799 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1800 return true; // not crash at error, just output error in debug mode
1803 return true;
1806 const char* Map::GetMapName() const
1808 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1811 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1813 cell.data.Part.reserved = ALL_DISTRICT;
1814 cell.SetNoCreate();
1815 MaNGOS::VisibleChangesNotifier notifier(*obj);
1816 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1817 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1818 cell_lock->Visit(cell_lock, player_notifier, *this);
1821 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1823 cell.data.Part.reserved = ALL_DISTRICT;
1825 MaNGOS::PlayerNotifier pl_notifier(*player);
1826 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1828 CellLock<ReadGuard> cell_lock(cell, cellpair);
1829 cell_lock->Visit(cell_lock, player_notifier, *this);
1832 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1834 MaNGOS::VisibleNotifier notifier(*player);
1836 cell.data.Part.reserved = ALL_DISTRICT;
1837 cell.SetNoCreate();
1838 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1839 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1840 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1841 cell_lock->Visit(cell_lock, world_notifier, *this);
1842 cell_lock->Visit(cell_lock, grid_notifier, *this);
1844 // send data
1845 notifier.Notify();
1848 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1850 CellLock<ReadGuard> cell_lock(cell, cellpair);
1851 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1852 cell.data.Part.reserved = ALL_DISTRICT;
1854 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1855 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1857 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1858 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1861 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1863 CellLock<ReadGuard> cell_lock(cell, cellpair);
1864 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1865 cell.data.Part.reserved = ALL_DISTRICT;
1866 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1868 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1869 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1871 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1872 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1875 void Map::SendInitSelf( Player * player )
1877 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1879 UpdateData data;
1881 bool hasTransport = false;
1883 // attach to player data current transport data
1884 if(Transport* transport = player->GetTransport())
1886 hasTransport = true;
1887 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1890 // build data for self presence in world at own client (one time for map)
1891 player->BuildCreateUpdateBlockForPlayer(&data, player);
1893 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1894 if(Transport* transport = player->GetTransport())
1896 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1898 if(player!=(*itr) && player->HaveAtClient(*itr))
1900 hasTransport = true;
1901 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1906 WorldPacket packet;
1907 data.BuildPacket(&packet, hasTransport);
1908 player->GetSession()->SendPacket(&packet);
1911 void Map::SendInitTransports( Player * player )
1913 // Hack to send out transports
1914 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1916 // no transports at map
1917 if (tmap.find(player->GetMapId()) == tmap.end())
1918 return;
1920 UpdateData transData;
1922 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1924 bool hasTransport = false;
1926 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1928 // send data for current transport in other place
1929 if((*i) != player->GetTransport() && (*i)->GetMapId()==i_id)
1931 hasTransport = true;
1932 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1936 WorldPacket packet;
1937 transData.BuildPacket(&packet, hasTransport);
1938 player->GetSession()->SendPacket(&packet);
1941 void Map::SendRemoveTransports( Player * player )
1943 // Hack to send out transports
1944 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1946 // no transports at map
1947 if (tmap.find(player->GetMapId()) == tmap.end())
1948 return;
1950 UpdateData transData;
1952 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1954 // except used transport
1955 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1956 if((*i) != player->GetTransport() && (*i)->GetMapId()!=i_id)
1957 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1959 WorldPacket packet;
1960 transData.BuildPacket(&packet);
1961 player->GetSession()->SendPacket(&packet);
1964 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1966 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1968 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1969 assert(false);
1971 i_grids[x][y] = grid;
1974 void Map::DoDelayedMovesAndRemoves()
1976 MoveAllCreaturesInMoveList();
1977 RemoveAllObjectsInRemoveList();
1980 void Map::AddObjectToRemoveList(WorldObject *obj)
1982 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1984 i_objectsToRemove.insert(obj);
1985 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1988 void Map::RemoveAllObjectsInRemoveList()
1990 if(i_objectsToRemove.empty())
1991 return;
1993 //sLog.outDebug("Object remover 1 check.");
1994 while(!i_objectsToRemove.empty())
1996 WorldObject* obj = *i_objectsToRemove.begin();
1997 i_objectsToRemove.erase(i_objectsToRemove.begin());
1999 switch(obj->GetTypeId())
2001 case TYPEID_CORPSE:
2003 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
2004 if (!corpse)
2005 sLog.outError("Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
2006 else
2007 Remove(corpse,true);
2008 break;
2010 case TYPEID_DYNAMICOBJECT:
2011 Remove((DynamicObject*)obj,true);
2012 break;
2013 case TYPEID_GAMEOBJECT:
2014 Remove((GameObject*)obj,true);
2015 break;
2016 case TYPEID_UNIT:
2017 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
2018 // make sure that like sources auras/etc removed before destructor start
2019 ((Creature*)obj)->CleanupsBeforeDelete ();
2020 Remove((Creature*)obj,true);
2021 break;
2022 default:
2023 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
2024 break;
2027 //sLog.outDebug("Object remover 2 check.");
2030 uint32 Map::GetPlayersCountExceptGMs() const
2032 uint32 count = 0;
2033 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2034 if(!itr->getSource()->isGameMaster())
2035 ++count;
2036 return count;
2039 void Map::SendToPlayers(WorldPacket const* data) const
2041 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2042 itr->getSource()->GetSession()->SendPacket(data);
2045 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
2047 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
2048 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
2049 cell_min << 2;
2050 cell_min -= 2;
2051 cell_max >> 2;
2052 cell_max += 2;
2054 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
2056 Player* plr = iter->getSource();
2058 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
2059 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2060 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2061 return true;
2064 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
2066 WorldObject* obj = *iter;
2068 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
2069 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2070 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2071 return true;
2074 return false;
2077 void Map::AddToActive( Creature* c )
2079 AddToActiveHelper(c);
2081 // also not allow unloading spawn grid to prevent creating creature clone at load
2082 if(!c->isPet() && c->GetDBTableGUIDLow())
2084 float x,y,z;
2085 c->GetRespawnCoord(x,y,z);
2086 GridPair p = MaNGOS::ComputeGridPair(x, y);
2087 if(getNGrid(p.x_coord, p.y_coord))
2088 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
2089 else
2091 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2092 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2093 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2098 void Map::RemoveFromActive( Creature* c )
2100 RemoveFromActiveHelper(c);
2102 // also allow unloading spawn grid
2103 if(!c->isPet() && c->GetDBTableGUIDLow())
2105 float x,y,z;
2106 c->GetRespawnCoord(x,y,z);
2107 GridPair p = MaNGOS::ComputeGridPair(x, y);
2108 if(getNGrid(p.x_coord, p.y_coord))
2109 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
2110 else
2112 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2113 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2114 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2119 template void Map::Add(Corpse *);
2120 template void Map::Add(Creature *);
2121 template void Map::Add(GameObject *);
2122 template void Map::Add(DynamicObject *);
2124 template void Map::Remove(Corpse *,bool);
2125 template void Map::Remove(Creature *,bool);
2126 template void Map::Remove(GameObject *, bool);
2127 template void Map::Remove(DynamicObject *, bool);
2129 /* ******* Dungeon Instance Maps ******* */
2131 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
2132 : Map(id, expiry, InstanceId, SpawnMode),
2133 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
2134 i_data(NULL), i_script_id(0)
2136 // the timer is started by default, and stopped when the first player joins
2137 // this make sure it gets unloaded if for some reason no player joins
2138 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2141 InstanceMap::~InstanceMap()
2143 if(i_data)
2145 delete i_data;
2146 i_data = NULL;
2151 Do map specific checks to see if the player can enter
2153 bool InstanceMap::CanEnter(Player *player)
2155 if(player->GetMapRef().getTarget() == this)
2157 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
2158 assert(false);
2159 return false;
2162 // cannot enter if the instance is full (player cap), GMs don't count
2163 uint32 maxPlayers = GetMaxPlayers();
2164 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
2166 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
2167 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
2168 return false;
2171 // cannot enter while players in the instance are in combat
2172 Group *pGroup = player->GetGroup();
2173 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
2175 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
2176 return false;
2179 return Map::CanEnter(player);
2183 Do map specific checks and add the player to the map if successful.
2185 bool InstanceMap::Add(Player *player)
2187 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
2188 // GMs still can teleport player in instance.
2189 // Is it needed?
2192 Guard guard(*this);
2193 if(!CanEnter(player))
2194 return false;
2196 // Dungeon only code
2197 if(IsDungeon())
2199 // get or create an instance save for the map
2200 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2201 if(!mapSave)
2203 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
2204 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
2207 // check for existing instance binds
2208 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
2209 if(playerBind && playerBind->perm)
2211 // cannot enter other instances if bound permanently
2212 if(playerBind->save != mapSave)
2214 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());
2215 assert(false);
2218 else
2220 Group *pGroup = player->GetGroup();
2221 if(pGroup)
2223 // solo saves should be reset when entering a group
2224 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
2225 if(playerBind)
2227 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());
2228 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());
2229 assert(false);
2231 // bind to the group or keep using the group save
2232 if(!groupBind)
2233 pGroup->BindToInstance(mapSave, false);
2234 else
2236 // cannot jump to a different instance without resetting it
2237 if(groupBind->save != mapSave)
2239 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());
2240 if(mapSave)
2241 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
2242 else
2243 sLog.outError("MapSave NULL");
2244 if(groupBind->save)
2245 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
2246 else
2247 sLog.outError("GroupBind save NULL");
2248 assert(false);
2250 // if the group/leader is permanently bound to the instance
2251 // players also become permanently bound when they enter
2252 if(groupBind->perm)
2254 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2255 data << uint32(0);
2256 player->GetSession()->SendPacket(&data);
2257 player->BindToInstance(mapSave, true);
2261 else
2263 // set up a solo bind or continue using it
2264 if(!playerBind)
2265 player->BindToInstance(mapSave, false);
2266 else
2267 // cannot jump to a different instance without resetting it
2268 assert(playerBind->save == mapSave);
2273 if(i_data) i_data->OnPlayerEnter(player);
2274 // for normal instances cancel the reset schedule when the
2275 // first player enters (no players yet)
2276 SetResetSchedule(false);
2278 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
2279 // initialize unload state
2280 m_unloadTimer = 0;
2281 m_resetAfterUnload = false;
2282 m_unloadWhenEmpty = false;
2285 // this will acquire the same mutex so it cannot be in the previous block
2286 Map::Add(player);
2287 return true;
2290 void InstanceMap::Update(const uint32& t_diff)
2292 Map::Update(t_diff);
2294 if(i_data)
2295 i_data->Update(t_diff);
2298 void InstanceMap::Remove(Player *player, bool remove)
2300 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2301 //if last player set unload timer
2302 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
2303 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2304 Map::Remove(player, remove);
2305 // for normal instances schedule the reset after all players have left
2306 SetResetSchedule(true);
2309 void InstanceMap::CreateInstanceData(bool load)
2311 if(i_data != NULL)
2312 return;
2314 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
2315 if (mInstance)
2317 i_script_id = mInstance->script_id;
2318 i_data = Script->CreateInstanceData(this);
2321 if(!i_data)
2322 return;
2324 if(load)
2326 // TODO: make a global storage for this
2327 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
2328 if (result)
2330 Field* fields = result->Fetch();
2331 const char* data = fields[0].GetString();
2332 if(data)
2334 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
2335 i_data->Load(data);
2337 delete result;
2340 else
2342 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
2343 i_data->Initialize();
2348 Returns true if there are no players in the instance
2350 bool InstanceMap::Reset(uint8 method)
2352 // note: since the map may not be loaded when the instance needs to be reset
2353 // the instance must be deleted from the DB by InstanceSaveManager
2355 if(HavePlayers())
2357 if(method == INSTANCE_RESET_ALL)
2359 // notify the players to leave the instance so it can be reset
2360 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2361 itr->getSource()->SendResetFailedNotify(GetId());
2363 else
2365 if(method == INSTANCE_RESET_GLOBAL)
2367 // set the homebind timer for players inside (1 minute)
2368 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2369 itr->getSource()->m_InstanceValid = false;
2372 // the unload timer is not started
2373 // instead the map will unload immediately after the players have left
2374 m_unloadWhenEmpty = true;
2375 m_resetAfterUnload = true;
2378 else
2380 // unloaded at next update
2381 m_unloadTimer = MIN_UNLOAD_DELAY;
2382 m_resetAfterUnload = true;
2385 return m_mapRefManager.isEmpty();
2388 void InstanceMap::PermBindAllPlayers(Player *player)
2390 if(!IsDungeon())
2391 return;
2393 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2394 if(!save)
2396 sLog.outError("Cannot bind players, no instance save available for map!");
2397 return;
2400 Group *group = player->GetGroup();
2401 // group members outside the instance group don't get bound
2402 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2404 Player* plr = itr->getSource();
2405 // players inside an instance cannot be bound to other instances
2406 // some players may already be permanently bound, in this case nothing happens
2407 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
2408 if(!bind || !bind->perm)
2410 plr->BindToInstance(save, true);
2411 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2412 data << uint32(0);
2413 plr->GetSession()->SendPacket(&data);
2416 // if the leader is not in the instance the group will not get a perm bind
2417 if(group && group->GetLeaderGUID() == plr->GetGUID())
2418 group->BindToInstance(save, true);
2422 void InstanceMap::UnloadAll(bool pForce)
2424 if(HavePlayers())
2426 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
2427 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2429 Player* plr = itr->getSource();
2430 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
2434 if(m_resetAfterUnload == true)
2435 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
2437 Map::UnloadAll(pForce);
2440 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
2442 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2443 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
2446 void InstanceMap::SetResetSchedule(bool on)
2448 // only for normal instances
2449 // the reset time is only scheduled when there are no payers inside
2450 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2451 if(IsDungeon() && !HavePlayers() && !IsRaid() && !IsHeroic())
2453 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2454 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2455 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
2459 uint32 InstanceMap::GetMaxPlayers() const
2461 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
2462 if(!iTemplate)
2463 return 0;
2464 return IsHeroic() ? iTemplate->maxPlayersHeroic : iTemplate->maxPlayers;
2467 /* ******* Battleground Instance Maps ******* */
2469 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
2470 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
2474 BattleGroundMap::~BattleGroundMap()
2478 bool BattleGroundMap::CanEnter(Player * player)
2480 if(player->GetMapRef().getTarget() == this)
2482 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2483 assert(false);
2484 return false;
2487 if(player->GetBattleGroundId() != GetInstanceId())
2488 return false;
2490 // player number limit is checked in bgmgr, no need to do it here
2492 return Map::CanEnter(player);
2495 bool BattleGroundMap::Add(Player * player)
2498 Guard guard(*this);
2499 if(!CanEnter(player))
2500 return false;
2501 // reset instance validity, battleground maps do not homebind
2502 player->m_InstanceValid = true;
2504 return Map::Add(player);
2507 void BattleGroundMap::Remove(Player *player, bool remove)
2509 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2510 Map::Remove(player, remove);
2513 void BattleGroundMap::SetUnload()
2515 m_unloadTimer = MIN_UNLOAD_DELAY;
2518 void BattleGroundMap::UnloadAll(bool pForce)
2520 while(HavePlayers())
2522 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2524 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2525 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2526 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2527 // note that this remove is not needed if the code works well in other places
2528 plr->GetMapRef().unlink();
2532 Map::UnloadAll(pForce);
2535 Creature*
2536 Map::GetCreature(uint64 guid)
2538 Creature * ret = ObjectAccessor::GetObjectInWorld(guid, (Creature*)NULL);
2539 if(!ret)
2540 return NULL;
2542 if(ret->GetMapId() != GetId())
2543 return NULL;
2545 if(ret->GetInstanceId() != GetInstanceId())
2546 return NULL;
2548 return ret;
2551 GameObject*
2552 Map::GetGameObject(uint64 guid)
2554 GameObject * ret = ObjectAccessor::GetObjectInWorld(guid, (GameObject*)NULL);
2555 if(!ret)
2556 return NULL;
2557 if(ret->GetMapId() != GetId())
2558 return NULL;
2559 if(ret->GetInstanceId() != GetInstanceId())
2560 return NULL;
2561 return ret;
2564 DynamicObject*
2565 Map::GetDynamicObject(uint64 guid)
2567 DynamicObject * ret = ObjectAccessor::GetObjectInWorld(guid, (DynamicObject*)NULL);
2568 if(!ret)
2569 return NULL;
2570 if(ret->GetMapId() != GetId())
2571 return NULL;
2572 if(ret->GetInstanceId() != GetInstanceId())
2573 return NULL;
2574 return ret;