DynamicNavigationMesh.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../Navigation/CrowdAgent.h"
  29. #include "../Navigation/DynamicNavigationMesh.h"
  30. #include "../Navigation/NavArea.h"
  31. #include "../Navigation/NavBuildData.h"
  32. #include "../Navigation/NavigationEvents.h"
  33. #include "../Navigation/Obstacle.h"
  34. #include "../Navigation/OffMeshConnection.h"
  35. #include "../Scene/Node.h"
  36. #include "../Scene/Scene.h"
  37. #include "../Scene/SceneEvents.h"
  38. #include <LZ4/lz4.h>
  39. // ATOMIC BEGIN
  40. #include <Detour/include/DetourNavMesh.h>
  41. #include <Detour/include/DetourNavMeshBuilder.h>
  42. #include <DetourTileCache/include/DetourTileCache.h>
  43. #include <DetourTileCache/include/DetourTileCacheBuilder.h>
  44. #include <Recast/include/Recast.h>
  45. // ATOMIC END
  46. // DebugNew is deliberately not used because the macro 'free' conflicts with DetourTileCache's LinearAllocator interface
  47. //#include "../DebugNew.h"
  48. static const unsigned TILECACHE_MAXLAYERS = 255;
  49. namespace Atomic
  50. {
  51. extern const char* NAVIGATION_CATEGORY;
  52. static const int DEFAULT_MAX_OBSTACLES = 1024;
  53. static const int DEFAULT_MAX_LAYERS = 16;
  54. struct DynamicNavigationMesh::TileCacheData
  55. {
  56. unsigned char* data;
  57. int dataSize;
  58. };
  59. struct TileCompressor : public dtTileCacheCompressor
  60. {
  61. virtual int maxCompressedSize(const int bufferSize)
  62. {
  63. return (int)(bufferSize * 1.05f);
  64. }
  65. virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
  66. unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
  67. {
  68. *compressedSize = LZ4_compress_default((const char*)buffer, (char*)compressed, bufferSize, LZ4_compressBound(bufferSize));
  69. return DT_SUCCESS;
  70. }
  71. virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
  72. unsigned char* buffer, const int maxBufferSize, int* bufferSize)
  73. {
  74. *bufferSize = LZ4_decompress_safe((const char*)compressed, (char*)buffer, compressedSize, maxBufferSize);
  75. return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
  76. }
  77. };
  78. struct MeshProcess : public dtTileCacheMeshProcess
  79. {
  80. DynamicNavigationMesh* owner_;
  81. PODVector<Vector3> offMeshVertices_;
  82. PODVector<float> offMeshRadii_;
  83. PODVector<unsigned short> offMeshFlags_;
  84. PODVector<unsigned char> offMeshAreas_;
  85. PODVector<unsigned char> offMeshDir_;
  86. inline MeshProcess(DynamicNavigationMesh* owner) :
  87. owner_(owner)
  88. {
  89. }
  90. virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags)
  91. {
  92. // Update poly flags from areas.
  93. // \todo Assignment of flags from areas?
  94. for (int i = 0; i < params->polyCount; ++i)
  95. {
  96. if (polyAreas[i] != RC_NULL_AREA)
  97. polyFlags[i] = RC_WALKABLE_AREA;
  98. }
  99. BoundingBox bounds;
  100. rcVcopy(&bounds.min_.x_, params->bmin);
  101. rcVcopy(&bounds.max_.x_, params->bmin);
  102. // collect off-mesh connections
  103. PODVector<OffMeshConnection*> offMeshConnections = owner_->CollectOffMeshConnections(bounds);
  104. if (offMeshConnections.Size() > 0)
  105. {
  106. if (offMeshConnections.Size() != offMeshRadii_.Size())
  107. {
  108. Matrix3x4 inverse = owner_->GetNode()->GetWorldTransform().Inverse();
  109. ClearConnectionData();
  110. for (unsigned i = 0; i < offMeshConnections.Size(); ++i)
  111. {
  112. OffMeshConnection* connection = offMeshConnections[i];
  113. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  114. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  115. offMeshVertices_.Push(start);
  116. offMeshVertices_.Push(end);
  117. offMeshRadii_.Push(connection->GetRadius());
  118. offMeshFlags_.Push((unsigned short)connection->GetMask());
  119. offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  120. offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0));
  121. }
  122. }
  123. params->offMeshConCount = offMeshRadii_.Size();
  124. params->offMeshConVerts = &offMeshVertices_[0].x_;
  125. params->offMeshConRad = &offMeshRadii_[0];
  126. params->offMeshConFlags = &offMeshFlags_[0];
  127. params->offMeshConAreas = &offMeshAreas_[0];
  128. params->offMeshConDir = &offMeshDir_[0];
  129. }
  130. }
  131. void ClearConnectionData()
  132. {
  133. offMeshVertices_.Clear();
  134. offMeshRadii_.Clear();
  135. offMeshFlags_.Clear();
  136. offMeshAreas_.Clear();
  137. offMeshDir_.Clear();
  138. }
  139. };
  140. // From the Detour/Recast Sample_TempObstacles.cpp
  141. struct LinearAllocator : public dtTileCacheAlloc
  142. {
  143. unsigned char* buffer;
  144. int capacity;
  145. int top;
  146. int high;
  147. LinearAllocator(const int cap) :
  148. buffer(0), capacity(0), top(0), high(0)
  149. {
  150. resize(cap);
  151. }
  152. ~LinearAllocator()
  153. {
  154. dtFree(buffer);
  155. }
  156. void resize(const int cap)
  157. {
  158. if (buffer)
  159. dtFree(buffer);
  160. buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
  161. capacity = cap;
  162. }
  163. virtual void reset()
  164. {
  165. high = Max(high, top);
  166. top = 0;
  167. }
  168. virtual void* alloc(const int size)
  169. {
  170. if (!buffer)
  171. return 0;
  172. if (top + size > capacity)
  173. return 0;
  174. unsigned char* mem = &buffer[top];
  175. top += size;
  176. return mem;
  177. }
  178. virtual void free(void*)
  179. {
  180. }
  181. };
  182. DynamicNavigationMesh::DynamicNavigationMesh(Context* context) :
  183. NavigationMesh(context),
  184. tileCache_(0),
  185. maxObstacles_(1024),
  186. maxLayers_(DEFAULT_MAX_LAYERS),
  187. drawObstacles_(false)
  188. {
  189. //64 is the largest tile-size that DetourTileCache will tolerate without silently failing
  190. tileSize_ = 64;
  191. partitionType_ = NAVMESH_PARTITION_MONOTONE;
  192. allocator_ = new LinearAllocator(32000); //32kb to start
  193. compressor_ = new TileCompressor();
  194. meshProcessor_ = new MeshProcess(this);
  195. }
  196. DynamicNavigationMesh::~DynamicNavigationMesh()
  197. {
  198. ReleaseNavigationMesh();
  199. }
  200. void DynamicNavigationMesh::RegisterObject(Context* context)
  201. {
  202. context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY);
  203. ATOMIC_COPY_BASE_ATTRIBUTES(NavigationMesh);
  204. ATOMIC_ACCESSOR_ATTRIBUTE("Max Obstacles", GetMaxObstacles, SetMaxObstacles, unsigned, DEFAULT_MAX_OBSTACLES, AM_DEFAULT);
  205. ATOMIC_ACCESSOR_ATTRIBUTE("Max Layers", GetMaxLayers, SetMaxLayers, unsigned, DEFAULT_MAX_LAYERS, AM_DEFAULT);
  206. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Obstacles", GetDrawObstacles, SetDrawObstacles, bool, false, AM_DEFAULT);
  207. }
  208. bool DynamicNavigationMesh::Allocate(const BoundingBox& boundingBox, unsigned maxTiles)
  209. {
  210. // Release existing navigation data and zero the bounding box
  211. ReleaseNavigationMesh();
  212. if (!node_)
  213. return false;
  214. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  215. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  216. boundingBox_ = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  217. maxTiles = NextPowerOfTwo(maxTiles);
  218. // Calculate number of tiles
  219. int gridW = 0, gridH = 0;
  220. float tileEdgeLength = (float)tileSize_ * cellSize_;
  221. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  222. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  223. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  224. // Calculate max number of polygons, 22 bits available to identify both tile & polygon within tile
  225. unsigned tileBits = LogBaseTwo(maxTiles);
  226. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  227. dtNavMeshParams params;
  228. rcVcopy(params.orig, &boundingBox_.min_.x_);
  229. params.tileWidth = tileEdgeLength;
  230. params.tileHeight = tileEdgeLength;
  231. params.maxTiles = maxTiles;
  232. params.maxPolys = maxPolys;
  233. navMesh_ = dtAllocNavMesh();
  234. if (!navMesh_)
  235. {
  236. ATOMIC_LOGERROR("Could not allocate navigation mesh");
  237. return false;
  238. }
  239. if (dtStatusFailed(navMesh_->init(&params)))
  240. {
  241. ATOMIC_LOGERROR("Could not initialize navigation mesh");
  242. ReleaseNavigationMesh();
  243. return false;
  244. }
  245. dtTileCacheParams tileCacheParams;
  246. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  247. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  248. tileCacheParams.ch = cellHeight_;
  249. tileCacheParams.cs = cellSize_;
  250. tileCacheParams.width = tileSize_;
  251. tileCacheParams.height = tileSize_;
  252. tileCacheParams.maxSimplificationError = edgeMaxError_;
  253. tileCacheParams.maxTiles = maxTiles * maxLayers_;
  254. tileCacheParams.maxObstacles = maxObstacles_;
  255. // Settings from NavigationMesh
  256. tileCacheParams.walkableClimb = agentMaxClimb_;
  257. tileCacheParams.walkableHeight = agentHeight_;
  258. tileCacheParams.walkableRadius = agentRadius_;
  259. tileCache_ = dtAllocTileCache();
  260. if (!tileCache_)
  261. {
  262. ATOMIC_LOGERROR("Could not allocate tile cache");
  263. ReleaseNavigationMesh();
  264. return false;
  265. }
  266. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  267. {
  268. ATOMIC_LOGERROR("Could not initialize tile cache");
  269. ReleaseNavigationMesh();
  270. return false;
  271. }
  272. ATOMIC_LOGDEBUG("Allocated empty navigation mesh with max " + String(maxTiles) + " tiles");
  273. // Scan for obstacles to insert into us
  274. PODVector<Node*> obstacles;
  275. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  276. for (unsigned i = 0; i < obstacles.Size(); ++i)
  277. {
  278. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  279. if (obs && obs->IsEnabledEffective())
  280. AddObstacle(obs);
  281. }
  282. // Send a notification event to concerned parties that we've been fully rebuilt
  283. {
  284. using namespace NavigationMeshRebuilt;
  285. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  286. buildEventParams[P_NODE] = node_;
  287. buildEventParams[P_MESH] = this;
  288. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  289. }
  290. return true;
  291. }
  292. bool DynamicNavigationMesh::Build()
  293. {
  294. ATOMIC_PROFILE(BuildNavigationMesh);
  295. // Release existing navigation data and zero the bounding box
  296. ReleaseNavigationMesh();
  297. if (!node_)
  298. return false;
  299. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  300. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  301. Vector<NavigationGeometryInfo> geometryList;
  302. CollectGeometries(geometryList);
  303. if (geometryList.Empty())
  304. return true; // Nothing to do
  305. // Build the combined bounding box
  306. for (unsigned i = 0; i < geometryList.Size(); ++i)
  307. boundingBox_.Merge(geometryList[i].boundingBox_);
  308. // Expand bounding box by padding
  309. boundingBox_.min_ -= padding_;
  310. boundingBox_.max_ += padding_;
  311. {
  312. ATOMIC_PROFILE(BuildNavigationMesh);
  313. // Calculate number of tiles
  314. int gridW = 0, gridH = 0;
  315. float tileEdgeLength = (float)tileSize_ * cellSize_;
  316. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  317. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  318. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  319. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  320. unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_)) * maxLayers_;
  321. unsigned tileBits = LogBaseTwo(maxTiles);
  322. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  323. dtNavMeshParams params;
  324. rcVcopy(params.orig, &boundingBox_.min_.x_);
  325. params.tileWidth = tileEdgeLength;
  326. params.tileHeight = tileEdgeLength;
  327. params.maxTiles = maxTiles;
  328. params.maxPolys = maxPolys;
  329. navMesh_ = dtAllocNavMesh();
  330. if (!navMesh_)
  331. {
  332. ATOMIC_LOGERROR("Could not allocate navigation mesh");
  333. return false;
  334. }
  335. if (dtStatusFailed(navMesh_->init(&params)))
  336. {
  337. ATOMIC_LOGERROR("Could not initialize navigation mesh");
  338. ReleaseNavigationMesh();
  339. return false;
  340. }
  341. dtTileCacheParams tileCacheParams;
  342. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  343. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  344. tileCacheParams.ch = cellHeight_;
  345. tileCacheParams.cs = cellSize_;
  346. tileCacheParams.width = tileSize_;
  347. tileCacheParams.height = tileSize_;
  348. tileCacheParams.maxSimplificationError = edgeMaxError_;
  349. tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * maxLayers_;
  350. tileCacheParams.maxObstacles = maxObstacles_;
  351. // Settings from NavigationMesh
  352. tileCacheParams.walkableClimb = agentMaxClimb_;
  353. tileCacheParams.walkableHeight = agentHeight_;
  354. tileCacheParams.walkableRadius = agentRadius_;
  355. tileCache_ = dtAllocTileCache();
  356. if (!tileCache_)
  357. {
  358. ATOMIC_LOGERROR("Could not allocate tile cache");
  359. ReleaseNavigationMesh();
  360. return false;
  361. }
  362. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  363. {
  364. ATOMIC_LOGERROR("Could not initialize tile cache");
  365. ReleaseNavigationMesh();
  366. return false;
  367. }
  368. // Build each tile
  369. unsigned numTiles = 0;
  370. for (int z = 0; z < numTilesZ_; ++z)
  371. {
  372. for (int x = 0; x < numTilesX_; ++x)
  373. {
  374. TileCacheData tiles[TILECACHE_MAXLAYERS];
  375. int layerCt = BuildTile(geometryList, x, z, tiles);
  376. for (int i = 0; i < layerCt; ++i)
  377. {
  378. dtCompressedTileRef tileRef;
  379. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  380. if (dtStatusFailed((dtStatus)status))
  381. {
  382. dtFree(tiles[i].data);
  383. tiles[i].data = 0x0;
  384. }
  385. }
  386. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  387. ++numTiles;
  388. }
  389. }
  390. // For a full build it's necessary to update the nav mesh
  391. // not doing so will cause dependent components to crash, like CrowdManager
  392. tileCache_->update(0, navMesh_);
  393. ATOMIC_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  394. // Send a notification event to concerned parties that we've been fully rebuilt
  395. {
  396. using namespace NavigationMeshRebuilt;
  397. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  398. buildEventParams[P_NODE] = node_;
  399. buildEventParams[P_MESH] = this;
  400. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  401. }
  402. // Scan for obstacles to insert into us
  403. PODVector<Node*> obstacles;
  404. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  405. for (unsigned i = 0; i < obstacles.Size(); ++i)
  406. {
  407. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  408. if (obs && obs->IsEnabledEffective())
  409. AddObstacle(obs);
  410. }
  411. return true;
  412. }
  413. }
  414. bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox)
  415. {
  416. ATOMIC_PROFILE(BuildPartialNavigationMesh);
  417. if (!node_)
  418. return false;
  419. if (!navMesh_)
  420. {
  421. ATOMIC_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  422. return false;
  423. }
  424. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  425. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  426. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  427. float tileEdgeLength = (float)tileSize_ * cellSize_;
  428. Vector<NavigationGeometryInfo> geometryList;
  429. CollectGeometries(geometryList);
  430. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  431. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  432. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  433. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  434. unsigned numTiles = BuildTiles(geometryList, IntVector2(sx, sz), IntVector2(ex, ez));
  435. ATOMIC_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  436. return true;
  437. }
  438. bool DynamicNavigationMesh::Build(const IntVector2& from, const IntVector2& to)
  439. {
  440. ATOMIC_PROFILE(BuildPartialNavigationMesh);
  441. if (!node_)
  442. return false;
  443. if (!navMesh_)
  444. {
  445. ATOMIC_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  446. return false;
  447. }
  448. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  449. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  450. Vector<NavigationGeometryInfo> geometryList;
  451. CollectGeometries(geometryList);
  452. unsigned numTiles = BuildTiles(geometryList, from, to);
  453. ATOMIC_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  454. return true;
  455. }
  456. PODVector<unsigned char> DynamicNavigationMesh::GetTileData(const IntVector2& tile) const
  457. {
  458. VectorBuffer ret;
  459. WriteTiles(ret, tile.x_, tile.y_);
  460. return ret.GetBuffer();
  461. }
  462. bool DynamicNavigationMesh::IsObstacleInTile(Obstacle* obstacle, const IntVector2& tile) const
  463. {
  464. const BoundingBox tileBoundingBox = GetTileBoudningBox(tile);
  465. const Vector3 obstaclePosition = obstacle->GetNode()->GetWorldPosition();
  466. return tileBoundingBox.DistanceToPoint(obstaclePosition) < obstacle->GetRadius();
  467. }
  468. bool DynamicNavigationMesh::AddTile(const PODVector<unsigned char>& tileData)
  469. {
  470. MemoryBuffer buffer(tileData);
  471. return ReadTiles(buffer, false);
  472. }
  473. void DynamicNavigationMesh::RemoveTile(const IntVector2& tile)
  474. {
  475. if (!navMesh_)
  476. return;
  477. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  478. const int existingCt = tileCache_->getTilesAt(tile.x_, tile.y_, existing, maxLayers_);
  479. for (int i = 0; i < existingCt; ++i)
  480. {
  481. unsigned char* data = 0x0;
  482. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  483. dtFree(data);
  484. }
  485. NavigationMesh::RemoveTile(tile);
  486. }
  487. void DynamicNavigationMesh::RemoveAllTiles()
  488. {
  489. int numTiles = tileCache_->getTileCount();
  490. for (int i = 0; i < numTiles; ++i)
  491. {
  492. const dtCompressedTile* tile = tileCache_->getTile(i);
  493. assert(tile);
  494. if (tile->header)
  495. tileCache_->removeTile(tileCache_->getTileRef(tile), 0, 0);
  496. }
  497. NavigationMesh::RemoveAllTiles();
  498. ATOMIC_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  499. }
  500. void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  501. {
  502. if (!debug || !navMesh_ || !node_)
  503. return;
  504. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  505. const dtNavMesh* navMesh = navMesh_;
  506. for (int j = 0; j < navMesh->getMaxTiles(); ++j)
  507. {
  508. const dtMeshTile* tile = navMesh->getTile(j);
  509. assert(tile);
  510. if (!tile->header)
  511. continue;
  512. for (int i = 0; i < tile->header->polyCount; ++i)
  513. {
  514. dtPoly* poly = tile->polys + i;
  515. for (unsigned j = 0; j < poly->vertCount; ++j)
  516. {
  517. debug->AddLine(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  518. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  519. Color::YELLOW, depthTest);
  520. }
  521. }
  522. }
  523. Scene* scene = GetScene();
  524. if (scene)
  525. {
  526. // Draw Obstacle components
  527. if (drawObstacles_)
  528. {
  529. PODVector<Node*> obstacles;
  530. scene->GetChildrenWithComponent<Obstacle>(obstacles, true);
  531. for (unsigned i = 0; i < obstacles.Size(); ++i)
  532. {
  533. Obstacle* obstacle = obstacles[i]->GetComponent<Obstacle>();
  534. if (obstacle && obstacle->IsEnabledEffective())
  535. obstacle->DrawDebugGeometry(debug, depthTest);
  536. }
  537. }
  538. // Draw OffMeshConnection components
  539. if (drawOffMeshConnections_)
  540. {
  541. PODVector<Node*> connections;
  542. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  543. for (unsigned i = 0; i < connections.Size(); ++i)
  544. {
  545. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  546. if (connection && connection->IsEnabledEffective())
  547. connection->DrawDebugGeometry(debug, depthTest);
  548. }
  549. }
  550. // Draw NavArea components
  551. if (drawNavAreas_)
  552. {
  553. PODVector<Node*> areas;
  554. scene->GetChildrenWithComponent<NavArea>(areas, true);
  555. for (unsigned i = 0; i < areas.Size(); ++i)
  556. {
  557. NavArea* area = areas[i]->GetComponent<NavArea>();
  558. if (area && area->IsEnabledEffective())
  559. area->DrawDebugGeometry(debug, depthTest);
  560. }
  561. }
  562. }
  563. }
  564. void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest)
  565. {
  566. Scene* scene = GetScene();
  567. if (scene)
  568. {
  569. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  570. if (debug)
  571. DrawDebugGeometry(debug, depthTest);
  572. }
  573. }
  574. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  575. {
  576. ReleaseNavigationMesh();
  577. if (value.Empty())
  578. return;
  579. MemoryBuffer buffer(value);
  580. boundingBox_ = buffer.ReadBoundingBox();
  581. numTilesX_ = buffer.ReadInt();
  582. numTilesZ_ = buffer.ReadInt();
  583. dtNavMeshParams params;
  584. buffer.Read(&params, sizeof(dtNavMeshParams));
  585. navMesh_ = dtAllocNavMesh();
  586. if (!navMesh_)
  587. {
  588. ATOMIC_LOGERROR("Could not allocate navigation mesh");
  589. return;
  590. }
  591. if (dtStatusFailed(navMesh_->init(&params)))
  592. {
  593. ATOMIC_LOGERROR("Could not initialize navigation mesh");
  594. ReleaseNavigationMesh();
  595. return;
  596. }
  597. dtTileCacheParams tcParams;
  598. buffer.Read(&tcParams, sizeof(tcParams));
  599. tileCache_ = dtAllocTileCache();
  600. if (!tileCache_)
  601. {
  602. ATOMIC_LOGERROR("Could not allocate tile cache");
  603. ReleaseNavigationMesh();
  604. return;
  605. }
  606. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  607. {
  608. ATOMIC_LOGERROR("Could not initialize tile cache");
  609. ReleaseNavigationMesh();
  610. return;
  611. }
  612. ReadTiles(buffer, true);
  613. // \todo Shall we send E_NAVIGATION_MESH_REBUILT here?
  614. ATOMIC_LOGERROR("Failed to add tile");
  615. }
  616. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  617. {
  618. VectorBuffer ret;
  619. if (navMesh_ && tileCache_)
  620. {
  621. ret.WriteBoundingBox(boundingBox_);
  622. ret.WriteInt(numTilesX_);
  623. ret.WriteInt(numTilesZ_);
  624. const dtNavMeshParams* params = navMesh_->getParams();
  625. ret.Write(params, sizeof(dtNavMeshParams));
  626. const dtTileCacheParams* tcParams = tileCache_->getParams();
  627. ret.Write(tcParams, sizeof(dtTileCacheParams));
  628. for (int z = 0; z < numTilesZ_; ++z)
  629. for (int x = 0; x < numTilesX_; ++x)
  630. WriteTiles(ret, x, z);
  631. }
  632. return ret.GetBuffer();
  633. }
  634. void DynamicNavigationMesh::SetMaxLayers(unsigned maxLayers)
  635. {
  636. // Set 3 as a minimum due to the tendency of layers to be constructed inside the hollow space of stacked objects
  637. // That behavior is unlikely to be expected by the end user
  638. maxLayers_ = Max(3U, Min(maxLayers, TILECACHE_MAXLAYERS));
  639. }
  640. void DynamicNavigationMesh::WriteTiles(Serializer& dest, int x, int z) const
  641. {
  642. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  643. const int ct = tileCache_->getTilesAt(x, z, tiles, maxLayers_);
  644. for (int i = 0; i < ct; ++i)
  645. {
  646. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  647. if (!tile || !tile->header || !tile->dataSize)
  648. continue; // Don't write "void-space" tiles
  649. // The header conveniently has the majority of the information required
  650. dest.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  651. dest.WriteInt(tile->dataSize);
  652. dest.Write(tile->data, (unsigned)tile->dataSize);
  653. }
  654. }
  655. bool DynamicNavigationMesh::ReadTiles(Deserializer& source, bool silent)
  656. {
  657. tileQueue_.Clear();
  658. while (!source.IsEof())
  659. {
  660. dtTileCacheLayerHeader header;
  661. source.Read(&header, sizeof(dtTileCacheLayerHeader));
  662. const int dataSize = source.ReadInt();
  663. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  664. if (!data)
  665. {
  666. ATOMIC_LOGERROR("Could not allocate data for navigation mesh tile");
  667. return false;
  668. }
  669. source.Read(data, (unsigned)dataSize);
  670. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  671. {
  672. ATOMIC_LOGERROR("Failed to add tile");
  673. dtFree(data);
  674. return false;
  675. }
  676. const IntVector2 tileIdx = IntVector2(header.tx, header.ty);
  677. if (tileQueue_.Empty() || tileQueue_.Back() != tileIdx)
  678. tileQueue_.Push(tileIdx);
  679. }
  680. for (unsigned i = 0; i < tileQueue_.Size(); ++i)
  681. tileCache_->buildNavMeshTilesAt(tileQueue_[i].x_, tileQueue_[i].y_, navMesh_);
  682. tileCache_->update(0, navMesh_);
  683. // Send event
  684. if (!silent)
  685. {
  686. for (unsigned i = 0; i < tileQueue_.Size(); ++i)
  687. {
  688. using namespace NavigationTileAdded;
  689. VariantMap& eventData = GetContext()->GetEventDataMap();
  690. eventData[P_NODE] = GetNode();
  691. eventData[P_MESH] = this;
  692. eventData[P_TILE] = tileQueue_[i];
  693. SendEvent(E_NAVIGATION_TILE_ADDED, eventData);
  694. }
  695. }
  696. return true;
  697. }
  698. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  699. {
  700. ATOMIC_PROFILE(BuildNavigationMeshTile);
  701. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  702. const BoundingBox tileBoundingBox = GetTileBoudningBox(IntVector2(x, z));
  703. DynamicNavBuildData build(allocator_.Get());
  704. rcConfig cfg;
  705. memset(&cfg, 0, sizeof cfg);
  706. cfg.cs = cellSize_;
  707. cfg.ch = cellHeight_;
  708. cfg.walkableSlopeAngle = agentMaxSlope_;
  709. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  710. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  711. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  712. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  713. cfg.maxSimplificationError = edgeMaxError_;
  714. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  715. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  716. cfg.maxVertsPerPoly = 6;
  717. cfg.tileSize = tileSize_;
  718. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  719. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  720. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  721. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  722. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  723. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  724. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  725. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  726. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  727. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  728. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  729. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  730. GetTileGeometry(&build, geometryList, expandedBox);
  731. if (build.vertices_.Empty() || build.indices_.Empty())
  732. return 0; // Nothing to do
  733. build.heightField_ = rcAllocHeightfield();
  734. if (!build.heightField_)
  735. {
  736. ATOMIC_LOGERROR("Could not allocate heightfield");
  737. return 0;
  738. }
  739. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  740. cfg.ch))
  741. {
  742. ATOMIC_LOGERROR("Could not create heightfield");
  743. return 0;
  744. }
  745. unsigned numTriangles = build.indices_.Size() / 3;
  746. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  747. memset(triAreas.Get(), 0, numTriangles);
  748. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  749. &build.indices_[0], numTriangles, triAreas.Get());
  750. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  751. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  752. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  753. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  754. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  755. build.compactHeightField_ = rcAllocCompactHeightfield();
  756. if (!build.compactHeightField_)
  757. {
  758. ATOMIC_LOGERROR("Could not allocate create compact heightfield");
  759. return 0;
  760. }
  761. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  762. *build.compactHeightField_))
  763. {
  764. ATOMIC_LOGERROR("Could not build compact heightfield");
  765. return 0;
  766. }
  767. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  768. {
  769. ATOMIC_LOGERROR("Could not erode compact heightfield");
  770. return 0;
  771. }
  772. // area volumes
  773. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  774. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  775. build.navAreas_[i].areaID_, *build.compactHeightField_);
  776. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  777. {
  778. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  779. {
  780. ATOMIC_LOGERROR("Could not build distance field");
  781. return 0;
  782. }
  783. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  784. cfg.mergeRegionArea))
  785. {
  786. ATOMIC_LOGERROR("Could not build regions");
  787. return 0;
  788. }
  789. }
  790. else
  791. {
  792. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  793. {
  794. ATOMIC_LOGERROR("Could not build monotone regions");
  795. return 0;
  796. }
  797. }
  798. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  799. if (!build.heightFieldLayers_)
  800. {
  801. ATOMIC_LOGERROR("Could not allocate height field layer set");
  802. return 0;
  803. }
  804. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight,
  805. *build.heightFieldLayers_))
  806. {
  807. ATOMIC_LOGERROR("Could not build height field layers");
  808. return 0;
  809. }
  810. int retCt = 0;
  811. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  812. {
  813. dtTileCacheLayerHeader header;
  814. header.magic = DT_TILECACHE_MAGIC;
  815. header.version = DT_TILECACHE_VERSION;
  816. header.tx = x;
  817. header.ty = z;
  818. header.tlayer = i;
  819. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  820. // Tile info.
  821. rcVcopy(header.bmin, layer->bmin);
  822. rcVcopy(header.bmax, layer->bmax);
  823. header.width = (unsigned char)layer->width;
  824. header.height = (unsigned char)layer->height;
  825. header.minx = (unsigned char)layer->minx;
  826. header.maxx = (unsigned char)layer->maxx;
  827. header.miny = (unsigned char)layer->miny;
  828. header.maxy = (unsigned char)layer->maxy;
  829. header.hmin = (unsigned short)layer->hmin;
  830. header.hmax = (unsigned short)layer->hmax;
  831. if (dtStatusFailed(
  832. dtBuildTileCacheLayer(compressor_.Get()/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
  833. &(tiles[retCt].data), &tiles[retCt].dataSize)))
  834. {
  835. ATOMIC_LOGERROR("Failed to build tile cache layers");
  836. return 0;
  837. }
  838. else
  839. ++retCt;
  840. }
  841. // Send a notification of the rebuild of this tile to anyone interested
  842. {
  843. using namespace NavigationAreaRebuilt;
  844. VariantMap& eventData = GetContext()->GetEventDataMap();
  845. eventData[P_NODE] = GetNode();
  846. eventData[P_MESH] = this;
  847. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  848. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  849. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  850. }
  851. return retCt;
  852. }
  853. unsigned DynamicNavigationMesh::BuildTiles(Vector<NavigationGeometryInfo>& geometryList, const IntVector2& from, const IntVector2& to)
  854. {
  855. unsigned numTiles = 0;
  856. for (int z = from.y_; z <= to.y_; ++z)
  857. {
  858. for (int x = from.x_; x <= to.x_; ++x)
  859. {
  860. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  861. const int existingCt = tileCache_->getTilesAt(x, z, existing, maxLayers_);
  862. for (int i = 0; i < existingCt; ++i)
  863. {
  864. unsigned char* data = 0x0;
  865. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  866. dtFree(data);
  867. }
  868. TileCacheData tiles[TILECACHE_MAXLAYERS];
  869. int layerCt = BuildTile(geometryList, x, z, tiles);
  870. for (int i = 0; i < layerCt; ++i)
  871. {
  872. dtCompressedTileRef tileRef;
  873. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  874. if (dtStatusFailed((dtStatus)status))
  875. {
  876. dtFree(tiles[i].data);
  877. tiles[i].data = 0x0;
  878. }
  879. else
  880. {
  881. tileCache_->buildNavMeshTile(tileRef, navMesh_);
  882. ++numTiles;
  883. }
  884. }
  885. }
  886. }
  887. return numTiles;
  888. }
  889. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  890. {
  891. PODVector<OffMeshConnection*> connections;
  892. node_->GetComponents<OffMeshConnection>(connections, true);
  893. for (unsigned i = 0; i < connections.Size(); ++i)
  894. {
  895. OffMeshConnection* connection = connections[i];
  896. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  897. {
  898. // discard this connection
  899. connections.Erase(i);
  900. --i;
  901. }
  902. }
  903. return connections;
  904. }
  905. void DynamicNavigationMesh::ReleaseNavigationMesh()
  906. {
  907. NavigationMesh::ReleaseNavigationMesh();
  908. ReleaseTileCache();
  909. }
  910. void DynamicNavigationMesh::ReleaseTileCache()
  911. {
  912. dtFreeTileCache(tileCache_);
  913. tileCache_ = 0;
  914. }
  915. void DynamicNavigationMesh::OnSceneSet(Scene* scene)
  916. {
  917. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  918. if (scene)
  919. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, ATOMIC_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  920. else
  921. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  922. }
  923. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  924. {
  925. if (tileCache_)
  926. {
  927. float pos[3];
  928. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  929. rcVcopy(pos, &obsPos.x_);
  930. dtObstacleRef refHolder;
  931. // Because dtTileCache doesn't process obstacle requests while updating tiles
  932. // it's necessary update until sufficient request space is available
  933. while (tileCache_->isObstacleQueueFull())
  934. tileCache_->update(1, navMesh_);
  935. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  936. {
  937. ATOMIC_LOGERROR("Failed to add obstacle");
  938. return;
  939. }
  940. obstacle->obstacleId_ = refHolder;
  941. assert(refHolder > 0);
  942. if (!silent)
  943. {
  944. using namespace NavigationObstacleAdded;
  945. VariantMap& eventData = GetContext()->GetEventDataMap();
  946. eventData[P_NODE] = obstacle->GetNode();
  947. eventData[P_OBSTACLE] = obstacle;
  948. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  949. eventData[P_RADIUS] = obstacle->GetRadius();
  950. eventData[P_HEIGHT] = obstacle->GetHeight();
  951. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  952. }
  953. }
  954. }
  955. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  956. {
  957. if (tileCache_)
  958. {
  959. RemoveObstacle(obstacle, true);
  960. AddObstacle(obstacle, true);
  961. }
  962. }
  963. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  964. {
  965. if (tileCache_ && obstacle->obstacleId_ > 0)
  966. {
  967. // Because dtTileCache doesn't process obstacle requests while updating tiles
  968. // it's necessary update until sufficient request space is available
  969. while (tileCache_->isObstacleQueueFull())
  970. tileCache_->update(1, navMesh_);
  971. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  972. {
  973. ATOMIC_LOGERROR("Failed to remove obstacle");
  974. return;
  975. }
  976. obstacle->obstacleId_ = 0;
  977. // Require a node in order to send an event
  978. if (!silent && obstacle->GetNode())
  979. {
  980. using namespace NavigationObstacleRemoved;
  981. VariantMap& eventData = GetContext()->GetEventDataMap();
  982. eventData[P_NODE] = obstacle->GetNode();
  983. eventData[P_OBSTACLE] = obstacle;
  984. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  985. eventData[P_RADIUS] = obstacle->GetRadius();
  986. eventData[P_HEIGHT] = obstacle->GetHeight();
  987. SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData);
  988. }
  989. }
  990. }
  991. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  992. {
  993. using namespace SceneSubsystemUpdate;
  994. if (tileCache_ && navMesh_ && IsEnabledEffective())
  995. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  996. }
  997. }