DynamicNavigationMesh.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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::Build()
  209. {
  210. ATOMIC_PROFILE(BuildNavigationMesh);
  211. // Release existing navigation data and zero the bounding box
  212. ReleaseNavigationMesh();
  213. if (!node_)
  214. return false;
  215. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  216. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  217. Vector<NavigationGeometryInfo> geometryList;
  218. CollectGeometries(geometryList);
  219. if (geometryList.Empty())
  220. return true; // Nothing to do
  221. // Build the combined bounding box
  222. for (unsigned i = 0; i < geometryList.Size(); ++i)
  223. boundingBox_.Merge(geometryList[i].boundingBox_);
  224. // Expand bounding box by padding
  225. boundingBox_.min_ -= padding_;
  226. boundingBox_.max_ += padding_;
  227. {
  228. ATOMIC_PROFILE(BuildNavigationMesh);
  229. // Calculate number of tiles
  230. int gridW = 0, gridH = 0;
  231. float tileEdgeLength = (float)tileSize_ * cellSize_;
  232. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  233. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  234. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  235. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  236. unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_)) * maxLayers_;
  237. unsigned tileBits = 0;
  238. unsigned temp = maxTiles;
  239. while (temp > 1)
  240. {
  241. temp >>= 1;
  242. ++tileBits;
  243. }
  244. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  245. dtNavMeshParams params;
  246. rcVcopy(params.orig, &boundingBox_.min_.x_);
  247. params.tileWidth = tileEdgeLength;
  248. params.tileHeight = tileEdgeLength;
  249. params.maxTiles = maxTiles;
  250. params.maxPolys = maxPolys;
  251. navMesh_ = dtAllocNavMesh();
  252. if (!navMesh_)
  253. {
  254. ATOMIC_LOGERROR("Could not allocate navigation mesh");
  255. return false;
  256. }
  257. if (dtStatusFailed(navMesh_->init(&params)))
  258. {
  259. ATOMIC_LOGERROR("Could not initialize navigation mesh");
  260. ReleaseNavigationMesh();
  261. return false;
  262. }
  263. dtTileCacheParams tileCacheParams;
  264. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  265. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  266. tileCacheParams.ch = cellHeight_;
  267. tileCacheParams.cs = cellSize_;
  268. tileCacheParams.width = tileSize_;
  269. tileCacheParams.height = tileSize_;
  270. tileCacheParams.maxSimplificationError = edgeMaxError_;
  271. tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * maxLayers_;
  272. tileCacheParams.maxObstacles = maxObstacles_;
  273. // Settings from NavigationMesh
  274. tileCacheParams.walkableClimb = agentMaxClimb_;
  275. tileCacheParams.walkableHeight = agentHeight_;
  276. tileCacheParams.walkableRadius = agentRadius_;
  277. tileCache_ = dtAllocTileCache();
  278. if (!tileCache_)
  279. {
  280. ATOMIC_LOGERROR("Could not allocate tile cache");
  281. ReleaseNavigationMesh();
  282. return false;
  283. }
  284. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  285. {
  286. ATOMIC_LOGERROR("Could not initialize tile cache");
  287. ReleaseNavigationMesh();
  288. return false;
  289. }
  290. // Build each tile
  291. unsigned numTiles = 0;
  292. for (int z = 0; z < numTilesZ_; ++z)
  293. {
  294. for (int x = 0; x < numTilesX_; ++x)
  295. {
  296. TileCacheData tiles[TILECACHE_MAXLAYERS];
  297. int layerCt = BuildTile(geometryList, x, z, tiles);
  298. for (int i = 0; i < layerCt; ++i)
  299. {
  300. dtCompressedTileRef tileRef;
  301. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  302. if (dtStatusFailed((dtStatus)status))
  303. {
  304. dtFree(tiles[i].data);
  305. tiles[i].data = 0x0;
  306. }
  307. }
  308. ++numTiles;
  309. }
  310. for (int x = 0; x < numTilesX_; ++x)
  311. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  312. }
  313. // For a full build it's necessary to update the nav mesh
  314. // not doing so will cause dependent components to crash, like CrowdManager
  315. tileCache_->update(0, navMesh_);
  316. ATOMIC_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  317. // Send a notification event to concerned parties that we've been fully rebuilt
  318. {
  319. using namespace NavigationMeshRebuilt;
  320. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  321. buildEventParams[P_NODE] = node_;
  322. buildEventParams[P_MESH] = this;
  323. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  324. }
  325. // Scan for obstacles to insert into us
  326. PODVector<Node*> obstacles;
  327. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  328. for (unsigned i = 0; i < obstacles.Size(); ++i)
  329. {
  330. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  331. if (obs && obs->IsEnabledEffective())
  332. AddObstacle(obs);
  333. }
  334. return true;
  335. }
  336. }
  337. bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox)
  338. {
  339. ATOMIC_PROFILE(BuildPartialNavigationMesh);
  340. if (!node_)
  341. return false;
  342. if (!navMesh_)
  343. {
  344. ATOMIC_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  345. return false;
  346. }
  347. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  348. ATOMIC_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  349. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  350. float tileEdgeLength = (float)tileSize_ * cellSize_;
  351. Vector<NavigationGeometryInfo> geometryList;
  352. CollectGeometries(geometryList);
  353. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  354. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  355. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  356. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  357. unsigned numTiles = 0;
  358. for (int z = sz; z <= ez; ++z)
  359. {
  360. for (int x = sx; x <= ex; ++x)
  361. {
  362. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  363. const int existingCt = tileCache_->getTilesAt(x, z, existing, maxLayers_);
  364. for (int i = 0; i < existingCt; ++i)
  365. {
  366. unsigned char* data = 0x0;
  367. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  368. dtFree(data);
  369. }
  370. TileCacheData tiles[TILECACHE_MAXLAYERS];
  371. int layerCt = BuildTile(geometryList, x, z, tiles);
  372. for (int i = 0; i < layerCt; ++i)
  373. {
  374. dtCompressedTileRef tileRef;
  375. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  376. if (dtStatusFailed((dtStatus)status))
  377. {
  378. dtFree(tiles[i].data);
  379. tiles[i].data = 0x0;
  380. }
  381. else
  382. {
  383. tileCache_->buildNavMeshTile(tileRef, navMesh_);
  384. ++numTiles;
  385. }
  386. }
  387. }
  388. }
  389. ATOMIC_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  390. return true;
  391. }
  392. void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  393. {
  394. if (!debug || !navMesh_ || !node_)
  395. return;
  396. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  397. const dtNavMesh* navMesh = navMesh_;
  398. for (int z = 0; z < numTilesZ_; ++z)
  399. {
  400. for (int x = 0; x < numTilesX_; ++x)
  401. {
  402. // Get the layers from the tile-cache
  403. const dtMeshTile* tiles[TILECACHE_MAXLAYERS];
  404. int tileCount = navMesh->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  405. for (int i = 0; i < tileCount; ++i)
  406. {
  407. const dtMeshTile* tile = tiles[i];
  408. if (!tile)
  409. continue;
  410. for (int i = 0; i < tile->header->polyCount; ++i)
  411. {
  412. dtPoly* poly = tile->polys + i;
  413. for (unsigned j = 0; j < poly->vertCount; ++j)
  414. {
  415. debug->AddLine(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  416. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  417. Color::YELLOW, depthTest);
  418. }
  419. }
  420. }
  421. }
  422. }
  423. Scene* scene = GetScene();
  424. if (scene)
  425. {
  426. // Draw Obstacle components
  427. if (drawObstacles_)
  428. {
  429. PODVector<Node*> obstacles;
  430. scene->GetChildrenWithComponent<Obstacle>(obstacles, true);
  431. for (unsigned i = 0; i < obstacles.Size(); ++i)
  432. {
  433. Obstacle* obstacle = obstacles[i]->GetComponent<Obstacle>();
  434. if (obstacle && obstacle->IsEnabledEffective())
  435. obstacle->DrawDebugGeometry(debug, depthTest);
  436. }
  437. }
  438. // Draw OffMeshConnection components
  439. if (drawOffMeshConnections_)
  440. {
  441. PODVector<Node*> connections;
  442. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  443. for (unsigned i = 0; i < connections.Size(); ++i)
  444. {
  445. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  446. if (connection && connection->IsEnabledEffective())
  447. connection->DrawDebugGeometry(debug, depthTest);
  448. }
  449. }
  450. // Draw NavArea components
  451. if (drawNavAreas_)
  452. {
  453. PODVector<Node*> areas;
  454. scene->GetChildrenWithComponent<NavArea>(areas, true);
  455. for (unsigned i = 0; i < areas.Size(); ++i)
  456. {
  457. NavArea* area = areas[i]->GetComponent<NavArea>();
  458. if (area && area->IsEnabledEffective())
  459. area->DrawDebugGeometry(debug, depthTest);
  460. }
  461. }
  462. }
  463. }
  464. void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest)
  465. {
  466. Scene* scene = GetScene();
  467. if (scene)
  468. {
  469. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  470. if (debug)
  471. DrawDebugGeometry(debug, depthTest);
  472. }
  473. }
  474. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  475. {
  476. ReleaseNavigationMesh();
  477. if (value.Empty())
  478. return;
  479. MemoryBuffer buffer(value);
  480. boundingBox_ = buffer.ReadBoundingBox();
  481. numTilesX_ = buffer.ReadInt();
  482. numTilesZ_ = buffer.ReadInt();
  483. dtNavMeshParams params;
  484. buffer.Read(&params, sizeof(dtNavMeshParams));
  485. navMesh_ = dtAllocNavMesh();
  486. if (!navMesh_)
  487. {
  488. ATOMIC_LOGERROR("Could not allocate navigation mesh");
  489. return;
  490. }
  491. if (dtStatusFailed(navMesh_->init(&params)))
  492. {
  493. ATOMIC_LOGERROR("Could not initialize navigation mesh");
  494. ReleaseNavigationMesh();
  495. return;
  496. }
  497. dtTileCacheParams tcParams;
  498. buffer.Read(&tcParams, sizeof(tcParams));
  499. tileCache_ = dtAllocTileCache();
  500. if (!tileCache_)
  501. {
  502. ATOMIC_LOGERROR("Could not allocate tile cache");
  503. ReleaseNavigationMesh();
  504. return;
  505. }
  506. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  507. {
  508. ATOMIC_LOGERROR("Could not initialize tile cache");
  509. ReleaseNavigationMesh();
  510. return;
  511. }
  512. while (!buffer.IsEof())
  513. {
  514. dtTileCacheLayerHeader header;
  515. buffer.Read(&header, sizeof(dtTileCacheLayerHeader));
  516. const int dataSize = buffer.ReadInt();
  517. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  518. buffer.Read(data, (unsigned)dataSize);
  519. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  520. {
  521. ATOMIC_LOGERROR("Failed to add tile");
  522. dtFree(data);
  523. return;
  524. }
  525. }
  526. for (int x = 0; x < numTilesX_; ++x)
  527. {
  528. for (int z = 0; z < numTilesZ_; ++z)
  529. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  530. }
  531. tileCache_->update(0, navMesh_);
  532. }
  533. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  534. {
  535. VectorBuffer ret;
  536. if (navMesh_ && tileCache_)
  537. {
  538. ret.WriteBoundingBox(boundingBox_);
  539. ret.WriteInt(numTilesX_);
  540. ret.WriteInt(numTilesZ_);
  541. const dtNavMeshParams* params = navMesh_->getParams();
  542. ret.Write(params, sizeof(dtNavMeshParams));
  543. const dtTileCacheParams* tcParams = tileCache_->getParams();
  544. ret.Write(tcParams, sizeof(dtTileCacheParams));
  545. for (int z = 0; z < numTilesZ_; ++z)
  546. {
  547. for (int x = 0; x < numTilesX_; ++x)
  548. {
  549. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  550. const int ct = tileCache_->getTilesAt(x, z, tiles, maxLayers_);
  551. for (int i = 0; i < ct; ++i)
  552. {
  553. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  554. if (!tile || !tile->header || !tile->dataSize)
  555. continue; // Don't write "void-space" tiles
  556. // The header conveniently has the majority of the information required
  557. ret.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  558. ret.WriteInt(tile->dataSize);
  559. ret.Write(tile->data, (unsigned)tile->dataSize);
  560. }
  561. }
  562. }
  563. }
  564. return ret.GetBuffer();
  565. }
  566. void DynamicNavigationMesh::SetMaxLayers(unsigned maxLayers)
  567. {
  568. // Set 3 as a minimum due to the tendency of layers to be constructed inside the hollow space of stacked objects
  569. // That behavior is unlikely to be expected by the end user
  570. maxLayers_ = Max(3U, Min(maxLayers, TILECACHE_MAXLAYERS));
  571. }
  572. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  573. {
  574. ATOMIC_PROFILE(BuildNavigationMeshTile);
  575. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  576. float tileEdgeLength = (float)tileSize_ * cellSize_;
  577. BoundingBox tileBoundingBox(Vector3(
  578. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  579. boundingBox_.min_.y_,
  580. boundingBox_.min_.z_ + tileEdgeLength * (float)z),
  581. Vector3(
  582. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  583. boundingBox_.max_.y_,
  584. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
  585. DynamicNavBuildData build(allocator_.Get());
  586. rcConfig cfg;
  587. memset(&cfg, 0, sizeof cfg);
  588. cfg.cs = cellSize_;
  589. cfg.ch = cellHeight_;
  590. cfg.walkableSlopeAngle = agentMaxSlope_;
  591. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  592. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  593. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  594. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  595. cfg.maxSimplificationError = edgeMaxError_;
  596. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  597. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  598. cfg.maxVertsPerPoly = 6;
  599. cfg.tileSize = tileSize_;
  600. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  601. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  602. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  603. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  604. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  605. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  606. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  607. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  608. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  609. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  610. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  611. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  612. GetTileGeometry(&build, geometryList, expandedBox);
  613. if (build.vertices_.Empty() || build.indices_.Empty())
  614. return 0; // Nothing to do
  615. build.heightField_ = rcAllocHeightfield();
  616. if (!build.heightField_)
  617. {
  618. ATOMIC_LOGERROR("Could not allocate heightfield");
  619. return 0;
  620. }
  621. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  622. cfg.ch))
  623. {
  624. ATOMIC_LOGERROR("Could not create heightfield");
  625. return 0;
  626. }
  627. unsigned numTriangles = build.indices_.Size() / 3;
  628. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  629. memset(triAreas.Get(), 0, numTriangles);
  630. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  631. &build.indices_[0], numTriangles, triAreas.Get());
  632. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  633. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  634. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  635. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  636. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  637. build.compactHeightField_ = rcAllocCompactHeightfield();
  638. if (!build.compactHeightField_)
  639. {
  640. ATOMIC_LOGERROR("Could not allocate create compact heightfield");
  641. return 0;
  642. }
  643. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  644. *build.compactHeightField_))
  645. {
  646. ATOMIC_LOGERROR("Could not build compact heightfield");
  647. return 0;
  648. }
  649. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  650. {
  651. ATOMIC_LOGERROR("Could not erode compact heightfield");
  652. return 0;
  653. }
  654. // area volumes
  655. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  656. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  657. build.navAreas_[i].areaID_, *build.compactHeightField_);
  658. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  659. {
  660. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  661. {
  662. ATOMIC_LOGERROR("Could not build distance field");
  663. return 0;
  664. }
  665. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  666. cfg.mergeRegionArea))
  667. {
  668. ATOMIC_LOGERROR("Could not build regions");
  669. return 0;
  670. }
  671. }
  672. else
  673. {
  674. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  675. {
  676. ATOMIC_LOGERROR("Could not build monotone regions");
  677. return 0;
  678. }
  679. }
  680. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  681. if (!build.heightFieldLayers_)
  682. {
  683. ATOMIC_LOGERROR("Could not allocate height field layer set");
  684. return 0;
  685. }
  686. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight,
  687. *build.heightFieldLayers_))
  688. {
  689. ATOMIC_LOGERROR("Could not build height field layers");
  690. return 0;
  691. }
  692. int retCt = 0;
  693. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  694. {
  695. dtTileCacheLayerHeader header;
  696. header.magic = DT_TILECACHE_MAGIC;
  697. header.version = DT_TILECACHE_VERSION;
  698. header.tx = x;
  699. header.ty = z;
  700. header.tlayer = i;
  701. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  702. // Tile info.
  703. rcVcopy(header.bmin, layer->bmin);
  704. rcVcopy(header.bmax, layer->bmax);
  705. header.width = (unsigned char)layer->width;
  706. header.height = (unsigned char)layer->height;
  707. header.minx = (unsigned char)layer->minx;
  708. header.maxx = (unsigned char)layer->maxx;
  709. header.miny = (unsigned char)layer->miny;
  710. header.maxy = (unsigned char)layer->maxy;
  711. header.hmin = (unsigned short)layer->hmin;
  712. header.hmax = (unsigned short)layer->hmax;
  713. if (dtStatusFailed(
  714. dtBuildTileCacheLayer(compressor_.Get()/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
  715. &(tiles[retCt].data), &tiles[retCt].dataSize)))
  716. {
  717. ATOMIC_LOGERROR("Failed to build tile cache layers");
  718. return 0;
  719. }
  720. else
  721. ++retCt;
  722. }
  723. // Send a notification of the rebuild of this tile to anyone interested
  724. {
  725. using namespace NavigationAreaRebuilt;
  726. VariantMap& eventData = GetContext()->GetEventDataMap();
  727. eventData[P_NODE] = GetNode();
  728. eventData[P_MESH] = this;
  729. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  730. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  731. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  732. }
  733. return retCt;
  734. }
  735. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  736. {
  737. PODVector<OffMeshConnection*> connections;
  738. node_->GetComponents<OffMeshConnection>(connections, true);
  739. for (unsigned i = 0; i < connections.Size(); ++i)
  740. {
  741. OffMeshConnection* connection = connections[i];
  742. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  743. {
  744. // discard this connection
  745. connections.Erase(i);
  746. --i;
  747. }
  748. }
  749. return connections;
  750. }
  751. void DynamicNavigationMesh::ReleaseNavigationMesh()
  752. {
  753. NavigationMesh::ReleaseNavigationMesh();
  754. ReleaseTileCache();
  755. }
  756. void DynamicNavigationMesh::ReleaseTileCache()
  757. {
  758. dtFreeTileCache(tileCache_);
  759. tileCache_ = 0;
  760. }
  761. void DynamicNavigationMesh::OnSceneSet(Scene* scene)
  762. {
  763. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  764. if (scene)
  765. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, ATOMIC_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  766. else
  767. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  768. }
  769. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  770. {
  771. if (tileCache_)
  772. {
  773. float pos[3];
  774. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  775. rcVcopy(pos, &obsPos.x_);
  776. dtObstacleRef refHolder;
  777. // Because dtTileCache doesn't process obstacle requests while updating tiles
  778. // it's necessary update until sufficient request space is available
  779. while (tileCache_->isObstacleQueueFull())
  780. tileCache_->update(1, navMesh_);
  781. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  782. {
  783. ATOMIC_LOGERROR("Failed to add obstacle");
  784. return;
  785. }
  786. obstacle->obstacleId_ = refHolder;
  787. assert(refHolder > 0);
  788. if (!silent)
  789. {
  790. using namespace NavigationObstacleAdded;
  791. VariantMap& eventData = GetContext()->GetEventDataMap();
  792. eventData[P_NODE] = obstacle->GetNode();
  793. eventData[P_OBSTACLE] = obstacle;
  794. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  795. eventData[P_RADIUS] = obstacle->GetRadius();
  796. eventData[P_HEIGHT] = obstacle->GetHeight();
  797. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  798. }
  799. }
  800. }
  801. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  802. {
  803. if (tileCache_)
  804. {
  805. RemoveObstacle(obstacle, true);
  806. AddObstacle(obstacle, true);
  807. }
  808. }
  809. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  810. {
  811. if (tileCache_ && obstacle->obstacleId_ > 0)
  812. {
  813. // Because dtTileCache doesn't process obstacle requests while updating tiles
  814. // it's necessary update until sufficient request space is available
  815. while (tileCache_->isObstacleQueueFull())
  816. tileCache_->update(1, navMesh_);
  817. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  818. {
  819. ATOMIC_LOGERROR("Failed to remove obstacle");
  820. return;
  821. }
  822. obstacle->obstacleId_ = 0;
  823. // Require a node in order to send an event
  824. if (!silent && obstacle->GetNode())
  825. {
  826. using namespace NavigationObstacleRemoved;
  827. VariantMap& eventData = GetContext()->GetEventDataMap();
  828. eventData[P_NODE] = obstacle->GetNode();
  829. eventData[P_OBSTACLE] = obstacle;
  830. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  831. eventData[P_RADIUS] = obstacle->GetRadius();
  832. eventData[P_HEIGHT] = obstacle->GetHeight();
  833. SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData);
  834. }
  835. }
  836. }
  837. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  838. {
  839. using namespace SceneSubsystemUpdate;
  840. if (tileCache_ && navMesh_ && IsEnabledEffective())
  841. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  842. }
  843. }