DynamicNavigationMesh.cpp 33 KB

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