[9581] Fixed apply damage reduction to melee/ranged damage.
[getmangos.git] / src / game / Map.cpp
bloba1e5a846acf00ef5d43e7827eced2c720c6c026b
1 /*
2 * Copyright (C) 2005-2010 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 "Vehicle.h"
22 #include "GridNotifiers.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"
37 #include "DBCEnums.h"
39 #include "MapInstanced.h"
40 #include "InstanceSaveMgr.h"
41 #include "VMapFactory.h"
43 GridState* si_GridStates[MAX_GRID_STATE];
45 static char const* MAP_MAGIC = "MAPS";
46 static char const* MAP_VERSION_MAGIC = "v1.1";
47 static char const* MAP_AREA_MAGIC = "AREA";
48 static char const* MAP_HEIGHT_MAGIC = "MHGT";
49 static char const* MAP_LIQUID_MAGIC = "MLIQ";
51 struct ScriptAction
53 uint64 sourceGUID;
54 uint64 targetGUID;
55 uint64 ownerGUID; // owner of source if source is item
56 ScriptInfo const* script; // pointer to static script data
59 Map::~Map()
61 ObjectAccessor::DelinkMap(this);
62 UnloadAll(true);
64 if(!m_scriptSchedule.empty())
65 sWorld.DecreaseScheduledScriptCount(m_scriptSchedule.size());
68 bool Map::ExistMap(uint32 mapid,int gx,int gy)
70 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
71 char* tmp = new char[len];
72 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
74 FILE *pf=fopen(tmp,"rb");
76 if(!pf)
78 sLog.outError("Check existing of map file '%s': not exist!",tmp);
79 delete[] tmp;
80 return false;
83 map_fileheader header;
84 fread(&header, sizeof(header), 1, pf);
85 if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) ||
86 header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC)) ||
87 !IsAcceptableClientBuild(header.buildMagic))
89 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
90 delete [] tmp;
91 fclose(pf); //close file before return
92 return false;
95 delete [] tmp;
96 fclose(pf);
97 return true;
100 bool Map::ExistVMap(uint32 mapid,int gx,int gy)
102 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
104 if(vmgr->isMapLoadingEnabled())
106 // x and y are swapped !! => fixed now
107 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
108 if(!exists)
110 std::string name = vmgr->getDirFileName(mapid,gx,gy);
111 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());
112 return false;
117 return true;
120 void Map::LoadVMap(int gx,int gy)
122 // x and y are swapped !!
123 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
124 switch(vmapLoadResult)
126 case VMAP::VMAP_LOAD_RESULT_OK:
127 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
128 break;
129 case VMAP::VMAP_LOAD_RESULT_ERROR:
130 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);
131 break;
132 case VMAP::VMAP_LOAD_RESULT_IGNORED:
133 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
134 break;
138 void Map::LoadMap(int gx,int gy, bool reload)
140 if( i_InstanceId != 0 )
142 if(GridMaps[gx][gy])
143 return;
145 // load grid map for base map
146 if (!m_parentMap->GridMaps[gx][gy])
147 m_parentMap->EnsureGridCreated(GridPair(63-gx,63-gy));
149 ((MapInstanced*)(m_parentMap))->AddGridMapReference(GridPair(gx,gy));
150 GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
151 return;
154 if(GridMaps[gx][gy] && !reload)
155 return;
157 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
158 if(GridMaps[gx][gy])
160 sLog.outDetail("Unloading already loaded map %u before reloading.",i_id);
161 delete (GridMaps[gx][gy]);
162 GridMaps[gx][gy]=NULL;
165 // map file name
166 char *tmp=NULL;
167 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
168 tmp = new char[len];
169 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),i_id,gx,gy);
170 sLog.outDetail("Loading map %s",tmp);
171 // loading data
172 GridMaps[gx][gy] = new GridMap();
173 if (!GridMaps[gx][gy]->loadData(tmp))
175 sLog.outError("Error load map file: \n %s\n", tmp);
177 delete [] tmp;
180 void Map::LoadMapAndVMap(int gx,int gy)
182 LoadMap(gx,gy);
183 if(i_InstanceId == 0)
184 LoadVMap(gx, gy); // Only load the data for the base map
187 void Map::InitStateMachine()
189 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
190 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
191 si_GridStates[GRID_STATE_IDLE] = new IdleState;
192 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
195 void Map::DeleteStateMachine()
197 delete si_GridStates[GRID_STATE_INVALID];
198 delete si_GridStates[GRID_STATE_ACTIVE];
199 delete si_GridStates[GRID_STATE_IDLE];
200 delete si_GridStates[GRID_STATE_REMOVAL];
203 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
204 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
205 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0),
206 m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE),
207 m_activeNonPlayersIter(m_activeNonPlayers.end()),
208 i_gridExpiry(expiry), m_parentMap(_parent ? _parent : this)
210 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
212 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
214 //z code
215 GridMaps[idx][j] =NULL;
216 setNGrid(NULL, idx, j);
219 ObjectAccessor::LinkMap(this);
221 //lets initialize visibility distance for map
222 Map::InitVisibilityDistance();
225 void Map::InitVisibilityDistance()
227 //init visibility for continents
228 m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents();
231 // Template specialization of utility methods
232 template<class T>
233 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
235 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
238 template<>
239 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
241 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
244 template<>
245 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
247 // add to world object registry in grid
248 if(obj->GetType()!=CORPSE_BONES)
250 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
252 // add to grid object store
253 else
255 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj);
259 template<>
260 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
262 // add to world object registry in grid
263 if(obj->isPet() || obj->isVehicle())
265 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj);
266 obj->SetCurrentCell(cell);
268 // add to grid object store
269 else
271 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj);
272 obj->SetCurrentCell(cell);
276 template<class T>
277 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
279 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj);
282 template<>
283 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
285 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
288 template<>
289 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
291 // remove from world object registry in grid
292 if(obj->GetType()!=CORPSE_BONES)
294 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
296 // remove from grid object store
297 else
299 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj);
303 template<>
304 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
306 // remove from world object registry in grid
307 if(obj->isPet() || obj->isVehicle())
309 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj);
311 // remove from grid object store
312 else
314 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj);
318 template<class T>
319 void Map::DeleteFromWorld(T* obj)
321 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
322 delete obj;
325 template<>
326 void Map::DeleteFromWorld(Player* pl)
328 sObjectAccessor.RemoveObject(pl);
329 delete pl;
332 template<class T>
333 void Map::AddNotifier(T* , Cell const& , CellPair const& )
337 template<>
338 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
340 PlayerRelocationNotify(obj,cell,cellpair);
343 template<>
344 void Map::AddNotifier(Creature* obj, Cell const&, CellPair const&)
346 obj->SetNeedNotify();
349 void
350 Map::EnsureGridCreated(const GridPair &p)
352 if(!getNGrid(p.x_coord, p.y_coord))
354 Guard guard(*this);
355 if(!getNGrid(p.x_coord, p.y_coord))
357 setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD)),
358 p.x_coord, p.y_coord);
360 // build a linkage between this map and NGridType
361 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
363 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
365 //z coord
366 int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
367 int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
369 if(!GridMaps[gx][gy])
370 LoadMapAndVMap(gx,gy);
375 void
376 Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
378 NGridType *grid;
380 if(EnsureGridLoaded(cell))
382 grid = getNGrid(cell.GridX(), cell.GridY());
384 if (player)
386 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);
388 else
390 DEBUG_LOG("Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
393 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
394 grid->SetGridState(GRID_STATE_ACTIVE);
396 else
397 grid = getNGrid(cell.GridX(), cell.GridY());
399 if (player)
400 AddToGrid(player,grid,cell);
403 bool Map::EnsureGridLoaded(const Cell &cell)
405 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
406 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
408 assert(grid != NULL);
409 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
411 ObjectGridLoader loader(*grid, this, cell);
412 loader.LoadN();
414 // Add resurrectable corpses to world object list in grid
415 sObjectAccessor.AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
417 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
418 return true;
421 return false;
424 void Map::LoadGrid(const Cell& cell, bool no_unload)
426 EnsureGridLoaded(cell);
428 if(no_unload)
429 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
432 bool Map::Add(Player *player)
434 player->GetMapRef().link(this, player);
435 player->SetMap(this);
437 // update player state for other player and visa-versa
438 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
439 Cell cell(p);
440 EnsureGridLoadedAtEnter(cell, player);
441 player->AddToWorld();
443 SendInitSelf(player);
444 SendInitTransports(player);
446 UpdatePlayerVisibility(player,cell,p);
447 UpdateObjectsVisibilityFor(player,cell,p);
449 AddNotifier(player,cell,p);
450 return true;
453 template<class T>
454 void
455 Map::Add(T *obj)
457 assert(obj);
459 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
460 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
462 sLog.outError("Map::Add: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
463 return;
466 obj->SetMap(this);
468 Cell cell(p);
469 if(obj->isActiveObject())
470 EnsureGridLoadedAtEnter(cell);
471 else
472 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
474 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
475 assert( grid != NULL );
477 AddToGrid(obj,grid,cell);
478 obj->AddToWorld();
480 if(obj->isActiveObject())
481 AddToActive(obj);
483 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
485 UpdateObjectVisibility(obj,cell,p);
487 AddNotifier(obj,cell,p);
490 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
492 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
494 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
496 sLog.outError("Map::MessageBroadcast: 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);
497 return;
500 Cell cell(p);
501 cell.data.Part.reserved = ALL_DISTRICT;
502 cell.SetNoCreate();
504 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
505 return;
507 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
508 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
509 cell.Visit(p, message, *this, *player, GetVisibilityDistance());
512 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
514 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
516 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
518 sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
519 return;
522 Cell cell(p);
523 cell.data.Part.reserved = ALL_DISTRICT;
524 cell.SetNoCreate();
526 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
527 return;
529 //TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
530 //we have alot of blinking mobs because monster move packet send is broken...
531 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
532 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
533 cell.Visit(p, message, *this, *obj, GetVisibilityDistance());
536 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
538 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
540 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
542 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);
543 return;
546 Cell cell(p);
547 cell.data.Part.reserved = ALL_DISTRICT;
548 cell.SetNoCreate();
550 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
551 return;
553 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
554 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
555 cell.Visit(p, message, *this, *player, dist);
558 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
560 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
562 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
564 sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
565 return;
568 Cell cell(p);
569 cell.data.Part.reserved = ALL_DISTRICT;
570 cell.SetNoCreate();
572 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
573 return;
575 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
576 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
577 cell.Visit(p, message, *this, *obj, dist);
580 bool Map::loaded(const GridPair &p) const
582 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
585 void Map::Update(const uint32 &t_diff)
587 /// update players at tick
588 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
590 Player* plr = m_mapRefIter->getSource();
591 if(plr && plr->IsInWorld())
592 plr->Update(t_diff);
595 /// update active cells around players and active objects
596 resetMarkedCells();
598 MaNGOS::ObjectUpdater updater(t_diff);
599 // for creature
600 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
601 // for pets
602 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
604 // the player iterator is stored in the map object
605 // to make sure calls to Map::Remove don't invalidate it
606 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
608 Player* plr = m_mapRefIter->getSource();
610 if(!plr->IsInWorld())
611 continue;
613 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
615 // Check for correctness of standing_cell, it also avoids problems with update_cell
616 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
617 continue;
619 // the overloaded operators handle range checking
620 // so ther's no need for range checking inside the loop
621 CellPair begin_cell(standing_cell), end_cell(standing_cell);
622 //lets update mobs/objects in ALL visible cells around player!
623 CellArea area = Cell::CalculateCellArea(*plr, GetVisibilityDistance());
624 area.ResizeBorders(begin_cell, end_cell);
626 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
628 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
630 // marked cells are those that have been visited
631 // don't visit the same cell twice
632 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
633 if(!isCellMarked(cell_id))
635 markCell(cell_id);
636 CellPair pair(x,y);
637 Cell cell(pair);
638 cell.data.Part.reserved = CENTER_DISTRICT;
639 cell.SetNoCreate();
640 cell.Visit(pair, grid_object_update, *this);
641 cell.Visit(pair, world_object_update, *this);
647 // non-player active objects
648 if(!m_activeNonPlayers.empty())
650 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
652 // skip not in world
653 WorldObject* obj = *m_activeNonPlayersIter;
655 // step before processing, in this case if Map::Remove remove next object we correctly
656 // step to next-next, and if we step to end() then newly added objects can wait next update.
657 ++m_activeNonPlayersIter;
659 if(!obj->IsInWorld())
660 continue;
662 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
664 // Check for correctness of standing_cell, it also avoids problems with update_cell
665 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
666 continue;
668 // the overloaded operators handle range checking
669 // so ther's no need for range checking inside the loop
670 CellPair begin_cell(standing_cell), end_cell(standing_cell);
671 begin_cell << 1; begin_cell -= 1; // upper left
672 end_cell >> 1; end_cell += 1; // lower right
674 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
676 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
678 // marked cells are those that have been visited
679 // don't visit the same cell twice
680 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
681 if(!isCellMarked(cell_id))
683 markCell(cell_id);
684 CellPair pair(x,y);
685 Cell cell(pair);
686 cell.data.Part.reserved = CENTER_DISTRICT;
687 cell.SetNoCreate();
688 cell.Visit(pair, grid_object_update, *this);
689 cell.Visit(pair, world_object_update, *this);
696 // Send world objects and item update field changes
697 SendObjectUpdates();
699 // 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 !
700 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
701 if (!IsBattleGroundOrArena())
703 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
705 NGridType *grid = i->getSource();
706 GridInfo *info = i->getSource()->getGridInfoRef();
707 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
708 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
709 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
713 ///- Process necessary scripts
714 if (!m_scriptSchedule.empty())
715 ScriptsProcess();
718 void Map::Remove(Player *player, bool remove)
720 if(remove)
721 player->CleanupsBeforeDelete();
722 else
723 player->RemoveFromWorld();
725 // this may be called during Map::Update
726 // after decrement+unlink, ++m_mapRefIter will continue correctly
727 // when the first element of the list is being removed
728 // nocheck_prev will return the padding element of the RefManager
729 // instead of NULL in the case of prev
730 if(m_mapRefIter == player->GetMapRef())
731 m_mapRefIter = m_mapRefIter->nocheck_prev();
732 player->GetMapRef().unlink();
733 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
734 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
736 // invalid coordinates
737 player->ResetMap();
739 if( remove )
740 DeleteFromWorld(player);
742 return;
745 Cell cell(p);
747 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
749 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
750 return;
753 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
754 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
755 assert(grid != NULL);
757 RemoveFromGrid(player,grid,cell);
759 SendRemoveTransports(player);
760 UpdateObjectsVisibilityFor(player,cell,p);
762 player->ResetMap();
763 if( remove )
764 DeleteFromWorld(player);
767 bool Map::RemoveBones(uint64 guid, float x, float y)
769 if (IsRemovalGrid(x, y))
771 Corpse* corpse = ObjectAccessor::GetCorpseInMap(guid,GetId());
772 if (!corpse)
773 return false;
775 CellPair p = MaNGOS::ComputeCellPair(x,y);
776 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
778 sLog.outError("Map::RemoveBones: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord);
779 return false;
782 CellPair q = MaNGOS::ComputeCellPair(corpse->GetPositionX(),corpse->GetPositionY());
783 if(q.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || q.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
785 sLog.outError("Map::RemoveBones: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", corpse->GetGUIDLow(), corpse->GetTypeId(), corpse->GetPositionX(), corpse->GetPositionY(), q.x_coord, q.y_coord);
786 return false;
789 int32 dx = int32(p.x_coord) - int32(q.x_coord);
790 int32 dy = int32(p.y_coord) - int32(q.y_coord);
792 if (dx <= -2 || dx >= 2 || dy <= -2 || dy >= 2)
793 return false;
795 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
796 corpse->DeleteBonesFromWorld();
797 else
798 return false;
800 return true;
803 template<class T>
804 void
805 Map::Remove(T *obj, bool remove)
807 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
808 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
810 sLog.outError("Map::Remove: Object (GUID: %u TypeId:%u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
811 return;
814 Cell cell(p);
815 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
816 return;
818 DEBUG_LOG("Remove object (GUID: %u TypeId:%u) from grid[%u,%u]", obj->GetGUIDLow(), obj->GetTypeId(), cell.data.Part.grid_x, cell.data.Part.grid_y);
819 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
820 assert( grid != NULL );
822 if(obj->isActiveObject())
823 RemoveFromActive(obj);
825 if(remove)
826 obj->CleanupsBeforeDelete();
827 else
828 obj->RemoveFromWorld();
830 RemoveFromGrid(obj,grid,cell);
832 UpdateObjectVisibility(obj,cell,p);
834 obj->ResetMap();
835 if( remove )
837 // if option set then object already saved at this moment
838 if(!sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATLY))
839 obj->SaveRespawnTime();
840 DeleteFromWorld(obj);
844 void
845 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
847 assert(player);
849 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
850 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
852 Cell old_cell(old_val);
853 Cell new_cell(new_val);
854 new_cell |= old_cell;
855 bool same_cell = (new_cell == old_cell);
857 player->Relocate(x, y, z, orientation);
859 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
861 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());
863 // update player position for group at taxi flight
864 if(player->GetGroup() && player->isInFlight())
865 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
867 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
868 RemoveFromGrid(player, oldGrid,old_cell);
869 if( !old_cell.DiffGrid(new_cell) )
870 AddToGrid(player, oldGrid,new_cell);
871 else
872 EnsureGridLoadedAtEnter(new_cell, player);
875 // if move then update what player see and who seen
876 UpdatePlayerVisibility(player,new_cell,new_val);
877 UpdateObjectsVisibilityFor(player,new_cell,new_val);
878 PlayerRelocationNotify(player,new_cell,new_val);
879 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
880 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
882 ResetGridExpiry(*newGrid, 0.1f);
883 newGrid->SetGridState(GRID_STATE_ACTIVE);
887 void
888 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
890 assert(CheckGridIntegrity(creature,false));
892 Cell old_cell = creature->GetCurrentCell();
894 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
895 Cell new_cell(new_val);
897 // delay creature move for grid/cell to grid/cell moves
898 if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
900 #ifdef MANGOS_DEBUG
901 if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
902 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());
903 #endif
905 // do move or do move to respawn or remove creature if previous all fail
906 if(CreatureCellRelocation(creature,new_cell))
908 // update pos
909 creature->Relocate(x, y, z, ang);
911 // in diffcell/diffgrid case notifiers called in Creature::Update
912 creature->SetNeedNotify();
914 else
916 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
917 // creature coordinates will be updated and notifiers send
918 if(!CreatureRespawnRelocation(creature))
920 // ... or unload (if respawn grid also not loaded)
921 #ifdef MANGOS_DEBUG
922 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
923 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",creature->GetGUIDLow(),creature->GetEntry());
924 #endif
925 creature->SetNeedNotify();
929 else
931 creature->Relocate(x, y, z, ang);
932 creature->SetNeedNotify();
935 assert(CheckGridIntegrity(creature,true));
938 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
940 Cell const& old_cell = c->GetCurrentCell();
941 if(!old_cell.DiffGrid(new_cell) ) // in same grid
943 // if in same cell then none do
944 if(old_cell.DiffCell(new_cell))
946 #ifdef MANGOS_DEBUG
947 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
948 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());
949 #endif
951 if( !old_cell.DiffGrid(new_cell) )
953 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
954 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
955 c->SetCurrentCell(new_cell);
958 else
960 #ifdef MANGOS_DEBUG
961 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
962 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());
963 #endif
966 return true;
969 // in diff. grids but active creature
970 if(c->isActiveObject())
972 EnsureGridLoadedAtEnter(new_cell);
974 #ifdef MANGOS_DEBUG
975 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
976 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());
977 #endif
979 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
980 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
982 return true;
985 // in diff. loaded grid normal creature
986 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
988 #ifdef MANGOS_DEBUG
989 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
990 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());
991 #endif
993 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
995 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
996 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
999 return true;
1002 // fail to move: normal creature attempt move to unloaded grid
1003 #ifdef MANGOS_DEBUG
1004 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1005 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());
1006 #endif
1007 return false;
1010 bool Map::CreatureRespawnRelocation(Creature *c)
1012 float resp_x, resp_y, resp_z, resp_o;
1013 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
1015 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
1016 Cell resp_cell(resp_val);
1018 c->CombatStop();
1019 c->GetMotionMaster()->Clear();
1021 #ifdef MANGOS_DEBUG
1022 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1023 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());
1024 #endif
1026 // teleport it to respawn point (like normal respawn if player see)
1027 if(CreatureCellRelocation(c,resp_cell))
1029 c->Relocate(resp_x, resp_y, resp_z, resp_o);
1030 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
1031 c->SetNeedNotify();
1032 return true;
1034 else
1035 return false;
1038 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
1040 NGridType *grid = getNGrid(x, y);
1041 assert( grid != NULL);
1044 if(!pForce && ActiveObjectsNearGrid(x, y) )
1045 return false;
1047 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
1048 ObjectGridUnloader unloader(*grid);
1050 // Finish remove and delete all creatures with delayed remove before moving to respawn grids
1051 // Must know real mob position before move
1052 RemoveAllObjectsInRemoveList();
1054 // move creatures to respawn grids if this is diff.grid or to remove list
1055 unloader.MoveToRespawnN();
1057 // Finish remove and delete all creatures with delayed remove before unload
1058 RemoveAllObjectsInRemoveList();
1060 unloader.UnloadN();
1061 delete getNGrid(x, y);
1062 setNGrid(NULL, x, y);
1065 int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
1066 int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;
1068 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1069 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1071 if (i_InstanceId == 0)
1073 if(GridMaps[gx][gy])
1075 GridMaps[gx][gy]->unloadData();
1076 delete GridMaps[gx][gy];
1078 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gx, gy);
1080 else
1081 ((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridPair(gx, gy));
1083 GridMaps[gx][gy] = NULL;
1085 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1086 return true;
1089 void Map::UnloadAll(bool pForce)
1091 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1093 NGridType &grid(*i->getSource());
1094 ++i;
1095 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1099 MapDifficulty const* Map::GetMapDifficulty() const
1101 return GetMapDifficultyData(GetId(),GetDifficulty());
1104 uint32 Map::GetMaxPlayers() const
1106 if(MapDifficulty const* mapDiff = GetMapDifficulty())
1108 if(mapDiff->maxPlayers || IsRegularDifficulty()) // Normal case (expect that regular difficulty always have correct maxplayers)
1109 return mapDiff->maxPlayers;
1110 else // DBC have 0 maxplayers for heroic instances with expansion < 2
1111 { // The heroic entry exists, so we don't have to check anything, simply return normal max players
1112 MapDifficulty const* normalDiff = GetMapDifficultyData(i_id, REGULAR_DIFFICULTY);
1113 return normalDiff ? normalDiff->maxPlayers : 0;
1116 else // I'd rather assert(false);
1117 return 0;
1120 uint32 Map::GetMaxResetDelay() const
1122 MapDifficulty const* mapDiff = GetMapDifficulty();
1123 return mapDiff ? mapDiff->resetTime : 0;
1126 //*****************************
1127 // Grid function
1128 //*****************************
1129 GridMap::GridMap()
1131 m_flags = 0;
1132 // Area data
1133 m_gridArea = 0;
1134 m_area_map = NULL;
1135 // Height level data
1136 m_gridHeight = INVALID_HEIGHT;
1137 m_gridGetHeight = &GridMap::getHeightFromFlat;
1138 m_V9 = NULL;
1139 m_V8 = NULL;
1140 // Liquid data
1141 m_liquidType = 0;
1142 m_liquid_offX = 0;
1143 m_liquid_offY = 0;
1144 m_liquid_width = 0;
1145 m_liquid_height = 0;
1146 m_liquidLevel = INVALID_HEIGHT;
1147 m_liquid_type = NULL;
1148 m_liquid_map = NULL;
1151 GridMap::~GridMap()
1153 unloadData();
1156 bool GridMap::loadData(char *filename)
1158 // Unload old data if exist
1159 unloadData();
1161 map_fileheader header;
1162 // Not return error if file not found
1163 FILE *in = fopen(filename, "rb");
1164 if (!in)
1165 return true;
1166 fread(&header, sizeof(header),1,in);
1167 if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) &&
1168 header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC)) ||
1169 !IsAcceptableClientBuild(header.buildMagic))
1171 // loadup area data
1172 if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
1174 sLog.outError("Error loading map area data\n");
1175 fclose(in);
1176 return false;
1178 // loadup height data
1179 if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
1181 sLog.outError("Error loading map height data\n");
1182 fclose(in);
1183 return false;
1185 // loadup liquid data
1186 if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
1188 sLog.outError("Error loading map liquids data\n");
1189 fclose(in);
1190 return false;
1192 fclose(in);
1193 return true;
1195 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
1196 fclose(in);
1197 return false;
1200 void GridMap::unloadData()
1202 if (m_area_map) delete[] m_area_map;
1203 if (m_V9) delete[] m_V9;
1204 if (m_V8) delete[] m_V8;
1205 if (m_liquid_type) delete[] m_liquid_type;
1206 if (m_liquid_map) delete[] m_liquid_map;
1207 m_area_map = NULL;
1208 m_V9 = NULL;
1209 m_V8 = NULL;
1210 m_liquid_type = NULL;
1211 m_liquid_map = NULL;
1212 m_gridGetHeight = &GridMap::getHeightFromFlat;
1215 bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/)
1217 map_areaHeader header;
1218 fseek(in, offset, SEEK_SET);
1219 fread(&header, sizeof(header), 1, in);
1220 if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC)))
1221 return false;
1223 m_gridArea = header.gridArea;
1224 if (!(header.flags & MAP_AREA_NO_AREA))
1226 m_area_map = new uint16 [16*16];
1227 fread(m_area_map, sizeof(uint16), 16*16, in);
1229 return true;
1232 bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/)
1234 map_heightHeader header;
1235 fseek(in, offset, SEEK_SET);
1236 fread(&header, sizeof(header), 1, in);
1237 if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC)))
1238 return false;
1240 m_gridHeight = header.gridHeight;
1241 if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
1243 if ((header.flags & MAP_HEIGHT_AS_INT16))
1245 m_uint16_V9 = new uint16 [129*129];
1246 m_uint16_V8 = new uint16 [128*128];
1247 fread(m_uint16_V9, sizeof(uint16), 129*129, in);
1248 fread(m_uint16_V8, sizeof(uint16), 128*128, in);
1249 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
1250 m_gridGetHeight = &GridMap::getHeightFromUint16;
1252 else if ((header.flags & MAP_HEIGHT_AS_INT8))
1254 m_uint8_V9 = new uint8 [129*129];
1255 m_uint8_V8 = new uint8 [128*128];
1256 fread(m_uint8_V9, sizeof(uint8), 129*129, in);
1257 fread(m_uint8_V8, sizeof(uint8), 128*128, in);
1258 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
1259 m_gridGetHeight = &GridMap::getHeightFromUint8;
1261 else
1263 m_V9 = new float [129*129];
1264 m_V8 = new float [128*128];
1265 fread(m_V9, sizeof(float), 129*129, in);
1266 fread(m_V8, sizeof(float), 128*128, in);
1267 m_gridGetHeight = &GridMap::getHeightFromFloat;
1270 else
1271 m_gridGetHeight = &GridMap::getHeightFromFlat;
1272 return true;
1275 bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 /*size*/)
1277 map_liquidHeader header;
1278 fseek(in, offset, SEEK_SET);
1279 fread(&header, sizeof(header), 1, in);
1280 if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC)))
1281 return false;
1283 m_liquidType = header.liquidType;
1284 m_liquid_offX = header.offsetX;
1285 m_liquid_offY = header.offsetY;
1286 m_liquid_width = header.width;
1287 m_liquid_height= header.height;
1288 m_liquidLevel = header.liquidLevel;
1290 if (!(header.flags & MAP_LIQUID_NO_TYPE))
1292 m_liquid_type = new uint8 [16*16];
1293 fread(m_liquid_type, sizeof(uint8), 16*16, in);
1295 if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
1297 m_liquid_map = new float [m_liquid_width*m_liquid_height];
1298 fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
1300 return true;
1303 uint16 GridMap::getArea(float x, float y)
1305 if (!m_area_map)
1306 return m_gridArea;
1308 x = 16 * (32 - x/SIZE_OF_GRIDS);
1309 y = 16 * (32 - y/SIZE_OF_GRIDS);
1310 int lx = (int)x & 15;
1311 int ly = (int)y & 15;
1312 return m_area_map[lx*16 + ly];
1315 float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
1317 return m_gridHeight;
1320 float GridMap::getHeightFromFloat(float x, float y) const
1322 if (!m_V8 || !m_V9)
1323 return m_gridHeight;
1325 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1326 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1328 int x_int = (int)x;
1329 int y_int = (int)y;
1330 x -= x_int;
1331 y -= y_int;
1332 x_int&=(MAP_RESOLUTION - 1);
1333 y_int&=(MAP_RESOLUTION - 1);
1335 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1336 // +--------------> X
1337 // | h1-------h2 Coordinates is:
1338 // | | \ 1 / | h1 0,0
1339 // | | \ / | h2 0,1
1340 // | | 2 h5 3 | h3 1,0
1341 // | | / \ | h4 1,1
1342 // | | / 4 \ | h5 1/2,1/2
1343 // | h3-------h4
1344 // V Y
1345 // For find height need
1346 // 1 - detect triangle
1347 // 2 - solve linear equation from triangle points
1348 // Calculate coefficients for solve h = a*x + b*y + c
1350 float a,b,c;
1351 // Select triangle:
1352 if (x+y < 1)
1354 if (x > y)
1356 // 1 triangle (h1, h2, h5 points)
1357 float h1 = m_V9[(x_int )*129 + y_int];
1358 float h2 = m_V9[(x_int+1)*129 + y_int];
1359 float h5 = 2 * m_V8[x_int*128 + y_int];
1360 a = h2-h1;
1361 b = h5-h1-h2;
1362 c = h1;
1364 else
1366 // 2 triangle (h1, h3, h5 points)
1367 float h1 = m_V9[x_int*129 + y_int ];
1368 float h3 = m_V9[x_int*129 + y_int+1];
1369 float h5 = 2 * m_V8[x_int*128 + y_int];
1370 a = h5 - h1 - h3;
1371 b = h3 - h1;
1372 c = h1;
1375 else
1377 if (x > y)
1379 // 3 triangle (h2, h4, h5 points)
1380 float h2 = m_V9[(x_int+1)*129 + y_int ];
1381 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1382 float h5 = 2 * m_V8[x_int*128 + y_int];
1383 a = h2 + h4 - h5;
1384 b = h4 - h2;
1385 c = h5 - h4;
1387 else
1389 // 4 triangle (h3, h4, h5 points)
1390 float h3 = m_V9[(x_int )*129 + y_int+1];
1391 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1392 float h5 = 2 * m_V8[x_int*128 + y_int];
1393 a = h4 - h3;
1394 b = h3 + h4 - h5;
1395 c = h5 - h4;
1398 // Calculate height
1399 return a * x + b * y + c;
1402 float GridMap::getHeightFromUint8(float x, float y) const
1404 if (!m_uint8_V8 || !m_uint8_V9)
1405 return m_gridHeight;
1407 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1408 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1410 int x_int = (int)x;
1411 int y_int = (int)y;
1412 x -= x_int;
1413 y -= y_int;
1414 x_int&=(MAP_RESOLUTION - 1);
1415 y_int&=(MAP_RESOLUTION - 1);
1417 int32 a, b, c;
1418 uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
1419 if (x+y < 1)
1421 if (x > y)
1423 // 1 triangle (h1, h2, h5 points)
1424 int32 h1 = V9_h1_ptr[ 0];
1425 int32 h2 = V9_h1_ptr[129];
1426 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1427 a = h2-h1;
1428 b = h5-h1-h2;
1429 c = h1;
1431 else
1433 // 2 triangle (h1, h3, h5 points)
1434 int32 h1 = V9_h1_ptr[0];
1435 int32 h3 = V9_h1_ptr[1];
1436 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1437 a = h5 - h1 - h3;
1438 b = h3 - h1;
1439 c = h1;
1442 else
1444 if (x > y)
1446 // 3 triangle (h2, h4, h5 points)
1447 int32 h2 = V9_h1_ptr[129];
1448 int32 h4 = V9_h1_ptr[130];
1449 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1450 a = h2 + h4 - h5;
1451 b = h4 - h2;
1452 c = h5 - h4;
1454 else
1456 // 4 triangle (h3, h4, h5 points)
1457 int32 h3 = V9_h1_ptr[ 1];
1458 int32 h4 = V9_h1_ptr[130];
1459 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1460 a = h4 - h3;
1461 b = h3 + h4 - h5;
1462 c = h5 - h4;
1465 // Calculate height
1466 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1469 float GridMap::getHeightFromUint16(float x, float y) const
1471 if (!m_uint16_V8 || !m_uint16_V9)
1472 return m_gridHeight;
1474 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1475 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1477 int x_int = (int)x;
1478 int y_int = (int)y;
1479 x -= x_int;
1480 y -= y_int;
1481 x_int&=(MAP_RESOLUTION - 1);
1482 y_int&=(MAP_RESOLUTION - 1);
1484 int32 a, b, c;
1485 uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
1486 if (x+y < 1)
1488 if (x > y)
1490 // 1 triangle (h1, h2, h5 points)
1491 int32 h1 = V9_h1_ptr[ 0];
1492 int32 h2 = V9_h1_ptr[129];
1493 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1494 a = h2-h1;
1495 b = h5-h1-h2;
1496 c = h1;
1498 else
1500 // 2 triangle (h1, h3, h5 points)
1501 int32 h1 = V9_h1_ptr[0];
1502 int32 h3 = V9_h1_ptr[1];
1503 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1504 a = h5 - h1 - h3;
1505 b = h3 - h1;
1506 c = h1;
1509 else
1511 if (x > y)
1513 // 3 triangle (h2, h4, h5 points)
1514 int32 h2 = V9_h1_ptr[129];
1515 int32 h4 = V9_h1_ptr[130];
1516 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1517 a = h2 + h4 - h5;
1518 b = h4 - h2;
1519 c = h5 - h4;
1521 else
1523 // 4 triangle (h3, h4, h5 points)
1524 int32 h3 = V9_h1_ptr[ 1];
1525 int32 h4 = V9_h1_ptr[130];
1526 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1527 a = h4 - h3;
1528 b = h3 + h4 - h5;
1529 c = h5 - h4;
1532 // Calculate height
1533 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1536 float GridMap::getLiquidLevel(float x, float y)
1538 if (!m_liquid_map)
1539 return m_liquidLevel;
1541 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1542 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1544 int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
1545 int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
1547 if (cx_int < 0 || cx_int >=m_liquid_height)
1548 return INVALID_HEIGHT;
1549 if (cy_int < 0 || cy_int >=m_liquid_width )
1550 return INVALID_HEIGHT;
1552 return m_liquid_map[cx_int*m_liquid_width + cy_int];
1555 uint8 GridMap::getTerrainType(float x, float y)
1557 if (!m_liquid_type)
1558 return (uint8)m_liquidType;
1560 x = 16 * (32 - x/SIZE_OF_GRIDS);
1561 y = 16 * (32 - y/SIZE_OF_GRIDS);
1562 int lx = (int)x & 15;
1563 int ly = (int)y & 15;
1564 return m_liquid_type[lx*16 + ly];
1567 // Get water state on map
1568 inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
1570 // Check water type (if no water return)
1571 if (!m_liquid_type && !m_liquidType)
1572 return LIQUID_MAP_NO_WATER;
1574 // Get cell
1575 float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1576 float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1578 int x_int = (int)cx & (MAP_RESOLUTION-1);
1579 int y_int = (int)cy & (MAP_RESOLUTION-1);
1581 // Check water type in cell
1582 uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
1583 if (type == 0)
1584 return LIQUID_MAP_NO_WATER;
1586 // Check req liquid type mask
1587 if (ReqLiquidType && !(ReqLiquidType&type))
1588 return LIQUID_MAP_NO_WATER;
1590 // Check water level:
1591 // Check water height map
1592 int lx_int = x_int - m_liquid_offY;
1593 int ly_int = y_int - m_liquid_offX;
1594 if (lx_int < 0 || lx_int >=m_liquid_height)
1595 return LIQUID_MAP_NO_WATER;
1596 if (ly_int < 0 || ly_int >=m_liquid_width )
1597 return LIQUID_MAP_NO_WATER;
1599 // Get water level
1600 float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
1601 // Get ground level (sub 0.2 for fix some errors)
1602 float ground_level = getHeight(x, y);
1604 // Check water level and ground level
1605 if (liquid_level < ground_level || z < ground_level - 2)
1606 return LIQUID_MAP_NO_WATER;
1608 // All ok in water -> store data
1609 if (data)
1611 data->type = type;
1612 data->level = liquid_level;
1613 data->depth_level = ground_level;
1616 // For speed check as int values
1617 int delta = int((liquid_level - z) * 10);
1619 // Get position delta
1620 if (delta > 20) // Under water
1621 return LIQUID_MAP_UNDER_WATER;
1622 if (delta > 0 ) // In water
1623 return LIQUID_MAP_IN_WATER;
1624 if (delta > -1) // Walk on water
1625 return LIQUID_MAP_WATER_WALK;
1626 // Above water
1627 return LIQUID_MAP_ABOVE_WATER;
1630 inline GridMap *Map::GetGrid(float x, float y)
1632 // half opt method
1633 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1634 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1636 // ensure GridMap is loaded
1637 EnsureGridCreated(GridPair(63-gx,63-gy));
1639 return GridMaps[gx][gy];
1642 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1644 // find raw .map surface under Z coordinates
1645 float mapHeight;
1646 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1648 float _mapheight = gmap->getHeight(x,y);
1650 // look from a bit higher pos to find the floor, ignore under surface case
1651 if(z + 2.0f > _mapheight)
1652 mapHeight = _mapheight;
1653 else
1654 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1656 else
1657 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1659 float vmapHeight;
1660 if(pUseVmaps)
1662 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1663 if(vmgr->isHeightCalcEnabled())
1665 // look from a bit higher pos to find the floor
1666 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1668 else
1669 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1671 else
1672 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1674 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1675 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1677 if( vmapHeight > INVALID_HEIGHT )
1679 if( mapHeight > INVALID_HEIGHT )
1681 // we have mapheight and vmapheight and must select more appropriate
1683 // we are already under the surface or vmap height above map heigt
1684 // or if the distance of the vmap height is less the land height distance
1685 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1686 return vmapHeight;
1687 else
1688 return mapHeight; // better use .map surface height
1691 else
1692 return vmapHeight; // we have only vmapHeight (if have)
1694 else
1696 if(!pUseVmaps)
1697 return mapHeight; // explicitly use map data (if have)
1698 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1699 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1700 else
1701 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1705 uint16 Map::GetAreaFlag(float x, float y, float z) const
1707 uint16 areaflag;
1708 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1709 areaflag = gmap->getArea(x, y);
1710 // this used while not all *.map files generated (instances)
1711 else
1712 areaflag = GetAreaFlagByMapId(i_id);
1714 //FIXME: some hacks for areas above or underground for ground area
1715 // required for area specific spells/etc, until map/vmap data
1716 // not provided correct areaflag with this hacks
1717 switch(areaflag)
1719 case 1146: // Blade's Edge Mountains
1720 case 1409: // Forge Camp: Wrath (Blade's Edge Mountains)
1721 if (x > 3025.0f && x < 3207.0f && y > 6987.0f && y < 7165.0f && z < 183.0f)
1722 areaflag = 1404; // Blackwing Coven (Blade's Edge Mountains)
1723 break;
1724 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1725 case 1984: // Plaguelands: The Scarlet Enclave
1726 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1727 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1728 if(z > 350.0f) areaflag = 2048; break;
1729 // Acherus: The Ebon Hold (Eastern Plaguelands)
1730 case 856: // The Noxious Glade (Eastern Plaguelands)
1731 case 2456: // Death's Breach (Eastern Plaguelands)
1732 if(z > 350.0f) areaflag = 1950; break;
1733 // Winterfin Caverns
1734 case 1652: // Coldarra
1735 case 1653: // The Westrift
1736 case 1661: // Winterfin Village
1737 if (x > 3823.0f && x < 4141.5f && y > 6247.0f && y < 64890.0f && z < 42.5f)
1738 areaflag = 1723;
1739 break;
1740 // Moonrest Gardens
1741 case 1787:
1742 if (x > 3315.3f && x < 3361.6f && y > 2469.4f && y < 2565.8f && z > 197.0f)
1743 areaflag = 1786; // Surge Needle (cords not entirely correct, will need round circle if this is really needed(see spell 47097 eff 77))
1744 break;
1745 // Dalaran
1746 case 2492: // Forlorn Woods (Crystalsong Forest)
1747 case 2371: // Valley of Echoes (Icecrown Glacier)
1748 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1750 // Krasus' Landing (Dalaran), fast check
1751 if (x > 5758.77f && x < 5869.03f && y < 510.46f)
1753 // Krasus' Landing (Dalaran), with open east side
1754 if (y < 449.33f || (x-5813.9f)*(x-5813.9f)+(y-449.33f)*(y-449.33f) < 1864.0f)
1756 areaflag = 2531; // Note: also 2633, possible one flight allowed and other not allowed case
1757 break;
1761 // Sunreaver's Sanctuary (Dalaran) (Enter,Left,Right-border lines)
1762 if ((y-548.11f)/(568.80f-548.11f) <= (x-5849.30f)/(5866.57f-5849.30f) &&
1763 (y-582.76f)/(622.97f-582.76f) <= (x-5961.64f)/(5886.09f-5961.64f) &&
1764 (y-446.79f)/(508.22f-446.79f) >= (x-5867.66f)/(5846.12f-5867.66f))
1766 // need exclude 2 shop rooms
1767 if (((x-5862.26f)*(x-5862.26f)+(y-554.76f)*(y-554.76f) > 335.85f/*310.64f*/ || z > 671.12f) &&
1768 ((y-580.51f)/(608.37f-580.51f) <= (x-5896.23f)/(5859.79f-5896.23f) ||
1769 (y-580.51f)/(610.49f-580.51f) <= (x-5896.23f)/(5919.15f-5896.23f) || z > 669.10f))
1771 areaflag = 2687;
1772 break;
1776 // The Silver Enclave (Dalaran) (Enter,Left,Right-border lines)
1777 if ((y-693.19f)/(737.41f-693.19f) >= (x-5732.80f)/(5769.38f-5732.80f) &&
1778 (y-693.19f)/(787.00f-693.19f) >= (x-5732.80f)/(5624.17f-5732.80f) &&
1779 (y-737.41f)/(831.30f-737.41f) <= (x-5769.38f)/(5671.15f-5769.38f))
1781 // need exclude ground floor shop room
1782 if ((x-5758.07f)*(x-5758.07f)+(y-738.18f)*(y-738.18f) > 83.30f || z > 650.00f)
1784 areaflag = 3007;
1785 break;
1789 // Dalaran
1790 areaflag = 2153;
1792 break;
1793 // The Violet Citadel (Dalaran) or Dalaran
1794 case 2484: // The Twilight Rivulet (Crystalsong Forest)
1795 case 1593: // Crystalsong Forest
1796 // Dalaran
1797 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1799 // The Violet Citadel (Dalaran), fast check
1800 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1802 // The Violet Citadel (Dalaran)
1803 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1805 areaflag = 2696;
1806 break;
1810 // Sunreaver's Sanctuary (Dalaran) (Enter,Left,Right-border lines)
1811 if ((y-581.27f)/(596.73f-581.27f) <= (x-5858.57f)/(5871.87f-5858.57f) &&
1812 (y-582.76f)/(622.97f-582.76f) <= (x-5961.64f)/(5886.09f-5961.64f) &&
1813 (y-446.79f)/(508.22f-446.79f) >= (x-5867.66f)/(5846.12f-5867.66f))
1815 areaflag = 2687;
1816 break;
1819 // The Silver Enclave (Dalaran) (Enter,Left,Right-border lines)
1820 if ((y-693.19f)/(737.41f-693.19f) >= (x-5732.80f)/(5769.38f-5732.80f) &&
1821 (y-693.19f)/(787.00f-693.19f) >= (x-5732.80f)/(5624.17f-5732.80f) &&
1822 (y-737.41f)/(831.30f-737.41f) <= (x-5769.38f)/(5671.15f-5769.38f))
1824 // need exclude ground floor shop room
1825 if ((x-5758.07f)*(x-5758.07f)+(y-738.18f)*(y-738.18f) > 64.30f || z > 650.00f)
1827 areaflag = 3007;
1828 break;
1832 // Dalaran
1833 areaflag = 2153;
1835 break;
1836 // Vargoth's Retreat (Dalaran) or The Violet Citadel (Dalaran) or Dalaran
1837 case 2504: // Violet Stand (Crystalsong Forest)
1838 // Dalaran
1839 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1841 // The Violet Citadel (Dalaran), fast check
1842 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1844 // Vargoth's Retreat (Dalaran), nice slow circle with upper limit
1845 if (z < 898.0f && (x-5765.0f)*(x-5765.0f)+(y-862.4f)*(y-862.4f) < 262.0f)
1847 areaflag = 2748;
1848 break;
1851 // The Violet Citadel (Dalaran)
1852 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1854 areaflag = 2696;
1855 break;
1859 // Dalaran
1860 areaflag = 2153;
1862 break;
1863 // Maw of Neltharion (cave)
1864 case 164: // Dragonblight
1865 case 1797: // Obsidian Dragonshrine (Dragonblight)
1866 case 1827: // Wintergrasp
1867 case 2591: // The Cauldron of Flames (Wintergrasp)
1868 if (x > 4364.0f && x < 4632.0f && y > 1545.0f && y < 1886.0f && z < 200.0f) areaflag = 1853; break;
1869 // Undercity (sewers enter and path)
1870 case 179: // Tirisfal Glades
1871 if (x > 1595.0f && x < 1699.0f && y > 535.0f && y < 643.5f && z < 30.5f) areaflag = 685; break;
1872 // Undercity (Royal Quarter)
1873 case 210: // Silverpine Forest
1874 case 316: // The Shining Strand (Silverpine Forest)
1875 case 438: // Lordamere Lake (Silverpine Forest)
1876 if (x > 1237.0f && x < 1401.0f && y > 284.0f && y < 440.0f && z < -40.0f) areaflag = 685; break;
1877 // Undercity (cave and ground zone, part of royal quarter)
1878 case 607: // Ruins of Lordaeron (Tirisfal Glades)
1879 // ground and near to ground (by city walls)
1880 if(z > 0.0f)
1882 if (x > 1510.0f && x < 1839.0f && y > 29.77f && y < 433.0f) areaflag = 685;
1884 // more wide underground, part of royal quarter
1885 else
1887 if (x > 1299.0f && x < 1839.0f && y > 10.0f && y < 440.0f) areaflag = 685;
1889 break;
1890 // The Makers' Perch (ground) and Makers' Overlook (ground and cave)
1891 case 1335: // Sholazar Basin
1892 // The Makers' Perch ground (fast box)
1893 if (x > 6100.0f && x < 6250.0f && y > 5650.0f && y < 5800.0f)
1895 // nice slow circle
1896 if ((x-6183.0f)*(x-6183.0f)+(y-5717.0f)*(y-5717.0f) < 2500.0f)
1897 areaflag = 2189;
1899 // Makers' Overlook (ground and cave)
1900 else if (x > 5634.48f && x < 5774.53f && y < 3475.0f && z > 300.0f)
1902 if (y > 3380.26f || (y > 3265.0f && z < 360.0f))
1903 areaflag = 2187;
1905 break;
1906 // The Makers' Perch (underground)
1907 case 2147: // The Stormwright's Shelf (Sholazar Basin)
1908 if (x > 6199.0f && x < 6283.0f && y > 5705.0f && y < 5817.0f && z < 38.0f) areaflag = 2189; break;
1909 // Makers' Overlook (deep cave)
1910 case 267: // Icecrown
1911 if (x > 5684.0f && x < 5798.0f && y > 3035.0f && y < 3367.0f && z < 358.0f) areaflag = 2187; break;
1912 // Wyrmrest Temple (Dragonblight)
1913 case 1814: // Path of the Titans (Dragonblight)
1914 case 1897: // The Dragon Wastes (Dragonblight)
1915 // fast box
1916 if (x > 3400.0f && x < 3700.0f && y > 130.0f && y < 420.0f)
1918 // nice slow circle
1919 if ((x-3546.87f)*(x-3546.87f)+(y-272.71f)*(y-272.71f) < 19600.0f) areaflag = 1791;
1921 break;
1922 // The Forlorn Mine (The Storm Peaks)
1923 case 166: // The Storm Peaks
1924 case 2207: // Brunnhildar Village (The Storm Peaks)
1925 case 2209: // Sifreldar Village (The Storm Peaks)
1926 case 2227: // The Foot Steppes (The Storm Peaks)
1927 // fast big box
1928 if (x > 6812.0f && x < 7049.5f && y > -1474.5f && y < -1162.5f && z < 866.15f)
1930 // east, avoid ground east-south corner wrong detection
1931 if (x > 6925.0f && y > -1474.5f && y < -1290.0f)
1932 areaflag = 2213;
1933 // east middle, wide part
1934 else if (x > 6812.0f && y > -1400.0f && y < -1290.0f)
1935 areaflag = 2213;
1936 // west middle, avoid ground west-south corner wrong detection
1937 else if (x > 6833.0f && y > -1474.5f && y < -1233.0f)
1938 areaflag = 2213;
1939 // west, avoid ground west-south corner wrong detection
1940 else if (x > 6885.0f && y > -1474.5f && y < -1162.5f)
1941 areaflag = 2213;
1943 break;
1944 default:
1945 break;
1948 return areaflag;
1951 uint8 Map::GetTerrainType(float x, float y ) const
1953 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1954 return gmap->getTerrainType(x, y);
1955 else
1956 return 0;
1959 ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
1961 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1962 return gmap->getLiquidStatus(x, y, z, ReqLiquidType, data);
1963 else
1964 return LIQUID_MAP_NO_WATER;
1967 float Map::GetWaterLevel(float x, float y ) const
1969 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1970 return gmap->getLiquidLevel(x, y);
1971 else
1972 return 0;
1975 uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
1977 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1979 if (entry)
1980 return entry->ID;
1981 else
1982 return 0;
1985 uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
1987 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1989 if( entry )
1990 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1991 else
1992 return 0;
1995 void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
1997 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1999 areaid = entry ? entry->ID : 0;
2000 zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
2003 bool Map::IsInWater(float x, float y, float pZ) const
2005 // Check surface in x, y point for liquid
2006 if (const_cast<Map*>(this)->GetGrid(x, y))
2008 LiquidData liquid_status;
2009 if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, &liquid_status))
2011 if (liquid_status.level - liquid_status.depth_level > 2)
2012 return true;
2015 return false;
2018 bool Map::IsUnderWater(float x, float y, float z) const
2020 if (const_cast<Map*>(this)->GetGrid(x, y))
2022 if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
2023 return true;
2025 return false;
2028 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
2030 Cell const& cur_cell = c->GetCurrentCell();
2032 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
2033 Cell xy_cell(xy_val);
2034 if(xy_cell != cur_cell)
2036 sLog.outError("Creature (GUIDLow: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
2037 c->GetGUIDLow(),
2038 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
2039 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
2040 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
2041 return true; // not crash at error, just output error in debug mode
2044 return true;
2047 const char* Map::GetMapName() const
2049 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
2052 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
2054 cell.data.Part.reserved = ALL_DISTRICT;
2055 cell.SetNoCreate();
2056 MaNGOS::VisibleChangesNotifier notifier(*obj);
2057 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
2058 cell.Visit(cellpair, player_notifier, *this, *obj, GetVisibilityDistance());
2061 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
2063 cell.data.Part.reserved = ALL_DISTRICT;
2065 MaNGOS::PlayerNotifier pl_notifier(*player);
2066 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
2068 cell.Visit(cellpair, player_notifier, *this, *player, GetVisibilityDistance());
2071 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
2073 MaNGOS::VisibleNotifier notifier(*player);
2075 cell.data.Part.reserved = ALL_DISTRICT;
2076 cell.SetNoCreate();
2077 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
2078 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
2079 cell.Visit(cellpair, world_notifier, *this, *player, GetVisibilityDistance());
2080 cell.Visit(cellpair, grid_notifier, *this, *player, GetVisibilityDistance());
2082 // send data
2083 notifier.Notify();
2086 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
2088 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
2089 cell.data.Part.reserved = ALL_DISTRICT;
2091 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
2092 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
2094 float radius = MAX_CREATURE_ATTACK_RADIUS * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
2096 cell.Visit(cellpair, p2grid_relocation, *this, *player, radius);
2097 cell.Visit(cellpair, p2world_relocation, *this, *player, radius);
2100 void Map::SendInitSelf( Player * player )
2102 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
2104 UpdateData data;
2106 // attach to player data current transport data
2107 if(Transport* transport = player->GetTransport())
2109 transport->BuildCreateUpdateBlockForPlayer(&data, player);
2112 // build data for self presence in world at own client (one time for map)
2113 player->BuildCreateUpdateBlockForPlayer(&data, player);
2115 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
2116 if(Transport* transport = player->GetTransport())
2118 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
2120 if(player!=(*itr) && player->HaveAtClient(*itr))
2122 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
2127 WorldPacket packet;
2128 data.BuildPacket(&packet);
2129 player->GetSession()->SendPacket(&packet);
2132 void Map::SendInitTransports( Player * player )
2134 // Hack to send out transports
2135 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2137 // no transports at map
2138 if (tmap.find(player->GetMapId()) == tmap.end())
2139 return;
2141 UpdateData transData;
2143 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2145 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2147 // send data for current transport in other place
2148 if((*i) != player->GetTransport() && (*i)->GetMapId()==i_id)
2150 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
2154 WorldPacket packet;
2155 transData.BuildPacket(&packet);
2156 player->GetSession()->SendPacket(&packet);
2159 void Map::SendRemoveTransports( Player * player )
2161 // Hack to send out transports
2162 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2164 // no transports at map
2165 if (tmap.find(player->GetMapId()) == tmap.end())
2166 return;
2168 UpdateData transData;
2170 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2172 // except used transport
2173 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2174 if((*i) != player->GetTransport() && (*i)->GetMapId()!=i_id)
2175 (*i)->BuildOutOfRangeUpdateBlock(&transData);
2177 WorldPacket packet;
2178 transData.BuildPacket(&packet);
2179 player->GetSession()->SendPacket(&packet);
2182 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
2184 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
2186 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
2187 assert(false);
2189 i_grids[x][y] = grid;
2192 void Map::AddObjectToRemoveList(WorldObject *obj)
2194 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
2196 obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links
2198 i_objectsToRemove.insert(obj);
2199 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
2202 void Map::RemoveAllObjectsInRemoveList()
2204 if(i_objectsToRemove.empty())
2205 return;
2207 //sLog.outDebug("Object remover 1 check.");
2208 while(!i_objectsToRemove.empty())
2210 WorldObject* obj = *i_objectsToRemove.begin();
2211 i_objectsToRemove.erase(i_objectsToRemove.begin());
2213 switch(obj->GetTypeId())
2215 case TYPEID_CORPSE:
2217 // ??? WTF
2218 Corpse* corpse = GetCorpse(obj->GetGUID());
2219 if (!corpse)
2220 sLog.outError("Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
2221 else
2222 Remove(corpse,true);
2223 break;
2225 case TYPEID_DYNAMICOBJECT:
2226 Remove((DynamicObject*)obj,true);
2227 break;
2228 case TYPEID_GAMEOBJECT:
2229 Remove((GameObject*)obj,true);
2230 break;
2231 case TYPEID_UNIT:
2232 Remove((Creature*)obj,true);
2233 break;
2234 default:
2235 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
2236 break;
2239 //sLog.outDebug("Object remover 2 check.");
2242 uint32 Map::GetPlayersCountExceptGMs() const
2244 uint32 count = 0;
2245 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2246 if(!itr->getSource()->isGameMaster())
2247 ++count;
2248 return count;
2251 void Map::SendToPlayers(WorldPacket const* data) const
2253 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2254 itr->getSource()->GetSession()->SendPacket(data);
2257 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
2259 ASSERT(x < MAX_NUMBER_OF_GRIDS);
2260 ASSERT(y < MAX_NUMBER_OF_GRIDS);
2262 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
2263 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
2265 //we must find visible range in cells so we unload only non-visible cells...
2266 float viewDist = GetVisibilityDistance();
2267 int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;
2269 cell_min << cell_range;
2270 cell_min -= cell_range;
2271 cell_max >> cell_range;
2272 cell_max += cell_range;
2274 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
2276 Player* plr = iter->getSource();
2278 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
2279 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2280 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2281 return true;
2284 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
2286 WorldObject* obj = *iter;
2288 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
2289 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2290 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2291 return true;
2294 return false;
2297 void Map::AddToActive( Creature* c )
2299 AddToActiveHelper(c);
2301 // also not allow unloading spawn grid to prevent creating creature clone at load
2302 if(!c->isPet() && c->GetDBTableGUIDLow())
2304 float x,y,z;
2305 c->GetRespawnCoord(x,y,z);
2306 GridPair p = MaNGOS::ComputeGridPair(x, y);
2307 if(getNGrid(p.x_coord, p.y_coord))
2308 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
2309 else
2311 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2312 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2313 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2318 void Map::RemoveFromActive( Creature* c )
2320 RemoveFromActiveHelper(c);
2322 // also allow unloading spawn grid
2323 if(!c->isPet() && c->GetDBTableGUIDLow())
2325 float x,y,z;
2326 c->GetRespawnCoord(x,y,z);
2327 GridPair p = MaNGOS::ComputeGridPair(x, y);
2328 if(getNGrid(p.x_coord, p.y_coord))
2329 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
2330 else
2332 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2333 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2334 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2339 template void Map::Add(Corpse *);
2340 template void Map::Add(Creature *);
2341 template void Map::Add(GameObject *);
2342 template void Map::Add(DynamicObject *);
2344 template void Map::Remove(Corpse *,bool);
2345 template void Map::Remove(Creature *,bool);
2346 template void Map::Remove(GameObject *, bool);
2347 template void Map::Remove(DynamicObject *, bool);
2349 /* ******* Dungeon Instance Maps ******* */
2351 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
2352 : Map(id, expiry, InstanceId, SpawnMode, _parent),
2353 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
2354 i_data(NULL), i_script_id(0)
2356 //lets initialize visibility distance for dungeons
2357 InstanceMap::InitVisibilityDistance();
2359 // the timer is started by default, and stopped when the first player joins
2360 // this make sure it gets unloaded if for some reason no player joins
2361 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_UINT32_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2364 InstanceMap::~InstanceMap()
2366 if(i_data)
2368 delete i_data;
2369 i_data = NULL;
2373 void InstanceMap::InitVisibilityDistance()
2375 //init visibility distance for instances
2376 m_VisibleDistance = World::GetMaxVisibleDistanceInInstances();
2380 Do map specific checks to see if the player can enter
2382 bool InstanceMap::CanEnter(Player *player)
2384 if(player->GetMapRef().getTarget() == this)
2386 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
2387 assert(false);
2388 return false;
2391 // cannot enter if the instance is full (player cap), GMs don't count
2392 uint32 maxPlayers = GetMaxPlayers();
2393 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
2395 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
2396 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
2397 return false;
2400 // cannot enter while players in the instance are in combat
2401 Group *pGroup = player->GetGroup();
2402 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
2404 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
2405 return false;
2408 return Map::CanEnter(player);
2412 Do map specific checks and add the player to the map if successful.
2414 bool InstanceMap::Add(Player *player)
2416 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
2417 // GMs still can teleport player in instance.
2418 // Is it needed?
2421 Guard guard(*this);
2422 if(!CanEnter(player))
2423 return false;
2425 // Dungeon only code
2426 if(IsDungeon())
2428 // get or create an instance save for the map
2429 InstanceSave *mapSave = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2430 if(!mapSave)
2432 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
2433 mapSave = sInstanceSaveMgr.AddInstanceSave(GetId(), GetInstanceId(), Difficulty(GetSpawnMode()), 0, true);
2436 // check for existing instance binds
2437 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), Difficulty(GetSpawnMode()));
2438 if(playerBind && playerBind->perm)
2440 // cannot enter other instances if bound permanently
2441 if(playerBind->save != mapSave)
2443 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());
2444 assert(false);
2447 else
2449 Group *pGroup = player->GetGroup();
2450 if(pGroup)
2452 // solo saves should be reset when entering a group
2453 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(this);
2454 if(playerBind)
2456 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());
2457 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());
2458 assert(false);
2460 // bind to the group or keep using the group save
2461 if(!groupBind)
2462 pGroup->BindToInstance(mapSave, false);
2463 else
2465 // cannot jump to a different instance without resetting it
2466 if(groupBind->save != mapSave)
2468 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());
2469 if(mapSave)
2470 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
2471 else
2472 sLog.outError("MapSave NULL");
2473 if(groupBind->save)
2474 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
2475 else
2476 sLog.outError("GroupBind save NULL");
2477 assert(false);
2479 // if the group/leader is permanently bound to the instance
2480 // players also become permanently bound when they enter
2481 if(groupBind->perm)
2483 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2484 data << uint32(0);
2485 player->GetSession()->SendPacket(&data);
2486 player->BindToInstance(mapSave, true);
2490 else
2492 // set up a solo bind or continue using it
2493 if(!playerBind)
2494 player->BindToInstance(mapSave, false);
2495 else
2496 // cannot jump to a different instance without resetting it
2497 assert(playerBind->save == mapSave);
2502 // for normal instances cancel the reset schedule when the
2503 // first player enters (no players yet)
2504 SetResetSchedule(false);
2506 sLog.outDetail("MAP: Player '%s' is entering instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
2507 // initialize unload state
2508 m_unloadTimer = 0;
2509 m_resetAfterUnload = false;
2510 m_unloadWhenEmpty = false;
2513 // this will acquire the same mutex so it cannot be in the previous block
2514 Map::Add(player);
2516 if (i_data)
2517 i_data->OnPlayerEnter(player);
2519 return true;
2522 void InstanceMap::Update(const uint32& t_diff)
2524 Map::Update(t_diff);
2526 if(i_data)
2527 i_data->Update(t_diff);
2530 void InstanceMap::Remove(Player *player, bool remove)
2532 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2533 //if last player set unload timer
2534 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
2535 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_UINT32_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2536 Map::Remove(player, remove);
2537 // for normal instances schedule the reset after all players have left
2538 SetResetSchedule(true);
2541 void InstanceMap::CreateInstanceData(bool load)
2543 if(i_data != NULL)
2544 return;
2546 InstanceTemplate const* mInstance = ObjectMgr::GetInstanceTemplate(GetId());
2547 if (mInstance)
2549 i_script_id = mInstance->script_id;
2550 i_data = Script->CreateInstanceData(this);
2553 if(!i_data)
2554 return;
2556 if(load)
2558 // TODO: make a global storage for this
2559 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
2560 if (result)
2562 Field* fields = result->Fetch();
2563 const char* data = fields[0].GetString();
2564 if(data)
2566 sLog.outDebug("Loading instance data for `%s` with id %u", sObjectMgr.GetScriptName(i_script_id), i_InstanceId);
2567 i_data->Load(data);
2569 delete result;
2572 else
2574 sLog.outDebug("New instance data, \"%s\" ,initialized!", sObjectMgr.GetScriptName(i_script_id));
2575 i_data->Initialize();
2580 Returns true if there are no players in the instance
2582 bool InstanceMap::Reset(uint8 method)
2584 // note: since the map may not be loaded when the instance needs to be reset
2585 // the instance must be deleted from the DB by InstanceSaveManager
2587 if(HavePlayers())
2589 if(method == INSTANCE_RESET_ALL)
2591 // notify the players to leave the instance so it can be reset
2592 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2593 itr->getSource()->SendResetFailedNotify(GetId());
2595 else
2597 if(method == INSTANCE_RESET_GLOBAL)
2599 // set the homebind timer for players inside (1 minute)
2600 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2601 itr->getSource()->m_InstanceValid = false;
2604 // the unload timer is not started
2605 // instead the map will unload immediately after the players have left
2606 m_unloadWhenEmpty = true;
2607 m_resetAfterUnload = true;
2610 else
2612 // unloaded at next update
2613 m_unloadTimer = MIN_UNLOAD_DELAY;
2614 m_resetAfterUnload = true;
2617 return m_mapRefManager.isEmpty();
2620 void InstanceMap::PermBindAllPlayers(Player *player)
2622 if(!IsDungeon())
2623 return;
2625 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2626 if(!save)
2628 sLog.outError("Cannot bind players, no instance save available for map!");
2629 return;
2632 Group *group = player->GetGroup();
2633 // group members outside the instance group don't get bound
2634 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2636 Player* plr = itr->getSource();
2637 // players inside an instance cannot be bound to other instances
2638 // some players may already be permanently bound, in this case nothing happens
2639 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
2640 if(!bind || !bind->perm)
2642 plr->BindToInstance(save, true);
2643 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2644 data << uint32(0);
2645 plr->GetSession()->SendPacket(&data);
2648 // if the leader is not in the instance the group will not get a perm bind
2649 if(group && group->GetLeaderGUID() == plr->GetGUID())
2650 group->BindToInstance(save, true);
2654 void InstanceMap::UnloadAll(bool pForce)
2656 if(HavePlayers())
2658 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
2659 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2661 Player* plr = itr->getSource();
2662 plr->TeleportToHomebind();
2666 if(m_resetAfterUnload == true)
2667 sObjectMgr.DeleteRespawnTimeForInstance(GetInstanceId());
2669 Map::UnloadAll(pForce);
2672 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
2674 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2675 itr->getSource()->SendInstanceResetWarning(GetId(), itr->getSource()->GetDifficulty(IsRaid()), timeLeft);
2678 void InstanceMap::SetResetSchedule(bool on)
2680 // only for normal instances
2681 // the reset time is only scheduled when there are no payers inside
2682 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2683 if(IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon())
2685 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2686 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2687 else sInstanceSaveMgr.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), Difficulty(GetSpawnMode()), GetInstanceId()));
2691 /* ******* Battleground Instance Maps ******* */
2693 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode)
2694 : Map(id, expiry, InstanceId, spawnMode, _parent)
2696 //lets initialize visibility distance for BG/Arenas
2697 BattleGroundMap::InitVisibilityDistance();
2700 BattleGroundMap::~BattleGroundMap()
2704 void BattleGroundMap::InitVisibilityDistance()
2706 //init visibility distance for BG/Arenas
2707 m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas();
2710 bool BattleGroundMap::CanEnter(Player * player)
2712 if(player->GetMapRef().getTarget() == this)
2714 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2715 assert(false);
2716 return false;
2719 if(player->GetBattleGroundId() != GetInstanceId())
2720 return false;
2722 // player number limit is checked in bgmgr, no need to do it here
2724 return Map::CanEnter(player);
2727 bool BattleGroundMap::Add(Player * player)
2730 Guard guard(*this);
2731 if(!CanEnter(player))
2732 return false;
2733 // reset instance validity, battleground maps do not homebind
2734 player->m_InstanceValid = true;
2736 return Map::Add(player);
2739 void BattleGroundMap::Remove(Player *player, bool remove)
2741 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2742 Map::Remove(player, remove);
2745 void BattleGroundMap::SetUnload()
2747 m_unloadTimer = MIN_UNLOAD_DELAY;
2750 void BattleGroundMap::UnloadAll(bool pForce)
2752 while(HavePlayers())
2754 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2756 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2757 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2758 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2759 // note that this remove is not needed if the code works well in other places
2760 plr->GetMapRef().unlink();
2764 Map::UnloadAll(pForce);
2767 /// Put scripts in the execution queue
2768 void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
2770 ///- Find the script map
2771 ScriptMapMap::const_iterator s = scripts.find(id);
2772 if (s == scripts.end())
2773 return;
2775 // prepare static data
2776 uint64 sourceGUID = source->GetGUID();
2777 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2778 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2780 ///- Schedule script execution for all scripts in the script map
2781 ScriptMap const *s2 = &(s->second);
2782 bool immedScript = false;
2783 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
2785 ScriptAction sa;
2786 sa.sourceGUID = sourceGUID;
2787 sa.targetGUID = targetGUID;
2788 sa.ownerGUID = ownerGUID;
2790 sa.script = &iter->second;
2791 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + iter->first), sa));
2792 if (iter->first == 0)
2793 immedScript = true;
2795 sWorld.IncreaseScheduledScriptsCount();
2797 ///- If one of the effects should be immediate, launch the script execution
2798 if (immedScript)
2799 ScriptsProcess();
2802 void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
2804 // NOTE: script record _must_ exist until command executed
2806 // prepare static data
2807 uint64 sourceGUID = source->GetGUID();
2808 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2809 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2811 ScriptAction sa;
2812 sa.sourceGUID = sourceGUID;
2813 sa.targetGUID = targetGUID;
2814 sa.ownerGUID = ownerGUID;
2816 sa.script = &script;
2817 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + delay), sa));
2819 sWorld.IncreaseScheduledScriptsCount();
2821 ///- If effects should be immediate, launch the script execution
2822 if(delay == 0)
2823 ScriptsProcess();
2826 /// Process queued scripts
2827 void Map::ScriptsProcess()
2829 if (m_scriptSchedule.empty())
2830 return;
2832 ///- Process overdue queued scripts
2833 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
2834 // ok as multimap is a *sorted* associative container
2835 while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
2837 ScriptAction const& step = iter->second;
2839 Object* source = NULL;
2841 if(step.sourceGUID)
2843 switch(GUID_HIPART(step.sourceGUID))
2845 case HIGHGUID_ITEM:
2846 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
2848 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
2849 if(player)
2850 source = player->GetItemByGuid(step.sourceGUID);
2851 break;
2853 case HIGHGUID_UNIT:
2854 source = GetCreature(step.sourceGUID);
2855 break;
2856 case HIGHGUID_PET:
2857 source = GetPet(step.sourceGUID);
2858 break;
2859 case HIGHGUID_VEHICLE:
2860 source = GetVehicle(step.sourceGUID);
2861 break;
2862 case HIGHGUID_PLAYER:
2863 source = HashMapHolder<Player>::Find(step.sourceGUID);
2864 break;
2865 case HIGHGUID_GAMEOBJECT:
2866 source = GetGameObject(step.sourceGUID);
2867 break;
2868 case HIGHGUID_CORPSE:
2869 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
2870 break;
2871 default:
2872 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
2873 break;
2877 if(source && !source->IsInWorld()) source = NULL;
2879 Object* target = NULL;
2881 if(step.targetGUID)
2883 switch(GUID_HIPART(step.targetGUID))
2885 case HIGHGUID_UNIT:
2886 target = GetCreature(step.targetGUID);
2887 break;
2888 case HIGHGUID_PET:
2889 target = GetPet(step.targetGUID);
2890 break;
2891 case HIGHGUID_VEHICLE:
2892 target = GetVehicle(step.targetGUID);
2893 break;
2894 case HIGHGUID_PLAYER: // empty GUID case also
2895 target = HashMapHolder<Player>::Find(step.targetGUID);
2896 break;
2897 case HIGHGUID_GAMEOBJECT:
2898 target = GetGameObject(step.targetGUID);
2899 break;
2900 case HIGHGUID_CORPSE:
2901 target = HashMapHolder<Corpse>::Find(step.targetGUID);
2902 break;
2903 default:
2904 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
2905 break;
2909 if(target && !target->IsInWorld()) target = NULL;
2911 switch (step.script->command)
2913 case SCRIPT_COMMAND_TALK:
2915 if(!source)
2917 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
2918 break;
2921 if(source->GetTypeId()!=TYPEID_UNIT)
2923 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2924 break;
2927 uint64 unit_target = target ? target->GetGUID() : 0;
2929 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
2930 switch(step.script->datalong)
2932 case 0: // Say
2933 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
2934 break;
2935 case 1: // Whisper
2936 if(!unit_target)
2938 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
2939 break;
2941 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
2942 break;
2943 case 2: // Yell
2944 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
2945 break;
2946 case 3: // Emote text
2947 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
2948 break;
2949 default:
2950 break; // must be already checked at load
2952 break;
2955 case SCRIPT_COMMAND_EMOTE:
2956 if(!source)
2958 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
2959 break;
2962 if(source->GetTypeId()!=TYPEID_UNIT)
2964 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2965 break;
2968 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
2969 break;
2970 case SCRIPT_COMMAND_FIELD_SET:
2971 if(!source)
2973 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
2974 break;
2976 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2978 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2979 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2980 break;
2983 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
2984 break;
2985 case SCRIPT_COMMAND_MOVE_TO:
2986 if(!source)
2988 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
2989 break;
2992 if(source->GetTypeId()!=TYPEID_UNIT)
2994 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2995 break;
2997 ((Unit*)source)->MonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
2998 break;
2999 case SCRIPT_COMMAND_FLAG_SET:
3000 if(!source)
3002 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
3003 break;
3005 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
3007 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
3008 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
3009 break;
3012 source->SetFlag(step.script->datalong, step.script->datalong2);
3013 break;
3014 case SCRIPT_COMMAND_FLAG_REMOVE:
3015 if(!source)
3017 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
3018 break;
3020 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
3022 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
3023 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
3024 break;
3027 source->RemoveFlag(step.script->datalong, step.script->datalong2);
3028 break;
3030 case SCRIPT_COMMAND_TELEPORT_TO:
3032 // accept player in any one from target/source arg
3033 if (!target && !source)
3035 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
3036 break;
3039 // must be only Player
3040 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3042 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3043 break;
3046 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3048 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
3049 break;
3052 case SCRIPT_COMMAND_KILL_CREDIT:
3054 // accept player in any one from target/source arg
3055 if (!target && !source)
3057 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for NULL object.");
3058 break;
3061 // must be only Player
3062 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3064 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3065 break;
3068 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3070 if (step.script->datalong2)
3072 pSource->RewardPlayerAndGroupAtEvent(step.script->datalong, pSource);
3074 else
3076 pSource->KilledMonsterCredit(step.script->datalong, 0);
3079 break;
3082 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3084 if(!step.script->datalong) // creature not specified
3086 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
3087 break;
3090 if(!source)
3092 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
3093 break;
3096 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3098 if(!summoner)
3100 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3101 break;
3104 float x = step.script->x;
3105 float y = step.script->y;
3106 float z = step.script->z;
3107 float o = step.script->o;
3109 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
3110 if (!pCreature)
3112 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
3113 break;
3116 break;
3119 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3121 if(!step.script->datalong) // gameobject not specified
3123 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
3124 break;
3127 if(!source)
3129 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
3130 break;
3133 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3135 if(!summoner)
3137 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3138 break;
3141 GameObject *go = NULL;
3142 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
3144 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
3145 Cell cell(p);
3146 cell.data.Part.reserved = ALL_DISTRICT;
3148 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
3149 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
3151 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3152 cell.Visit(p, object_checker, *summoner->GetMap());
3154 if ( !go )
3156 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
3157 break;
3160 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
3161 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
3162 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
3163 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
3165 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
3166 break;
3169 if( go->isSpawned() )
3170 break; //gameobject already spawned
3172 go->SetLootState(GO_READY);
3173 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
3175 go->GetMap()->Add(go);
3176 break;
3178 case SCRIPT_COMMAND_OPEN_DOOR:
3180 if(!step.script->datalong) // door not specified
3182 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
3183 break;
3186 if(!source)
3188 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
3189 break;
3192 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3194 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3195 break;
3198 Unit* caster = (Unit*)source;
3200 GameObject *door = NULL;
3201 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3203 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3204 Cell cell(p);
3205 cell.data.Part.reserved = ALL_DISTRICT;
3207 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3208 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3210 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3211 cell.Visit(p, object_checker, *caster->GetMap());
3213 if (!door)
3215 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3216 break;
3218 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
3220 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3221 break;
3224 if (door->GetGoState() != GO_STATE_READY)
3225 break; //door already open
3227 door->UseDoorOrButton(time_to_close);
3229 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3230 ((GameObject*)target)->UseDoorOrButton(time_to_close);
3231 break;
3233 case SCRIPT_COMMAND_CLOSE_DOOR:
3235 if(!step.script->datalong) // guid for door not specified
3237 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
3238 break;
3241 if(!source)
3243 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
3244 break;
3247 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3249 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3250 break;
3253 Unit* caster = (Unit*)source;
3255 GameObject *door = NULL;
3256 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3258 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3259 Cell cell(p);
3260 cell.data.Part.reserved = ALL_DISTRICT;
3262 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3263 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3265 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3266 cell.Visit(p, object_checker, *caster->GetMap());
3268 if ( !door )
3270 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3271 break;
3273 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
3275 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3276 break;
3279 if( door->GetGoState() == GO_STATE_READY )
3280 break; //door already closed
3282 door->UseDoorOrButton(time_to_open);
3284 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3285 ((GameObject*)target)->UseDoorOrButton(time_to_open);
3287 break;
3289 case SCRIPT_COMMAND_QUEST_EXPLORED:
3291 if(!source)
3293 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
3294 break;
3297 if(!target)
3299 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
3300 break;
3303 // when script called for item spell casting then target == (unit or GO) and source is player
3304 WorldObject* worldObject;
3305 Player* player;
3307 if(target->GetTypeId()==TYPEID_PLAYER)
3309 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
3311 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
3312 break;
3315 worldObject = (WorldObject*)source;
3316 player = (Player*)target;
3318 else
3320 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
3322 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3323 break;
3326 if(source->GetTypeId()!=TYPEID_PLAYER)
3328 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
3329 break;
3332 worldObject = (WorldObject*)target;
3333 player = (Player*)source;
3336 // quest id and flags checked at script loading
3337 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
3338 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
3339 player->AreaExploredOrEventHappens(step.script->datalong);
3340 else
3341 player->FailQuest(step.script->datalong);
3343 break;
3346 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
3348 if(!source)
3350 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
3351 break;
3354 if(!source->isType(TYPEMASK_UNIT))
3356 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
3357 break;
3360 if(!target)
3362 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
3363 break;
3366 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
3368 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3369 break;
3372 Unit* caster = (Unit*)source;
3374 GameObject *go = (GameObject*)target;
3376 go->Use(caster);
3377 break;
3380 case SCRIPT_COMMAND_REMOVE_AURA:
3382 Object* cmdTarget = step.script->datalong2 ? source : target;
3384 if(!cmdTarget)
3386 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
3387 break;
3390 if(!cmdTarget->isType(TYPEMASK_UNIT))
3392 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
3393 break;
3396 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
3397 break;
3400 case SCRIPT_COMMAND_CAST_SPELL:
3402 if(!source)
3404 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
3405 break;
3408 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
3410 if(!cmdTarget)
3412 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
3413 break;
3416 if(!cmdTarget->isType(TYPEMASK_UNIT))
3418 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
3419 break;
3422 Unit* spellTarget = (Unit*)cmdTarget;
3424 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
3426 if(!cmdSource)
3428 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
3429 break;
3432 if(!cmdSource->isType(TYPEMASK_UNIT))
3434 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
3435 break;
3438 Unit* spellSource = (Unit*)cmdSource;
3440 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
3441 spellSource->CastSpell(spellTarget,step.script->datalong,false);
3443 break;
3446 case SCRIPT_COMMAND_PLAY_SOUND:
3448 if(!source)
3450 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
3451 break;
3454 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
3455 if(!pSource)
3457 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
3458 break;
3461 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3462 Player* pTarget = NULL;
3463 if(step.script->datalong2 & 1)
3465 if(!target)
3467 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
3468 break;
3471 if(target->GetTypeId()!=TYPEID_PLAYER)
3473 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
3474 break;
3477 pTarget = (Player*)target;
3480 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3481 if(step.script->datalong2 & 2)
3482 pSource->PlayDistanceSound(step.script->datalong,pTarget);
3483 else
3484 pSource->PlayDirectSound(step.script->datalong,pTarget);
3485 break;
3487 case SCRIPT_COMMAND_CREATE_ITEM:
3489 if (!target && !source)
3491 sLog.outError("SCRIPT_COMMAND_CREATE_ITEM call for NULL object.");
3492 break;
3495 // only Player
3496 if ((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3498 sLog.outError("SCRIPT_COMMAND_CREATE_ITEM call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3499 break;
3502 Player* pReceiver = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3504 if (Item* pItem = pReceiver->StoreNewItemInInventorySlot(step.script->datalong, step.script->datalong2))
3505 pReceiver->SendNewItem(pItem, step.script->datalong2, true, false);
3507 break;
3509 case SCRIPT_COMMAND_DESPAWN_SELF:
3511 if (!target && !source)
3513 sLog.outError("SCRIPT_COMMAND_DESPAWN_SELF call for NULL object.");
3514 break;
3517 // only creature
3518 if ((!target || target->GetTypeId() != TYPEID_UNIT) && (!source || source->GetTypeId() != TYPEID_UNIT))
3520 sLog.outError("SCRIPT_COMMAND_DESPAWN_SELF call for non-creature (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3521 break;
3524 Creature* pCreature = target && target->GetTypeId() == TYPEID_UNIT ? (Creature*)target : (Creature*)source;
3526 pCreature->ForcedDespawn(step.script->datalong);
3528 break;
3530 default:
3531 sLog.outError("Unknown script command %u called.",step.script->command);
3532 break;
3535 m_scriptSchedule.erase(iter);
3536 sWorld.DecreaseScheduledScriptCount();
3538 iter = m_scriptSchedule.begin();
3540 return;
3543 Creature* Map::GetCreature(ObjectGuid guid)
3545 return m_objectsStore.find<Creature>(guid.GetRawValue(), (Creature*)NULL);
3548 Vehicle* Map::GetVehicle(ObjectGuid guid)
3550 return m_objectsStore.find<Vehicle>(guid.GetRawValue(), (Vehicle*)NULL);
3553 Pet* Map::GetPet(ObjectGuid guid)
3555 return m_objectsStore.find<Pet>(guid.GetRawValue(), (Pet*)NULL);
3558 Corpse* Map::GetCorpse(ObjectGuid guid)
3560 Corpse * ret = ObjectAccessor::GetCorpseInMap(guid,GetId());
3561 if (!ret)
3562 return NULL;
3563 if (ret->GetInstanceId() != GetInstanceId())
3564 return NULL;
3565 return ret;
3568 Creature* Map::GetCreatureOrPetOrVehicle(ObjectGuid guid)
3570 switch(guid.GetHigh())
3572 case HIGHGUID_UNIT: return GetCreature(guid);
3573 case HIGHGUID_PET: return GetPet(guid);
3574 case HIGHGUID_VEHICLE: return GetVehicle(guid);
3575 default: break;
3578 return NULL;
3581 GameObject* Map::GetGameObject(ObjectGuid guid)
3583 return m_objectsStore.find<GameObject>(guid.GetRawValue(), (GameObject*)NULL);
3586 DynamicObject* Map::GetDynamicObject(ObjectGuid guid)
3588 return m_objectsStore.find<DynamicObject>(guid.GetRawValue(), (DynamicObject*)NULL);
3591 WorldObject* Map::GetWorldObject(ObjectGuid guid)
3593 switch(guid.GetHigh())
3595 case HIGHGUID_PLAYER: return ObjectAccessor::FindPlayer(guid);
3596 case HIGHGUID_GAMEOBJECT: return GetGameObject(guid);
3597 case HIGHGUID_UNIT: return GetCreature(guid);
3598 case HIGHGUID_PET: return GetPet(guid);
3599 case HIGHGUID_VEHICLE: return GetVehicle(guid);
3600 case HIGHGUID_DYNAMICOBJECT:return GetDynamicObject(guid);
3601 case HIGHGUID_CORPSE: return GetCorpse(guid);
3602 case HIGHGUID_MO_TRANSPORT:
3603 case HIGHGUID_TRANSPORT:
3604 default: break;
3607 return NULL;
3610 void Map::SendObjectUpdates()
3612 UpdateDataMapType update_players;
3614 while(!i_objectsToClientUpdate.empty())
3616 Object* obj = *i_objectsToClientUpdate.begin();
3617 i_objectsToClientUpdate.erase(i_objectsToClientUpdate.begin());
3618 obj->BuildUpdateData(update_players);
3621 WorldPacket packet; // here we allocate a std::vector with a size of 0x10000
3622 for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
3624 iter->second.BuildPacket(&packet);
3625 iter->first->GetSession()->SendPacket(&packet);
3626 packet.clear(); // clean the string
3630 uint32 Map::GenerateLocalLowGuid(HighGuid guidhigh)
3632 // TODO: for map local guid counters possible force reload map instead shutdown server at guid counter overflow
3633 switch(guidhigh)
3635 case HIGHGUID_DYNAMICOBJECT:
3636 return m_DynObjectGuids.Generate();
3637 case HIGHGUID_PET:
3638 return m_PetGuids.Generate();
3639 case HIGHGUID_VEHICLE:
3640 return m_VehicleGuids.Generate();
3641 default:
3642 ASSERT(0);
3645 ASSERT(0);
3646 return 0;