DynamicNavigationMesh.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../Navigation/CrowdAgent.h"
  29. #include "../Navigation/DynamicNavigationMesh.h"
  30. #include "../Navigation/NavArea.h"
  31. #include "../Navigation/NavBuildData.h"
  32. #include "../Navigation/NavigationEvents.h"
  33. #include "../Navigation/Obstacle.h"
  34. #include "../Navigation/OffMeshConnection.h"
  35. #include "../Scene/Node.h"
  36. #include "../Scene/Scene.h"
  37. #include "../Scene/SceneEvents.h"
  38. #include <LZ4/lz4.h>
  39. #include <Detour/DetourNavMesh.h>
  40. #include <Detour/DetourNavMeshBuilder.h>
  41. #include <DetourTileCache/DetourTileCache.h>
  42. #include <DetourTileCache/DetourTileCacheBuilder.h>
  43. #include <Recast/Recast.h>
  44. // DebugNew is deliberately not used because the macro 'free' conflicts with DetourTileCache's LinearAllocator interface
  45. //#include "../DebugNew.h"
  46. #define TILECACHE_MAXLAYERS 128
  47. namespace Urho3D
  48. {
  49. extern const char* NAVIGATION_CATEGORY;
  50. static const int DEFAULT_MAX_OBSTACLES = 1024;
  51. struct DynamicNavigationMesh::TileCacheData
  52. {
  53. unsigned char* data;
  54. int dataSize;
  55. };
  56. struct TileCompressor : public dtTileCacheCompressor
  57. {
  58. virtual int maxCompressedSize(const int bufferSize)
  59. {
  60. return (int)(bufferSize * 1.05f);
  61. }
  62. virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
  63. unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
  64. {
  65. *compressedSize = LZ4_compress((const char*)buffer, (char*)compressed, bufferSize);
  66. return DT_SUCCESS;
  67. }
  68. virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
  69. unsigned char* buffer, const int maxBufferSize, int* bufferSize)
  70. {
  71. *bufferSize = LZ4_decompress_safe((const char*)compressed, (char*)buffer, compressedSize, maxBufferSize);
  72. return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
  73. }
  74. };
  75. struct MeshProcess : public dtTileCacheMeshProcess
  76. {
  77. DynamicNavigationMesh* owner_;
  78. PODVector<Vector3> offMeshVertices_;
  79. PODVector<float> offMeshRadii_;
  80. PODVector<unsigned short> offMeshFlags_;
  81. PODVector<unsigned char> offMeshAreas_;
  82. PODVector<unsigned char> offMeshDir_;
  83. inline MeshProcess(DynamicNavigationMesh* owner) :
  84. owner_(owner)
  85. {
  86. }
  87. virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags)
  88. {
  89. // Update poly flags from areas.
  90. // \todo Assignment of flags from areas?
  91. for (int i = 0; i < params->polyCount; ++i)
  92. {
  93. if (polyAreas[i] != RC_NULL_AREA)
  94. polyFlags[i] = RC_WALKABLE_AREA;
  95. }
  96. BoundingBox bounds;
  97. rcVcopy(&bounds.min_.x_, params->bmin);
  98. rcVcopy(&bounds.max_.x_, params->bmin);
  99. // collect off-mesh connections
  100. PODVector<OffMeshConnection*> offMeshConnections = owner_->CollectOffMeshConnections(bounds);
  101. if (offMeshConnections.Size() > 0)
  102. {
  103. if (offMeshConnections.Size() != offMeshRadii_.Size())
  104. {
  105. Matrix3x4 inverse = owner_->GetNode()->GetWorldTransform().Inverse();
  106. ClearConnectionData();
  107. for (unsigned i = 0; i < offMeshConnections.Size(); ++i)
  108. {
  109. OffMeshConnection* connection = offMeshConnections[i];
  110. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  111. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  112. offMeshVertices_.Push(start);
  113. offMeshVertices_.Push(end);
  114. offMeshRadii_.Push(connection->GetRadius());
  115. offMeshFlags_.Push((unsigned short)connection->GetMask());
  116. offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  117. offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0));
  118. }
  119. }
  120. params->offMeshConCount = offMeshRadii_.Size();
  121. params->offMeshConVerts = &offMeshVertices_[0].x_;
  122. params->offMeshConRad = &offMeshRadii_[0];
  123. params->offMeshConFlags = &offMeshFlags_[0];
  124. params->offMeshConAreas = &offMeshAreas_[0];
  125. params->offMeshConDir = &offMeshDir_[0];
  126. }
  127. }
  128. void ClearConnectionData()
  129. {
  130. offMeshVertices_.Clear();
  131. offMeshRadii_.Clear();
  132. offMeshFlags_.Clear();
  133. offMeshAreas_.Clear();
  134. offMeshDir_.Clear();
  135. }
  136. };
  137. // From the Detour/Recast Sample_TempObstacles.cpp
  138. struct LinearAllocator : public dtTileCacheAlloc
  139. {
  140. unsigned char* buffer;
  141. int capacity;
  142. int top;
  143. int high;
  144. LinearAllocator(const int cap) :
  145. buffer(0), capacity(0), top(0), high(0)
  146. {
  147. resize(cap);
  148. }
  149. ~LinearAllocator()
  150. {
  151. dtFree(buffer);
  152. }
  153. void resize(const int cap)
  154. {
  155. if (buffer)
  156. dtFree(buffer);
  157. buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
  158. capacity = cap;
  159. }
  160. virtual void reset()
  161. {
  162. high = Max(high, top);
  163. top = 0;
  164. }
  165. virtual void* alloc(const int size)
  166. {
  167. if (!buffer)
  168. return 0;
  169. if (top + size > capacity)
  170. return 0;
  171. unsigned char* mem = &buffer[top];
  172. top += size;
  173. return mem;
  174. }
  175. virtual void free(void*)
  176. {
  177. }
  178. };
  179. DynamicNavigationMesh::DynamicNavigationMesh(Context* context) :
  180. NavigationMesh(context),
  181. tileCache_(0),
  182. maxObstacles_(1024),
  183. drawObstacles_(false)
  184. {
  185. //64 is the largest tile-size that DetourTileCache will tolerate without silently failing
  186. tileSize_ = 64;
  187. partitionType_ = NAVMESH_PARTITION_MONOTONE;
  188. allocator_ = new LinearAllocator(32000); //32kb to start
  189. compressor_ = new TileCompressor();
  190. meshProcessor_ = new MeshProcess(this);
  191. }
  192. DynamicNavigationMesh::~DynamicNavigationMesh()
  193. {
  194. ReleaseNavigationMesh();
  195. delete allocator_;
  196. allocator_ = 0;
  197. delete compressor_;
  198. compressor_ = 0;
  199. delete meshProcessor_;
  200. meshProcessor_ = 0;
  201. }
  202. void DynamicNavigationMesh::RegisterObject(Context* context)
  203. {
  204. context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY);
  205. COPY_BASE_ATTRIBUTES(NavigationMesh);
  206. ACCESSOR_ATTRIBUTE("Max Obstacles", GetMaxObstacles, SetMaxObstacles, unsigned, DEFAULT_MAX_OBSTACLES, AM_DEFAULT);
  207. ACCESSOR_ATTRIBUTE("Draw Obstacles", GetDrawObstacles, SetDrawObstacles, bool, false, 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((unsigned)(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 = (unsigned)(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((dtStatus)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 CrowdManager
  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((dtStatus)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(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  417. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  418. Color::YELLOW, depthTest);
  419. }
  420. }
  421. }
  422. }
  423. }
  424. Scene* scene = GetScene();
  425. if (scene)
  426. {
  427. // Draw Obstacle components
  428. if (drawObstacles_)
  429. {
  430. PODVector<Node*> obstacles;
  431. scene->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. // Draw OffMeshConnection components
  440. if (drawOffMeshConnections_)
  441. {
  442. PODVector<Node*> connections;
  443. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  444. for (unsigned i = 0; i < connections.Size(); ++i)
  445. {
  446. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  447. if (connection && connection->IsEnabledEffective())
  448. connection->DrawDebugGeometry(debug, depthTest);
  449. }
  450. }
  451. // Draw NavArea components
  452. if (drawNavAreas_)
  453. {
  454. PODVector<Node*> areas;
  455. scene->GetChildrenWithComponent<NavArea>(areas, true);
  456. for (unsigned i = 0; i < areas.Size(); ++i)
  457. {
  458. NavArea* area = areas[i]->GetComponent<NavArea>();
  459. if (area && area->IsEnabledEffective())
  460. area->DrawDebugGeometry(debug, depthTest);
  461. }
  462. }
  463. }
  464. }
  465. void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest)
  466. {
  467. Scene* scene = GetScene();
  468. if (scene)
  469. {
  470. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  471. if (debug)
  472. DrawDebugGeometry(debug, depthTest);
  473. }
  474. }
  475. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  476. {
  477. ReleaseNavigationMesh();
  478. if (value.Empty())
  479. return;
  480. MemoryBuffer buffer(value);
  481. boundingBox_ = buffer.ReadBoundingBox();
  482. numTilesX_ = buffer.ReadInt();
  483. numTilesZ_ = buffer.ReadInt();
  484. dtNavMeshParams params;
  485. buffer.Read(&params, sizeof(dtNavMeshParams));
  486. navMesh_ = dtAllocNavMesh();
  487. if (!navMesh_)
  488. {
  489. LOGERROR("Could not allocate navigation mesh");
  490. return;
  491. }
  492. if (dtStatusFailed(navMesh_->init(&params)))
  493. {
  494. LOGERROR("Could not initialize navigation mesh");
  495. ReleaseNavigationMesh();
  496. return;
  497. }
  498. dtTileCacheParams tcParams;
  499. buffer.Read(&tcParams, sizeof(tcParams));
  500. tileCache_ = dtAllocTileCache();
  501. if (!tileCache_)
  502. {
  503. LOGERROR("Could not allocate tile cache");
  504. ReleaseNavigationMesh();
  505. return;
  506. }
  507. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_, compressor_, meshProcessor_)))
  508. {
  509. LOGERROR("Could not initialize tile cache");
  510. ReleaseNavigationMesh();
  511. return;
  512. }
  513. while (!buffer.IsEof())
  514. {
  515. dtTileCacheLayerHeader header;
  516. buffer.Read(&header, sizeof(dtTileCacheLayerHeader));
  517. const int dataSize = buffer.ReadInt();
  518. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  519. buffer.Read(data, (unsigned)dataSize);
  520. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  521. {
  522. LOGERROR("Failed to add tile");
  523. dtFree(data);
  524. return;
  525. }
  526. }
  527. for (int x = 0; x < numTilesX_; ++x)
  528. {
  529. for (int z = 0; z < numTilesZ_; ++z)
  530. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  531. }
  532. tileCache_->update(0, navMesh_);
  533. }
  534. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  535. {
  536. VectorBuffer ret;
  537. if (navMesh_ && tileCache_)
  538. {
  539. ret.WriteBoundingBox(boundingBox_);
  540. ret.WriteInt(numTilesX_);
  541. ret.WriteInt(numTilesZ_);
  542. const dtNavMeshParams* params = navMesh_->getParams();
  543. ret.Write(params, sizeof(dtNavMeshParams));
  544. const dtTileCacheParams* tcParams = tileCache_->getParams();
  545. ret.Write(tcParams, sizeof(dtTileCacheParams));
  546. for (int z = 0; z < numTilesZ_; ++z)
  547. {
  548. for (int x = 0; x < numTilesX_; ++x)
  549. {
  550. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  551. const int ct = tileCache_->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  552. for (int i = 0; i < ct; ++i)
  553. {
  554. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  555. if (!tile || !tile->header || !tile->dataSize)
  556. continue; // Don't write "void-space" tiles
  557. // The header conveniently has the majority of the information required
  558. ret.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  559. ret.WriteInt(tile->dataSize);
  560. ret.Write(tile->data, (unsigned)tile->dataSize);
  561. }
  562. }
  563. }
  564. }
  565. return ret.GetBuffer();
  566. }
  567. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  568. {
  569. PROFILE(BuildNavigationMeshTile);
  570. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  571. float tileEdgeLength = (float)tileSize_ * cellSize_;
  572. BoundingBox tileBoundingBox(Vector3(
  573. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  574. boundingBox_.min_.y_,
  575. boundingBox_.min_.z_ + tileEdgeLength * (float)z),
  576. Vector3(
  577. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  578. boundingBox_.max_.y_,
  579. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
  580. DynamicNavBuildData build(allocator_);
  581. rcConfig cfg;
  582. memset(&cfg, 0, sizeof cfg);
  583. cfg.cs = cellSize_;
  584. cfg.ch = cellHeight_;
  585. cfg.walkableSlopeAngle = agentMaxSlope_;
  586. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  587. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  588. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  589. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  590. cfg.maxSimplificationError = edgeMaxError_;
  591. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  592. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  593. cfg.maxVertsPerPoly = 6;
  594. cfg.tileSize = tileSize_;
  595. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  596. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  597. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  598. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  599. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  600. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  601. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  602. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  603. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  604. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  605. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  606. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  607. GetTileGeometry(&build, geometryList, expandedBox);
  608. if (build.vertices_.Empty() || build.indices_.Empty())
  609. return 0; // Nothing to do
  610. build.heightField_ = rcAllocHeightfield();
  611. if (!build.heightField_)
  612. {
  613. LOGERROR("Could not allocate heightfield");
  614. return 0;
  615. }
  616. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  617. cfg.ch))
  618. {
  619. LOGERROR("Could not create heightfield");
  620. return 0;
  621. }
  622. unsigned numTriangles = build.indices_.Size() / 3;
  623. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  624. memset(triAreas.Get(), 0, numTriangles);
  625. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  626. &build.indices_[0], numTriangles, triAreas.Get());
  627. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  628. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  629. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  630. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  631. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  632. build.compactHeightField_ = rcAllocCompactHeightfield();
  633. if (!build.compactHeightField_)
  634. {
  635. LOGERROR("Could not allocate create compact heightfield");
  636. return 0;
  637. }
  638. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  639. *build.compactHeightField_))
  640. {
  641. LOGERROR("Could not build compact heightfield");
  642. return 0;
  643. }
  644. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  645. {
  646. LOGERROR("Could not erode compact heightfield");
  647. return 0;
  648. }
  649. // area volumes
  650. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  651. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  652. build.navAreas_[i].areaID_, *build.compactHeightField_);
  653. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  654. {
  655. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  656. {
  657. LOGERROR("Could not build distance field");
  658. return 0;
  659. }
  660. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  661. cfg.mergeRegionArea))
  662. {
  663. LOGERROR("Could not build regions");
  664. return 0;
  665. }
  666. }
  667. else
  668. {
  669. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  670. {
  671. LOGERROR("Could not build monotone regions");
  672. return 0;
  673. }
  674. }
  675. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  676. if (!build.heightFieldLayers_)
  677. {
  678. LOGERROR("Could not allocate height field layer set");
  679. return 0;
  680. }
  681. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight,
  682. *build.heightFieldLayers_))
  683. {
  684. LOGERROR("Could not build height field layers");
  685. return 0;
  686. }
  687. int retCt = 0;
  688. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  689. {
  690. dtTileCacheLayerHeader header;
  691. header.magic = DT_TILECACHE_MAGIC;
  692. header.version = DT_TILECACHE_VERSION;
  693. header.tx = x;
  694. header.ty = z;
  695. header.tlayer = i;
  696. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  697. // Tile info.
  698. rcVcopy(header.bmin, layer->bmin);
  699. rcVcopy(header.bmax, layer->bmax);
  700. header.width = (unsigned char)layer->width;
  701. header.height = (unsigned char)layer->height;
  702. header.minx = (unsigned char)layer->minx;
  703. header.maxx = (unsigned char)layer->maxx;
  704. header.miny = (unsigned char)layer->miny;
  705. header.maxy = (unsigned char)layer->maxy;
  706. header.hmin = (unsigned short)layer->hmin;
  707. header.hmax = (unsigned short)layer->hmax;
  708. if (dtStatusFailed(
  709. dtBuildTileCacheLayer(compressor_/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
  710. &(tiles[retCt].data), &tiles[retCt].dataSize)))
  711. {
  712. LOGERROR("Failed to build tile cache layers");
  713. return 0;
  714. }
  715. else
  716. ++retCt;
  717. }
  718. // Send a notification of the rebuild of this tile to anyone interested
  719. {
  720. using namespace NavigationAreaRebuilt;
  721. VariantMap& eventData = GetContext()->GetEventDataMap();
  722. eventData[P_NODE] = GetNode();
  723. eventData[P_MESH] = this;
  724. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  725. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  726. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  727. }
  728. return retCt;
  729. }
  730. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  731. {
  732. PODVector<OffMeshConnection*> connections;
  733. node_->GetComponents<OffMeshConnection>(connections, true);
  734. for (unsigned i = 0; i < connections.Size(); ++i)
  735. {
  736. OffMeshConnection* connection = connections[i];
  737. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  738. {
  739. // discard this connection
  740. connections.Erase(i);
  741. --i;
  742. }
  743. }
  744. return connections;
  745. }
  746. void DynamicNavigationMesh::ReleaseNavigationMesh()
  747. {
  748. NavigationMesh::ReleaseNavigationMesh();
  749. ReleaseTileCache();
  750. }
  751. void DynamicNavigationMesh::ReleaseTileCache()
  752. {
  753. dtFreeTileCache(tileCache_);
  754. tileCache_ = 0;
  755. }
  756. void DynamicNavigationMesh::OnSceneSet(Scene* scene)
  757. {
  758. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  759. if (scene)
  760. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, URHO3D_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  761. else
  762. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  763. }
  764. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  765. {
  766. if (tileCache_)
  767. {
  768. float pos[3];
  769. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  770. rcVcopy(pos, &obsPos.x_);
  771. dtObstacleRef refHolder;
  772. // Because dtTileCache doesn't process obstacle requests while updating tiles
  773. // it's necessary update until sufficient request space is available
  774. while (tileCache_->isObstacleQueueFull())
  775. tileCache_->update(1, navMesh_);
  776. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  777. {
  778. LOGERROR("Failed to add obstacle");
  779. return;
  780. }
  781. obstacle->obstacleId_ = refHolder;
  782. assert(refHolder > 0);
  783. if (!silent)
  784. {
  785. using namespace NavigationObstacleAdded;
  786. VariantMap& eventData = GetContext()->GetEventDataMap();
  787. eventData[P_NODE] = obstacle->GetNode();
  788. eventData[P_OBSTACLE] = obstacle;
  789. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  790. eventData[P_RADIUS] = obstacle->GetRadius();
  791. eventData[P_HEIGHT] = obstacle->GetHeight();
  792. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  793. }
  794. }
  795. }
  796. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  797. {
  798. if (tileCache_)
  799. {
  800. RemoveObstacle(obstacle, true);
  801. AddObstacle(obstacle, true);
  802. }
  803. }
  804. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  805. {
  806. if (tileCache_ && obstacle->obstacleId_ > 0)
  807. {
  808. // Because dtTileCache doesn't process obstacle requests while updating tiles
  809. // it's necessary update until sufficient request space is available
  810. while (tileCache_->isObstacleQueueFull())
  811. tileCache_->update(1, navMesh_);
  812. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  813. {
  814. LOGERROR("Failed to remove obstacle");
  815. return;
  816. }
  817. obstacle->obstacleId_ = 0;
  818. // Require a node in order to send an event
  819. if (!silent && obstacle->GetNode())
  820. {
  821. using namespace NavigationObstacleRemoved;
  822. VariantMap& eventData = GetContext()->GetEventDataMap();
  823. eventData[P_NODE] = obstacle->GetNode();
  824. eventData[P_OBSTACLE] = obstacle;
  825. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  826. eventData[P_RADIUS] = obstacle->GetRadius();
  827. eventData[P_HEIGHT] = obstacle->GetHeight();
  828. SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData);
  829. }
  830. }
  831. }
  832. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  833. {
  834. using namespace SceneSubsystemUpdate;
  835. if (tileCache_ && navMesh_ && IsEnabledEffective())
  836. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  837. }
  838. }