OregonCore  revision fb2a440-git
Your Favourite TBC server
MapTree.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of the OregonCore Project. See AUTHORS file for Copyright information
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation; either version 2 of the License, or (at your
7  * option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "MapTree.h"
19 #include "ModelInstance.h"
20 #include "VMapManager2.h"
21 #include "VMapDefinitions.h"
22 
23 #include <string>
24 #include <sstream>
25 #include <iomanip>
26 #include <limits>
27 
28 #ifndef NO_CORE_FUNCS
29  #include "Errors.h"
30 #else
31  #define ASSERT(x)
32 #endif
33 
34 using G3D::Vector3;
35 
36 namespace VMAP
37 {
38 
40 {
41  public:
43  bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool pStopAtFirstHit = true)
44  {
45  bool result = prims[entry].intersectRay(ray, distance, pStopAtFirstHit);
46  if (result)
47  hit = true;
48  return result;
49  }
50  bool didHit() { return hit; }
51  protected:
53  bool hit;
54 };
55 
57 {
58  public:
60  void operator()(const Vector3& point, uint32 entry)
61  {
62  #ifdef VMAP_DEBUG
63  DEBUG_LOG("AreaInfoCallback: trying to intersect '%s'", prims[entry].name.c_str());
64  #endif
65  prims[entry].intersectPoint(point, aInfo);
66  }
67 
70 };
71 
73 {
74  public:
75  LocationInfoCallback(ModelInstance* val, LocationInfo& info): prims(val), locInfo(info), result(false) {}
76  void operator()(const Vector3& point, uint32 entry)
77  {
78  #ifdef VMAP_DEBUG
79  DEBUG_LOG("LocationInfoCallback: trying to intersect '%s'", prims[entry].name.c_str());
80  #endif
81  if (prims[entry].GetLocationInfo(point, locInfo))
82  result = true;
83  }
84 
87  bool result;
88 };
89 
90 //=========================================================
91 
92 std::string StaticMapTree::getTileFileName(uint32 mapID, uint32 tileX, uint32 tileY)
93 {
94  std::stringstream tilefilename;
95  tilefilename.fill('0');
96  tilefilename << std::setw(3) << mapID << '_';
97  //tilefilename << std::setw(2) << tileX << '_' << std::setw(2) << tileY << ".vmtile";
98  tilefilename << std::setw(2) << tileY << '_' << std::setw(2) << tileX << ".vmtile";
99  return tilefilename.str();
100 }
101 
102 bool StaticMapTree::getAreaInfo(Vector3& pos, uint32& flags, int32& adtId, int32& rootId, int32& groupId) const
103 {
104  AreaInfoCallback intersectionCallBack(iTreeValues);
105  iTree.intersectPoint(pos, intersectionCallBack);
106  if (intersectionCallBack.aInfo.result)
107  {
108  flags = intersectionCallBack.aInfo.flags;
109  adtId = intersectionCallBack.aInfo.adtId;
110  rootId = intersectionCallBack.aInfo.rootId;
111  groupId = intersectionCallBack.aInfo.groupId;
112  pos.z = intersectionCallBack.aInfo.ground_Z;
113  return true;
114  }
115  return false;
116 }
117 
118 bool StaticMapTree::GetLocationInfo(const Vector3& pos, LocationInfo& info) const
119 {
120  LocationInfoCallback intersectionCallBack(iTreeValues, info);
121  iTree.intersectPoint(pos, intersectionCallBack);
122  return intersectionCallBack.result;
123 }
124 
125 StaticMapTree::StaticMapTree(uint32 mapID, const std::string& basePath):
126  iMapID(mapID), iTreeValues(0), iBasePath(basePath)
127 {
128  if (iBasePath.length() > 0 && iBasePath[iBasePath.length()-1] != '/' && iBasePath[iBasePath.length()-1] != '\\')
129  iBasePath.push_back('/');
130 }
131 
132 //=========================================================
135 {
136  delete[] iTreeValues;
137 }
138 
139 //=========================================================
145 bool StaticMapTree::getIntersectionTime(const G3D::Ray& pRay, float& pMaxDist, bool pStopAtFirstHit) const
146 {
147  float distance = pMaxDist;
148  MapRayCallback intersectionCallBack(iTreeValues);
149  iTree.intersectRay(pRay, intersectionCallBack, distance, pStopAtFirstHit);
150  if (intersectionCallBack.didHit())
151  pMaxDist = distance;
152  return intersectionCallBack.didHit();
153 }
154 //=========================================================
155 
156 bool StaticMapTree::isInLineOfSight(const Vector3& pos1, const Vector3& pos2) const
157 {
158  float maxDist = (pos2 - pos1).magnitude();
159  // return false if distance is over max float, in case of cheater teleporting to the end of the universe
160  if (maxDist == std::numeric_limits<float>::max() || !std::isfinite(maxDist))
161  return false;
162 
163  // valid map coords should *never ever* produce float overflow, but this would produce NaNs too
164  ASSERT(maxDist < std::numeric_limits<float>::max());
165  // prevent NaN values which can cause BIH intersection to enter infinite loop
166  if (maxDist < 1e-10f)
167  return true;
168  // direction with length of 1
169  G3D::Ray ray = G3D::Ray::fromOriginAndDirection(pos1, (pos2 - pos1) / maxDist);
170  if (getIntersectionTime(ray, maxDist, true))
171  return false;
172 
173  return true;
174 }
175 
176 //=========================================================
181 bool StaticMapTree::getObjectHitPos(const Vector3& pPos1, const Vector3& pPos2, Vector3& pResultHitPos, float pModifyDist) const
182 {
183  bool result = false;
184  float maxDist = (pPos2 - pPos1).magnitude();
185  // valid map coords should *never ever* produce float overflow, but this would produce NaNs too
186  ASSERT(maxDist < std::numeric_limits<float>::max());
187  // prevent NaN values which can cause BIH intersection to enter infinite loop
188  if (maxDist < 1e-10f)
189  {
190  pResultHitPos = pPos2;
191  return false;
192  }
193  Vector3 dir = (pPos2 - pPos1) / maxDist; // direction with length of 1
194  G3D::Ray ray(pPos1, dir);
195  float dist = maxDist;
196  if (getIntersectionTime(ray, dist, false))
197  {
198  pResultHitPos = pPos1 + dir * dist;
199  if (pModifyDist < 0)
200  {
201  if ((pResultHitPos - pPos1).magnitude() > -pModifyDist)
202  pResultHitPos = pResultHitPos + dir * pModifyDist;
203  else
204  pResultHitPos = pPos1;
205  }
206  else
207  pResultHitPos = pResultHitPos + dir * pModifyDist;
208 
209  result = true;
210  }
211  else
212  {
213  pResultHitPos = pPos2;
214  result = false;
215  }
216  return result;
217 }
218 
219 //=========================================================
220 
221 float StaticMapTree::getHeight(const Vector3& pPos, float maxSearchDist) const
222 {
223  float height = G3D::inf();
224  Vector3 dir = Vector3(0, 0, -1);
225  G3D::Ray ray(pPos, dir); // direction with length of 1
226  float maxDist = maxSearchDist;
227  if (getIntersectionTime(ray, maxDist, false))
228  height = pPos.z - maxDist;
229 
230  return (height);
231 }
232 
233 //=========================================================
234 
235 bool StaticMapTree::CanLoadMap(const std::string& vmapPath, uint32 mapID, uint32 tileX, uint32 tileY)
236 {
237  std::string basePath = vmapPath;
238  if (basePath.length() > 0 && basePath[basePath.length()-1] != '/' && basePath[basePath.length()-1] != '\\')
239  basePath.push_back('/');
240  std::string fullname = basePath + VMapManager2::getMapFileName(mapID);
241  bool success = true;
242  FILE* rf = fopen(fullname.c_str(), "rb");
243  if (!rf)
244  return false;
245  // @todo: check magic number when implemented...
246  char tiled;
247  char chunk[8];
248  if (!readChunk(rf, chunk, VMAP_MAGIC, 8) || fread(&tiled, sizeof(char), 1, rf) != 1)
249  {
250  fclose(rf);
251  return false;
252  }
253  if (tiled)
254  {
255  std::string tilefile = basePath + getTileFileName(mapID, tileX, tileY);
256  FILE* tf = fopen(tilefile.c_str(), "rb");
257  if (!tf)
258  success = false;
259  else
260  {
261  if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
262  success = false;
263  fclose(tf);
264  }
265  }
266  fclose(rf);
267  return success;
268 }
269 
270  //=========================================================
271 
272 bool StaticMapTree::InitMap(const std::string& fname, VMapManager2* vm)
273 {
274  DEBUG_LOG("StaticMapTree::InitMap() : initializing StaticMapTree '%s'", fname.c_str());
275  bool success = true;
276  std::string fullname = iBasePath + fname;
277  FILE* rf = fopen(fullname.c_str(), "rb");
278  if (!rf)
279  return false;
280  else
281  {
282  char chunk[8];
283  //general info
284  if (!readChunk(rf, chunk, VMAP_MAGIC, 8)) success = false;
285  char tiled = '\0';
286  if (success && fread(&tiled, sizeof(char), 1, rf) != 1) success = false;
287  iIsTiled = bool(tiled);
288  // Nodes
289  if (success && !readChunk(rf, chunk, "NODE", 4)) success = false;
290  if (success) success = iTree.readFromFile(rf);
291  if (success)
292  {
295  }
296 
297  if (success && !readChunk(rf, chunk, "GOBJ", 4)) success = false;
298  // global model spawns
299  // only non-tiled maps have them, and if so exactly one (so far at least...)
300  ModelSpawn spawn;
301  #ifdef VMAP_DEBUG
302  DEBUG_LOG("StaticMapTree::InitMap() : map isTiled: %u", static_cast<uint32>(iIsTiled));
303  #endif
304  if (!iIsTiled && ModelSpawn::readFromFile(rf, spawn))
305  {
306  WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name);
307  DEBUG_LOG("StaticMapTree::InitMap(): loading %s", spawn.name.c_str());
308  if (model)
309  {
310  // assume that global model always is the first and only tree value (could be improved...)
311  iTreeValues[0] = ModelInstance(spawn, model);
312  iLoadedSpawns[0] = 1;
313  }
314  else
315  {
316  success = false;
317  ERROR_LOG("StaticMapTree::InitMap() : could not acquire WorldModel pointer for '%s'", spawn.name.c_str());
318  }
319  }
320 
321  fclose(rf);
322  }
323  return success;
324 }
325 
326  //=========================================================
327 
329 {
330  for (loadedSpawnMap::iterator i = iLoadedSpawns.begin(); i != iLoadedSpawns.end(); ++i)
331  {
332  iTreeValues[i->first].setUnloaded();
333  for (uint32 refCount = 0; refCount < i->second; ++refCount)
334  vm->releaseModelInstance(iTreeValues[i->first].name);
335  }
336  iLoadedSpawns.clear();
337  iLoadedTiles.clear();
338 }
339 
340  //=========================================================
341 
343 {
344  if (!iIsTiled)
345  {
346  // currently, core creates grids for all maps, whether it has terrain tiles or not
347  // so we need "fake" tile loads to know when we can unload map geometry
348  iLoadedTiles[packTileID(tileX, tileY)] = false;
349  return true;
350  }
351  if (!iTreeValues)
352  {
353  ERROR_LOG("StaticMapTree::LoadMapTile() : tree has not been initialized [%u, %u]", tileX, tileY);
354  return false;
355  }
356  bool result = true;
357 
358  std::string tilefile = iBasePath + getTileFileName(iMapID, tileX, tileY);
359  FILE* tf = fopen(tilefile.c_str(), "rb");
360  if (tf)
361  {
362  char chunk[8];
363 
364  if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
365  result = false;
366  uint32 numSpawns = 0;
367  if (result && fread(&numSpawns, sizeof(uint32), 1, tf) != 1)
368  result = false;
369  for (uint32 i = 0; i < numSpawns && result; ++i)
370  {
371  // read model spawns
372  ModelSpawn spawn;
373  result = ModelSpawn::readFromFile(tf, spawn);
374  if (result)
375  {
376  // acquire model instance
377  WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name);
378  if (!model)
379  ERROR_LOG("StaticMapTree::LoadMapTile() : could not acquire WorldModel pointer [%u, %u]", tileX, tileY);
380 
381  // update tree
382  uint32 referencedVal;
383 
384  if (fread(&referencedVal, sizeof(uint32), 1, tf) == 1)
385  {
386  if (!iLoadedSpawns.count(referencedVal))
387  {
388  if (referencedVal > iNTreeValues)
389  {
390  ERROR_LOG("StaticMapTree::LoadMapTile() : invalid tree element (%u/%u) referenced in tile %s", referencedVal, iNTreeValues, tilefile.c_str());
391  continue;
392  }
393  iTreeValues[referencedVal] = ModelInstance(spawn, model);
394  iLoadedSpawns[referencedVal] = 1;
395  }
396  else
397  {
398  ++iLoadedSpawns[referencedVal];
399  #ifdef VMAP_DEBUG
400  if (iTreeValues[referencedVal].ID != spawn.ID)
401  DEBUG_LOG("StaticMapTree::LoadMapTile() : trying to load wrong spawn in node");
402  else if (iTreeValues[referencedVal].name != spawn.name)
403  DEBUG_LOG("StaticMapTree::LoadMapTile() : name collision on GUID=%u", spawn.ID);
404  #endif
405  }
406  }
407  else
408  result = false;
409  }
410  }
411  iLoadedTiles[packTileID(tileX, tileY)] = true;
412  fclose(tf);
413  }
414  else
415  iLoadedTiles[packTileID(tileX, tileY)] = false;
416 
417  return result;
418 }
419 
420  //=========================================================
421 
423 {
424  uint32 tileID = packTileID(tileX, tileY);
425  loadedTileMap::iterator tile = iLoadedTiles.find(tileID);
426  if (tile == iLoadedTiles.end())
427  {
428  ERROR_LOG("StaticMapTree::UnloadMapTile() : trying to unload non-loaded tile - Map:%u X:%u Y:%u", iMapID, tileX, tileY);
429  return;
430  }
431  if (tile->second) // file associated with tile
432  {
433  std::string tilefile = iBasePath + getTileFileName(iMapID, tileX, tileY);
434  FILE* tf = fopen(tilefile.c_str(), "rb");
435  if (tf)
436  {
437  bool result = true;
438  char chunk[8];
439  if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
440  result = false;
441  uint32 numSpawns;
442  if (fread(&numSpawns, sizeof(uint32), 1, tf) != 1)
443  result = false;
444  for (uint32 i = 0; i < numSpawns && result; ++i)
445  {
446  // read model spawns
447  ModelSpawn spawn;
448  result = ModelSpawn::readFromFile(tf, spawn);
449  if (result)
450  {
451  // release model instance
452  vm->releaseModelInstance(spawn.name);
453 
454  // update tree
455  uint32 referencedNode;
456 
457  if (fread(&referencedNode, sizeof(uint32), 1, tf) != 1)
458  result = false;
459  else
460  {
461  if (!iLoadedSpawns.count(referencedNode))
462  ERROR_LOG("StaticMapTree::UnloadMapTile() : trying to unload non-referenced model '%s' (ID:%u)", spawn.name.c_str(), spawn.ID);
463  else if (--iLoadedSpawns[referencedNode] == 0)
464  {
465  iTreeValues[referencedNode].setUnloaded();
466  iLoadedSpawns.erase(referencedNode);
467  }
468  }
469  }
470  }
471  fclose(tf);
472  }
473  }
474  iLoadedTiles.erase(tile);
475 }
476 
477 }
float ground_Z
Definition: MapTree.h:92
LocationInfo & locInfo
Definition: MapTree.cpp:86
static uint32 packTileID(uint32 tileX, uint32 tileY)
Definition: MapTree.h:63
ModelInstance * prims
Definition: MapTree.cpp:68
static bool readFromFile(FILE *rf, ModelSpawn &spawn)
bool isInLineOfSight(const G3D::Vector3 &pos1, const G3D::Vector3 &pos2) const
Definition: MapTree.cpp:156
bool getObjectHitPos(const G3D::Vector3 &pos1, const G3D::Vector3 &pos2, G3D::Vector3 &pResultHitPos, float pModifyDist) const
Definition: MapTree.cpp:181
bool result
Definition: MapTree.h:90
int32 groupId
Definition: MapTree.h:96
ACE_INT32 int32
Definition: Define.h:67
void operator()(const Vector3 &point, uint32 entry)
Definition: MapTree.cpp:60
bool operator()(const G3D::Ray &ray, uint32 entry, float &distance, bool pStopAtFirstHit=true)
Definition: MapTree.cpp:43
NULL Dbg ErrDB Arena Chat Char Map MMap false
Definition: Log.cpp:556
Definition: adtfile.h:56
float getHeight(const G3D::Vector3 &pPos, float maxSearchDist) const
Definition: MapTree.cpp:221
void releaseModelInstance(const std::string &filename)
static std::string getMapFileName(unsigned int mapId)
void intersectRay(const Ray &r, RayCallback &intersectCallback, float &maxDist, bool stopAtFirst=false) const
uint32 primCount()
bool readChunk(FILE *rf, char *dest, const char *compare, uint32 len)
loadedSpawnMap iLoadedSpawns
Definition: MapTree.h:55
ModelInstance * iTreeValues
Definition: MapTree.h:47
StaticMapTree(uint32 mapID, const std::string &basePath)
Definition: MapTree.cpp:125
#define ERROR_LOG(...)
uint32 flags
Definition: MapTree.h:93
MapRayCallback(ModelInstance *val)
Definition: MapTree.cpp:42
uint32 iNTreeValues
Definition: MapTree.h:48
void UnloadMapTile(uint32 tileX, uint32 tileY, VMapManager2 *vm)
Definition: MapTree.cpp:422
ModelInstance * prims
Definition: MapTree.cpp:85
int32 adtId
Definition: MapTree.h:94
#define DEBUG_LOG(...)
Definition: Log.h:194
bool readFromFile(FILE *rf)
LocationInfoCallback(ModelInstance *val, LocationInfo &info)
Definition: MapTree.cpp:75
bool intersectRay(const G3D::Ray &pRay, float &pMaxDist, bool pStopAtFirstHit) const
static bool CanLoadMap(const std::string &basePath, uint32 mapID, uint32 tileX, uint32 tileY)
Definition: MapTree.cpp:235
void UnloadMap(VMapManager2 *vm)
Definition: MapTree.cpp:328
bool getIntersectionTime(const G3D::Ray &pRay, float &pMaxDist, bool pStopAtFirstHit) const
Definition: MapTree.cpp:145
#define ASSERT
Definition: Errors.h:29
bool GetLocationInfo(const Vector3 &pos, LocationInfo &info) const
Definition: MapTree.cpp:118
std::string name
Definition: ModelInstance.h:52
loadedTileMap iLoadedTiles
Definition: MapTree.h:53
AreaInfoCallback(ModelInstance *val)
Definition: MapTree.cpp:59
bool getAreaInfo(G3D::Vector3 &pos, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
Definition: MapTree.cpp:102
bool LoadMapTile(uint32 tileX, uint32 tileY, VMapManager2 *vm)
Definition: MapTree.cpp:342
ACE_UINT32 uint32
Definition: Define.h:71
WorldModel * acquireModelInstance(const std::string &basepath, const std::string &filename)
void operator()(const Vector3 &point, uint32 entry)
Definition: MapTree.cpp:76
const char VMAP_MAGIC[]
static std::string getTileFileName(uint32 mapID, uint32 tileX, uint32 tileY)
Definition: MapTree.cpp:92
~StaticMapTree()
Make sure to call unloadMap() to unregister acquired model references before destroying.
Definition: MapTree.cpp:134
std::string iBasePath
Definition: MapTree.h:56
bool InitMap(const std::string &fname, VMapManager2 *vm)
Definition: MapTree.cpp:272
void intersectPoint(const G3D::Vector3 &p, AreaInfo &info) const
int32 rootId
Definition: MapTree.h:95
ModelInstance * prims
Definition: MapTree.cpp:52