DynamicNavigationMesh.cpp 31 KB

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