DynamicNavigationMesh.cpp 33 KB

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