* Even more restructuring of the game library.

--HG--
branch : trunk
This commit is contained in:
XTZGZoReX
2010-06-06 22:55:56 +02:00
parent 840d4ab99d
commit 62200e8d02
169 changed files with 0 additions and 0 deletions
+177
View File
@@ -0,0 +1,177 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_CELL_H
#define TRINITY_CELL_H
#include <cmath>
#include "GameSystem/TypeContainer.h"
#include "GameSystem/TypeContainerVisitor.h"
#include "GridDefines.h"
class Map;
class WorldObject;
enum District
{
UPPER_DISTRICT = 1,
LOWER_DISTRICT = 1 << 1,
LEFT_DISTRICT = 1 << 2,
RIGHT_DISTRICT = 1 << 3,
CENTER_DISTRICT = 1 << 4,
UPPER_LEFT_DISTRICT = (UPPER_DISTRICT | LEFT_DISTRICT),
UPPER_RIGHT_DISTRICT = (UPPER_DISTRICT | RIGHT_DISTRICT),
LOWER_LEFT_DISTRICT = (LOWER_DISTRICT | LEFT_DISTRICT),
LOWER_RIGHT_DISTRICT = (LOWER_DISTRICT | RIGHT_DISTRICT),
ALL_DISTRICT = (UPPER_DISTRICT | LOWER_DISTRICT | LEFT_DISTRICT | RIGHT_DISTRICT | CENTER_DISTRICT)
};
struct CellArea
{
CellArea() : right_offset(0), left_offset(0), upper_offset(0), lower_offset(0) {}
CellArea(int right, int left, int upper, int lower) : right_offset(right), left_offset(left), upper_offset(upper), lower_offset(lower) {}
bool operator!() const { return !right_offset && !left_offset && !upper_offset && !lower_offset; }
void ResizeBorders(CellPair& begin_cell, CellPair& end_cell) const
{
begin_cell << left_offset;
begin_cell -= lower_offset;
end_cell >> right_offset;
end_cell += upper_offset;
}
int right_offset;
int left_offset;
int upper_offset;
int lower_offset;
};
struct Cell
{
Cell() { data.All = 0; }
Cell(const Cell &cell) { data.All = cell.data.All; }
explicit Cell(CellPair const& p);
void operator|=(Cell &cell)
{
data.Part.reserved = 0;
cell.data.Part.reserved = 0;
uint32 x, y, old_x, old_y;
Compute(x, y);
cell.Compute(old_x, old_y);
if (std::abs(int(x-old_x)) > 1 || std::abs(int(y-old_y)) > 1)
{
data.Part.reserved = ALL_DISTRICT;
cell.data.Part.reserved = ALL_DISTRICT;
return;
}
if (x < old_x)
{
data.Part.reserved |= LEFT_DISTRICT;
cell.data.Part.reserved |= RIGHT_DISTRICT;
}
else if (old_x < x)
{
data.Part.reserved |= RIGHT_DISTRICT;
cell.data.Part.reserved |= LEFT_DISTRICT;
}
if (y < old_y)
{
data.Part.reserved |= UPPER_DISTRICT;
cell.data.Part.reserved |= LOWER_DISTRICT;
}
else if (old_y < y)
{
data.Part.reserved |= LOWER_DISTRICT;
cell.data.Part.reserved |= UPPER_DISTRICT;
}
}
void Compute(uint32 &x, uint32 &y) const
{
x = data.Part.grid_x*MAX_NUMBER_OF_CELLS + data.Part.cell_x;
y = data.Part.grid_y*MAX_NUMBER_OF_CELLS + data.Part.cell_y;
}
bool DiffCell(const Cell &cell) const
{
return(data.Part.cell_x != cell.data.Part.cell_x ||
data.Part.cell_y != cell.data.Part.cell_y);
}
bool DiffGrid(const Cell &cell) const
{
return(data.Part.grid_x != cell.data.Part.grid_x ||
data.Part.grid_y != cell.data.Part.grid_y);
}
uint32 CellX() const { return data.Part.cell_x; }
uint32 CellY() const { return data.Part.cell_y; }
uint32 GridX() const { return data.Part.grid_x; }
uint32 GridY() const { return data.Part.grid_y; }
bool NoCreate() const { return data.Part.nocreate; }
void SetNoCreate() { data.Part.nocreate = 1; }
CellPair cellPair() const
{
return CellPair(
data.Part.grid_x*MAX_NUMBER_OF_CELLS+data.Part.cell_x,
data.Part.grid_y*MAX_NUMBER_OF_CELLS+data.Part.cell_y);
}
Cell& operator=(const Cell &cell)
{
this->data.All = cell.data.All;
return *this;
}
bool operator == (const Cell &cell) const { return (data.All == cell.data.All); }
bool operator != (const Cell &cell) const { return !operator == (cell); }
union
{
struct
{
unsigned grid_x : 6;
unsigned grid_y : 6;
unsigned cell_x : 6;
unsigned cell_y : 6;
unsigned nocreate : 1;
unsigned reserved : 7;
} Part;
uint32 All;
} data;
template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &) const;
template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &, const WorldObject&, float) const;
template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &, float, float, float) const;
static CellArea CalculateCellArea(const WorldObject &obj, float radius);
static CellArea CalculateCellArea(float x, float y, float radius);
private:
template<class T, class CONTAINER> void VisitCircle(TypeContainerVisitor<T, CONTAINER> &, Map &, const CellPair&, const CellPair&) const;
};
#endif
+297
View File
@@ -0,0 +1,297 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_CELLIMPL_H
#define TRINITY_CELLIMPL_H
#include <cmath>
#include "Cell.h"
#include "Map.h"
#include "Object.h"
inline Cell::Cell(CellPair const& p)
{
data.Part.grid_x = p.x_coord / MAX_NUMBER_OF_CELLS;
data.Part.grid_y = p.y_coord / MAX_NUMBER_OF_CELLS;
data.Part.cell_x = p.x_coord % MAX_NUMBER_OF_CELLS;
data.Part.cell_y = p.y_coord % MAX_NUMBER_OF_CELLS;
data.Part.nocreate = 0;
data.Part.reserved = 0;
}
template<class T, class CONTAINER>
inline void
Cell::Visit(const CellPair& standing_cell, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m) const
{
if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
return;
uint16 district = (District)this->data.Part.reserved;
if (district == CENTER_DISTRICT)
{
m.Visit(*this, visitor);
return;
}
// set up the cell range based on the district
// the overloaded operators handle range checking
CellPair begin_cell = standing_cell;
CellPair end_cell = standing_cell;
switch(district)
{
case ALL_DISTRICT:
{
begin_cell << 1; begin_cell -= 1; // upper left
end_cell >> 1; end_cell += 1; // lower right
break;
}
case UPPER_LEFT_DISTRICT:
{
begin_cell << 1; begin_cell -= 1; // upper left
break;
}
case UPPER_RIGHT_DISTRICT:
{
begin_cell -= 1; // up
end_cell >> 1; // right
break;
}
case LOWER_LEFT_DISTRICT:
{
begin_cell << 1; // left
end_cell += 1; // down
break;
}
case LOWER_RIGHT_DISTRICT:
{
end_cell >> 1; end_cell += 1; // lower right
break;
}
case LEFT_DISTRICT:
{
begin_cell -= 1; // up
end_cell >> 1; end_cell += 1; // lower right
break;
}
case RIGHT_DISTRICT:
{
begin_cell << 1; begin_cell -= 1; // upper left
end_cell += 1; // down
break;
}
case UPPER_DISTRICT:
{
begin_cell << 1; begin_cell -= 1; // upper left
end_cell >> 1; // right
break;
}
case LOWER_DISTRICT:
{
begin_cell << 1; // left
end_cell >> 1; end_cell += 1; // lower right
break;
}
default:
{
assert(false);
break;
}
}
// loop the cell range
for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; x++)
{
for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; y++)
{
CellPair cell_pair(x,y);
Cell r_zone(cell_pair);
r_zone.data.Part.nocreate = this->data.Part.nocreate;
m.Visit(r_zone, visitor);
}
}
}
inline int CellHelper(const float radius)
{
if (radius < 1.0f)
return 0;
return (int)ceilf(radius/SIZE_OF_GRID_CELL);
}
inline CellArea Cell::CalculateCellArea(const WorldObject &obj, float radius)
{
return Cell::CalculateCellArea(obj.GetPositionX(), obj.GetPositionY(), radius);
}
inline CellArea Cell::CalculateCellArea(float x, float y, float radius)
{
if (radius <= 0.0f)
return CellArea();
//lets calculate object coord offsets from cell borders.
//TODO: add more correct/generic method for this task
const float x_offset = (x - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
const float y_offset = (y - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
const float x_val = floor(x_offset + CENTER_GRID_CELL_ID + 0.5f);
const float y_val = floor(y_offset + CENTER_GRID_CELL_ID + 0.5f);
const float x_off = (x_offset - x_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
const float y_off = (y_offset - y_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
const float tmp_diff = radius - CENTER_GRID_CELL_OFFSET;
//lets calculate upper/lower/right/left corners for cell search
int right = CellHelper(tmp_diff + x_off);
int left = CellHelper(tmp_diff - x_off);
int upper = CellHelper(tmp_diff + y_off);
int lower = CellHelper(tmp_diff - y_off);
return CellArea(right, left, upper, lower);
}
template<class T, class CONTAINER>
inline void
Cell::Visit(const CellPair& standing_cell, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, float radius, float x_off, float y_off) const
{
if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
return;
//no jokes here... Actually placing ASSERT() here was good idea, but
//we had some problems with DynamicObjects, which pass radius = 0.0f (DB issue?)
//maybe it is better to just return when radius <= 0.0f?
if (radius <= 0.0f)
{
m.Visit(*this, visitor);
return;
}
//lets limit the upper value for search radius
if (radius > 333.0f)
radius = 333.0f;
//lets calculate object coord offsets from cell borders.
CellArea area = Cell::CalculateCellArea(x_off, y_off, radius);
//if radius fits inside standing cell
if (!area)
{
m.Visit(*this, visitor);
return;
}
CellPair begin_cell = standing_cell;
CellPair end_cell = standing_cell;
area.ResizeBorders(begin_cell, end_cell);
//visit all cells, found in CalculateCellArea()
//if radius is known to reach cell area more than 4x4 then we should call optimized VisitCircle
//currently this technique works with MAX_NUMBER_OF_CELLS 16 and higher, with lower values
//there are nothing to optimize because SIZE_OF_GRID_CELL is too big...
if (((end_cell.x_coord - begin_cell.x_coord) > 4) && ((end_cell.y_coord - begin_cell.y_coord) > 4))
{
VisitCircle(visitor, m, begin_cell, end_cell);
return;
}
//ALWAYS visit standing cell first!!! Since we deal with small radiuses
//it is very essential to call visitor for standing cell firstly...
m.Visit(*this, visitor);
// loop the cell range
for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
{
for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
{
CellPair cell_pair(x,y);
//lets skip standing cell since we already visited it
if (cell_pair != standing_cell)
{
Cell r_zone(cell_pair);
r_zone.data.Part.nocreate = this->data.Part.nocreate;
m.Visit(r_zone, visitor);
}
}
}
}
template<class T, class CONTAINER>
inline void
Cell::Visit(const CellPair& l, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, const WorldObject &obj, float radius) const
{
//we should increase search radius by object's radius, otherwise
//we could have problems with huge creatures, which won't attack nearest players etc
Visit(l, visitor, m, radius + obj.GetObjectSize(), obj.GetPositionX(), obj.GetPositionY());
}
template<class T, class CONTAINER>
inline void
Cell::VisitCircle(TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, const CellPair& begin_cell, const CellPair& end_cell) const
{
//here is an algorithm for 'filling' circum-squared octagon
uint32 x_shift = (uint32)ceilf((end_cell.x_coord - begin_cell.x_coord) * 0.3f - 0.5f);
//lets calculate x_start/x_end coords for central strip...
const uint32 x_start = begin_cell.x_coord + x_shift;
const uint32 x_end = end_cell.x_coord - x_shift;
//visit central strip with constant width...
for (uint32 x = x_start; x <= x_end; ++x)
{
for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
{
CellPair cell_pair(x,y);
Cell r_zone(cell_pair);
r_zone.data.Part.nocreate = this->data.Part.nocreate;
m.Visit(r_zone, visitor);
}
}
//if x_shift == 0 then we have too small cell area, which were already
//visited at previous step, so just return from procedure...
if (x_shift == 0)
return;
uint32 y_start = end_cell.y_coord;
uint32 y_end = begin_cell.y_coord;
//now we are visiting borders of an octagon...
for (uint32 step = 1; step <= (x_start - begin_cell.x_coord); ++step)
{
//each step reduces strip height by 2 cells...
y_end += 1;
y_start -= 1;
for (uint32 y = y_start; y >= y_end; --y)
{
//we visit cells symmetrically from both sides, heading from center to sides and from up to bottom
//e.g. filling 2 trapezoids after filling central cell strip...
CellPair cell_pair_left(x_start - step, y);
Cell r_zone_left(cell_pair_left);
r_zone_left.data.Part.nocreate = this->data.Part.nocreate;
m.Visit(r_zone_left, visitor);
//right trapezoid cell visit
CellPair cell_pair_right(x_end + step, y);
Cell r_zone_right(cell_pair_right);
r_zone_right.data.Part.nocreate = this->data.Part.nocreate;
m.Visit(r_zone_right, visitor);
}
}
}
#endif
+193
View File
@@ -0,0 +1,193 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_GRIDDEFINES_H
#define TRINITY_GRIDDEFINES_H
#include "Common.h"
#include "GameSystem/NGrid.h"
#include <cmath>
// Forward class definitions
class Corpse;
class Creature;
class DynamicObject;
class GameObject;
class Pet;
class Player;
#define MAX_NUMBER_OF_CELLS 8
#define MAX_NUMBER_OF_GRIDS 64
#define SIZE_OF_GRIDS 533.33333f
#define CENTER_GRID_ID (MAX_NUMBER_OF_GRIDS/2)
#define CENTER_GRID_OFFSET (SIZE_OF_GRIDS/2)
#define MIN_GRID_DELAY (MINUTE*IN_MILISECONDS)
#define MIN_MAP_UPDATE_DELAY 50
#define SIZE_OF_GRID_CELL (SIZE_OF_GRIDS/MAX_NUMBER_OF_CELLS)
#define CENTER_GRID_CELL_ID (MAX_NUMBER_OF_CELLS*MAX_NUMBER_OF_GRIDS/2)
#define CENTER_GRID_CELL_OFFSET (SIZE_OF_GRID_CELL/2)
#define TOTAL_NUMBER_OF_CELLS_PER_MAP (MAX_NUMBER_OF_GRIDS*MAX_NUMBER_OF_CELLS)
#define MAP_RESOLUTION 128
#define MAP_SIZE (SIZE_OF_GRIDS*MAX_NUMBER_OF_GRIDS)
#define MAP_HALFSIZE (MAP_SIZE/2)
// Creature used instead pet to simplify *::Visit templates (not required duplicate code for Creature->Pet case)
typedef TYPELIST_4(Player, Creature/*pets*/, Corpse/*resurrectable*/, DynamicObject/*farsight target*/) AllWorldObjectTypes;
typedef TYPELIST_4(GameObject, Creature/*except pets*/, DynamicObject, Corpse/*Bones*/) AllGridObjectTypes;
typedef GridRefManager<Corpse> CorpseMapType;
typedef GridRefManager<Creature> CreatureMapType;
typedef GridRefManager<DynamicObject> DynamicObjectMapType;
typedef GridRefManager<GameObject> GameObjectMapType;
typedef GridRefManager<Player> PlayerMapType;
typedef Grid<Player, AllWorldObjectTypes,AllGridObjectTypes> GridType;
typedef NGrid<MAX_NUMBER_OF_CELLS, Player, AllWorldObjectTypes, AllGridObjectTypes> NGridType;
typedef TypeMapContainer<AllGridObjectTypes> GridTypeMapContainer;
typedef TypeMapContainer<AllWorldObjectTypes> WorldTypeMapContainer;
template<const unsigned int LIMIT>
struct CoordPair
{
CoordPair(uint32 x=0, uint32 y=0) : x_coord(x), y_coord(y) {}
CoordPair(const CoordPair<LIMIT> &obj) : x_coord(obj.x_coord), y_coord(obj.y_coord) {}
bool operator == (const CoordPair<LIMIT> &obj) const { return (obj.x_coord == x_coord && obj.y_coord == y_coord); }
bool operator != (const CoordPair<LIMIT> &obj) const { return !operator == (obj); }
CoordPair<LIMIT>& operator=(const CoordPair<LIMIT> &obj)
{
x_coord = obj.x_coord;
y_coord = obj.y_coord;
return *this;
}
void operator<<(const uint32 val)
{
if (x_coord > val)
x_coord -= val;
else
x_coord = 0;
}
void operator>>(const uint32 val)
{
if (x_coord+val < LIMIT)
x_coord += val;
else
x_coord = LIMIT - 1;
}
void operator-=(const uint32 val)
{
if (y_coord > val)
y_coord -= val;
else
y_coord = 0;
}
void operator+=(const uint32 val)
{
if (y_coord+val < LIMIT)
y_coord += val;
else
y_coord = LIMIT - 1;
}
uint32 x_coord;
uint32 y_coord;
};
typedef CoordPair<MAX_NUMBER_OF_GRIDS> GridPair;
typedef CoordPair<TOTAL_NUMBER_OF_CELLS_PER_MAP> CellPair;
namespace Trinity
{
template<class RET_TYPE, int CENTER_VAL>
inline RET_TYPE Compute(float x, float y, float center_offset, float size)
{
// calculate and store temporary values in double format for having same result as same mySQL calculations
double x_offset = (double(x) - center_offset)/size;
double y_offset = (double(y) - center_offset)/size;
int x_val = int(x_offset+CENTER_VAL + 0.5);
int y_val = int(y_offset+CENTER_VAL + 0.5);
return RET_TYPE(x_val, y_val);
}
inline GridPair ComputeGridPair(float x, float y)
{
return Compute<GridPair, CENTER_GRID_ID>(x, y, CENTER_GRID_OFFSET, SIZE_OF_GRIDS);
}
inline CellPair ComputeCellPair(float x, float y)
{
return Compute<CellPair, CENTER_GRID_CELL_ID>(x, y, CENTER_GRID_CELL_OFFSET, SIZE_OF_GRID_CELL);
}
inline CellPair ComputeCellPair(float x, float y, float &x_off, float &y_off)
{
double x_offset = (double(x) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
double y_offset = (double(y) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
int x_val = int(x_offset + CENTER_GRID_CELL_ID + 0.5);
int y_val = int(y_offset + CENTER_GRID_CELL_ID + 0.5);
x_off = (float(x_offset) - x_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
y_off = (float(y_offset) - y_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
return CellPair(x_val, y_val);
}
inline void NormalizeMapCoord(float &c)
{
if (c > MAP_HALFSIZE - 0.5)
c = MAP_HALFSIZE - 0.5;
else if (c < -(MAP_HALFSIZE - 0.5))
c = -(MAP_HALFSIZE - 0.5);
}
inline bool IsValidMapCoord(float c)
{
return finite(c) && (std::fabs(c) <= MAP_HALFSIZE - 0.5);
}
inline bool IsValidMapCoord(float x, float y)
{
return IsValidMapCoord(x) && IsValidMapCoord(y);
}
inline bool IsValidMapCoord(float x, float y, float z)
{
return IsValidMapCoord(x,y) && finite(z);
}
inline bool IsValidMapCoord(float x, float y, float z, float o)
{
return IsValidMapCoord(x,y,z) && finite(o);
}
}
#endif
+353
View File
@@ -0,0 +1,353 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "UpdateData.h"
#include "Item.h"
#include "Map.h"
#include "Transports.h"
#include "ObjectAccessor.h"
#include "CellImpl.h"
using namespace Trinity;
void
VisibleNotifier::SendToSelf()
{
// at this moment i_clientGUIDs have guids that not iterate at grid level checks
// but exist one case when this possible and object not out of range: transports
if (Transport* transport = i_player.GetTransport())
for (Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr != transport->GetPassengers().end();++itr)
{
if (vis_guids.find((*itr)->GetGUID()) != vis_guids.end())
{
vis_guids.erase((*itr)->GetGUID());
i_player.UpdateVisibilityOf((*itr), i_data, i_visibleNow);
if (!(*itr)->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
(*itr)->UpdateVisibilityOf(&i_player);
}
}
for (Player::ClientGUIDs::const_iterator it = vis_guids.begin();it != vis_guids.end(); ++it)
{
i_player.m_clientGUIDs.erase(*it);
i_data.AddOutOfRangeGUID(*it);
if (IS_PLAYER_GUID(*it))
{
Player* plr = ObjectAccessor::FindPlayer(*it);
if (plr && plr->IsInWorld() && !plr->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
plr->UpdateVisibilityOf(&i_player);
}
}
if (!i_data.HasData())
return;
WorldPacket packet;
i_data.BuildPacket(&packet);
i_player.GetSession()->SendPacket(&packet);
for (std::set<Unit*>::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it)
i_player.SendInitialVisiblePackets(*it);
}
void
VisibleChangesNotifier::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
if (iter->getSource() == &i_object)
continue;
iter->getSource()->UpdateVisibilityOf(&i_object);
if (!iter->getSource()->GetSharedVisionList().empty())
for (SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
i != iter->getSource()->GetSharedVisionList().end(); ++i)
if ((*i)->m_seer == iter->getSource())
(*i)->UpdateVisibilityOf(&i_object);
}
}
void
VisibleChangesNotifier::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
if (!iter->getSource()->GetSharedVisionList().empty())
for (SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
i != iter->getSource()->GetSharedVisionList().end(); ++i)
if ((*i)->m_seer == iter->getSource())
(*i)->UpdateVisibilityOf(&i_object);
}
void
VisibleChangesNotifier::Visit(DynamicObjectMapType &m)
{
for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
if (IS_PLAYER_GUID(iter->getSource()->GetCasterGUID()))
if (Player* caster = (Player*)iter->getSource()->GetCaster())
if (caster->m_seer == iter->getSource())
caster->UpdateVisibilityOf(&i_object);
}
inline void CreatureUnitRelocationWorker(Creature* c, Unit* u)
{
if (!u->isAlive() || !c->isAlive() || c == u || u->isInFlight())
return;
if (c->HasReactState(REACT_AGGRESSIVE) && !c->hasUnitState(UNIT_STAT_SIGHTLESS))
if (c->_IsWithinDist(u, c->m_SightDistance, true) && c->IsAIEnabled)
c->AI()->MoveInLineOfSight_Safe(u);
}
void PlayerRelocationNotifier::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
Player* plr = iter->getSource();
vis_guids.erase(plr->GetGUID());
i_player.UpdateVisibilityOf(plr,i_data,i_visibleNow);
if (plr->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
continue;
plr->UpdateVisibilityOf(&i_player);
}
}
void PlayerRelocationNotifier::Visit(CreatureMapType &m)
{
bool relocated_for_ai = (&i_player == i_player.m_seer);
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
Creature * c = iter->getSource();
vis_guids.erase(c->GetGUID());
i_player.UpdateVisibilityOf(c,i_data,i_visibleNow);
if (relocated_for_ai && !c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
CreatureUnitRelocationWorker(c, &i_player);
}
}
void CreatureRelocationNotifier::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
Player * pl = iter->getSource();
if (!pl->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
pl->UpdateVisibilityOf(&i_creature);
CreatureUnitRelocationWorker(&i_creature, pl);
}
}
void CreatureRelocationNotifier::Visit(CreatureMapType &m)
{
if (!i_creature.isAlive())
return;
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
Creature* c = iter->getSource();
CreatureUnitRelocationWorker(&i_creature, c);
if (!c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
CreatureUnitRelocationWorker(c, &i_creature);
}
}
void DelayedUnitRelocation::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
Creature * unit = iter->getSource();
if (!unit->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
continue;
CreatureRelocationNotifier relocate(*unit);
TypeContainerVisitor<CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocate);
TypeContainerVisitor<CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocate);
cell.Visit(p, c2world_relocation, i_map, *unit, i_radius);
cell.Visit(p, c2grid_relocation, i_map, *unit, i_radius);
}
}
void DelayedUnitRelocation::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
Player * player = iter->getSource();
WorldObject const *viewPoint = player->m_seer;
if (!viewPoint->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
continue;
if (player != viewPoint && !viewPoint->IsPositionValid())
continue;
CellPair pair2(Trinity::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
Cell cell2(pair2);
//cell.SetNoCreate(); need load cells around viewPoint or player, that's why its commented
PlayerRelocationNotifier relocate(*player);
TypeContainerVisitor<PlayerRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocate);
TypeContainerVisitor<PlayerRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocate);
cell2.Visit(pair2, c2world_relocation, i_map, *viewPoint, i_radius);
cell2.Visit(pair2, c2grid_relocation, i_map, *viewPoint, i_radius);
relocate.SendToSelf();
}
}
void AIRelocationNotifier::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
Creature *c = iter->getSource();
CreatureUnitRelocationWorker(c, &i_unit);
if (isCreature)
CreatureUnitRelocationWorker((Creature*)&i_unit, c);
}
}
void
MessageDistDeliverer::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
Player *target = iter->getSource();
if (!target->InSamePhase(i_phaseMask))
continue;
if (target->GetExactDistSq(i_source) > i_distSq)
continue;
// Send packet to all who are sharing the player's vision
if (!target->GetSharedVisionList().empty())
{
SharedVisionList::const_iterator i = target->GetSharedVisionList().begin();
for (; i != target->GetSharedVisionList().end(); ++i)
if ((*i)->m_seer == target)
SendPacket(*i);
}
if (target->m_seer == target || target->GetVehicle())
SendPacket(target);
}
}
void
MessageDistDeliverer::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
if (!iter->getSource()->InSamePhase(i_phaseMask))
continue;
if (iter->getSource()->GetExactDistSq(i_source) > i_distSq)
continue;
// Send packet to all who are sharing the creature's vision
if (!iter->getSource()->GetSharedVisionList().empty())
{
SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
for (; i != iter->getSource()->GetSharedVisionList().end(); ++i)
if ((*i)->m_seer == iter->getSource())
SendPacket(*i);
}
}
}
void
MessageDistDeliverer::Visit(DynamicObjectMapType &m)
{
for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
{
if (!iter->getSource()->InSamePhase(i_phaseMask))
continue;
if (iter->getSource()->GetExactDistSq(i_source) > i_distSq)
continue;
if (IS_PLAYER_GUID(iter->getSource()->GetCasterGUID()))
{
// Send packet back to the caster if the caster has vision of dynamic object
Player* caster = (Player*)iter->getSource()->GetCaster();
if (caster && caster->m_seer == iter->getSource())
SendPacket(caster);
}
}
}
/*
void
MessageDistDeliverer::VisitObject(Player* plr)
{
if (!i_ownTeamOnly || (i_source.GetTypeId() == TYPEID_PLAYER && plr->GetTeam() == ((Player&)i_source).GetTeam()))
{
SendPacket(plr);
}
}
*/
template<class T> void
ObjectUpdater::Visit(GridRefManager<T> &m)
{
for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
{
if (iter->getSource()->IsInWorld())
iter->getSource()->Update(i_timeDiff);
}
}
bool CannibalizeObjectCheck::operator()(Corpse* u)
{
// ignore bones
if (u->GetType() == CORPSE_BONES)
return false;
Player* owner = ObjectAccessor::FindPlayer(u->GetOwnerGUID());
if (!owner || i_funit->IsFriendlyTo(owner))
return false;
if (i_funit->IsWithinDistInMap(u, i_range))
return true;
return false;
}
template void ObjectUpdater::Visit<GameObject>(GameObjectMapType &);
template void ObjectUpdater::Visit<DynamicObject>(DynamicObjectMapType &);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,453 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_GRIDNOTIFIERSIMPL_H
#define TRINITY_GRIDNOTIFIERSIMPL_H
#include "GridNotifiers.h"
#include "WorldPacket.h"
#include "Corpse.h"
#include "Player.h"
#include "UpdateData.h"
#include "CreatureAI.h"
#include "SpellAuras.h"
template<class T>
inline void
Trinity::VisibleNotifier::Visit(GridRefManager<T> &m)
{
for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
{
vis_guids.erase(iter->getSource()->GetGUID());
i_player.UpdateVisibilityOf(iter->getSource(),i_data,i_visibleNow);
}
}
inline void
Trinity::ObjectUpdater::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
if (iter->getSource()->IsInWorld() && !iter->getSource()->isSpiritService())
iter->getSource()->Update(i_timeDiff);
}
// SEARCHERS & LIST SEARCHERS & WORKERS
// WorldObject searchers & workers
template<class Check>
void Trinity::WorldObjectSearcher<Check>::Visit(GameObjectMapType &m)
{
// already found
if (i_object)
return;
for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::WorldObjectSearcher<Check>::Visit(PlayerMapType &m)
{
// already found
if (i_object)
return;
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::WorldObjectSearcher<Check>::Visit(CreatureMapType &m)
{
// already found
if (i_object)
return;
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::WorldObjectSearcher<Check>::Visit(CorpseMapType &m)
{
// already found
if (i_object)
return;
for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::WorldObjectSearcher<Check>::Visit(DynamicObjectMapType &m)
{
// already found
if (i_object)
return;
for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::WorldObjectListSearcher<Check>::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::WorldObjectListSearcher<Check>::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::WorldObjectListSearcher<Check>::Visit(CorpseMapType &m)
{
for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::WorldObjectListSearcher<Check>::Visit(GameObjectMapType &m)
{
for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::WorldObjectListSearcher<Check>::Visit(DynamicObjectMapType &m)
{
for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
// Gameobject searchers
template<class Check>
void Trinity::GameObjectSearcher<Check>::Visit(GameObjectMapType &m)
{
// already found
if (i_object)
return;
for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::GameObjectLastSearcher<Check>::Visit(GameObjectMapType &m)
{
for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
i_object = itr->getSource();
}
}
template<class Check>
void Trinity::GameObjectListSearcher<Check>::Visit(GameObjectMapType &m)
{
for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
// Unit searchers
template<class Check>
void Trinity::UnitSearcher<Check>::Visit(CreatureMapType &m)
{
// already found
if (i_object)
return;
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::UnitSearcher<Check>::Visit(PlayerMapType &m)
{
// already found
if (i_object)
return;
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::UnitLastSearcher<Check>::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
i_object = itr->getSource();
}
}
template<class Check>
void Trinity::UnitLastSearcher<Check>::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
i_object = itr->getSource();
}
}
template<class Check>
void Trinity::UnitListSearcher<Check>::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::UnitListSearcher<Check>::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
// Creature searchers
template<class Check>
void Trinity::CreatureSearcher<Check>::Visit(CreatureMapType &m)
{
// already found
if (i_object)
return;
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Check>
void Trinity::CreatureLastSearcher<Check>::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
i_object = itr->getSource();
}
}
template<class Check>
void Trinity::CreatureListSearcher<Check>::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::PlayerListSearcher<Check>::Visit(PlayerMapType &m)
{
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
if (i_check(itr->getSource()))
i_objects.push_back(itr->getSource());
}
template<class Check>
void Trinity::PlayerSearcher<Check>::Visit(PlayerMapType &m)
{
// already found
if (i_object)
return;
for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (i_check(itr->getSource()))
{
i_object = itr->getSource();
return;
}
}
}
template<class Builder>
void Trinity::LocalizedPacketDo<Builder>::operator()(Player* p)
{
int32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
uint32 cache_idx = loc_idx+1;
WorldPacket* data;
// create if not cached yet
if (i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
{
if (i_data_cache.size() < cache_idx+1)
i_data_cache.resize(cache_idx+1);
data = new WorldPacket(SMSG_MESSAGECHAT, 200);
i_builder(*data,loc_idx);
i_data_cache[cache_idx] = data;
}
else
data = i_data_cache[cache_idx];
p->SendDirectMessage(data);
}
template<class Builder>
void Trinity::LocalizedPacketListDo<Builder>::operator()(Player* p)
{
int32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
uint32 cache_idx = loc_idx+1;
WorldPacketList* data_list;
// create if not cached yet
if (i_data_cache.size() < cache_idx+1 || i_data_cache[cache_idx].empty())
{
if (i_data_cache.size() < cache_idx+1)
i_data_cache.resize(cache_idx+1);
data_list = &i_data_cache[cache_idx];
i_builder(*data_list,loc_idx);
}
else
data_list = &i_data_cache[cache_idx];
for (size_t i = 0; i < data_list->size(); ++i)
p->SendDirectMessage((*data_list)[i]);
}
#endif // TRINITY_GRIDNOTIFIERSIMPL_H
+76
View File
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "GridStates.h"
#include "GridNotifiers.h"
#include "GameSystem/Grid.h"
#include "Log.h"
void
InvalidState::Update(Map &, NGridType &, GridInfo &, const uint32 &/*x*/, const uint32 &/*y*/, const uint32 &) const
{
}
void
ActiveState::Update(Map &m, NGridType &grid, GridInfo & info, const uint32 &x, const uint32 &y, const uint32 &t_diff) const
{
// Only check grid activity every (grid_expiry/10) ms, because it's really useless to do it every cycle
info.UpdateTimeTracker(t_diff);
if (info.getTimeTracker().Passed())
{
if (grid.ActiveObjectsInGrid() == 0 && !m.ActiveObjectsNearGrid(x, y))
{
ObjectGridStoper stoper(grid);
stoper.StopN();
grid.SetGridState(GRID_STATE_IDLE);
sLog.outDebug("Grid[%u,%u] on map %u moved to IDLE state", x, y, m.GetId());
}
else
{
m.ResetGridExpiry(grid, 0.1f);
}
}
}
void
IdleState::Update(Map &m, NGridType &grid, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &) const
{
m.ResetGridExpiry(grid);
grid.SetGridState(GRID_STATE_REMOVAL);
sLog.outDebug("Grid[%u,%u] on map %u moved to REMOVAL state", x, y, m.GetId());
}
void
RemovalState::Update(Map &m, NGridType &grid, GridInfo &info, const uint32 &x, const uint32 &y, const uint32 &t_diff) const
{
if (!info.getUnloadLock())
{
info.UpdateTimeTracker(t_diff);
if (info.getTimeTracker().Passed())
{
if (!m.UnloadGrid(x, y, false))
{
sLog.outDebug("Grid[%u,%u] for map %u differed unloading due to players or active objects nearby", x, y, m.GetId());
m.ResetGridExpiry(grid);
}
}
}
}
+76
View File
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_GRIDSTATES_H
#define TRINITY_GRIDSTATES_H
#include "Map.h"
#include "Object.h"
class GridState
{
public:
#ifdef TRINITY_DEBUG
#define MAGIC_TESTVAL 0xFBE823BA
GridState() { i_Magic = MAGIC_TESTVAL; }
bool checkMagic()
{
if (i_Magic != MAGIC_TESTVAL)
{
sLog.outError("!!! GridState: Magic value gone !!!");
return false;
}
return true;
}
void setMagic() { i_Magic = MAGIC_TESTVAL; }
unsigned int i_Magic;
#endif
virtual void Update(Map &, NGridType&, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const = 0;
};
class InvalidState : public GridState
{
public:
void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
};
class ActiveState : public GridState
{
public:
void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
};
class IdleState : public GridState
{
public:
void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
};
class RemovalState : public GridState
{
public:
void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
};
#endif
@@ -0,0 +1,325 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ObjectGridLoader.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Creature.h"
#include "Vehicle.h"
#include "GameObject.h"
#include "DynamicObject.h"
#include "Corpse.h"
#include "World.h"
#include "CellImpl.h"
#include "CreatureAI.h"
class ObjectGridRespawnMover
{
public:
ObjectGridRespawnMover() {}
void Move(GridType &grid);
template<class T> void Visit(GridRefManager<T> &) {}
void Visit(CreatureMapType &m);
};
void
ObjectGridRespawnMover::Move(GridType &grid)
{
TypeContainerVisitor<ObjectGridRespawnMover, GridTypeMapContainer > mover(*this);
grid.Visit(mover);
}
void
ObjectGridRespawnMover::Visit(CreatureMapType &m)
{
// creature in unloading grid can have respawn point in another grid
// if it will be unloaded then it will not respawn in original grid until unload/load original grid
// move to respawn point to prevent this case. For player view in respawn grid this will be normal respawn.
for (CreatureMapType::iterator iter = m.begin(); iter != m.end();)
{
Creature * c = iter->getSource();
++iter;
assert(!c->isPet() && "ObjectGridRespawnMover don't must be called for pets");
Cell const& cur_cell = c->GetCurrentCell();
float resp_x, resp_y, resp_z;
c->GetRespawnCoord(resp_x, resp_y, resp_z);
CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
Cell resp_cell(resp_val);
if (cur_cell.DiffGrid(resp_cell))
{
c->GetMap()->CreatureRespawnRelocation(c);
// false result ignored: will be unload with other creatures at grid
}
}
}
// for loading world object at grid loading (Corpses)
class ObjectWorldLoader
{
public:
explicit ObjectWorldLoader(ObjectGridLoader& gloader)
: i_cell(gloader.i_cell), i_grid(gloader.i_grid), i_map(gloader.i_map), i_corpses (0)
{}
void Visit(CorpseMapType &m);
template<class T> void Visit(GridRefManager<T>&) { }
private:
Cell i_cell;
NGridType &i_grid;
Map* i_map;
public:
uint32 i_corpses;
};
template<class T> void addUnitState(T* /*obj*/, CellPair const& /*cell_pair*/)
{
}
template<> void addUnitState(Creature *obj, CellPair const& cell_pair)
{
Cell cell(cell_pair);
obj->SetCurrentCell(cell);
if (obj->isSpiritService())
obj->setDeathState(DEAD);
}
template <class T>
void AddObjectHelper(CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map, T *obj)
{
obj->GetGridRef().link(&m, obj);
addUnitState(obj,cell);
obj->AddToWorld();
if (obj->isActiveObject())
map->AddToActive(obj);
++count;
}
template <class T>
void LoadHelper(CellGuidSet const& guid_set, CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map)
{
for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid)
{
T* obj = new T;
uint32 guid = *i_guid;
//sLog.outString("DEBUG: LoadHelper from table: %s for (guid: %u) Loading",table,guid);
if (!obj->LoadFromDB(guid, map))
{
delete obj;
continue;
}
AddObjectHelper(cell, m, count, map, obj);
}
}
void LoadHelper(CellCorpseSet const& cell_corpses, CellPair &cell, CorpseMapType &m, uint32 &count, Map* map)
{
if (cell_corpses.empty())
return;
for (CellCorpseSet::const_iterator itr = cell_corpses.begin(); itr != cell_corpses.end(); ++itr)
{
if (itr->second != map->GetInstanceId())
continue;
uint32 player_guid = itr->first;
Corpse *obj = ObjectAccessor::Instance().GetCorpseForPlayerGUID(player_guid);
if (!obj)
continue;
// TODO: this is a hack
// corpse's map should be reset when the map is unloaded
// but it may still exist when the grid is unloaded but map is not
// in that case map == currMap
obj->SetMap(map);
AddObjectHelper(cell, m, count, map, obj);
}
}
void
ObjectGridLoader::Visit(GameObjectMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x,y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
LoadHelper(cell_guids.gameobjects, cell_pair, m, i_gameObjects, i_map);
}
void
ObjectGridLoader::Visit(CreatureMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x,y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
LoadHelper(cell_guids.creatures, cell_pair, m, i_creatures, i_map);
}
void
ObjectWorldLoader::Visit(CorpseMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x,y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
// corpses are always added to spawn mode 0 and they are spawned by their instance id
CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), 0, cell_id);
LoadHelper(cell_guids.corpses, cell_pair, m, i_corpses, i_map);
}
void
ObjectGridLoader::Load(GridType &grid)
{
{
TypeContainerVisitor<ObjectGridLoader, GridTypeMapContainer > loader(*this);
grid.Visit(loader);
}
{
ObjectWorldLoader wloader(*this);
TypeContainerVisitor<ObjectWorldLoader, WorldTypeMapContainer > loader(wloader);
grid.Visit(loader);
i_corpses = wloader.i_corpses;
}
}
void ObjectGridLoader::LoadN(void)
{
i_gameObjects = 0; i_creatures = 0; i_corpses = 0;
i_cell.data.Part.cell_y = 0;
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
i_cell.data.Part.cell_x = x;
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
i_cell.data.Part.cell_y = y;
GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
loader.Load(i_grid(x, y), *this);
}
}
sLog.outDebug("%u GameObjects, %u Creatures, and %u Corpses/Bones loaded for grid %u on map %u", i_gameObjects, i_creatures, i_corpses,i_grid.GetGridId(), i_map->GetId());
}
void ObjectGridUnloader::MoveToRespawnN()
{
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
ObjectGridRespawnMover mover;
mover.Move(i_grid(x, y));
}
}
}
void
ObjectGridUnloader::Unload(GridType &grid)
{
TypeContainerVisitor<ObjectGridUnloader, GridTypeMapContainer > unloader(*this);
grid.Visit(unloader);
}
template<class T>
void
ObjectGridUnloader::Visit(GridRefManager<T> &m)
{
while (!m.isEmpty())
{
T *obj = m.getFirst()->getSource();
// if option set then object already saved at this moment
if (!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
obj->SaveRespawnTime();
///- object will get delinked from the manager when deleted
delete obj;
}
}
void
ObjectGridStoper::Stop(GridType &grid)
{
TypeContainerVisitor<ObjectGridStoper, GridTypeMapContainer > stoper(*this);
grid.Visit(stoper);
}
void
ObjectGridStoper::Visit(CreatureMapType &m)
{
// stop any fights at grid de-activation and remove dynobjects created at cast by creatures
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
iter->getSource()->RemoveAllDynObjects();
if (iter->getSource()->isInCombat())
{
iter->getSource()->CombatStop();
iter->getSource()->DeleteThreatList();
iter->getSource()->AI()->EnterEvadeMode();
}
}
}
void
ObjectGridCleaner::Stop(GridType &grid)
{
TypeContainerVisitor<ObjectGridCleaner, GridTypeMapContainer > stoper(*this);
grid.Visit(stoper);
}
void
ObjectGridCleaner::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
iter->getSource()->CleanupsBeforeDelete();
}
template<class T>
void
ObjectGridCleaner::Visit(GridRefManager<T> &m)
{
for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
iter->getSource()->RemoveFromWorld();
}
template void ObjectGridUnloader::Visit(CreatureMapType &);
template void ObjectGridUnloader::Visit(GameObjectMapType &);
template void ObjectGridUnloader::Visit(DynamicObjectMapType &);
template void ObjectGridUnloader::Visit(CorpseMapType &);
template void ObjectGridCleaner::Visit<GameObject>(GameObjectMapType &);
template void ObjectGridCleaner::Visit<DynamicObject>(DynamicObjectMapType &);
template void ObjectGridCleaner::Visit<Corpse>(CorpseMapType &);
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_OBJECTGRIDLOADER_H
#define TRINITY_OBJECTGRIDLOADER_H
#include "Utilities/TypeList.h"
#include "Platform/Define.h"
#include "GameSystem/GridLoader.h"
#include "GridDefines.h"
#include "Cell.h"
class ObjectWorldLoader;
class ObjectGridLoader
{
friend class ObjectWorldLoader;
public:
ObjectGridLoader(NGridType &grid, Map* map, const Cell &cell)
: i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0)
{}
void Load(GridType &grid);
void Visit(GameObjectMapType &m);
void Visit(CreatureMapType &m);
void Visit(CorpseMapType &) {}
void Visit(DynamicObjectMapType&) { }
void LoadN(void);
private:
Cell i_cell;
NGridType &i_grid;
Map* i_map;
uint32 i_gameObjects;
uint32 i_creatures;
uint32 i_corpses;
};
class ObjectGridUnloader
{
public:
ObjectGridUnloader(NGridType &grid) : i_grid(grid) {}
void MoveToRespawnN();
void UnloadN()
{
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
loader.Unload(i_grid(x, y), *this);
}
}
}
void Unload(GridType &grid);
template<class T> void Visit(GridRefManager<T> &m);
private:
NGridType &i_grid;
};
class ObjectGridStoper
{
public:
ObjectGridStoper(NGridType &grid) : i_grid(grid) {}
void StopN()
{
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
loader.Stop(i_grid(x, y), *this);
}
}
}
void Stop(GridType &grid);
void Visit(CreatureMapType &m);
template<class NONACTIVE> void Visit(GridRefManager<NONACTIVE> &) {}
private:
NGridType &i_grid;
};
class ObjectGridCleaner
{
public:
ObjectGridCleaner(NGridType &grid) : i_grid(grid) {}
void CleanN()
{
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
loader.Stop(i_grid(x, y), *this);
}
}
}
void Stop(GridType &grid);
void Visit(CreatureMapType &m);
template<class T> void Visit(GridRefManager<T> &);
private:
NGridType &i_grid;
};
typedef GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> GridLoaderType;
#endif
File diff suppressed because it is too large Load Diff
+689
View File
@@ -0,0 +1,689 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_MAP_H
#define TRINITY_MAP_H
#include "Platform/Define.h"
#include "Policies/ThreadingModel.h"
#include "ace/RW_Thread_Mutex.h"
#include "ace/Thread_Mutex.h"
#include "DBCStructure.h"
#include "GridDefines.h"
#include "Cell.h"
#include "Timer.h"
#include "SharedDefines.h"
#include "GameSystem/GridRefManager.h"
#include "MapRefManager.h"
#include "mersennetwister/MersenneTwister.h"
#include <bitset>
#include <list>
class Unit;
class WorldPacket;
class InstanceData;
class Group;
class InstanceSave;
class Object;
class WorldObject;
class TempSummon;
class Player;
class CreatureGroup;
struct ScriptInfo;
struct ScriptAction;
struct Position;
class BattleGround;
//******************************************
// Map file format defines
//******************************************
#define MAP_MAGIC 'SPAM'
#define MAP_VERSION_MAGIC '0.1w'
#define MAP_AREA_MAGIC 'AERA'
#define MAP_HEIGHT_MAGIC 'TGHM'
#define MAP_LIQUID_MAGIC 'QILM'
struct map_fileheader
{
uint32 mapMagic;
uint32 versionMagic;
uint32 areaMapOffset;
uint32 areaMapSize;
uint32 heightMapOffset;
uint32 heightMapSize;
uint32 liquidMapOffset;
uint32 liquidMapSize;
};
#define MAP_AREA_NO_AREA 0x0001
struct map_areaHeader
{
uint32 fourcc;
uint16 flags;
uint16 gridArea;
};
#define MAP_HEIGHT_NO_HEIGHT 0x0001
#define MAP_HEIGHT_AS_INT16 0x0002
#define MAP_HEIGHT_AS_INT8 0x0004
struct map_heightHeader
{
uint32 fourcc;
uint32 flags;
float gridHeight;
float gridMaxHeight;
};
#define MAP_LIQUID_NO_TYPE 0x0001
#define MAP_LIQUID_NO_HEIGHT 0x0002
struct map_liquidHeader
{
uint32 fourcc;
uint16 flags;
uint16 liquidType;
uint8 offsetX;
uint8 offsetY;
uint8 width;
uint8 height;
float liquidLevel;
};
enum ZLiquidStatus
{
LIQUID_MAP_NO_WATER = 0x00000000,
LIQUID_MAP_ABOVE_WATER = 0x00000001,
LIQUID_MAP_WATER_WALK = 0x00000002,
LIQUID_MAP_IN_WATER = 0x00000004,
LIQUID_MAP_UNDER_WATER = 0x00000008
};
#define MAP_LIQUID_TYPE_NO_WATER 0x00
#define MAP_LIQUID_TYPE_WATER 0x01
#define MAP_LIQUID_TYPE_OCEAN 0x02
#define MAP_LIQUID_TYPE_MAGMA 0x04
#define MAP_LIQUID_TYPE_SLIME 0x08
#define MAP_ALL_LIQUIDS (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME)
#define MAP_LIQUID_TYPE_DARK_WATER 0x10
#define MAP_LIQUID_TYPE_WMO_WATER 0x20
struct LiquidData
{
uint32 type;
float level;
float depth_level;
};
class GridMap
{
uint32 m_flags;
// Area data
uint16 m_gridArea;
uint16 *m_area_map;
// Height level data
float m_gridHeight;
float m_gridIntHeightMultiplier;
union{
float *m_V9;
uint16 *m_uint16_V9;
uint8 *m_uint8_V9;
};
union{
float *m_V8;
uint16 *m_uint16_V8;
uint8 *m_uint8_V8;
};
// Liquid data
uint16 m_liquidType;
uint8 m_liquid_offX;
uint8 m_liquid_offY;
uint8 m_liquid_width;
uint8 m_liquid_height;
float m_liquidLevel;
uint8 *m_liquid_type;
float *m_liquid_map;
bool loadAreaData(FILE *in, uint32 offset, uint32 size);
bool loadHeihgtData(FILE *in, uint32 offset, uint32 size);
bool loadLiquidData(FILE *in, uint32 offset, uint32 size);
// Get height functions and pointers
typedef float (GridMap::*pGetHeightPtr) (float x, float y) const;
pGetHeightPtr m_gridGetHeight;
float getHeightFromFloat(float x, float y) const;
float getHeightFromUint16(float x, float y) const;
float getHeightFromUint8(float x, float y) const;
float getHeightFromFlat(float x, float y) const;
public:
GridMap();
~GridMap();
bool loadData(char *filaname);
void unloadData();
uint16 getArea(float x, float y);
inline float getHeight(float x, float y) {return (this->*m_gridGetHeight)(x, y);}
float getLiquidLevel(float x, float y);
uint8 getTerrainType(float x, float y);
ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data = 0);
};
struct CreatureMover
{
CreatureMover() : x(0), y(0), z(0), ang(0) {}
CreatureMover(float _x, float _y, float _z, float _ang) : x(_x), y(_y), z(_z), ang(_ang) {}
float x, y, z, ang;
};
// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some platform
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push,1)
#endif
struct InstanceTemplate
{
uint32 map;
uint32 parent;
uint32 access_id;
float startLocX;
float startLocY;
float startLocZ;
float startLocO;
uint32 script_id;
bool allowMount;
};
enum LevelRequirementVsMode
{
LEVELREQUIREMENT_HEROIC = 70
};
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
typedef UNORDERED_MAP<Creature*, CreatureMover> CreatureMoveList;
#define MAX_HEIGHT 100000.0f // can be use for find ground height at surface
#define INVALID_HEIGHT -100000.0f // for check, must be equal to VMAP_INVALID_HEIGHT, real value for unknown height is VMAP_INVALID_HEIGHT_VALUE
#define MIN_UNLOAD_DELAY 1 // immediate unload
typedef std::map<uint32/*leaderDBGUID*/, CreatureGroup*> CreatureGroupHolderType;
class Map : public GridRefManager<NGridType>, public Trinity::ObjectLevelLockable<Map, ACE_Thread_Mutex>
{
friend class MapReference;
public:
Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = NULL);
virtual ~Map();
// currently unused for normal maps
bool CanUnload(uint32 diff)
{
if (!m_unloadTimer) return false;
if (m_unloadTimer <= diff) return true;
m_unloadTimer -= diff;
return false;
}
virtual bool Add(Player *);
virtual void Remove(Player *, bool);
template<class T> void Add(T *);
template<class T> void Remove(T *, bool);
virtual void Update(const uint32&);
/*
void MessageBroadcast(Player *, WorldPacket *, bool to_self);
void MessageBroadcast(WorldObject *, WorldPacket *);
void MessageDistBroadcast(Player *, WorldPacket *, float dist, bool to_self, bool own_team_only = false);
void MessageDistBroadcast(WorldObject *, WorldPacket *, float dist);
*/
float GetVisibilityDistance() const { return m_VisibleDistance; }
//function for setting up visibility distance for maps on per-type/per-Id basis
virtual void InitVisibilityDistance();
void PlayerRelocation(Player *, float x, float y, float z, float orientation);
void CreatureRelocation(Creature *creature, float x, float y, float z, float ang);
template<class T, class CONTAINER> void Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor);
bool IsRemovalGrid(float x, float y) const
{
GridPair p = Trinity::ComputeGridPair(x, y);
return !getNGrid(p.x_coord, p.y_coord) || getNGrid(p.x_coord, p.y_coord)->GetGridState() == GRID_STATE_REMOVAL;
}
bool IsLoaded(float x, float y) const
{
GridPair p = Trinity::ComputeGridPair(x, y);
return loaded(p);
}
bool GetUnloadLock(const GridPair &p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); }
void SetUnloadLock(const GridPair &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadExplicitLock(on); }
void LoadGrid(float x, float y);
bool UnloadGrid(const uint32 &x, const uint32 &y, bool pForce);
virtual void UnloadAll();
void ResetGridExpiry(NGridType &grid, float factor = 1) const
{
grid.ResetTimeTracker(time_t(float(i_gridExpiry)*factor));
}
time_t GetGridExpiry(void) const { return i_gridExpiry; }
uint32 GetId(void) const { return i_mapEntry->MapID; }
static bool ExistMap(uint32 mapid, int gx, int gy);
static bool ExistVMap(uint32 mapid, int gx, int gy);
static void InitStateMachine();
static void DeleteStateMachine();
Map const * GetParent() const { return m_parentMap; }
// some calls like isInWater should not use vmaps due to processor power
// can return INVALID_HEIGHT if under z+2 z coord not found height
float GetHeight(float x, float y, float z, bool pCheckVMap=true) const;
ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data = 0) const;
uint16 GetAreaFlag(float x, float y, float z, bool *isOutdoors=0) const;
bool GetAreaInfo(float x, float y, float z, uint32 &mogpflags, int32 &adtId, int32 &rootId, int32 &groupId) const;
bool IsOutdoors(float x, float y, float z) const;
uint8 GetTerrainType(float x, float y) const;
float GetWaterLevel(float x, float y) const;
bool IsInWater(float x, float y, float z, LiquidData *data = 0) const;
bool IsUnderWater(float x, float y, float z) const;
static uint32 GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id);
static uint32 GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id);
static void GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id);
uint32 GetAreaId(float x, float y, float z) const
{
return GetAreaIdByAreaFlag(GetAreaFlag(x,y,z),GetId());
}
uint32 GetZoneId(float x, float y, float z) const
{
return GetZoneIdByAreaFlag(GetAreaFlag(x,y,z),GetId());
}
void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const
{
GetZoneAndAreaIdByAreaFlag(zoneid,areaid,GetAreaFlag(x,y,z),GetId());
}
void MoveAllCreaturesInMoveList();
void RemoveAllObjectsInRemoveList();
virtual void RemoveAllPlayers();
bool CreatureRespawnRelocation(Creature *c); // used only in MoveAllCreaturesInMoveList and ObjectGridUnloader
// assert print helper
bool CheckGridIntegrity(Creature* c, bool moved) const;
uint32 GetInstanceId() const { return i_InstanceId; }
uint8 GetSpawnMode() const { return (i_spawnMode); }
virtual bool CanEnter(Player* /*player*/) { return true; }
const char* GetMapName() const;
// have meaning only for instanced map (that have set real difficulty)
Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); }
bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; }
MapDifficulty const* GetMapDifficulty() const;
bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); }
// NOTE: this duplicate of Instanceable(), but Instanceable() can be changed when BG also will be instanceable
bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); }
bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); }
bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); }
bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; }
bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; }
bool IsBattleGround() const { return i_mapEntry && i_mapEntry->IsBattleGround(); }
bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); }
bool IsBattleGroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattleGroundOrArena(); }
bool GetEntrancePos(int32 &mapid, float &x, float &y)
{
if (!i_mapEntry)
return false;
return i_mapEntry->GetEntrancePos(mapid, x, y);
}
void AddObjectToRemoveList(WorldObject *obj);
void AddObjectToSwitchList(WorldObject *obj, bool on);
virtual void DelayedUpdate(const uint32 diff);
virtual bool RemoveBones(uint64 guid, float x, float y);
void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellPair cellpair);
void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellPair cellpair);
void resetMarkedCells() { marked_cells.reset(); }
bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); }
void markCell(uint32 pCellId) { marked_cells.set(pCellId); }
bool HavePlayers() const { return !m_mapRefManager.isEmpty(); }
uint32 GetPlayersCountExceptGMs() const;
bool ActiveObjectsNearGrid(uint32 x, uint32 y) const;
void AddWorldObject(WorldObject *obj) { i_worldObjects.insert(obj); }
void RemoveWorldObject(WorldObject *obj) { i_worldObjects.erase(obj); }
void SendToPlayers(WorldPacket const* data) const;
typedef MapRefManager PlayerList;
PlayerList const& GetPlayers() const { return m_mapRefManager; }
//per-map script storage
void ScriptsStart(std::map<uint32, std::multimap<uint32, ScriptInfo> > const& scripts, uint32 id, Object* source, Object* target);
void ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target);
// must called with AddToWorld
template<class T>
void AddToActive(T* obj) { AddToActiveHelper(obj); }
void AddToActive(Creature* obj);
// must called with RemoveFromWorld
template<class T>
void RemoveFromActive(T* obj) { RemoveFromActiveHelper(obj); }
void RemoveFromActive(Creature* obj);
template<class T> void SwitchGridContainers(T* obj, bool active);
template<class NOTIFIER> void VisitAll(const float &x, const float &y, float radius, NOTIFIER &notifier);
template<class NOTIFIER> void VisitWorld(const float &x, const float &y, float radius, NOTIFIER &notifier);
template<class NOTIFIER> void VisitGrid(const float &x, const float &y, float radius, NOTIFIER &notifier);
CreatureGroupHolderType CreatureGroupHolder;
void UpdateIteratorBack(Player *player);
#ifdef MAP_BASED_RAND_GEN
MTRand mtRand;
int32 irand(int32 min, int32 max) { return int32 (mtRand.randInt(max - min)) + min; }
uint32 urand(uint32 min, uint32 max) { return mtRand.randInt(max - min) + min; }
int32 rand32() { return mtRand.randInt(); }
double rand_norm() { return mtRand.randExc(); }
double rand_chance() { return mtRand.randExc(100.0); }
#endif
TempSummon *SummonCreature(uint32 entry, const Position &pos, SummonPropertiesEntry const *properties = NULL, uint32 duration = 0, Unit *summoner = NULL, uint32 vehId = 0);
Creature* GetCreature(uint64 guid);
GameObject* GetGameObject(uint64 guid);
DynamicObject* GetDynamicObject(uint64 guid);
private:
void LoadMapAndVMap(int gx, int gy);
void LoadVMap(int gx, int gy);
void LoadMap(int gx,int gy, bool reload = false);
GridMap *GetGrid(float x, float y);
void SetTimer(uint32 t) { i_gridExpiry = t < MIN_GRID_DELAY ? MIN_GRID_DELAY : t; }
void SendInitSelf(Player * player);
void SendInitTransports(Player * player);
void SendRemoveTransports(Player * player);
bool CreatureCellRelocation(Creature *creature, Cell new_cell);
void AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang);
CreatureMoveList i_creaturesToMove;
bool loaded(const GridPair &) const;
void EnsureGridCreated(const GridPair &);
bool EnsureGridLoaded(Cell const&);
void EnsureGridLoadedAtEnter(Cell const&, Player* player = NULL);
void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); }
template<class T> void AddType(T *obj);
template<class T> void RemoveType(T *obj, bool);
NGridType* getNGrid(uint32 x, uint32 y) const
{
ASSERT(x < MAX_NUMBER_OF_GRIDS);
ASSERT(y < MAX_NUMBER_OF_GRIDS);
return i_grids[x][y];
}
bool isGridObjectDataLoaded(uint32 x, uint32 y) const { return getNGrid(x,y)->isGridObjectDataLoaded(); }
void setGridObjectDataLoaded(bool pLoaded, uint32 x, uint32 y) { getNGrid(x,y)->setGridObjectDataLoaded(pLoaded); }
void setNGrid(NGridType* grid, uint32 x, uint32 y);
void ScriptsProcess();
void UpdateActiveCells(const float &x, const float &y, const uint32 &t_diff);
protected:
void SetUnloadReferenceLock(const GridPair &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadReferenceLock(on); }
typedef Trinity::ObjectLevelLockable<Map, ACE_Thread_Mutex>::Lock Guard;
MapEntry const* i_mapEntry;
uint8 i_spawnMode;
uint32 i_InstanceId;
uint32 m_unloadTimer;
float m_VisibleDistance;
MapRefManager m_mapRefManager;
MapRefManager::iterator m_mapRefIter;
int32 m_VisibilityNotifyPeriod;
typedef std::set<WorldObject*> ActiveNonPlayers;
ActiveNonPlayers m_activeNonPlayers;
ActiveNonPlayers::iterator m_activeNonPlayersIter;
private:
time_t i_gridExpiry;
//used for fast base_map (e.g. MapInstanced class object) search for
//InstanceMaps and BattleGroundMaps...
Map* m_parentMap;
NGridType* i_grids[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
GridMap *GridMaps[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
std::bitset<TOTAL_NUMBER_OF_CELLS_PER_MAP*TOTAL_NUMBER_OF_CELLS_PER_MAP> marked_cells;
//these functions used to process player/mob aggro reactions and
//visibility calculations. Highly optimized for massive calculations
void ProcessRelocationNotifies(const uint32 &diff);
bool i_scriptLock;
std::set<WorldObject *> i_objectsToRemove;
std::map<WorldObject*, bool> i_objectsToSwitch;
std::set<WorldObject*> i_worldObjects;
std::multimap<time_t, ScriptAction> m_scriptSchedule;
// Type specific code for add/remove to/from grid
template<class T>
void AddToGrid(T*, NGridType *, Cell const&);
template<class T>
void RemoveFromGrid(T*, NGridType *, Cell const&);
template<class T>
void DeleteFromWorld(T*);
template<class T>
void AddToActiveHelper(T* obj)
{
m_activeNonPlayers.insert(obj);
}
template<class T>
void RemoveFromActiveHelper(T* obj)
{
// Map::Update for active object in proccess
if (m_activeNonPlayersIter != m_activeNonPlayers.end())
{
ActiveNonPlayers::iterator itr = m_activeNonPlayers.find(obj);
if (itr == m_activeNonPlayers.end())
return;
if (itr == m_activeNonPlayersIter)
++m_activeNonPlayersIter;
m_activeNonPlayers.erase(itr);
}
else
m_activeNonPlayers.erase(obj);
}
};
enum InstanceResetMethod
{
INSTANCE_RESET_ALL,
INSTANCE_RESET_CHANGE_DIFFICULTY,
INSTANCE_RESET_GLOBAL,
INSTANCE_RESET_GROUP_DISBAND,
INSTANCE_RESET_GROUP_JOIN,
INSTANCE_RESET_RESPAWN_DELAY
};
class InstanceMap : public Map
{
public:
InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent);
~InstanceMap();
bool Add(Player *);
void Remove(Player *, bool);
void Update(const uint32&);
void CreateInstanceData(bool load);
bool Reset(uint8 method);
uint32 GetScriptId() { return i_script_id; }
InstanceData* GetInstanceData() { return i_data; }
void PermBindAllPlayers(Player *player);
void UnloadAll();
bool CanEnter(Player* player);
void SendResetWarnings(uint32 timeLeft) const;
void SetResetSchedule(bool on);
uint32 GetMaxPlayers() const;
uint32 GetMaxResetDelay() const;
virtual void InitVisibilityDistance();
private:
bool m_resetAfterUnload;
bool m_unloadWhenEmpty;
InstanceData* i_data;
uint32 i_script_id;
};
class BattleGroundMap : public Map
{
public:
BattleGroundMap(uint32 id, time_t, uint32 InstanceId, Map* _parent, uint8 spawnMode);
~BattleGroundMap();
bool Add(Player *);
void Remove(Player *, bool);
bool CanEnter(Player* player);
void SetUnload();
//void UnloadAll(bool pForce);
void RemoveAllPlayers();
virtual void InitVisibilityDistance();
BattleGround* GetBG() { return m_bg; }
void SetBG(BattleGround* bg) { m_bg = bg; }
private:
BattleGround* m_bg;
};
/*inline
uint64
Map::CalculateGridMask(const uint32 &y) const
{
uint64 mask = 1;
mask <<= y;
return mask;
}
*/
template<class T, class CONTAINER>
inline void
Map::Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor)
{
const uint32 x = cell.GridX();
const uint32 y = cell.GridY();
const uint32 cell_x = cell.CellX();
const uint32 cell_y = cell.CellY();
if (!cell.NoCreate() || loaded(GridPair(x,y)))
{
EnsureGridLoaded(cell);
getNGrid(x, y)->Visit(cell_x, cell_y, visitor);
}
}
template<class NOTIFIER>
inline void
Map::VisitAll(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellPair p(Trinity::ComputeCellPair(x, y));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, WorldTypeMapContainer> world_object_notifier(notifier);
cell.Visit(p, world_object_notifier, *this, radius, x, y);
TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
cell.Visit(p, grid_object_notifier, *this, radius, x, y);
}
template<class NOTIFIER>
inline void
Map::VisitWorld(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellPair p(Trinity::ComputeCellPair(x, y));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, WorldTypeMapContainer> world_object_notifier(notifier);
cell.Visit(p, world_object_notifier, *this, radius, x, y);
}
template<class NOTIFIER>
inline void
Map::VisitGrid(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellPair p(Trinity::ComputeCellPair(x, y));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
cell.Visit(p, grid_object_notifier, *this, radius, x, y);
}
#endif
+268
View File
@@ -0,0 +1,268 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MapInstanced.h"
#include "ObjectMgr.h"
#include "MapManager.h"
#include "BattleGround.h"
#include "VMapFactory.h"
#include "InstanceSaveMgr.h"
#include "World.h"
MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, DUNGEON_DIFFICULTY_NORMAL)
{
// initialize instanced maps list
m_InstancedMaps.clear();
// fill with zero
memset(&GridMapReference, 0, MAX_NUMBER_OF_GRIDS*MAX_NUMBER_OF_GRIDS*sizeof(uint16));
}
void MapInstanced::InitVisibilityDistance()
{
if (m_InstancedMaps.empty())
return;
//initialize visibility distances for all instance copies
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
{
(*i).second->InitVisibilityDistance();
}
}
void MapInstanced::Update(const uint32& t)
{
// take care of loaded GridMaps (when unused, unload it!)
Map::Update(t);
// update the instanced maps
InstancedMaps::iterator i = m_InstancedMaps.begin();
while (i != m_InstancedMaps.end())
{
if (i->second->CanUnload(t))
{
if (!DestroyInstance(i)) // iterator incremented
{
//m_unloadTimer
}
}
else
{
// update only here, because it may schedule some bad things before delete
i->second->Update(t);
++i;
}
}
}
void MapInstanced::DelayedUpdate(const uint32 diff)
{
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->DelayedUpdate(diff);
Map::DelayedUpdate(diff); // this may be removed
}
/*
void MapInstanced::RelocationNotify()
{
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->RelocationNotify();
}
*/
bool MapInstanced::RemoveBones(uint64 guid, float x, float y)
{
bool remove_result = false;
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
{
remove_result = remove_result || i->second->RemoveBones(guid, x, y);
}
return remove_result || Map::RemoveBones(guid,x,y);
}
void MapInstanced::UnloadAll()
{
// Unload instanced maps
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->UnloadAll();
// Delete the maps only after everything is unloaded to prevent crashes
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
delete i->second;
m_InstancedMaps.clear();
// Unload own grids (just dummy(placeholder) grids, neccesary to unload GridMaps!)
Map::UnloadAll();
}
/*
- return the right instance for the object, based on its InstanceId
- create the instance if it's not created already
- the player is not actually added to the instance (only in InstanceMap::Add)
*/
Map* MapInstanced::CreateInstance(const uint32 mapId, Player * player)
{
if (GetId() != mapId || !player)
return NULL;
Map* map = NULL;
uint32 NewInstanceId = 0; // instanceId of the resulting map
if (IsBattleGroundOrArena())
{
// instantiate or find existing bg map for player
// the instance id is set in battlegroundid
NewInstanceId = player->GetBattleGroundId();
if (!NewInstanceId) return NULL;
map = _FindMap(NewInstanceId);
if (!map)
map = CreateBattleGround(NewInstanceId, player->GetBattleGround());
}
else
{
InstancePlayerBind *pBind = player->GetBoundInstance(GetId(), player->GetDifficulty(IsRaid()));
InstanceSave *pSave = pBind ? pBind->save : NULL;
// the player's permanent player bind is taken into consideration first
// then the player's group bind and finally the solo bind.
if (!pBind || !pBind->perm)
{
InstanceGroupBind *groupBind = NULL;
Group *group = player->GetGroup();
// use the player's difficulty setting (it may not be the same as the group's)
if (group)
{
groupBind = group->GetBoundInstance(this);
if (groupBind)
pSave = groupBind->save;
}
}
if (pSave)
{
// solo/perm/group
NewInstanceId = pSave->GetInstanceId();
map = _FindMap(NewInstanceId);
// it is possible that the save exists but the map doesn't
if (!map)
map = CreateInstance(NewInstanceId, pSave, pSave->GetDifficulty());
}
else
{
// if no instanceId via group members or instance saves is found
// the instance will be created for the first time
NewInstanceId = MapManager::Instance().GenerateInstanceId();
Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficulty(IsRaid()) : player->GetDifficulty(IsRaid());
map = CreateInstance(NewInstanceId, NULL, diff);
}
}
return map;
}
InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave *save, Difficulty difficulty)
{
// load/create a map
Guard guard(*this);
// make sure we have a valid map id
const MapEntry* entry = sMapStore.LookupEntry(GetId());
if (!entry)
{
sLog.outError("CreateInstance: no entry for map %d", GetId());
assert(false);
}
const InstanceTemplate * iTemplate = objmgr.GetInstanceTemplate(GetId());
if (!iTemplate)
{
sLog.outError("CreateInstance: no instance template for map %d", GetId());
assert(false);
}
// some instances only have one difficulty
MapDifficulty const* mapDiff = GetMapDifficultyData(GetId(),difficulty);
if (!mapDiff)
difficulty = DUNGEON_DIFFICULTY_NORMAL;
sLog.outDebug("MapInstanced::CreateInstance: %s map instance %d for %d created with difficulty %s", save?"":"new ", InstanceId, GetId(), difficulty?"heroic":"normal");
InstanceMap *map = new InstanceMap(GetId(), GetGridExpiry(), InstanceId, difficulty, this);
ASSERT(map->IsDungeon());
bool load_data = save != NULL;
map->CreateInstanceData(load_data);
m_InstancedMaps[InstanceId] = map;
return map;
}
BattleGroundMap* MapInstanced::CreateBattleGround(uint32 InstanceId, BattleGround* bg)
{
// load/create a map
Guard guard(*this);
sLog.outDebug("MapInstanced::CreateBattleGround: map bg %d for %d created.", InstanceId, GetId());
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),bg->GetMinLevel());
uint8 spawnMode = bracketEntry ? bracketEntry->difficulty : REGULAR_DIFFICULTY;
BattleGroundMap *map = new BattleGroundMap(GetId(), GetGridExpiry(), InstanceId, this, spawnMode);
ASSERT(map->IsBattleGroundOrArena());
map->SetBG(bg);
bg->SetBgMap(map);
m_InstancedMaps[InstanceId] = map;
return map;
}
// increments the iterator after erase
bool MapInstanced::DestroyInstance(InstancedMaps::iterator &itr)
{
itr->second->RemoveAllPlayers();
if (itr->second->HavePlayers())
{
++itr;
return false;
}
itr->second->UnloadAll();
// should only unload VMaps if this is the last instance and grid unloading is enabled
if (m_InstancedMaps.size() <= 1 && sWorld.getConfig(CONFIG_GRID_UNLOAD))
{
VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(itr->second->GetId());
// in that case, unload grids of the base map, too
// so in the next map creation, (EnsureGridCreated actually) VMaps will be reloaded
Map::UnloadAll();
}
// erase map
delete itr->second;
m_InstancedMaps.erase(itr++);
return true;
}
bool MapInstanced::CanEnter(Player * /*player*/)
{
//assert(false);
return true;
}
+80
View File
@@ -0,0 +1,80 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_MAP_INSTANCED_H
#define TRINITY_MAP_INSTANCED_H
#include "Map.h"
#include "InstanceSaveMgr.h"
#include "DBCEnums.h"
class MapInstanced : public Map
{
friend class MapManager;
public:
typedef UNORDERED_MAP< uint32, Map* > InstancedMaps;
MapInstanced(uint32 id, time_t expiry);
~MapInstanced() {}
// functions overwrite Map versions
void Update(const uint32&);
void DelayedUpdate(const uint32 diff);
//void RelocationNotify();
bool RemoveBones(uint64 guid, float x, float y);
void UnloadAll();
bool CanEnter(Player* player);
Map* CreateInstance(const uint32 mapId, Player * player);
Map* FindMap(uint32 InstanceId) const { return _FindMap(InstanceId); }
bool DestroyInstance(InstancedMaps::iterator &itr);
void AddGridMapReference(const GridPair &p)
{
++GridMapReference[p.x_coord][p.y_coord];
SetUnloadReferenceLock(GridPair(63-p.x_coord, 63-p.y_coord), true);
}
void RemoveGridMapReference(GridPair const& p)
{
--GridMapReference[p.x_coord][p.y_coord];
if (!GridMapReference[p.x_coord][p.y_coord])
SetUnloadReferenceLock(GridPair(63-p.x_coord, 63-p.y_coord), false);
}
InstancedMaps &GetInstancedMaps() { return m_InstancedMaps; }
virtual void InitVisibilityDistance();
private:
InstanceMap* CreateInstance(uint32 InstanceId, InstanceSave *save, Difficulty difficulty);
BattleGroundMap* CreateBattleGround(uint32 InstanceId, BattleGround* bg);
InstancedMaps m_InstancedMaps;
Map* _FindMap(uint32 InstanceId) const
{
InstancedMaps::const_iterator i = m_InstancedMaps.find(InstanceId);
return(i == m_InstancedMaps.end() ? NULL : i->second);
}
uint16 GridMapReference[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
};
#endif
+395
View File
@@ -0,0 +1,395 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MapManager.h"
#include "InstanceSaveMgr.h"
#include "Policies/SingletonImp.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "ObjectAccessor.h"
#include "Transports.h"
#include "GridDefines.h"
#include "MapInstanced.h"
#include "InstanceData.h"
#include "DestinationHolderImp.h"
#include "Config/ConfigEnv.h"
#include "World.h"
#include "CellImpl.h"
#include "Corpse.h"
#include "ObjectMgr.h"
#include "Language.h"
#include "WorldPacket.h"
#define CLASS_LOCK Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex>
INSTANTIATE_SINGLETON_2(MapManager, CLASS_LOCK);
INSTANTIATE_CLASS_MUTEX(MapManager, ACE_Thread_Mutex);
extern GridState* si_GridStates[]; // debugging code, should be deleted some day
MapManager::MapManager()
{
i_gridCleanUpDelay = sWorld.getConfig(CONFIG_INTERVAL_GRIDCLEAN);
i_timer.SetInterval(sWorld.getConfig(CONFIG_INTERVAL_MAPUPDATE));
}
MapManager::~MapManager()
{
for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
delete iter->second;
for (TransportSet::iterator i = m_Transports.begin(); i != m_Transports.end(); ++i)
delete *i;
Map::DeleteStateMachine();
}
void MapManager::Initialize()
{
Map::InitStateMachine();
// debugging code, should be deleted some day
{
for (uint8 i = 0; i < MAX_GRID_STATE; ++i)
i_GridStates[i] = si_GridStates[i];
i_GridStateErrorCount = 0;
}
int num_threads(sWorld.getConfig(CONFIG_NUMTHREADS));
// Start mtmaps if needed.
if (num_threads > 0 && m_updater.activate(num_threads) == -1)
abort();
InitMaxInstanceId();
}
void MapManager::InitializeVisibilityDistanceInfo()
{
for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
(*iter).second->InitVisibilityDistance();
}
// debugging code, should be deleted some day
void MapManager::checkAndCorrectGridStatesArray()
{
bool ok = true;
for (int i=0; i<MAX_GRID_STATE; i++)
{
if (i_GridStates[i] != si_GridStates[i])
{
sLog.outError("MapManager::checkGridStates(), GridState: si_GridStates is currupt !!!");
ok = false;
si_GridStates[i] = i_GridStates[i];
}
#ifdef TRINITY_DEBUG
// inner class checking only when compiled with debug
if (!si_GridStates[i]->checkMagic())
{
ok = false;
si_GridStates[i]->setMagic();
}
#endif
}
if (!ok)
++i_GridStateErrorCount;
}
Map* MapManager::_createBaseMap(uint32 id)
{
Map *m = _findMap(id);
if (m == NULL)
{
Guard guard(*this);
const MapEntry* entry = sMapStore.LookupEntry(id);
if (entry && entry->Instanceable())
{
m = new MapInstanced(id, i_gridCleanUpDelay);
}
else
{
m = new Map(id, i_gridCleanUpDelay, 0, REGULAR_DIFFICULTY);
}
i_maps[id] = m;
}
assert(m != NULL);
return m;
}
Map* MapManager::CreateMap(uint32 id, const WorldObject* obj, uint32 /*instanceId*/)
{
ASSERT(obj);
//if (!obj->IsInWorld()) sLog.outError("GetMap: called for map %d with object (typeid %d, guid %d, mapid %d, instanceid %d) who is not in world!", id, obj->GetTypeId(), obj->GetGUIDLow(), obj->GetMapId(), obj->GetInstanceId());
Map *m = _createBaseMap(id);
if (m && (obj->GetTypeId() == TYPEID_PLAYER) && m->Instanceable()) m = ((MapInstanced*)m)->CreateInstance(id, (Player*)obj);
return m;
}
Map* MapManager::FindMap(uint32 mapid, uint32 instanceId) const
{
Map *map = _findMap(mapid);
if (!map)
return NULL;
if (!map->Instanceable())
return instanceId == 0 ? map : NULL;
return ((MapInstanced*)map)->FindMap(instanceId);
}
bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck)
{
const MapEntry *entry = sMapStore.LookupEntry(mapid);
if (!entry)
return false;
if (!entry->IsDungeon())
return true;
const char *mapName = entry->name[player->GetSession()->GetSessionDbcLocale()];
Group* pGroup = player->GetGroup();
if (entry->IsRaid())
{
// can only enter in a raid group
// GMs can avoid raid limitations
if ((!pGroup || !pGroup->isRaidGroup()) && !player->isGameMaster() && !sWorld.getConfig(CONFIG_INSTANCE_IGNORE_RAID))
{
// probably there must be special opcode, because client has this string constant in GlobalStrings.lua
// TODO: this is not a good place to send the message
player->GetSession()->SendAreaTriggerMessage(player->GetSession()->GetTrinityString(LANG_INSTANCE_RAID_GROUP_ONLY), mapName);
sLog.outDebug("MAP: Player '%s' must be in a raid group to enter instance '%s'", player->GetName(), mapName);
return false;
}
}
//The player has a heroic mode and tries to enter into instance which has no a heroic mode
MapDifficulty const* mapDiff = GetMapDifficultyData(entry->MapID,player->GetDifficulty(entry->IsRaid()));
if (!mapDiff)
{
bool isNormalTargetMap = entry->IsRaid()
? (player->GetRaidDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL)
: (player->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL);
// Send aborted message
// FIX ME: what about absent normal/heroic mode with specific players limit...
player->SendTransferAborted(mapid, TRANSFER_ABORT_DIFFICULTY, isNormalTargetMap ? DUNGEON_DIFFICULTY_NORMAL : DUNGEON_DIFFICULTY_HEROIC);
return false;
}
if (!player->isAlive())
{
if (Corpse *corpse = player->GetCorpse())
{
// let enter in ghost mode in instance that connected to inner instance with corpse
uint32 instance_map = corpse->GetMapId();
do
{
if (instance_map == mapid)
break;
InstanceTemplate const* instance = objmgr.GetInstanceTemplate(instance_map);
instance_map = instance ? instance->parent : 0;
}
while (instance_map);
if (!instance_map)
{
WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE);
player->GetSession()->SendPacket(&data);
sLog.outDebug("MAP: Player '%s' does not have a corpse in instance '%s' and cannot enter.", player->GetName(), mapName);
return false;
}
sLog.outDebug("MAP: Player '%s' has corpse in instance '%s' and can enter.", player->GetName(), mapName);
}
else
sLog.outDebug("Map::CanPlayerEnter - player '%s' is dead but does not have a corpse!", player->GetName());
}
InstanceTemplate const* instance = objmgr.GetInstanceTemplate(mapid);
if (!instance)
return false;
//Get instance where player's group is bound & its map
if (pGroup)
{
InstanceGroupBind* boundedInstance = pGroup->GetBoundInstance(player);
if (boundedInstance && boundedInstance->save)
{
if (Map *boundedMap = MapManager::Instance().FindMap(mapid,boundedInstance->save->GetInstanceId()))
{
// Player permanently bounded to different instance than groups one
InstancePlayerBind* playerBoundedInstance = player->GetBoundInstance(mapid, player->GetDungeonDifficulty());
if (playerBoundedInstance && playerBoundedInstance->perm && playerBoundedInstance->save &&
boundedInstance->save->GetInstanceId() != playerBoundedInstance->save->GetInstanceId())
{
//TODO: send some kind of error message to the player
return false;
}
// Encounters in progress
if (!loginCheck && entry->IsRaid() && ((InstanceMap*)boundedMap)->GetInstanceData() && ((InstanceMap*)boundedMap)->GetInstanceData()->IsEncounterInProgress())
{
sLog.outDebug("MAP: Player '%s' cannot enter instance '%s' while an encounter is in progress.", player->GetName(), mapName);
player->SendTransferAborted(mapid, TRANSFER_ABORT_ZONE_IN_COMBAT);
return false;
}
// Instance is full
MapDifficulty const* mapDiff = ((InstanceMap*)boundedMap)->GetMapDifficulty();
int8 maxPlayers = mapDiff ? mapDiff->maxPlayers : 0;
if (maxPlayers != -1) //-1: unlimited access
{
if (boundedMap->GetPlayersCountExceptGMs() >= (loginCheck ? maxPlayers+1 : maxPlayers))
{
sLog.outDebug("MAP: Player '%s' cannot enter instance '%s' because it is full.", player->GetName(), mapName);
player->SendTransferAborted(mapid, TRANSFER_ABORT_MAX_PLAYERS);
return false;
}
}
}
}
}
//Other requirements
return player->Satisfy(objmgr.GetAccessRequirement(instance->access_id), mapid, true);
}
void MapManager::RemoveBonesFromMap(uint32 mapid, uint64 guid, float x, float y)
{
bool remove_result = _createBaseMap(mapid)->RemoveBones(guid, x, y);
if (!remove_result)
{
sLog.outDebug("Bones %u not found in world. Delete from DB also.", GUID_LOPART(guid));
}
}
void MapManager::Update(uint32 diff)
{
i_timer.Update(diff);
if (!i_timer.Passed())
return;
MapMapType::iterator iter = i_maps.begin();
for (; iter != i_maps.end(); ++iter)
{
if (m_updater.activated())
m_updater.schedule_update(*iter->second, i_timer.GetCurrent());
else
{
iter->second->Update(i_timer.GetCurrent());
}
}
if (m_updater.activated())
m_updater.wait();
for (iter = i_maps.begin(); iter != i_maps.end(); ++iter)
iter->second->DelayedUpdate(i_timer.GetCurrent());
ObjectAccessor::Instance().Update(i_timer.GetCurrent());
for (TransportSet::iterator iter = m_Transports.begin(); iter != m_Transports.end(); ++iter)
(*iter)->Update(i_timer.GetCurrent());
i_timer.SetCurrent(0);
}
void MapManager::DoDelayedMovesAndRemoves()
{
}
bool MapManager::ExistMapAndVMap(uint32 mapid, float x,float y)
{
GridPair p = Trinity::ComputeGridPair(x,y);
int gx=63-p.x_coord;
int gy=63-p.y_coord;
return Map::ExistMap(mapid,gx,gy) && Map::ExistVMap(mapid,gx,gy);
}
bool MapManager::IsValidMAP(uint32 mapid)
{
MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
return mEntry && (!mEntry->IsDungeon() || objmgr.GetInstanceTemplate(mapid));
// TODO: add check for battleground template
}
void MapManager::UnloadAll()
{
for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
iter->second->UnloadAll();
while (!i_maps.empty())
{
delete i_maps.begin()->second;
i_maps.erase(i_maps.begin());
}
if (m_updater.activated())
m_updater.deactivate();
}
void MapManager::InitMaxInstanceId()
{
i_MaxInstanceId = 0;
QueryResult_AutoPtr result = CharacterDatabase.Query("SELECT MAX(id) FROM instance");
if (result)
i_MaxInstanceId = result->Fetch()[0].GetUInt32();
}
uint32 MapManager::GetNumInstances()
{
Guard guard(*this);
uint32 ret = 0;
for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr)
{
Map *map = itr->second;
if (!map->Instanceable())
continue;
MapInstanced::InstancedMaps &maps = ((MapInstanced *)map)->GetInstancedMaps();
for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
if (mitr->second->IsDungeon()) ret++;
}
return ret;
}
uint32 MapManager::GetNumPlayersInInstances()
{
Guard guard(*this);
uint32 ret = 0;
for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr)
{
Map *map = itr->second;
if (!map->Instanceable())
continue;
MapInstanced::InstancedMaps &maps = ((MapInstanced *)map)->GetInstancedMaps();
for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
if (mitr->second->IsDungeon())
ret += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
}
return ret;
}
+158
View File
@@ -0,0 +1,158 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef TRINITY_MAPMANAGER_H
#define TRINITY_MAPMANAGER_H
#include "Platform/Define.h"
#include "Policies/Singleton.h"
#include "ace/Thread_Mutex.h"
#include "Common.h"
#include "Map.h"
#include "GridStates.h"
#include "MapUpdater.h"
class Transport;
class MapManager : public Trinity::Singleton<MapManager, Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex> >
{
friend class Trinity::OperatorNew<MapManager>;
typedef UNORDERED_MAP<uint32, Map*> MapMapType;
typedef std::pair<UNORDERED_MAP<uint32, Map*>::iterator, bool> MapMapPair;
public:
Map* CreateMap(uint32, const WorldObject* obj, uint32 instanceId);
Map const* CreateBaseMap(uint32 id) const { return const_cast<MapManager*>(this)->_createBaseMap(id); }
Map* FindMap(uint32 mapid, uint32 instanceId = 0) const;
uint16 GetAreaFlag(uint32 mapid, float x, float y, float z) const
{
Map const* m = CreateBaseMap(mapid);
return m->GetAreaFlag(x, y, z);
}
uint32 GetAreaId(uint32 mapid, float x, float y, float z) const
{
return Map::GetAreaIdByAreaFlag(GetAreaFlag(mapid, x, y, z),mapid);
}
uint32 GetZoneId(uint32 mapid, float x, float y, float z) const
{
return Map::GetZoneIdByAreaFlag(GetAreaFlag(mapid, x, y, z),mapid);
}
void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, uint32 mapid, float x, float y, float z)
{
Map::GetZoneAndAreaIdByAreaFlag(zoneid,areaid,GetAreaFlag(mapid, x, y, z),mapid);
}
void Initialize(void);
void Update(uint32);
void SetGridCleanUpDelay(uint32 t)
{
if (t < MIN_GRID_DELAY)
i_gridCleanUpDelay = MIN_GRID_DELAY;
else
i_gridCleanUpDelay = t;
}
void SetMapUpdateInterval(uint32 t)
{
if (t > MIN_MAP_UPDATE_DELAY)
t = MIN_MAP_UPDATE_DELAY;
i_timer.SetInterval(t);
i_timer.Reset();
}
//void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false);
void UnloadAll();
static bool ExistMapAndVMap(uint32 mapid, float x, float y);
static bool IsValidMAP(uint32 mapid);
static bool IsValidMapCoord(uint32 mapid, float x,float y)
{
return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y);
}
static bool IsValidMapCoord(uint32 mapid, float x,float y,float z)
{
return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y,z);
}
static bool IsValidMapCoord(uint32 mapid, float x,float y,float z,float o)
{
return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y,z,o);
}
static bool IsValidMapCoord(WorldLocation const& loc)
{
return IsValidMapCoord(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation());
}
void DoDelayedMovesAndRemoves();
void LoadTransports();
typedef std::set<Transport *> TransportSet;
TransportSet m_Transports;
typedef std::map<uint32, TransportSet> TransportMap;
TransportMap m_TransportsByMap;
bool CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck = false);
void RemoveBonesFromMap(uint32 mapid, uint64 guid, float x, float y);
uint32 GenerateInstanceId() { return ++i_MaxInstanceId; }
void InitMaxInstanceId();
void InitializeVisibilityDistanceInfo();
/* statistics */
uint32 GetNumInstances();
uint32 GetNumPlayersInInstances();
private:
// debugging code, should be deleted some day
void checkAndCorrectGridStatesArray(); // just for debugging to find some memory overwrites
GridState* i_GridStates[MAX_GRID_STATE]; // shadow entries to the global array in Map.cpp
int i_GridStateErrorCount;
private:
MapManager();
~MapManager();
MapManager(const MapManager &);
MapManager& operator=(const MapManager &);
Map* _createBaseMap(uint32 id);
Map* _findMap(uint32 id) const
{
MapMapType::const_iterator iter = i_maps.find(id);
return (iter == i_maps.end() ? NULL : iter->second);
}
typedef Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex>::Lock Guard;
uint32 i_gridCleanUpDelay;
MapMapType i_maps;
IntervalTimer i_timer;
uint32 i_MaxInstanceId;
MapUpdater m_updater;
};
#endif
+45
View File
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _MAPREFMANAGER
#define _MAPREFMANAGER
#include "Utilities/LinkedReference/RefManager.h"
class MapReference;
class MapRefManager : public RefManager<Map, Player>
{
public:
typedef LinkedListHead::Iterator< MapReference > iterator;
typedef LinkedListHead::Iterator< MapReference const > const_iterator;
MapReference* getFirst() { return (MapReference*)RefManager<Map, Player>::getFirst(); }
MapReference const* getFirst() const { return (MapReference const*)RefManager<Map, Player>::getFirst(); }
MapReference* getLast() { return (MapReference*)RefManager<Map, Player>::getLast(); }
MapReference const* getLast() const { return (MapReference const*)RefManager<Map, Player>::getLast(); }
iterator begin() { return iterator(getFirst()); }
iterator end() { return iterator(NULL); }
iterator rbegin() { return iterator(getLast()); }
iterator rend() { return iterator(NULL); }
const_iterator begin() const { return const_iterator(getFirst()); }
const_iterator end() const { return const_iterator(NULL); }
};
#endif
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _MAPREFERENCE_H
#define _MAPREFERENCE_H
#include "Utilities/LinkedReference/Reference.h"
#include "Map.h"
class MapReference : public Reference<Map, Player>
{
protected:
void targetObjectBuildLink()
{
// called from link()
getTarget()->m_mapRefManager.insertFirst(this);
getTarget()->m_mapRefManager.incSize();
}
void targetObjectDestroyLink()
{
// called from unlink()
if (isValid()) getTarget()->m_mapRefManager.decSize();
}
void sourceObjectDestroyLink()
{
// called from invalidate()
getTarget()->m_mapRefManager.decSize();
}
public:
MapReference() : Reference<Map, Player>() {}
~MapReference() { unlink(); }
MapReference *next() { return (MapReference*)Reference<Map, Player>::next(); }
MapReference const *next() const { return (MapReference const*)Reference<Map, Player>::next(); }
MapReference *nockeck_prev() { return (MapReference*)Reference<Map, Player>::nocheck_prev(); }
MapReference const *nocheck_prev() const { return (MapReference const*)Reference<Map, Player>::nocheck_prev(); }
};
#endif
+129
View File
@@ -0,0 +1,129 @@
#include "MapUpdater.h"
#include "DelayExecutor.h"
#include "Map.h"
#include "Database/DatabaseEnv.h"
#include <ace/Guard_T.h>
#include <ace/Method_Request.h>
class WDBThreadStartReq1 : public ACE_Method_Request
{
public:
WDBThreadStartReq1()
{
}
virtual int call()
{
WorldDatabase.ThreadStart();
return 0;
}
};
class WDBThreadEndReq1 : public ACE_Method_Request
{
public:
WDBThreadEndReq1()
{
}
virtual int call()
{
WorldDatabase.ThreadEnd();
return 0;
}
};
class MapUpdateRequest : public ACE_Method_Request
{
private:
Map& m_map;
MapUpdater& m_updater;
ACE_UINT32 m_diff;
public:
MapUpdateRequest(Map& m, MapUpdater& u, ACE_UINT32 d)
: m_map(m), m_updater(u), m_diff(d)
{
}
virtual int call()
{
m_map.Update (m_diff);
m_updater.update_finished ();
return 0;
}
};
MapUpdater::MapUpdater()
: m_mutex(), m_condition(m_mutex), m_executor(), pending_requests(0)
{
}
MapUpdater::~MapUpdater()
{
deactivate();
}
int MapUpdater::activate(size_t num_threads)
{
return m_executor.activate((int)num_threads, new WDBThreadStartReq1, new WDBThreadEndReq1);
}
int MapUpdater::deactivate()
{
wait();
return m_executor.deactivate();
}
int MapUpdater::wait()
{
ACE_GUARD_RETURN(ACE_Thread_Mutex, guard, m_mutex, -1);
while (pending_requests > 0)
m_condition.wait();
return 0;
}
int MapUpdater::schedule_update(Map& map, ACE_UINT32 diff)
{
ACE_GUARD_RETURN(ACE_Thread_Mutex, guard, m_mutex, -1);
++pending_requests;
if (m_executor.execute(new MapUpdateRequest(map, *this, diff)) == -1)
{
ACE_DEBUG((LM_ERROR, ACE_TEXT("(%t) \n"), ACE_TEXT("Failed to schedule Map Update")));
--pending_requests;
return -1;
}
return 0;
}
bool MapUpdater::activated()
{
return m_executor.activated();
}
void MapUpdater::update_finished()
{
ACE_GUARD(ACE_Thread_Mutex, guard, m_mutex);
if (pending_requests == 0)
{
ACE_ERROR((LM_ERROR, ACE_TEXT("(%t)\n"), ACE_TEXT("MapUpdater::update_finished BUG, report to devs")));
return;
}
--pending_requests;
m_condition.broadcast();
}
+40
View File
@@ -0,0 +1,40 @@
#ifndef _MAP_UPDATER_H_INCLUDED
#define _MAP_UPDATER_H_INCLUDED
#include <ace/Thread_Mutex.h>
#include <ace/Condition_Thread_Mutex.h>
#include "DelayExecutor.h"
class Map;
class MapUpdater
{
public:
MapUpdater();
virtual ~MapUpdater();
friend class MapUpdateRequest;
int schedule_update(Map& map, ACE_UINT32 diff);
int wait();
int activate(size_t num_threads);
int deactivate();
bool activated();
private:
DelayExecutor m_executor;
ACE_Condition_Thread_Mutex m_condition;
ACE_Thread_Mutex m_mutex;
size_t pending_requests;
void update_finished();
};
#endif //_MAP_UPDATER_H_INCLUDED
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef ZONE_SCRIPT_H_
#define ZONE_SCRIPT_H_
#include "Common.h"
#include "Creature.h"
//struct CreatureData;
class Creature;
class GameObject;
class ZoneScript
{
public:
explicit ZoneScript() {}
virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, const CreatureData *data) { return data->id; }
virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; }
virtual void OnCreatureCreate(Creature *, bool /*add*/) {}
virtual void OnGameObjectCreate(GameObject * /*go*/, bool /*add*/) {}
//All-purpose data storage 64 bit
virtual uint64 GetData64(uint32 /*DataId*/) { return 0; }
virtual void SetData64(uint32 /*DataId*/, uint64 /*Value*/) {}
//All-purpose data storage 32 bit
virtual uint32 GetData(uint32 /*DataId*/) { return 0; }
virtual void SetData(uint32 /*DataId*/, uint32 /*Value*/) {}
virtual void ProcessEvent(GameObject * /*obj*/, uint32 /*eventId*/) {}
};
#endif