[7397] Implement above ground zone 4395 detection.
[AHbot.git] / src / game / Map.cpp
blob0796e3a4f7f0c6ca4d6e79f410a4ceb7e4c8f8d7
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_3.00";
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 GridMaps[x][y] = baseMap->GridMaps[x][y];
142 return;
145 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
146 if(GridMaps[x][y])
148 sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
149 delete (GridMaps[x][y]);
150 GridMaps[x][y]=NULL;
153 // map file name
154 char *tmp=NULL;
155 // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
156 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
157 tmp = new char[len];
158 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
159 sLog.outDetail("Loading map %s",tmp);
160 // loading data
161 FILE *pf=fopen(tmp,"rb");
162 if(!pf)
164 delete [] tmp;
165 return;
168 char magic[8];
169 fread(magic,1,8,pf);
170 if(strncmp(MAP_MAGIC,magic,8))
172 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
173 delete [] tmp;
174 fclose(pf); //close file before return
175 return;
177 delete [] tmp;
179 GridMap * buf= new GridMap;
180 fread(buf,1,sizeof(GridMap),pf);
181 fclose(pf);
183 GridMaps[x][y] = buf;
186 void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
188 LoadMap(mapid,instanceid,x,y);
189 if(instanceid == 0)
190 LoadVMap(x, y); // Only load the data for the base map
193 void Map::InitStateMachine()
195 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
196 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
197 si_GridStates[GRID_STATE_IDLE] = new IdleState;
198 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201 void Map::DeleteStateMachine()
203 delete si_GridStates[GRID_STATE_INVALID];
204 delete si_GridStates[GRID_STATE_ACTIVE];
205 delete si_GridStates[GRID_STATE_IDLE];
206 delete si_GridStates[GRID_STATE_REMOVAL];
209 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
210 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
211 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0), i_gridExpiry(expiry),
212 m_activeNonPlayersIter(m_activeNonPlayers.end())
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::EnsureGridLoaded(const Cell &cell, Player *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)
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("Active object 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);
392 if (player)
393 AddToGrid(player,grid,cell);
396 void
397 Map::LoadGrid(const Cell& cell, bool no_unload)
399 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
400 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
402 assert(grid != NULL);
403 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
405 ObjectGridLoader loader(*grid, this, cell);
406 loader.LoadN();
408 // Add resurrectable corpses to world object list in grid
409 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
411 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
412 if(no_unload)
413 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
415 LoadVMap(63-cell.GridX(),63-cell.GridY());
418 bool Map::Add(Player *player)
420 player->GetMapRef().link(this, player);
422 player->SetInstanceId(GetInstanceId());
424 // update player state for other player and visa-versa
425 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
426 Cell cell(p);
427 EnsureGridLoaded(cell, player);
428 player->AddToWorld();
430 SendInitSelf(player);
431 SendInitTransports(player);
433 UpdatePlayerVisibility(player,cell,p);
434 UpdateObjectsVisibilityFor(player,cell,p);
436 AddNotifier(player,cell,p);
437 return true;
440 template<class T>
441 void
442 Map::Add(T *obj)
444 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
446 assert(obj);
448 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
450 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);
451 return;
454 Cell cell(p);
455 if(obj->isActiveObject())
456 EnsureGridLoaded(cell);
457 else
458 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
460 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
461 assert( grid != NULL );
463 AddToGrid(obj,grid,cell);
464 obj->AddToWorld();
466 if(obj->isActiveObject())
467 AddToActive(obj);
469 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
471 UpdateObjectVisibility(obj,cell,p);
473 AddNotifier(obj,cell,p);
476 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
478 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
480 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
482 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);
483 return;
486 Cell cell(p);
487 cell.data.Part.reserved = ALL_DISTRICT;
489 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
490 return;
492 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
493 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
494 CellLock<ReadGuard> cell_lock(cell, p);
495 cell_lock->Visit(cell_lock, message, *this);
498 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
500 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->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: 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);
505 return;
508 Cell cell(p);
509 cell.data.Part.reserved = ALL_DISTRICT;
510 cell.SetNoCreate();
512 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
513 return;
515 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
516 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
517 CellLock<ReadGuard> cell_lock(cell, p);
518 cell_lock->Visit(cell_lock, message, *this);
521 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
523 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
525 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
527 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);
528 return;
531 Cell cell(p);
532 cell.data.Part.reserved = ALL_DISTRICT;
534 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
535 return;
537 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
538 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
539 CellLock<ReadGuard> cell_lock(cell, p);
540 cell_lock->Visit(cell_lock, message, *this);
543 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
545 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
547 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
549 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);
550 return;
553 Cell cell(p);
554 cell.data.Part.reserved = ALL_DISTRICT;
555 cell.SetNoCreate();
557 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
558 return;
560 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
561 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
562 CellLock<ReadGuard> cell_lock(cell, p);
563 cell_lock->Visit(cell_lock, message, *this);
566 bool Map::loaded(const GridPair &p) const
568 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
571 void Map::Update(const uint32 &t_diff)
573 resetMarkedCells();
575 MaNGOS::ObjectUpdater updater(t_diff);
576 // for creature
577 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
578 // for pets
579 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
581 // the player iterator is stored in the map object
582 // to make sure calls to Map::Remove don't invalidate it
583 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
585 Player* plr = m_mapRefIter->getSource();
587 if(!plr->IsInWorld())
588 continue;
590 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
592 // Check for correctness of standing_cell, it also avoids problems with update_cell
593 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
594 continue;
596 // the overloaded operators handle range checking
597 // so ther's no need for range checking inside the loop
598 CellPair begin_cell(standing_cell), end_cell(standing_cell);
599 begin_cell << 1; begin_cell -= 1; // upper left
600 end_cell >> 1; end_cell += 1; // lower right
602 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
604 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
606 // marked cells are those that have been visited
607 // don't visit the same cell twice
608 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
609 if(!isCellMarked(cell_id))
611 markCell(cell_id);
612 CellPair pair(x,y);
613 Cell cell(pair);
614 cell.data.Part.reserved = CENTER_DISTRICT;
615 cell.SetNoCreate();
616 CellLock<NullGuard> cell_lock(cell, pair);
617 cell_lock->Visit(cell_lock, grid_object_update, *this);
618 cell_lock->Visit(cell_lock, world_object_update, *this);
624 // non-player active objects
625 if(!m_activeNonPlayers.empty())
627 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
629 // skip not in world
630 WorldObject* obj = *m_activeNonPlayersIter;
632 // step before processing, in this case if Map::Remove remove next object we correctly
633 // step to next-next, and if we step to end() then newly added objects can wait next update.
634 ++m_activeNonPlayersIter;
636 if(!obj->IsInWorld())
637 continue;
639 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
641 // Check for correctness of standing_cell, it also avoids problems with update_cell
642 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
643 continue;
645 // the overloaded operators handle range checking
646 // so ther's no need for range checking inside the loop
647 CellPair begin_cell(standing_cell), end_cell(standing_cell);
648 begin_cell << 1; begin_cell -= 1; // upper left
649 end_cell >> 1; end_cell += 1; // lower right
651 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
653 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
655 // marked cells are those that have been visited
656 // don't visit the same cell twice
657 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
658 if(!isCellMarked(cell_id))
660 markCell(cell_id);
661 CellPair pair(x,y);
662 Cell cell(pair);
663 cell.data.Part.reserved = CENTER_DISTRICT;
664 cell.SetNoCreate();
665 CellLock<NullGuard> cell_lock(cell, pair);
666 cell_lock->Visit(cell_lock, grid_object_update, *this);
667 cell_lock->Visit(cell_lock, world_object_update, *this);
674 // 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 !
675 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
676 if (IsBattleGroundOrArena())
677 return;
679 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
681 NGridType *grid = i->getSource();
682 GridInfo *info = i->getSource()->getGridInfoRef();
683 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
684 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
685 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
689 void Map::Remove(Player *player, bool remove)
691 // this may be called during Map::Update
692 // after decrement+unlink, ++m_mapRefIter will continue correctly
693 // when the first element of the list is being removed
694 // nocheck_prev will return the padding element of the RefManager
695 // instead of NULL in the case of prev
696 if(m_mapRefIter == player->GetMapRef())
697 m_mapRefIter = m_mapRefIter->nocheck_prev();
698 player->GetMapRef().unlink();
699 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
700 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
702 // invalid coordinates
703 player->RemoveFromWorld();
705 if( remove )
706 DeleteFromWorld(player);
708 return;
711 Cell cell(p);
713 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
715 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
716 return;
719 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
720 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
721 assert(grid != NULL);
723 player->RemoveFromWorld();
724 RemoveFromGrid(player,grid,cell);
726 SendRemoveTransports(player);
728 UpdateObjectsVisibilityFor(player,cell,p);
730 if( remove )
731 DeleteFromWorld(player);
734 bool Map::RemoveBones(uint64 guid, float x, float y)
736 if (IsRemovalGrid(x, y))
738 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
739 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
740 corpse->DeleteBonesFromWorld();
741 else
742 return false;
744 return true;
747 template<class T>
748 void
749 Map::Remove(T *obj, bool remove)
751 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
752 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
754 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);
755 return;
758 Cell cell(p);
759 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
760 return;
762 DEBUG_LOG("Remove object " I64FMT " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
763 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
764 assert( grid != NULL );
766 if(obj->isActiveObject())
767 RemoveFromActive(obj);
769 obj->RemoveFromWorld();
770 RemoveFromGrid(obj,grid,cell);
772 UpdateObjectVisibility(obj,cell,p);
774 if( remove )
776 // if option set then object already saved at this moment
777 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
778 obj->SaveRespawnTime();
779 DeleteFromWorld(obj);
783 void
784 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
786 assert(player);
788 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
789 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
791 Cell old_cell(old_val);
792 Cell new_cell(new_val);
793 new_cell |= old_cell;
794 bool same_cell = (new_cell == old_cell);
796 player->Relocate(x, y, z, orientation);
798 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
800 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());
802 // update player position for group at taxi flight
803 if(player->GetGroup() && player->isInFlight())
804 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
806 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
807 RemoveFromGrid(player, oldGrid,old_cell);
808 if( !old_cell.DiffGrid(new_cell) )
809 AddToGrid(player, oldGrid,new_cell);
810 else
811 EnsureGridLoaded(new_cell, player);
814 // if move then update what player see and who seen
815 UpdatePlayerVisibility(player,new_cell,new_val);
816 UpdateObjectsVisibilityFor(player,new_cell,new_val);
817 PlayerRelocationNotify(player,new_cell,new_val);
818 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
819 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
821 ResetGridExpiry(*newGrid, 0.1f);
822 newGrid->SetGridState(GRID_STATE_ACTIVE);
826 void
827 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
829 assert(CheckGridIntegrity(creature,false));
831 Cell old_cell = creature->GetCurrentCell();
833 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
834 Cell new_cell(new_val);
836 // delay creature move for grid/cell to grid/cell moves
837 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
839 #ifdef MANGOS_DEBUG
840 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
841 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());
842 #endif
843 AddCreatureToMoveList(creature,x,y,z,ang);
844 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
846 else
848 creature->Relocate(x, y, z, ang);
849 CreatureRelocationNotify(creature,new_cell,new_val);
851 assert(CheckGridIntegrity(creature,true));
854 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
856 if(!c)
857 return;
859 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
862 void Map::MoveAllCreaturesInMoveList()
864 while(!i_creaturesToMove.empty())
866 // get data and remove element;
867 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
868 Creature* c = iter->first;
869 CreatureMover cm = iter->second;
870 i_creaturesToMove.erase(iter);
872 // calculate cells
873 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
874 Cell new_cell(new_val);
876 // do move or do move to respawn or remove creature if previous all fail
877 if(CreatureCellRelocation(c,new_cell))
879 // update pos
880 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
881 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
883 else
885 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
886 // creature coordinates will be updated and notifiers send
887 if(!CreatureRespawnRelocation(c))
889 // ... or unload (if respawn grid also not loaded)
890 #ifdef MANGOS_DEBUG
891 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
892 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
893 #endif
894 c->CleanupsBeforeDelete();
895 AddObjectToRemoveList(c);
901 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
903 Cell const& old_cell = c->GetCurrentCell();
904 if(!old_cell.DiffGrid(new_cell) ) // in same grid
906 // if in same cell then none do
907 if(old_cell.DiffCell(new_cell))
909 #ifdef MANGOS_DEBUG
910 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
911 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());
912 #endif
914 if( !old_cell.DiffGrid(new_cell) )
916 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
917 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
918 c->SetCurrentCell(new_cell);
921 else
923 #ifdef MANGOS_DEBUG
924 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
925 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());
926 #endif
929 return true;
932 // in diff. grids but active creature
933 if(c->isActiveObject())
935 EnsureGridLoaded(new_cell);
937 #ifdef MANGOS_DEBUG
938 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
939 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());
940 #endif
942 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
943 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
945 return true;
948 // in diff. loaded grid normal creature
949 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
951 #ifdef MANGOS_DEBUG
952 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
953 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());
954 #endif
956 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
958 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
959 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
962 return true;
965 // fail to move: normal creature attempt move to unloaded grid
966 #ifdef MANGOS_DEBUG
967 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
968 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());
969 #endif
970 return false;
973 bool Map::CreatureRespawnRelocation(Creature *c)
975 float resp_x, resp_y, resp_z, resp_o;
976 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
978 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
979 Cell resp_cell(resp_val);
981 c->CombatStop();
982 c->GetMotionMaster()->Clear();
984 #ifdef MANGOS_DEBUG
985 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
986 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());
987 #endif
989 // teleport it to respawn point (like normal respawn if player see)
990 if(CreatureCellRelocation(c,resp_cell))
992 c->Relocate(resp_x, resp_y, resp_z, resp_o);
993 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
994 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
995 return true;
997 else
998 return false;
1001 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
1003 NGridType *grid = getNGrid(x, y);
1004 assert( grid != NULL);
1007 if(!pForce && ActiveObjectsNearGrid(x, y) )
1008 return false;
1010 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
1011 ObjectGridUnloader unloader(*grid);
1013 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
1014 // Must know real mob position before move
1015 DoDelayedMovesAndRemoves();
1017 // move creatures to respawn grids if this is diff.grid or to remove list
1018 unloader.MoveToRespawnN();
1020 // Finish creature moves, remove and delete all creatures with delayed remove before unload
1021 DoDelayedMovesAndRemoves();
1023 unloader.UnloadN();
1024 delete getNGrid(x, y);
1025 setNGrid(NULL, x, y);
1027 int gx=63-x;
1028 int gy=63-y;
1030 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1031 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1033 if (i_InstanceId == 0)
1035 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
1036 // x and y are swapped
1037 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
1039 else
1040 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
1041 GridMaps[gx][gy] = NULL;
1043 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1044 return true;
1047 void Map::UnloadAll(bool pForce)
1049 // clear all delayed moves, useless anyway do this moves before map unload.
1050 i_creaturesToMove.clear();
1052 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1054 NGridType &grid(*i->getSource());
1055 ++i;
1056 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1060 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1062 GridPair p = MaNGOS::ComputeGridPair(x, y);
1064 // half opt method
1065 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1066 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1068 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
1069 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
1071 // ensure GridMap is loaded
1072 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1074 // find raw .map surface under Z coordinates
1075 float mapHeight;
1076 if(GridMap* gmap = GridMaps[gx][gy])
1078 int lx_int = (int)lx;
1079 int ly_int = (int)ly;
1080 lx -= lx_int;
1081 ly -= ly_int;
1083 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1084 // +--------------> X
1085 // | h1-------h2 Coordinates is:
1086 // | | \ 1 / | h1 0,0
1087 // | | \ / | h2 0,1
1088 // | | 2 h5 3 | h3 1,0
1089 // | | / \ | h4 1,1
1090 // | | / 4 \ | h5 1/2,1/2
1091 // | h3-------h4
1092 // V Y
1093 // For find height need
1094 // 1 - detect triangle
1095 // 2 - solve linear equation from triangle points
1097 // Calculate coefficients for solve h = a*x + b*y + c
1098 float a,b,c;
1099 // Select triangle:
1100 if (lx+ly < 1)
1102 if (lx > ly)
1104 // 1 triangle (h1, h2, h5 points)
1105 float h1 = gmap->v9[lx_int][ly_int];
1106 float h2 = gmap->v9[lx_int+1][ly_int];
1107 float h5 = 2 * gmap->v8[lx_int][ly_int];
1108 a = h2-h1;
1109 b = h5-h1-h2;
1110 c = h1;
1112 else
1114 // 2 triangle (h1, h3, h5 points)
1115 float h1 = gmap->v9[lx_int][ly_int];
1116 float h3 = gmap->v9[lx_int][ly_int+1];
1117 float h5 = 2 * gmap->v8[lx_int][ly_int];
1118 a = h5 - h1 - h3;
1119 b = h3 - h1;
1120 c = h1;
1123 else
1125 if (lx > ly)
1127 // 3 triangle (h2, h4, h5 points)
1128 float h2 = gmap->v9[lx_int+1][ly_int];
1129 float h4 = gmap->v9[lx_int+1][ly_int+1];
1130 float h5 = 2 * gmap->v8[lx_int][ly_int];
1131 a = h2 + h4 - h5;
1132 b = h4 - h2;
1133 c = h5 - h4;
1135 else
1137 // 4 triangle (h3, h4, h5 points)
1138 float h3 = gmap->v9[lx_int][ly_int+1];
1139 float h4 = gmap->v9[lx_int+1][ly_int+1];
1140 float h5 = 2 * gmap->v8[lx_int][ly_int];
1141 a = h4 - h3;
1142 b = h3 + h4 - h5;
1143 c = h5 - h4;
1146 // Calculate height
1147 float _mapheight = a * lx + b * ly + c;
1149 // look from a bit higher pos to find the floor, ignore under surface case
1150 if(z + 2.0f > _mapheight)
1151 mapHeight = _mapheight;
1152 else
1153 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1155 else
1156 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1158 float vmapHeight;
1159 if(pUseVmaps)
1161 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1162 if(vmgr->isHeightCalcEnabled())
1164 // look from a bit higher pos to find the floor
1165 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1167 else
1168 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1170 else
1171 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1173 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1174 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1176 if( vmapHeight > INVALID_HEIGHT )
1178 if( mapHeight > INVALID_HEIGHT )
1180 // we have mapheight and vmapheight and must select more appropriate
1182 // we are already under the surface or vmap height above map heigt
1183 // or if the distance of the vmap height is less the land height distance
1184 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1185 return vmapHeight;
1186 else
1187 return mapHeight; // better use .map surface height
1190 else
1191 return vmapHeight; // we have only vmapHeight (if have)
1193 else
1195 if(!pUseVmaps)
1196 return mapHeight; // explicitly use map data (if have)
1197 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1198 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1199 else
1200 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1204 uint16 Map::GetAreaFlag(float x, float y, float z) const
1206 //local x,y coords
1207 float lx,ly;
1208 int gx,gy;
1209 GridPair p = MaNGOS::ComputeGridPair(x, y);
1211 // half opt method
1212 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1213 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1215 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1216 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1217 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1219 // ensure GridMap is loaded
1220 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1222 uint16 areaflag;
1223 if(GridMaps[gx][gy])
1224 areaflag = GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1225 // this used while not all *.map files generated (instances)
1226 else
1227 areaflag = GetAreaFlagByMapId(i_id);
1229 //FIXME: some hacks for areas above or underground for ground area
1230 // required for area specific spells/etc, until map/vmap data
1231 // not provided correct areaflag with this hacks
1232 switch(areaflag)
1234 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1235 case 1984: // Plaguelands: The Scarlet Enclave
1236 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1237 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1238 if(z > 350.0f) areaflag = 2048; break;
1239 // Acherus: The Ebon Hold (Eastern Plaguelands)
1240 case 856: // The Noxious Glade (Eastern Plaguelands)
1241 case 2456: // Death's Breach (Eastern Plaguelands)
1242 if(z > 350.0f) areaflag = 1950; break;
1243 // Dalaran
1244 case 1593:
1245 case 2484:
1246 case 2492:
1247 if( (x < 6116 && x > 5568) && (y < 982 && y > 282) && z > 563.0f) areaflag = 2153; break;
1250 return areaflag;
1253 uint8 Map::GetTerrainType(float x, float y ) const
1255 //local x,y coords
1256 float lx,ly;
1257 int gx,gy;
1259 // half opt method
1260 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1261 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1263 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1264 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1266 // ensure GridMap is loaded
1267 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1269 if(GridMaps[gx][gy])
1270 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1271 else
1272 return 0;
1275 float Map::GetWaterLevel(float x, float y ) const
1277 //local x,y coords
1278 float lx,ly;
1279 int gx,gy;
1281 // half opt method
1282 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1283 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1285 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1286 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1288 // ensure GridMap is loaded
1289 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1291 if(GridMaps[gx][gy])
1292 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1293 else
1294 return 0;
1297 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1299 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1301 if (entry)
1302 return entry->ID;
1303 else
1304 return 0;
1307 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1309 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1311 if( entry )
1312 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1313 else
1314 return 0;
1317 bool Map::IsInWater(float x, float y, float pZ) const
1319 // This method is called too often to use vamps for that (4. parameter = false).
1320 // The pZ pos is taken anyway for future use
1321 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1323 // underground or instance without vmap
1324 if(z <= INVALID_HEIGHT)
1325 return false;
1327 float water_z = GetWaterLevel(x,y);
1328 uint8 flag = GetTerrainType(x,y);
1329 return (z < (water_z-2)) && (flag & 0x01);
1332 bool Map::IsUnderWater(float x, float y, float z) const
1334 float water_z = GetWaterLevel(x,y);
1335 uint8 flag = GetTerrainType(x,y);
1336 return (z < (water_z-2)) && (flag & 0x01);
1339 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1341 Cell const& cur_cell = c->GetCurrentCell();
1343 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1344 Cell xy_cell(xy_val);
1345 if(xy_cell != cur_cell)
1347 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]",
1348 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1349 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1350 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1351 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1352 return true; // not crash at error, just output error in debug mode
1355 return true;
1358 const char* Map::GetMapName() const
1360 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1363 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1365 cell.data.Part.reserved = ALL_DISTRICT;
1366 cell.SetNoCreate();
1367 MaNGOS::VisibleChangesNotifier notifier(*obj);
1368 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1369 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1370 cell_lock->Visit(cell_lock, player_notifier, *this);
1373 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1375 cell.data.Part.reserved = ALL_DISTRICT;
1377 MaNGOS::PlayerNotifier pl_notifier(*player);
1378 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1380 CellLock<ReadGuard> cell_lock(cell, cellpair);
1381 cell_lock->Visit(cell_lock, player_notifier, *this);
1384 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1386 MaNGOS::VisibleNotifier notifier(*player);
1388 cell.data.Part.reserved = ALL_DISTRICT;
1389 cell.SetNoCreate();
1390 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1391 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1392 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1393 cell_lock->Visit(cell_lock, world_notifier, *this);
1394 cell_lock->Visit(cell_lock, grid_notifier, *this);
1396 // send data
1397 notifier.Notify();
1400 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1402 CellLock<ReadGuard> cell_lock(cell, cellpair);
1403 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1404 cell.data.Part.reserved = ALL_DISTRICT;
1406 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1407 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1409 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1410 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1413 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1415 CellLock<ReadGuard> cell_lock(cell, cellpair);
1416 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1417 cell.data.Part.reserved = ALL_DISTRICT;
1418 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1420 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1421 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1423 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1424 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1427 void Map::SendInitSelf( Player * player )
1429 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1431 UpdateData data;
1433 bool hasTransport = false;
1435 // attach to player data current transport data
1436 if(Transport* transport = player->GetTransport())
1438 hasTransport = true;
1439 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1442 // build data for self presence in world at own client (one time for map)
1443 player->BuildCreateUpdateBlockForPlayer(&data, player);
1445 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1446 if(Transport* transport = player->GetTransport())
1448 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1450 if(player!=(*itr) && player->HaveAtClient(*itr))
1452 hasTransport = true;
1453 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1458 WorldPacket packet;
1459 data.BuildPacket(&packet, hasTransport);
1460 player->GetSession()->SendPacket(&packet);
1463 void Map::SendInitTransports( Player * player )
1465 // Hack to send out transports
1466 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1468 // no transports at map
1469 if (tmap.find(player->GetMapId()) == tmap.end())
1470 return;
1472 UpdateData transData;
1474 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1476 bool hasTransport = false;
1478 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1480 if((*i) != player->GetTransport()) // send data for current transport in other place
1482 hasTransport = true;
1483 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1487 WorldPacket packet;
1488 transData.BuildPacket(&packet, hasTransport);
1489 player->GetSession()->SendPacket(&packet);
1492 void Map::SendRemoveTransports( Player * player )
1494 // Hack to send out transports
1495 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1497 // no transports at map
1498 if (tmap.find(player->GetMapId()) == tmap.end())
1499 return;
1501 UpdateData transData;
1503 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1505 // except used transport
1506 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1507 if(player->GetTransport() != (*i))
1508 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1510 WorldPacket packet;
1511 transData.BuildPacket(&packet);
1512 player->GetSession()->SendPacket(&packet);
1515 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1517 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1519 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1520 assert(false);
1522 i_grids[x][y] = grid;
1525 void Map::DoDelayedMovesAndRemoves()
1527 MoveAllCreaturesInMoveList();
1528 RemoveAllObjectsInRemoveList();
1531 void Map::AddObjectToRemoveList(WorldObject *obj)
1533 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1535 i_objectsToRemove.insert(obj);
1536 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1539 void Map::RemoveAllObjectsInRemoveList()
1541 if(i_objectsToRemove.empty())
1542 return;
1544 //sLog.outDebug("Object remover 1 check.");
1545 while(!i_objectsToRemove.empty())
1547 WorldObject* obj = *i_objectsToRemove.begin();
1548 i_objectsToRemove.erase(i_objectsToRemove.begin());
1550 switch(obj->GetTypeId())
1552 case TYPEID_CORPSE:
1554 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1555 if (!corpse)
1556 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1557 else
1558 Remove(corpse,true);
1559 break;
1561 case TYPEID_DYNAMICOBJECT:
1562 Remove((DynamicObject*)obj,true);
1563 break;
1564 case TYPEID_GAMEOBJECT:
1565 Remove((GameObject*)obj,true);
1566 break;
1567 case TYPEID_UNIT:
1568 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1569 // make sure that like sources auras/etc removed before destructor start
1570 ((Creature*)obj)->CleanupsBeforeDelete ();
1571 Remove((Creature*)obj,true);
1572 break;
1573 default:
1574 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1575 break;
1578 //sLog.outDebug("Object remover 2 check.");
1581 uint32 Map::GetPlayersCountExceptGMs() const
1583 uint32 count = 0;
1584 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1585 if(!itr->getSource()->isGameMaster())
1586 ++count;
1587 return count;
1590 void Map::SendToPlayers(WorldPacket const* data) const
1592 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1593 itr->getSource()->GetSession()->SendPacket(data);
1596 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
1598 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
1599 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
1600 cell_min << 2;
1601 cell_min -= 2;
1602 cell_max >> 2;
1603 cell_max += 2;
1605 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
1607 Player* plr = iter->getSource();
1609 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
1610 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1611 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1612 return true;
1615 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
1617 WorldObject* obj = *iter;
1619 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
1620 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1621 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1622 return true;
1625 return false;
1628 void Map::AddToActive( Creature* c )
1630 AddToActiveHelper(c);
1632 // also not allow unloading spawn grid to prevent creating creature clone at load
1633 if(!c->isPet() && c->GetDBTableGUIDLow())
1635 float x,y,z;
1636 c->GetRespawnCoord(x,y,z);
1637 GridPair p = MaNGOS::ComputeGridPair(x, y);
1638 if(getNGrid(p.x_coord, p.y_coord))
1639 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
1640 else
1642 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
1643 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
1644 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
1649 void Map::RemoveFromActive( Creature* c )
1651 RemoveFromActiveHelper(c);
1653 // also allow unloading spawn grid
1654 if(!c->isPet() && c->GetDBTableGUIDLow())
1656 float x,y,z;
1657 c->GetRespawnCoord(x,y,z);
1658 GridPair p = MaNGOS::ComputeGridPair(x, y);
1659 if(getNGrid(p.x_coord, p.y_coord))
1660 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
1661 else
1663 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
1664 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
1665 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
1670 template void Map::Add(Corpse *);
1671 template void Map::Add(Creature *);
1672 template void Map::Add(GameObject *);
1673 template void Map::Add(DynamicObject *);
1675 template void Map::Remove(Corpse *,bool);
1676 template void Map::Remove(Creature *,bool);
1677 template void Map::Remove(GameObject *, bool);
1678 template void Map::Remove(DynamicObject *, bool);
1680 /* ******* Dungeon Instance Maps ******* */
1682 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1683 : Map(id, expiry, InstanceId, SpawnMode),
1684 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
1685 i_data(NULL), i_script_id(0)
1687 // the timer is started by default, and stopped when the first player joins
1688 // this make sure it gets unloaded if for some reason no player joins
1689 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1692 InstanceMap::~InstanceMap()
1694 if(i_data)
1696 delete i_data;
1697 i_data = NULL;
1702 Do map specific checks to see if the player can enter
1704 bool InstanceMap::CanEnter(Player *player)
1706 if(player->GetMapRef().getTarget() == this)
1708 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1709 assert(false);
1710 return false;
1713 // cannot enter if the instance is full (player cap), GMs don't count
1714 uint32 maxPlayers = GetMaxPlayers();
1715 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
1717 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
1718 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1719 return false;
1722 // cannot enter while players in the instance are in combat
1723 Group *pGroup = player->GetGroup();
1724 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1726 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1727 return false;
1730 return Map::CanEnter(player);
1734 Do map specific checks and add the player to the map if successful.
1736 bool InstanceMap::Add(Player *player)
1738 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1739 // GMs still can teleport player in instance.
1740 // Is it needed?
1743 Guard guard(*this);
1744 if(!CanEnter(player))
1745 return false;
1747 // get or create an instance save for the map
1748 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1749 if(!mapSave)
1751 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1752 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1755 // check for existing instance binds
1756 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1757 if(playerBind && playerBind->perm)
1759 // cannot enter other instances if bound permanently
1760 if(playerBind->save != mapSave)
1762 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());
1763 assert(false);
1766 else
1768 Group *pGroup = player->GetGroup();
1769 if(pGroup)
1771 // solo saves should be reset when entering a group
1772 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1773 if(playerBind)
1775 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());
1776 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());
1777 assert(false);
1779 // bind to the group or keep using the group save
1780 if(!groupBind)
1781 pGroup->BindToInstance(mapSave, false);
1782 else
1784 // cannot jump to a different instance without resetting it
1785 if(groupBind->save != mapSave)
1787 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());
1788 if(mapSave)
1789 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1790 else
1791 sLog.outError("MapSave NULL");
1792 if(groupBind->save)
1793 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1794 else
1795 sLog.outError("GroupBind save NULL");
1796 assert(false);
1798 // if the group/leader is permanently bound to the instance
1799 // players also become permanently bound when they enter
1800 if(groupBind->perm)
1802 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1803 data << uint32(0);
1804 player->GetSession()->SendPacket(&data);
1805 player->BindToInstance(mapSave, true);
1809 else
1811 // set up a solo bind or continue using it
1812 if(!playerBind)
1813 player->BindToInstance(mapSave, false);
1814 else
1815 // cannot jump to a different instance without resetting it
1816 assert(playerBind->save == mapSave);
1820 if(i_data) i_data->OnPlayerEnter(player);
1821 // for normal instances cancel the reset schedule when the
1822 // first player enters (no players yet)
1823 SetResetSchedule(false);
1825 player->SendInitWorldStates();
1826 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1827 // initialize unload state
1828 m_unloadTimer = 0;
1829 m_resetAfterUnload = false;
1830 m_unloadWhenEmpty = false;
1833 // this will acquire the same mutex so it cannot be in the previous block
1834 Map::Add(player);
1835 return true;
1838 void InstanceMap::Update(const uint32& t_diff)
1840 Map::Update(t_diff);
1842 if(i_data)
1843 i_data->Update(t_diff);
1846 void InstanceMap::Remove(Player *player, bool remove)
1848 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1849 //if last player set unload timer
1850 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
1851 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1852 Map::Remove(player, remove);
1853 // for normal instances schedule the reset after all players have left
1854 SetResetSchedule(true);
1857 void InstanceMap::CreateInstanceData(bool load)
1859 if(i_data != NULL)
1860 return;
1862 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1863 if (mInstance)
1865 i_script_id = mInstance->script_id;
1866 i_data = Script->CreateInstanceData(this);
1869 if(!i_data)
1870 return;
1872 if(load)
1874 // TODO: make a global storage for this
1875 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1876 if (result)
1878 Field* fields = result->Fetch();
1879 const char* data = fields[0].GetString();
1880 if(data)
1882 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
1883 i_data->Load(data);
1885 delete result;
1888 else
1890 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
1891 i_data->Initialize();
1896 Returns true if there are no players in the instance
1898 bool InstanceMap::Reset(uint8 method)
1900 // note: since the map may not be loaded when the instance needs to be reset
1901 // the instance must be deleted from the DB by InstanceSaveManager
1903 if(HavePlayers())
1905 if(method == INSTANCE_RESET_ALL)
1907 // notify the players to leave the instance so it can be reset
1908 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1909 itr->getSource()->SendResetFailedNotify(GetId());
1911 else
1913 if(method == INSTANCE_RESET_GLOBAL)
1915 // set the homebind timer for players inside (1 minute)
1916 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1917 itr->getSource()->m_InstanceValid = false;
1920 // the unload timer is not started
1921 // instead the map will unload immediately after the players have left
1922 m_unloadWhenEmpty = true;
1923 m_resetAfterUnload = true;
1926 else
1928 // unloaded at next update
1929 m_unloadTimer = MIN_UNLOAD_DELAY;
1930 m_resetAfterUnload = true;
1933 return m_mapRefManager.isEmpty();
1936 void InstanceMap::PermBindAllPlayers(Player *player)
1938 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1939 if(!save)
1941 sLog.outError("Cannot bind players, no instance save available for map!\n");
1942 return;
1945 Group *group = player->GetGroup();
1946 // group members outside the instance group don't get bound
1947 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1949 Player* plr = itr->getSource();
1950 // players inside an instance cannot be bound to other instances
1951 // some players may already be permanently bound, in this case nothing happens
1952 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1953 if(!bind || !bind->perm)
1955 plr->BindToInstance(save, true);
1956 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1957 data << uint32(0);
1958 plr->GetSession()->SendPacket(&data);
1961 // if the leader is not in the instance the group will not get a perm bind
1962 if(group && group->GetLeaderGUID() == plr->GetGUID())
1963 group->BindToInstance(save, true);
1967 time_t InstanceMap::GetResetTime()
1969 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1970 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1973 void InstanceMap::UnloadAll(bool pForce)
1975 if(HavePlayers())
1977 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1978 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1980 Player* plr = itr->getSource();
1981 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1985 if(m_resetAfterUnload == true)
1986 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1988 Map::UnloadAll(pForce);
1991 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
1993 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1994 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
1997 void InstanceMap::SetResetSchedule(bool on)
1999 // only for normal instances
2000 // the reset time is only scheduled when there are no payers inside
2001 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2002 if(!HavePlayers() && !IsRaid() && !IsHeroic())
2004 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2005 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2006 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
2010 uint32 InstanceMap::GetMaxPlayers() const
2012 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
2013 if(!iTemplate)
2014 return 0;
2015 return IsHeroic() ? iTemplate->maxPlayersHeroic : iTemplate->maxPlayers;
2018 /* ******* Battleground Instance Maps ******* */
2020 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
2021 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
2025 BattleGroundMap::~BattleGroundMap()
2029 bool BattleGroundMap::CanEnter(Player * player)
2031 if(player->GetMapRef().getTarget() == this)
2033 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2034 assert(false);
2035 return false;
2038 if(player->GetBattleGroundId() != GetInstanceId())
2039 return false;
2041 // player number limit is checked in bgmgr, no need to do it here
2043 return Map::CanEnter(player);
2046 bool BattleGroundMap::Add(Player * player)
2049 Guard guard(*this);
2050 if(!CanEnter(player))
2051 return false;
2052 // reset instance validity, battleground maps do not homebind
2053 player->m_InstanceValid = true;
2055 return Map::Add(player);
2058 void BattleGroundMap::Remove(Player *player, bool remove)
2060 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2061 Map::Remove(player, remove);
2064 void BattleGroundMap::SetUnload()
2066 m_unloadTimer = MIN_UNLOAD_DELAY;
2069 void BattleGroundMap::UnloadAll(bool pForce)
2071 while(HavePlayers())
2073 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2075 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2076 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2077 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2078 // note that this remove is not needed if the code works well in other places
2079 plr->GetMapRef().unlink();
2083 Map::UnloadAll(pForce);