DynamicNavigationMesh.cpp 39 KB

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