navMesh.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 Daniel Buckmaster
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "navMesh.h"
  23. #include "navContext.h"
  24. #include <DetourDebugDraw.h>
  25. #include <RecastDebugDraw.h>
  26. #include "math/mathUtils.h"
  27. #include "math/mRandom.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/engineAPI.h"
  30. #include "console/typeValidators.h"
  31. #include "scene/sceneRenderState.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "renderInstance/renderPassManager.h"
  34. #include "gfx/primBuilder.h"
  35. #include "core/stream/bitStream.h"
  36. #include "math/mathIO.h"
  37. #include "core/fileio.h"
  38. extern bool gEditingMission;
  39. IMPLEMENT_CO_NETOBJECT_V1(NavMesh);
  40. const U32 NavMesh::mMaxVertsPerPoly = 3;
  41. SimObjectPtr<SimSet> NavMesh::smServerSet = NULL;
  42. ImplementEnumType(NavMeshWaterMethod,
  43. "The method used to include water surfaces in the NavMesh.\n")
  44. { NavMesh::Ignore, "Ignore", "Ignore all water surfaces.\n" },
  45. { NavMesh::Solid, "Solid", "Treat water surfaces as solid and walkable.\n" },
  46. { NavMesh::Impassable, "Impassable", "Treat water as an impassable obstacle.\n" },
  47. EndImplementEnumType;
  48. SimSet *NavMesh::getServerSet()
  49. {
  50. if(!smServerSet)
  51. {
  52. SimSet *set = NULL;
  53. if(Sim::findObject("ServerNavMeshSet", set))
  54. smServerSet = set;
  55. else
  56. {
  57. smServerSet = new SimSet();
  58. smServerSet->registerObject("ServerNavMeshSet");
  59. Sim::getRootGroup()->addObject(smServerSet);
  60. }
  61. }
  62. return smServerSet;
  63. }
  64. SimObjectPtr<EventManager> NavMesh::smEventManager = NULL;
  65. EventManager *NavMesh::getEventManager()
  66. {
  67. if(!smEventManager)
  68. {
  69. smEventManager = new EventManager();
  70. smEventManager->registerObject("NavEventManager");
  71. Sim::getRootGroup()->addObject(smEventManager);
  72. smEventManager->setMessageQueue("NavEventManagerQueue");
  73. smEventManager->registerEvent("NavMeshCreated");
  74. smEventManager->registerEvent("NavMeshRemoved");
  75. smEventManager->registerEvent("NavMeshStartUpdate");
  76. smEventManager->registerEvent("NavMeshUpdate");
  77. smEventManager->registerEvent("NavMeshTileUpdate");
  78. smEventManager->registerEvent("NavMeshUpdateBox");
  79. smEventManager->registerEvent("NavMeshObstacleAdded");
  80. smEventManager->registerEvent("NavMeshObstacleRemoved");
  81. }
  82. return smEventManager;
  83. }
  84. DefineEngineFunction(getNavMeshEventManager, S32, (),,
  85. "@brief Get the EventManager object for all NavMesh updates.")
  86. {
  87. return NavMesh::getEventManager()->getId();
  88. }
  89. DefineEngineFunction(NavMeshUpdateAll, void, (S32 objid, bool remove), (0, false),
  90. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  91. {
  92. SceneObject *obj;
  93. if(!Sim::findObject(objid, obj))
  94. return;
  95. obj->mPathfindingIgnore = remove;
  96. SimSet *set = NavMesh::getServerSet();
  97. for(U32 i = 0; i < set->size(); i++)
  98. {
  99. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  100. if (m)
  101. {
  102. m->cancelBuild();
  103. m->buildTiles(obj->getWorldBox());
  104. }
  105. }
  106. }
  107. DefineEngineFunction(NavMeshUpdateAroundObject, void, (S32 objid, bool remove), (0, false),
  108. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  109. {
  110. SceneObject *obj;
  111. if (!Sim::findObject(objid, obj))
  112. return;
  113. obj->mPathfindingIgnore = remove;
  114. SimSet *set = NavMesh::getServerSet();
  115. for (U32 i = 0; i < set->size(); i++)
  116. {
  117. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  118. if (m)
  119. {
  120. m->cancelBuild();
  121. m->buildTiles(obj->getWorldBox());
  122. }
  123. }
  124. }
  125. DefineEngineFunction(NavMeshIgnore, void, (S32 objid, bool _ignore), (0, true),
  126. "@brief Flag this object as not generating a navmesh result.")
  127. {
  128. SceneObject *obj;
  129. if(!Sim::findObject(objid, obj))
  130. return;
  131. obj->mPathfindingIgnore = _ignore;
  132. }
  133. DefineEngineFunction(NavMeshUpdateOne, void, (S32 meshid, S32 objid, bool remove), (0, 0, false),
  134. "@brief Update all tiles in a given NavMesh that intersect the given object's world box.")
  135. {
  136. NavMesh *mesh;
  137. SceneObject *obj;
  138. if(!Sim::findObject(meshid, mesh))
  139. {
  140. Con::errorf("NavMeshUpdateOne: cannot find NavMesh %d", meshid);
  141. return;
  142. }
  143. if(!Sim::findObject(objid, obj))
  144. {
  145. Con::errorf("NavMeshUpdateOne: cannot find SceneObject %d", objid);
  146. return;
  147. }
  148. if(remove)
  149. obj->disableCollision();
  150. mesh->buildTiles(obj->getWorldBox());
  151. if(remove)
  152. obj->enableCollision();
  153. }
  154. NavMesh::NavMesh()
  155. {
  156. mTypeMask |= StaticShapeObjectType | MarkerObjectType;
  157. mFileName = StringTable->EmptyString();
  158. mNetFlags.clear(Ghostable);
  159. mSaveIntermediates = false;
  160. nm = NULL;
  161. ctx = NULL;
  162. mWaterMethod = Ignore;
  163. dMemset(&cfg, 0, sizeof(cfg));
  164. mCellSize = mCellHeight = 0.2f;
  165. mWalkableHeight = 2.0f;
  166. mWalkableClimb = 0.3f;
  167. mWalkableRadius = 0.5f;
  168. mWalkableSlope = 40.0f;
  169. mBorderSize = 1;
  170. mDetailSampleDist = 6.0f;
  171. mDetailSampleMaxError = 1.0f;
  172. mMaxEdgeLen = 12;
  173. mMaxSimplificationError = 1.3f;
  174. mMinRegionArea = 8;
  175. mMergeRegionArea = 20;
  176. mTileSize = 10.0f;
  177. mMaxPolysPerTile = 128;
  178. mSmallCharacters = false;
  179. mRegularCharacters = true;
  180. mLargeCharacters = false;
  181. mVehicles = false;
  182. mCoverSet = StringTable->EmptyString();
  183. mInnerCover = false;
  184. mCoverDist = 1.0f;
  185. mPeekDist = 0.7f;
  186. mAlwaysRender = false;
  187. mBuilding = false;
  188. }
  189. NavMesh::~NavMesh()
  190. {
  191. dtFreeNavMesh(nm);
  192. nm = NULL;
  193. delete ctx;
  194. ctx = NULL;
  195. }
  196. bool NavMesh::setProtectedDetailSampleDist(void *obj, const char *index, const char *data)
  197. {
  198. F32 dist = dAtof(data);
  199. if(dist == 0.0f || dist >= 0.9f)
  200. return true;
  201. Con::errorf("NavMesh::detailSampleDist must be 0 or greater than 0.9!");
  202. return false;
  203. }
  204. bool NavMesh::setProtectedAlwaysRender(void *obj, const char *index, const char *data)
  205. {
  206. NavMesh *mesh = static_cast<NavMesh*>(obj);
  207. bool always = dAtob(data);
  208. if(always)
  209. {
  210. if(!gEditingMission)
  211. mesh->mNetFlags.set(Ghostable);
  212. }
  213. else
  214. {
  215. if(!gEditingMission)
  216. mesh->mNetFlags.clear(Ghostable);
  217. }
  218. mesh->mAlwaysRender = always;
  219. mesh->setMaskBits(LoadFlag);
  220. return true;
  221. }
  222. FRangeValidator ValidCellSize(0.01f, 10.0f);
  223. FRangeValidator ValidSlopeAngle(0.0f, 89.9f);
  224. IRangeValidator PositiveInt(0, S32_MAX);
  225. IRangeValidator NaturalNumber(1, S32_MAX);
  226. FRangeValidator CornerAngle(0.0f, 90.0f);
  227. void NavMesh::initPersistFields()
  228. {
  229. addGroup("NavMesh Options");
  230. addField("fileName", TypeString, Offset(mFileName, NavMesh),
  231. "Name of the data file to store this navmesh in (relative to engine executable).");
  232. addField("waterMethod", TYPEID<NavMeshWaterMethod>(), Offset(mWaterMethod, NavMesh),
  233. "The method to use to handle water surfaces.");
  234. addFieldV("cellSize", TypeF32, Offset(mCellSize, NavMesh), &ValidCellSize,
  235. "Length/width of a voxel.");
  236. addFieldV("cellHeight", TypeF32, Offset(mCellHeight, NavMesh), &ValidCellSize,
  237. "Height of a voxel.");
  238. addFieldV("tileSize", TypeF32, Offset(mTileSize, NavMesh), &CommonValidators::PositiveNonZeroFloat,
  239. "The horizontal size of tiles.");
  240. addFieldV("actorHeight", TypeF32, Offset(mWalkableHeight, NavMesh), &CommonValidators::PositiveFloat,
  241. "Height of an actor.");
  242. addFieldV("actorClimb", TypeF32, Offset(mWalkableClimb, NavMesh), &CommonValidators::PositiveFloat,
  243. "Maximum climbing height of an actor.");
  244. addFieldV("actorRadius", TypeF32, Offset(mWalkableRadius, NavMesh), &CommonValidators::PositiveFloat,
  245. "Radius of an actor.");
  246. addFieldV("walkableSlope", TypeF32, Offset(mWalkableSlope, NavMesh), &ValidSlopeAngle,
  247. "Maximum walkable slope in degrees.");
  248. addField("smallCharacters", TypeBool, Offset(mSmallCharacters, NavMesh),
  249. "Is this NavMesh for smaller-than-usual characters?");
  250. addField("regularCharacters", TypeBool, Offset(mRegularCharacters, NavMesh),
  251. "Is this NavMesh for regular-sized characters?");
  252. addField("largeCharacters", TypeBool, Offset(mLargeCharacters, NavMesh),
  253. "Is this NavMesh for larger-than-usual characters?");
  254. addField("vehicles", TypeBool, Offset(mVehicles, NavMesh),
  255. "Is this NavMesh for characters driving vehicles?");
  256. endGroup("NavMesh Options");
  257. addGroup("NavMesh Annotations");
  258. addField("coverGroup", TypeString, Offset(mCoverSet, NavMesh),
  259. "Name of the SimGroup to store cover points in.");
  260. addField("innerCover", TypeBool, Offset(mInnerCover, NavMesh),
  261. "Add cover points everywhere, not just on corners?");
  262. addField("coverDist", TypeF32, Offset(mCoverDist, NavMesh),
  263. "Distance from the edge of the NavMesh to search for cover.");
  264. addField("peekDist", TypeF32, Offset(mPeekDist, NavMesh),
  265. "Distance to the side of each cover point that peeking happens.");
  266. endGroup("NavMesh Annotations");
  267. addGroup("NavMesh Rendering");
  268. addProtectedField("alwaysRender", TypeBool, Offset(mAlwaysRender, NavMesh),
  269. &setProtectedAlwaysRender, &defaultProtectedGetFn,
  270. "Display this NavMesh even outside the editor.");
  271. endGroup("NavMesh Rendering");
  272. addGroup("NavMesh Advanced Options");
  273. addFieldV("borderSize", TypeS32, Offset(mBorderSize, NavMesh), &PositiveInt,
  274. "Size of the non-walkable border around the navigation mesh (in voxels).");
  275. addProtectedField("detailSampleDist", TypeF32, Offset(mDetailSampleDist, NavMesh),
  276. &setProtectedDetailSampleDist, &defaultProtectedGetFn,
  277. "Sets the sampling distance to use when generating the detail mesh.");
  278. addFieldV("detailSampleError", TypeF32, Offset(mDetailSampleMaxError, NavMesh), &CommonValidators::PositiveFloat,
  279. "The maximum distance the detail mesh surface should deviate from heightfield data.");
  280. addFieldV("maxEdgeLen", TypeS32, Offset(mDetailSampleDist, NavMesh), &PositiveInt,
  281. "The maximum allowed length for contour edges along the border of the mesh.");
  282. addFieldV("simplificationError", TypeF32, Offset(mMaxSimplificationError, NavMesh), &CommonValidators::PositiveFloat,
  283. "The maximum distance a simplfied contour's border edges should deviate from the original raw contour.");
  284. addFieldV("minRegionArea", TypeS32, Offset(mMinRegionArea, NavMesh), &PositiveInt,
  285. "The minimum number of cells allowed to form isolated island areas.");
  286. addFieldV("mergeRegionArea", TypeS32, Offset(mMergeRegionArea, NavMesh), &PositiveInt,
  287. "Any regions with a span count smaller than this value will, if possible, be merged with larger regions.");
  288. addFieldV("maxPolysPerTile", TypeS32, Offset(mMaxPolysPerTile, NavMesh), &NaturalNumber,
  289. "The maximum number of polygons allowed in a tile.");
  290. endGroup("NavMesh Advanced Options");
  291. Parent::initPersistFields();
  292. }
  293. bool NavMesh::onAdd()
  294. {
  295. if(!Parent::onAdd())
  296. return false;
  297. mObjBox.set(Point3F(-0.5f, -0.5f, -0.5f),
  298. Point3F( 0.5f, 0.5f, 0.5f));
  299. resetWorldBox();
  300. addToScene();
  301. if(gEditingMission || mAlwaysRender)
  302. {
  303. mNetFlags.set(Ghostable);
  304. if(isClientObject())
  305. renderToDrawer();
  306. }
  307. if(isServerObject())
  308. {
  309. getServerSet()->addObject(this);
  310. ctx = new NavContext();
  311. setProcessTick(true);
  312. if(getEventManager())
  313. getEventManager()->postEvent("NavMeshCreated", getIdString());
  314. }
  315. load();
  316. return true;
  317. }
  318. void NavMesh::onRemove()
  319. {
  320. if(getEventManager())
  321. getEventManager()->postEvent("NavMeshRemoved", getIdString());
  322. removeFromScene();
  323. Parent::onRemove();
  324. }
  325. void NavMesh::setTransform(const MatrixF &mat)
  326. {
  327. Parent::setTransform(mat);
  328. }
  329. void NavMesh::setScale(const VectorF &scale)
  330. {
  331. Parent::setScale(scale);
  332. }
  333. S32 NavMesh::addLink(const Point3F &from, const Point3F &to, U32 flags)
  334. {
  335. Point3F rcFrom = DTStoRC(from), rcTo = DTStoRC(to);
  336. mLinkVerts.push_back(rcFrom.x);
  337. mLinkVerts.push_back(rcFrom.y);
  338. mLinkVerts.push_back(rcFrom.z);
  339. mLinkVerts.push_back(rcTo.x);
  340. mLinkVerts.push_back(rcTo.y);
  341. mLinkVerts.push_back(rcTo.z);
  342. mLinksUnsynced.push_back(true);
  343. mLinkRads.push_back(mWalkableRadius);
  344. mLinkDirs.push_back(0);
  345. mLinkAreas.push_back(OffMeshArea);
  346. if (flags == 0) {
  347. Point3F dir = to - from;
  348. F32 drop = -dir.z;
  349. dir.z = 0;
  350. // If we drop more than we travel horizontally, we're a drop link.
  351. if(drop > dir.len())
  352. mLinkFlags.push_back(DropFlag);
  353. else
  354. mLinkFlags.push_back(JumpFlag);
  355. }
  356. mLinkIDs.push_back(1000 + mCurLinkID);
  357. mLinkSelectStates.push_back(Unselected);
  358. mDeleteLinks.push_back(false);
  359. mCurLinkID++;
  360. return mLinkIDs.size() - 1;
  361. }
  362. DefineEngineMethod(NavMesh, addLink, S32, (Point3F from, Point3F to, U32 flags), (0),
  363. "Add a link to this NavMesh between two points.\n\n"
  364. "")
  365. {
  366. return object->addLink(from, to, flags);
  367. }
  368. S32 NavMesh::getLink(const Point3F &pos)
  369. {
  370. for(U32 i = 0; i < mLinkIDs.size(); i++)
  371. {
  372. if(mDeleteLinks[i])
  373. continue;
  374. SphereF start(getLinkStart(i), mLinkRads[i]);
  375. SphereF end(getLinkEnd(i), mLinkRads[i]);
  376. if(start.isContained(pos) || end.isContained(pos))
  377. return i;
  378. }
  379. return -1;
  380. }
  381. DefineEngineMethod(NavMesh, getLink, S32, (Point3F pos),,
  382. "Get the off-mesh link closest to a given world point.")
  383. {
  384. return object->getLink(pos);
  385. }
  386. S32 NavMesh::getLinkCount()
  387. {
  388. return mLinkIDs.size();
  389. }
  390. DefineEngineMethod(NavMesh, getLinkCount, S32, (),,
  391. "Return the number of links this mesh has.")
  392. {
  393. return object->getLinkCount();
  394. }
  395. LinkData NavMesh::getLinkFlags(U32 idx)
  396. {
  397. if(idx < mLinkIDs.size())
  398. {
  399. return LinkData(mLinkFlags[idx]);
  400. }
  401. return LinkData();
  402. }
  403. DefineEngineMethod(NavMesh, getLinkFlags, S32, (U32 id),,
  404. "Get the flags set for a particular off-mesh link.")
  405. {
  406. return object->getLinkFlags(id).getFlags();
  407. }
  408. void NavMesh::setLinkFlags(U32 idx, const LinkData &d)
  409. {
  410. if(idx < mLinkIDs.size())
  411. {
  412. mLinkFlags[idx] = d.getFlags();
  413. mLinksUnsynced[idx] = true;
  414. }
  415. }
  416. DefineEngineMethod(NavMesh, setLinkFlags, void, (U32 id, U32 flags),,
  417. "Set the flags of a particular off-mesh link.")
  418. {
  419. LinkData d(flags);
  420. object->setLinkFlags(id, d);
  421. }
  422. Point3F NavMesh::getLinkStart(U32 idx)
  423. {
  424. return RCtoDTS(Point3F(
  425. mLinkVerts[idx*6],
  426. mLinkVerts[idx*6 + 1],
  427. mLinkVerts[idx*6 + 2]));
  428. }
  429. DefineEngineMethod(NavMesh, getLinkStart, Point3F, (U32 id),,
  430. "Get the starting point of an off-mesh link.")
  431. {
  432. return object->getLinkStart(id);
  433. }
  434. Point3F NavMesh::getLinkEnd(U32 idx)
  435. {
  436. return RCtoDTS(Point3F(
  437. mLinkVerts[idx*6 + 3],
  438. mLinkVerts[idx*6 + 4],
  439. mLinkVerts[idx*6 + 5]));
  440. }
  441. DefineEngineMethod(NavMesh, getLinkEnd, Point3F, (U32 id),,
  442. "Get the ending point of an off-mesh link.")
  443. {
  444. return object->getLinkEnd(id);
  445. }
  446. void NavMesh::selectLink(U32 idx, bool select, bool hover)
  447. {
  448. if(idx < mLinkIDs.size())
  449. {
  450. if(!select)
  451. mLinkSelectStates[idx] = Unselected;
  452. else
  453. mLinkSelectStates[idx] = hover ? Hovered : Selected;
  454. }
  455. }
  456. void NavMesh::eraseLink(U32 i)
  457. {
  458. mLinkVerts.erase(i*6, 6);
  459. mLinksUnsynced.erase(i);
  460. mLinkRads.erase(i);
  461. mLinkDirs.erase(i);
  462. mLinkAreas.erase(i);
  463. mLinkFlags.erase(i);
  464. mLinkIDs.erase(i);
  465. mLinkSelectStates.erase(i);
  466. mDeleteLinks.erase(i);
  467. }
  468. void NavMesh::eraseLinks()
  469. {
  470. mLinkVerts.clear();
  471. mLinksUnsynced.clear();
  472. mLinkRads.clear();
  473. mLinkDirs.clear();
  474. mLinkAreas.clear();
  475. mLinkFlags.clear();
  476. mLinkIDs.clear();
  477. mLinkSelectStates.clear();
  478. mDeleteLinks.clear();
  479. }
  480. void NavMesh::setLinkCount(U32 c)
  481. {
  482. eraseLinks();
  483. mLinkVerts.setSize(c * 6);
  484. mLinksUnsynced.setSize(c);
  485. mLinkRads.setSize(c);
  486. mLinkDirs.setSize(c);
  487. mLinkAreas.setSize(c);
  488. mLinkFlags.setSize(c);
  489. mLinkIDs.setSize(c);
  490. mLinkSelectStates.setSize(c);
  491. mDeleteLinks.setSize(c);
  492. }
  493. void NavMesh::deleteLink(U32 idx)
  494. {
  495. if(idx < mLinkIDs.size())
  496. {
  497. mDeleteLinks[idx] = true;
  498. if(mLinksUnsynced[idx])
  499. eraseLink(idx);
  500. else
  501. mLinksUnsynced[idx] = true;
  502. }
  503. }
  504. DefineEngineMethod(NavMesh, deleteLink, void, (U32 id),,
  505. "Delete a given off-mesh link.")
  506. {
  507. object->deleteLink(id);
  508. }
  509. DefineEngineMethod(NavMesh, deleteLinks, void, (),,
  510. "Deletes all off-mesh links on this NavMesh.")
  511. {
  512. //object->eraseLinks();
  513. }
  514. bool NavMesh::build(bool background, bool saveIntermediates)
  515. {
  516. if(mBuilding)
  517. cancelBuild();
  518. else
  519. {
  520. if(getEventManager())
  521. getEventManager()->postEvent("NavMeshStartUpdate", getIdString());
  522. }
  523. mBuilding = true;
  524. ctx->startTimer(RC_TIMER_TOTAL);
  525. dtFreeNavMesh(nm);
  526. // Allocate a new navmesh.
  527. nm = dtAllocNavMesh();
  528. if(!nm)
  529. {
  530. Con::errorf("Could not allocate dtNavMesh for NavMesh %s", getIdString());
  531. return false;
  532. }
  533. updateConfig();
  534. // Build navmesh parameters from console members.
  535. dtNavMeshParams params;
  536. rcVcopy(params.orig, cfg.bmin);
  537. params.tileWidth = cfg.tileSize * mCellSize;
  538. params.tileHeight = cfg.tileSize * mCellSize;
  539. params.maxTiles = mCeil(getWorldBox().len_x() / params.tileWidth) * mCeil(getWorldBox().len_y() / params.tileHeight);
  540. params.maxPolys = mMaxPolysPerTile;
  541. // Initialise our navmesh.
  542. if(dtStatusFailed(nm->init(&params)))
  543. {
  544. Con::errorf("Could not init dtNavMesh for NavMesh %s", getIdString());
  545. return false;
  546. }
  547. // Update links to be deleted.
  548. for(U32 i = 0; i < mLinkIDs.size();)
  549. {
  550. if(mDeleteLinks[i])
  551. eraseLink(i);
  552. else
  553. i++;
  554. }
  555. mLinksUnsynced.fill(false);
  556. mCurLinkID = 0;
  557. mSaveIntermediates = saveIntermediates;
  558. updateTiles(true);
  559. if(!background)
  560. {
  561. while(!mDirtyTiles.empty())
  562. buildNextTile();
  563. }
  564. return true;
  565. }
  566. DefineEngineMethod(NavMesh, build, bool, (bool background, bool save), (true, false),
  567. "@brief Create a Recast nav mesh.")
  568. {
  569. return object->build(background, save);
  570. }
  571. void NavMesh::cancelBuild()
  572. {
  573. mDirtyTiles.clear();
  574. ctx->stopTimer(RC_TIMER_TOTAL);
  575. mBuilding = false;
  576. }
  577. DefineEngineMethod(NavMesh, cancelBuild, void, (),,
  578. "@brief Cancel the current NavMesh build.")
  579. {
  580. object->cancelBuild();
  581. }
  582. void NavMesh::inspectPostApply()
  583. {
  584. if(mBuilding)
  585. cancelBuild();
  586. }
  587. void NavMesh::updateConfig()
  588. {
  589. // Build rcConfig object from our console members.
  590. dMemset(&cfg, 0, sizeof(cfg));
  591. cfg.cs = mCellSize;
  592. cfg.ch = mCellHeight;
  593. Box3F box = DTStoRC(getWorldBox());
  594. rcVcopy(cfg.bmin, box.minExtents);
  595. rcVcopy(cfg.bmax, box.maxExtents);
  596. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  597. cfg.walkableHeight = mCeil(mWalkableHeight / mCellHeight);
  598. cfg.walkableClimb = mCeil(mWalkableClimb / mCellHeight);
  599. cfg.walkableRadius = mCeil(mWalkableRadius / mCellSize);
  600. cfg.walkableSlopeAngle = mWalkableSlope;
  601. cfg.borderSize = cfg.walkableRadius + 3;
  602. cfg.detailSampleDist = mDetailSampleDist;
  603. cfg.detailSampleMaxError = mDetailSampleMaxError;
  604. cfg.maxEdgeLen = mMaxEdgeLen;
  605. cfg.maxSimplificationError = mMaxSimplificationError;
  606. cfg.maxVertsPerPoly = mMaxVertsPerPoly;
  607. cfg.minRegionArea = mMinRegionArea;
  608. cfg.mergeRegionArea = mMergeRegionArea;
  609. cfg.tileSize = mTileSize / cfg.cs;
  610. }
  611. S32 NavMesh::getTile(const Point3F& pos)
  612. {
  613. if(mBuilding)
  614. return -1;
  615. for(U32 i = 0; i < mTiles.size(); i++)
  616. {
  617. if(mTiles[i].box.isContained(pos))
  618. return i;
  619. }
  620. return -1;
  621. }
  622. Box3F NavMesh::getTileBox(U32 id)
  623. {
  624. if(mBuilding || id >= mTiles.size())
  625. return Box3F::Invalid;
  626. return mTiles[id].box;
  627. }
  628. void NavMesh::updateTiles(bool dirty)
  629. {
  630. PROFILE_SCOPE(NavMesh_updateTiles);
  631. if(!isProperlyAdded())
  632. return;
  633. mTiles.clear();
  634. mTileData.clear();
  635. mDirtyTiles.clear();
  636. const Box3F &box = DTStoRC(getWorldBox());
  637. if(box.isEmpty())
  638. return;
  639. updateConfig();
  640. // Calculate tile dimensions.
  641. const U32 ts = cfg.tileSize;
  642. const U32 tw = (cfg.width + ts-1) / ts;
  643. const U32 th = (cfg.height + ts-1) / ts;
  644. const F32 tcs = cfg.tileSize * cfg.cs;
  645. // Iterate over tiles.
  646. F32 tileBmin[3], tileBmax[3];
  647. for(U32 y = 0; y < th; ++y)
  648. {
  649. for(U32 x = 0; x < tw; ++x)
  650. {
  651. tileBmin[0] = cfg.bmin[0] + x*tcs;
  652. tileBmin[1] = cfg.bmin[1];
  653. tileBmin[2] = cfg.bmin[2] + y*tcs;
  654. tileBmax[0] = cfg.bmin[0] + (x+1)*tcs;
  655. tileBmax[1] = cfg.bmax[1];
  656. tileBmax[2] = cfg.bmin[2] + (y+1)*tcs;
  657. mTiles.push_back(
  658. Tile(RCtoDTS(tileBmin, tileBmax),
  659. x, y,
  660. tileBmin, tileBmax));
  661. if(dirty)
  662. mDirtyTiles.push_back_unique(mTiles.size() - 1);
  663. if(mSaveIntermediates)
  664. mTileData.increment();
  665. }
  666. }
  667. }
  668. void NavMesh::processTick(const Move *move)
  669. {
  670. buildNextTile();
  671. }
  672. void NavMesh::buildNextTile()
  673. {
  674. PROFILE_SCOPE(NavMesh_buildNextTile);
  675. if(!mDirtyTiles.empty())
  676. {
  677. // Pop a single dirty tile and process it.
  678. U32 i = mDirtyTiles.front();
  679. mDirtyTiles.pop_front();
  680. const Tile &tile = mTiles[i];
  681. // Intermediate data for tile build.
  682. TileData tempdata;
  683. TileData &tdata = mSaveIntermediates ? mTileData[i] : tempdata;
  684. // Remove any previous data.
  685. nm->removeTile(nm->getTileRefAt(tile.x, tile.y, 0), 0, 0);
  686. // Generate navmesh for this tile.
  687. U32 dataSize = 0;
  688. unsigned char* data = buildTileData(tile, tdata, dataSize);
  689. if(data)
  690. {
  691. // Add new data (navmesh owns and deletes the data).
  692. dtStatus status = nm->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0);
  693. int success = 1;
  694. if(dtStatusFailed(status))
  695. {
  696. success = 0;
  697. dtFree(data);
  698. }
  699. if(getEventManager())
  700. {
  701. String str = String::ToString("%d %d %d (%d, %d) %d %.3f %s",
  702. getId(),
  703. i, mTiles.size(),
  704. tile.x, tile.y,
  705. success,
  706. ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f,
  707. castConsoleTypeToString(tile.box));
  708. getEventManager()->postEvent("NavMeshTileUpdate", str.c_str());
  709. setMaskBits(LoadFlag);
  710. }
  711. }
  712. // Did we just build the last tile?
  713. if(mDirtyTiles.empty())
  714. {
  715. ctx->stopTimer(RC_TIMER_TOTAL);
  716. if(getEventManager())
  717. {
  718. String str = String::ToString("%d", getId());
  719. getEventManager()->postEvent("NavMeshUpdate", str.c_str());
  720. setMaskBits(LoadFlag);
  721. }
  722. mBuilding = false;
  723. }
  724. }
  725. }
  726. static void buildCallback(SceneObject* object,void *key)
  727. {
  728. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  729. if (!object->mPathfindingIgnore)
  730. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  731. }
  732. unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dataSize)
  733. {
  734. // Push out tile boundaries a bit.
  735. F32 tileBmin[3], tileBmax[3];
  736. rcVcopy(tileBmin, tile.bmin);
  737. rcVcopy(tileBmax, tile.bmax);
  738. tileBmin[0] -= cfg.borderSize * cfg.cs;
  739. tileBmin[2] -= cfg.borderSize * cfg.cs;
  740. tileBmax[0] += cfg.borderSize * cfg.cs;
  741. tileBmax[2] += cfg.borderSize * cfg.cs;
  742. // Parse objects from level into RC-compatible format.
  743. Box3F box = RCtoDTS(tileBmin, tileBmax);
  744. SceneContainer::CallbackInfo info;
  745. info.context = PLC_Navigation;
  746. info.boundingBox = box;
  747. data.geom.clear();
  748. info.polyList = &data.geom;
  749. info.key = this;
  750. getContainer()->findObjects(box, StaticObjectType | DynamicShapeObjectType, buildCallback, &info);
  751. // Parse water objects into the same list, but remember how much geometry was /not/ water.
  752. U32 nonWaterVertCount = data.geom.getVertCount();
  753. U32 nonWaterTriCount = data.geom.getTriCount();
  754. if(mWaterMethod != Ignore)
  755. {
  756. getContainer()->findObjects(box, WaterObjectType, buildCallback, &info);
  757. }
  758. // Check for no geometry.
  759. if (!data.geom.getVertCount())
  760. {
  761. data.geom.clear();
  762. return NULL;
  763. }
  764. // Figure out voxel dimensions of this tile.
  765. U32 width = 0, height = 0;
  766. width = cfg.tileSize + cfg.borderSize * 2;
  767. height = cfg.tileSize + cfg.borderSize * 2;
  768. // Create a heightfield to voxelise our input geometry.
  769. data.hf = rcAllocHeightfield();
  770. if(!data.hf)
  771. {
  772. Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString());
  773. return NULL;
  774. }
  775. if(!rcCreateHeightfield(ctx, *data.hf, width, height, tileBmin, tileBmax, cfg.cs, cfg.ch))
  776. {
  777. Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString());
  778. return NULL;
  779. }
  780. unsigned char *areas = new unsigned char[data.geom.getTriCount()];
  781. dMemset(areas, 0, data.geom.getTriCount() * sizeof(unsigned char));
  782. // Mark walkable triangles with the appropriate area flags, and rasterize.
  783. if(mWaterMethod == Solid)
  784. {
  785. // Treat water as solid: i.e. mark areas as walkable based on angle.
  786. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  787. data.geom.getVerts(), data.geom.getVertCount(),
  788. data.geom.getTris(), data.geom.getTriCount(), areas);
  789. }
  790. else
  791. {
  792. // Treat water as impassable: leave all area flags 0.
  793. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  794. data.geom.getVerts(), nonWaterVertCount,
  795. data.geom.getTris(), nonWaterTriCount, areas);
  796. }
  797. rcRasterizeTriangles(ctx,
  798. data.geom.getVerts(), data.geom.getVertCount(),
  799. data.geom.getTris(), areas, data.geom.getTriCount(),
  800. *data.hf, cfg.walkableClimb);
  801. delete[] areas;
  802. // Filter out areas with low ceilings and other stuff.
  803. rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *data.hf);
  804. rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf);
  805. rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *data.hf);
  806. data.chf = rcAllocCompactHeightfield();
  807. if(!data.chf)
  808. {
  809. Con::errorf("Out of memory (rcCompactHeightField) for NavMesh %s", getIdString());
  810. return NULL;
  811. }
  812. if(!rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf, *data.chf))
  813. {
  814. Con::errorf("Could not generate rcCompactHeightField for NavMesh %s", getIdString());
  815. return NULL;
  816. }
  817. if(!rcErodeWalkableArea(ctx, cfg.walkableRadius, *data.chf))
  818. {
  819. Con::errorf("Could not erode walkable area for NavMesh %s", getIdString());
  820. return NULL;
  821. }
  822. //--------------------------
  823. // Todo: mark areas here.
  824. //const ConvexVolume* vols = m_geom->getConvexVolumes();
  825. //for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
  826. //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
  827. //--------------------------
  828. if(false)
  829. {
  830. if(!rcBuildRegionsMonotone(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  831. {
  832. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  833. return NULL;
  834. }
  835. }
  836. else
  837. {
  838. if(!rcBuildDistanceField(ctx, *data.chf))
  839. {
  840. Con::errorf("Could not build distance field for NavMesh %s", getIdString());
  841. return NULL;
  842. }
  843. if(!rcBuildRegions(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  844. {
  845. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  846. return NULL;
  847. }
  848. }
  849. data.cs = rcAllocContourSet();
  850. if(!data.cs)
  851. {
  852. Con::errorf("Out of memory (rcContourSet) for NavMesh %s", getIdString());
  853. return NULL;
  854. }
  855. if(!rcBuildContours(ctx, *data.chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *data.cs))
  856. {
  857. Con::errorf("Could not construct rcContourSet for NavMesh %s", getIdString());
  858. return NULL;
  859. }
  860. if(data.cs->nconts <= 0)
  861. {
  862. Con::errorf("No contours in rcContourSet for NavMesh %s", getIdString());
  863. return NULL;
  864. }
  865. data.pm = rcAllocPolyMesh();
  866. if(!data.pm)
  867. {
  868. Con::errorf("Out of memory (rcPolyMesh) for NavMesh %s", getIdString());
  869. return NULL;
  870. }
  871. if(!rcBuildPolyMesh(ctx, *data.cs, cfg.maxVertsPerPoly, *data.pm))
  872. {
  873. Con::errorf("Could not construct rcPolyMesh for NavMesh %s", getIdString());
  874. return NULL;
  875. }
  876. data.pmd = rcAllocPolyMeshDetail();
  877. if(!data.pmd)
  878. {
  879. Con::errorf("Out of memory (rcPolyMeshDetail) for NavMesh %s", getIdString());
  880. return NULL;
  881. }
  882. if(!rcBuildPolyMeshDetail(ctx, *data.pm, *data.chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *data.pmd))
  883. {
  884. Con::errorf("Could not construct rcPolyMeshDetail for NavMesh %s", getIdString());
  885. return NULL;
  886. }
  887. if(data.pm->nverts >= 0xffff)
  888. {
  889. Con::errorf("Too many vertices in rcPolyMesh for NavMesh %s", getIdString());
  890. return NULL;
  891. }
  892. for(U32 i = 0; i < data.pm->npolys; i++)
  893. {
  894. if(data.pm->areas[i] == RC_WALKABLE_AREA)
  895. data.pm->areas[i] = GroundArea;
  896. if(data.pm->areas[i] == GroundArea)
  897. data.pm->flags[i] |= WalkFlag;
  898. if(data.pm->areas[i] == WaterArea)
  899. data.pm->flags[i] |= SwimFlag;
  900. }
  901. unsigned char* navData = 0;
  902. int navDataSize = 0;
  903. dtNavMeshCreateParams params;
  904. dMemset(&params, 0, sizeof(params));
  905. params.verts = data.pm->verts;
  906. params.vertCount = data.pm->nverts;
  907. params.polys = data.pm->polys;
  908. params.polyAreas = data.pm->areas;
  909. params.polyFlags = data.pm->flags;
  910. params.polyCount = data.pm->npolys;
  911. params.nvp = data.pm->nvp;
  912. params.detailMeshes = data.pmd->meshes;
  913. params.detailVerts = data.pmd->verts;
  914. params.detailVertsCount = data.pmd->nverts;
  915. params.detailTris = data.pmd->tris;
  916. params.detailTriCount = data.pmd->ntris;
  917. params.offMeshConVerts = mLinkVerts.address();
  918. params.offMeshConRad = mLinkRads.address();
  919. params.offMeshConDir = mLinkDirs.address();
  920. params.offMeshConAreas = mLinkAreas.address();
  921. params.offMeshConFlags = mLinkFlags.address();
  922. params.offMeshConUserID = mLinkIDs.address();
  923. params.offMeshConCount = mLinkIDs.size();
  924. params.walkableHeight = mWalkableHeight;
  925. params.walkableRadius = mWalkableRadius;
  926. params.walkableClimb = mWalkableClimb;
  927. params.tileX = tile.x;
  928. params.tileY = tile.y;
  929. params.tileLayer = 0;
  930. rcVcopy(params.bmin, data.pm->bmin);
  931. rcVcopy(params.bmax, data.pm->bmax);
  932. params.cs = cfg.cs;
  933. params.ch = cfg.ch;
  934. params.buildBvTree = true;
  935. if(!dtCreateNavMeshData(&params, &navData, &navDataSize))
  936. {
  937. Con::errorf("Could not create dtNavMeshData for tile (%d, %d) of NavMesh %s",
  938. tile.x, tile.y, getIdString());
  939. return NULL;
  940. }
  941. dataSize = navDataSize;
  942. return navData;
  943. }
  944. /// This method should never be called in a separate thread to the rendering
  945. /// or pathfinding logic. It directly replaces data in the dtNavMesh for
  946. /// this NavMesh object.
  947. void NavMesh::buildTiles(const Box3F &box)
  948. {
  949. PROFILE_SCOPE(NavMesh_buildTiles);
  950. // Make sure we've already built or loaded.
  951. if(!nm)
  952. return;
  953. // Iterate over tiles.
  954. for(U32 i = 0; i < mTiles.size(); i++)
  955. {
  956. const Tile &tile = mTiles[i];
  957. // Check tile box.
  958. if(!tile.box.isOverlapped(box))
  959. continue;
  960. // Mark as dirty.
  961. mDirtyTiles.push_back_unique(i);
  962. }
  963. if(mDirtyTiles.size())
  964. ctx->startTimer(RC_TIMER_TOTAL);
  965. }
  966. DefineEngineMethod(NavMesh, buildTiles, void, (Box3F box),,
  967. "@brief Rebuild the tiles overlapped by the input box.")
  968. {
  969. return object->buildTiles(box);
  970. }
  971. void NavMesh::buildTile(const U32 &tile)
  972. {
  973. PROFILE_SCOPE(NavMesh_buildTile);
  974. if(tile < mTiles.size())
  975. {
  976. mDirtyTiles.push_back_unique(tile);
  977. ctx->startTimer(RC_TIMER_TOTAL);
  978. }
  979. }
  980. void NavMesh::buildLinks()
  981. {
  982. // Make sure we've already built or loaded.
  983. if(!nm)
  984. return;
  985. // Iterate over tiles.
  986. for(U32 i = 0; i < mTiles.size(); i++)
  987. {
  988. const Tile &tile = mTiles[i];
  989. // Iterate over links
  990. for(U32 j = 0; j < mLinkIDs.size(); j++)
  991. {
  992. if (mLinksUnsynced[j])
  993. {
  994. if(tile.box.isContained(getLinkStart(j)) ||
  995. tile.box.isContained(getLinkEnd(j)))
  996. {
  997. // Mark tile for build.
  998. mDirtyTiles.push_back_unique(i);
  999. // Delete link if necessary
  1000. if(mDeleteLinks[j])
  1001. {
  1002. eraseLink(j);
  1003. j--;
  1004. }
  1005. else
  1006. mLinksUnsynced[j] = false;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. if(mDirtyTiles.size())
  1012. ctx->startTimer(RC_TIMER_TOTAL);
  1013. }
  1014. DefineEngineMethod(NavMesh, buildLinks, void, (),,
  1015. "@brief Build tiles of this mesh where there are unsynchronised links.")
  1016. {
  1017. object->buildLinks();
  1018. }
  1019. void NavMesh::deleteCoverPoints()
  1020. {
  1021. SimSet *set = NULL;
  1022. if(Sim::findObject(mCoverSet, set))
  1023. set->deleteAllObjects();
  1024. }
  1025. DefineEngineMethod(NavMesh, deleteCoverPoints, void, (),,
  1026. "@brief Remove all cover points for this NavMesh.")
  1027. {
  1028. object->deleteCoverPoints();
  1029. }
  1030. bool NavMesh::createCoverPoints()
  1031. {
  1032. if(!nm || !isServerObject())
  1033. return false;
  1034. SimSet *set = NULL;
  1035. if(Sim::findObject(mCoverSet, set))
  1036. {
  1037. set->deleteAllObjects();
  1038. }
  1039. else
  1040. {
  1041. set = new SimGroup();
  1042. if(set->registerObject(mCoverSet))
  1043. {
  1044. getGroup()->addObject(set);
  1045. }
  1046. else
  1047. {
  1048. delete set;
  1049. set = getGroup();
  1050. }
  1051. }
  1052. dtNavMeshQuery *query = dtAllocNavMeshQuery();
  1053. if(!query || dtStatusFailed(query->init(nm, 1)))
  1054. return false;
  1055. dtQueryFilter f;
  1056. // Iterate over all polys in our navmesh.
  1057. const int MAX_SEGS = 6;
  1058. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1059. {
  1060. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1061. if(!tile->header) continue;
  1062. const dtPolyRef base = nm->getPolyRefBase(tile);
  1063. for(U32 j = 0; j < tile->header->polyCount; ++j)
  1064. {
  1065. const dtPolyRef ref = base | j;
  1066. float segs[MAX_SEGS*6];
  1067. int nsegs = 0;
  1068. query->getPolyWallSegments(ref, &f, segs, NULL, &nsegs, MAX_SEGS);
  1069. for(int segIDx = 0; segIDx < nsegs; ++segIDx)
  1070. {
  1071. const float* sa = &segs[segIDx *6];
  1072. const float* sb = &segs[segIDx *6+3];
  1073. Point3F a = RCtoDTS(sa), b = RCtoDTS(sb);
  1074. F32 len = (b - a).len();
  1075. if(len < mWalkableRadius * 2)
  1076. continue;
  1077. Point3F edge = b - a;
  1078. edge.normalize();
  1079. // Number of points to try placing - for now, one at each end.
  1080. U32 pointCount = (len > mWalkableRadius * 4) ? 2 : 1;
  1081. for(U32 pointIDx = 0; pointIDx < pointCount; pointIDx++)
  1082. {
  1083. MatrixF mat;
  1084. Point3F pos;
  1085. // If we're only placing one point, put it in the middle.
  1086. if(pointCount == 1)
  1087. pos = a + edge * len / 2;
  1088. // Otherwise, stand off from edge ends.
  1089. else
  1090. {
  1091. if(pointIDx % 2)
  1092. pos = a + edge * (pointIDx /2+1) * mWalkableRadius;
  1093. else
  1094. pos = b - edge * (pointIDx /2+1) * mWalkableRadius;
  1095. }
  1096. CoverPointData data;
  1097. if(testEdgeCover(pos, edge, data))
  1098. {
  1099. CoverPoint *m = new CoverPoint();
  1100. if(!m->registerObject())
  1101. delete m;
  1102. else
  1103. {
  1104. m->setTransform(data.trans);
  1105. m->setSize(data.size);
  1106. m->setPeek(data.peek[0], data.peek[1], data.peek[2]);
  1107. if(set)
  1108. set->addObject(m);
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. }
  1115. return true;
  1116. }
  1117. DefineEngineMethod(NavMesh, createCoverPoints, bool, (),,
  1118. "@brief Create cover points for this NavMesh.")
  1119. {
  1120. return object->createCoverPoints();
  1121. }
  1122. bool NavMesh::testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data)
  1123. {
  1124. data.peek[0] = data.peek[1] = data.peek[2] = false;
  1125. // Get the edge normal.
  1126. Point3F norm;
  1127. mCross(dir, Point3F(0, 0, 1), &norm);
  1128. RayInfo ray;
  1129. U32 hits = 0;
  1130. for(U32 j = 0; j < CoverPoint::NumSizes; j++)
  1131. {
  1132. Point3F test = pos + Point3F(0.0f, 0.0f, mWalkableHeight * j / CoverPoint::NumSizes);
  1133. if(getContainer()->castRay(test, test + norm * mCoverDist, StaticObjectType, &ray))
  1134. {
  1135. // Test peeking.
  1136. Point3F left = test + dir * mPeekDist;
  1137. data.peek[0] = !getContainer()->castRay(test, left, StaticObjectType, &ray)
  1138. && !getContainer()->castRay(left, left + norm * mCoverDist, StaticObjectType, &ray);
  1139. Point3F right = test - dir * mPeekDist;
  1140. data.peek[1] = !getContainer()->castRay(test, right, StaticObjectType, &ray)
  1141. && !getContainer()->castRay(right, right + norm * mCoverDist, StaticObjectType, &ray);
  1142. Point3F over = test + Point3F(0, 0, 1) * 0.2f;
  1143. data.peek[2] = !getContainer()->castRay(test, over, StaticObjectType, &ray)
  1144. && !getContainer()->castRay(over, over + norm * mCoverDist, StaticObjectType, &ray);
  1145. if(mInnerCover || data.peek[0] || data.peek[1] || data.peek[2])
  1146. hits++;
  1147. // If we couldn't peek here, we may be able to peek further up.
  1148. }
  1149. else
  1150. // No cover at this height - break off.
  1151. break;
  1152. }
  1153. if(hits > 0)
  1154. {
  1155. data.size = (CoverPoint::Size)(hits - 1);
  1156. data.trans = MathUtils::createOrientFromDir(norm);
  1157. data.trans.setPosition(pos);
  1158. }
  1159. return hits > 0;
  1160. }
  1161. void NavMesh::renderToDrawer()
  1162. {
  1163. mDbgDraw.clear();
  1164. // Recast debug draw
  1165. NetObject *no = getServerObject();
  1166. if(no)
  1167. {
  1168. NavMesh *n = static_cast<NavMesh*>(no);
  1169. if(n->nm)
  1170. {
  1171. mDbgDraw.beginGroup(0);
  1172. duDebugDrawNavMesh (&mDbgDraw, *n->nm, 0);
  1173. mDbgDraw.beginGroup(1);
  1174. duDebugDrawNavMeshPortals(&mDbgDraw, *n->nm);
  1175. mDbgDraw.beginGroup(2);
  1176. duDebugDrawNavMeshBVTree (&mDbgDraw, *n->nm);
  1177. }
  1178. }
  1179. }
  1180. void NavMesh::prepRenderImage(SceneRenderState *state)
  1181. {
  1182. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1183. ri->renderDelegate.bind(this, &NavMesh::render);
  1184. ri->type = RenderPassManager::RIT_Object;
  1185. ri->translucentSort = true;
  1186. ri->defaultKey = 1;
  1187. state->getRenderPass()->addInst(ri);
  1188. }
  1189. void NavMesh::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
  1190. {
  1191. if(overrideMat)
  1192. return;
  1193. if(state->isReflectPass())
  1194. return;
  1195. PROFILE_SCOPE(NavMesh_Render);
  1196. // Recast debug draw
  1197. NetObject *no = getServerObject();
  1198. if(no)
  1199. {
  1200. NavMesh *n = static_cast<NavMesh*>(no);
  1201. if(n->isSelected())
  1202. {
  1203. GFXDrawUtil *drawer = GFX->getDrawUtil();
  1204. GFXStateBlockDesc desc;
  1205. desc.setZReadWrite(true, false);
  1206. desc.setBlend(true);
  1207. desc.setCullMode(GFXCullNone);
  1208. drawer->drawCube(desc, getWorldBox(), n->mBuilding
  1209. ? ColorI(255, 0, 0, 80)
  1210. : ColorI(136, 228, 255, 45));
  1211. desc.setFillModeWireframe();
  1212. drawer->drawCube(desc, getWorldBox(), ColorI::BLACK);
  1213. }
  1214. if(n->mBuilding)
  1215. {
  1216. int alpha = 80;
  1217. if(!n->isSelected() || !Con::getBoolVariable("$Nav::EditorOpen"))
  1218. alpha = 20;
  1219. mDbgDraw.overrideColor(duRGBA(255, 0, 0, alpha));
  1220. }
  1221. else
  1222. {
  1223. mDbgDraw.cancelOverride();
  1224. }
  1225. if((!gEditingMission && n->mAlwaysRender) || (gEditingMission && Con::getBoolVariable("$Nav::Editor::renderMesh", 1))) mDbgDraw.renderGroup(0);
  1226. if(Con::getBoolVariable("$Nav::Editor::renderPortals")) mDbgDraw.renderGroup(1);
  1227. if(Con::getBoolVariable("$Nav::Editor::renderBVTree")) mDbgDraw.renderGroup(2);
  1228. }
  1229. }
  1230. void NavMesh::renderLinks(duDebugDraw &dd)
  1231. {
  1232. if(mBuilding)
  1233. return;
  1234. dd.depthMask(true);
  1235. dd.begin(DU_DRAW_LINES);
  1236. for(U32 i = 0; i < mLinkIDs.size(); i++)
  1237. {
  1238. U32 col = 0;
  1239. switch(mLinkSelectStates[i])
  1240. {
  1241. case Unselected: col = mLinksUnsynced[i] ? duRGBA(255, 0, 0, 200) : duRGBA(0, 0, 255, 255); break;
  1242. case Hovered: col = duRGBA(255, 255, 255, 255); break;
  1243. case Selected: col = duRGBA(0, 255, 0, 255); break;
  1244. }
  1245. F32 *s = &mLinkVerts[i*6];
  1246. F32 *e = &mLinkVerts[i*6 + 3];
  1247. if(!mDeleteLinks[i])
  1248. duAppendCircle(&dd, s[0], s[1], s[2], mLinkRads[i], col);
  1249. duAppendArc(&dd,
  1250. s[0], s[1], s[2],
  1251. e[0], e[1], e[2],
  1252. 0.3f,
  1253. 0.0f, mLinkFlags[i] == DropFlag ? 0.0f : 0.4f,
  1254. col);
  1255. if(!mDeleteLinks[i])
  1256. duAppendCircle(&dd, e[0], e[1], e[2], mLinkRads[i], col);
  1257. }
  1258. dd.end();
  1259. }
  1260. void NavMesh::renderTileData(duDebugDrawTorque &dd, U32 tile)
  1261. {
  1262. if(tile >= mTileData.size())
  1263. return;
  1264. if(nm)
  1265. {
  1266. dd.beginGroup(0);
  1267. if(mTileData[tile].chf) duDebugDrawCompactHeightfieldSolid(&dd, *mTileData[tile].chf);
  1268. dd.beginGroup(1);
  1269. int col = duRGBA(255, 0, 255, 255);
  1270. RecastPolyList &in = mTileData[tile].geom;
  1271. dd.begin(DU_DRAW_LINES);
  1272. const F32 *verts = in.getVerts();
  1273. const S32 *tris = in.getTris();
  1274. for(U32 t = 0; t < in.getTriCount(); t++)
  1275. {
  1276. dd.vertex(&verts[tris[t*3]*3], col);
  1277. dd.vertex(&verts[tris[t*3+1]*3], col);
  1278. dd.vertex(&verts[tris[t*3+1]*3], col);
  1279. dd.vertex(&verts[tris[t*3+2]*3], col);
  1280. dd.vertex(&verts[tris[t*3+2]*3], col);
  1281. dd.vertex(&verts[tris[t*3]*3], col);
  1282. }
  1283. dd.end();
  1284. }
  1285. }
  1286. void NavMesh::onEditorEnable()
  1287. {
  1288. mNetFlags.set(Ghostable);
  1289. if(isClientObject() && !mAlwaysRender)
  1290. addToScene();
  1291. }
  1292. void NavMesh::onEditorDisable()
  1293. {
  1294. if(!mAlwaysRender)
  1295. {
  1296. mNetFlags.clear(Ghostable);
  1297. if(isClientObject())
  1298. removeFromScene();
  1299. }
  1300. }
  1301. U32 NavMesh::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  1302. {
  1303. U32 retMask = Parent::packUpdate(conn, mask, stream);
  1304. mathWrite(*stream, getTransform());
  1305. mathWrite(*stream, getScale());
  1306. stream->writeFlag(mAlwaysRender);
  1307. return retMask;
  1308. }
  1309. void NavMesh::unpackUpdate(NetConnection *conn, BitStream *stream)
  1310. {
  1311. Parent::unpackUpdate(conn, stream);
  1312. mathRead(*stream, &mObjToWorld);
  1313. mathRead(*stream, &mObjScale);
  1314. mAlwaysRender = stream->readFlag();
  1315. setTransform(mObjToWorld);
  1316. renderToDrawer();
  1317. }
  1318. static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET';
  1319. static const int NAVMESHSET_VERSION = 1;
  1320. struct NavMeshSetHeader
  1321. {
  1322. int magic;
  1323. int version;
  1324. int numTiles;
  1325. dtNavMeshParams params;
  1326. };
  1327. struct NavMeshTileHeader
  1328. {
  1329. dtTileRef tileRef;
  1330. int dataSize;
  1331. };
  1332. bool NavMesh::load()
  1333. {
  1334. if(!dStrlen(mFileName))
  1335. return false;
  1336. File file;
  1337. if(file.open(mFileName, File::Read) != File::Ok)
  1338. {
  1339. file.close();
  1340. Con::errorf("Could not open file %s when loading navmesh %s.",
  1341. mFileName, getName() ? getName() : getIdString());
  1342. return false;
  1343. }
  1344. // Read header.
  1345. NavMeshSetHeader header;
  1346. file.read(sizeof(NavMeshSetHeader), (char*)&header);
  1347. if(header.magic != NAVMESHSET_MAGIC)
  1348. {
  1349. file.close();
  1350. Con::errorf("Navmesh magic incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1351. getName() ? getName() : getIdString(), mFileName);
  1352. return false;
  1353. }
  1354. if(header.version != NAVMESHSET_VERSION)
  1355. {
  1356. file.close();
  1357. Con::errorf("Navmesh version incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1358. getName() ? getName() : getIdString(), mFileName);
  1359. return false;
  1360. }
  1361. if(nm)
  1362. dtFreeNavMesh(nm);
  1363. nm = dtAllocNavMesh();
  1364. if(!nm)
  1365. {
  1366. file.close();
  1367. Con::errorf("Out of memory when loading navmesh %s.",
  1368. getName() ? getName() : getIdString());
  1369. return false;
  1370. }
  1371. dtStatus status = nm->init(&header.params);
  1372. if(dtStatusFailed(status))
  1373. {
  1374. file.close();
  1375. Con::errorf("Failed to initialise navmesh params when loading navmesh %s.",
  1376. getName() ? getName() : getIdString());
  1377. return false;
  1378. }
  1379. // Read tiles.
  1380. for(U32 i = 0; i < header.numTiles; ++i)
  1381. {
  1382. NavMeshTileHeader tileHeader;
  1383. file.read(sizeof(NavMeshTileHeader), (char*)&tileHeader);
  1384. if(!tileHeader.tileRef || !tileHeader.dataSize)
  1385. break;
  1386. unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
  1387. if(!data) break;
  1388. memset(data, 0, tileHeader.dataSize);
  1389. file.read(tileHeader.dataSize, (char*)data);
  1390. nm->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
  1391. }
  1392. S32 s;
  1393. file.read(sizeof(S32), (char*)&s);
  1394. setLinkCount(s);
  1395. if (s > 0)
  1396. {
  1397. file.read(sizeof(F32) * s * 6, (char*)const_cast<F32*>(mLinkVerts.address()));
  1398. file.read(sizeof(F32) * s, (char*)const_cast<F32*>(mLinkRads.address()));
  1399. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkDirs.address()));
  1400. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkAreas.address()));
  1401. file.read(sizeof(U16) * s, (char*)const_cast<U16*>(mLinkFlags.address()));
  1402. file.read(sizeof(F32) * s, (char*)const_cast<U32*>(mLinkIDs.address()));
  1403. }
  1404. mLinksUnsynced.fill(false);
  1405. mLinkSelectStates.fill(Unselected);
  1406. mDeleteLinks.fill(false);
  1407. file.close();
  1408. updateTiles();
  1409. if(isServerObject())
  1410. {
  1411. setMaskBits(LoadFlag);
  1412. if(getEventManager())
  1413. getEventManager()->postEvent("NavMeshUpdate", getIdString());
  1414. }
  1415. return true;
  1416. }
  1417. DefineEngineMethod(NavMesh, load, bool, (),,
  1418. "@brief Load this NavMesh from its file.")
  1419. {
  1420. return object->load();
  1421. }
  1422. bool NavMesh::save()
  1423. {
  1424. if(!dStrlen(mFileName) || !nm)
  1425. return false;
  1426. File file;
  1427. if(file.open(mFileName, File::Write) != File::Ok)
  1428. {
  1429. file.close();
  1430. Con::errorf("Could not open file %s when saving navmesh %s.",
  1431. mFileName, getName() ? getName() : getIdString());
  1432. return false;
  1433. }
  1434. // Store header.
  1435. NavMeshSetHeader header;
  1436. header.magic = NAVMESHSET_MAGIC;
  1437. header.version = NAVMESHSET_VERSION;
  1438. header.numTiles = 0;
  1439. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1440. {
  1441. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1442. if (!tile || !tile->header || !tile->dataSize) continue;
  1443. header.numTiles++;
  1444. }
  1445. memcpy(&header.params, nm->getParams(), sizeof(dtNavMeshParams));
  1446. file.write(sizeof(NavMeshSetHeader), (const char*)&header);
  1447. // Store tiles.
  1448. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1449. {
  1450. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1451. if(!tile || !tile->header || !tile->dataSize) continue;
  1452. NavMeshTileHeader tileHeader;
  1453. tileHeader.tileRef = nm->getTileRef(tile);
  1454. tileHeader.dataSize = tile->dataSize;
  1455. file.write(sizeof(tileHeader), (const char*)&tileHeader);
  1456. file.write(tile->dataSize, (const char*)tile->data);
  1457. }
  1458. S32 s = mLinkIDs.size();
  1459. file.write(sizeof(S32), (const char*)&s);
  1460. if (s > 0)
  1461. {
  1462. file.write(sizeof(F32) * s * 6, (const char*)mLinkVerts.address());
  1463. file.write(sizeof(F32) * s, (const char*)mLinkRads.address());
  1464. file.write(sizeof(U8) * s, (const char*)mLinkDirs.address());
  1465. file.write(sizeof(U8) * s, (const char*)mLinkAreas.address());
  1466. file.write(sizeof(U16) * s, (const char*)mLinkFlags.address());
  1467. file.write(sizeof(U32) * s, (const char*)mLinkIDs.address());
  1468. }
  1469. file.close();
  1470. return true;
  1471. }
  1472. DefineEngineMethod(NavMesh, save, void, (),,
  1473. "@brief Save this NavMesh to its file.")
  1474. {
  1475. object->save();
  1476. }
  1477. void NavMesh::write(Stream &stream, U32 tabStop, U32 flags)
  1478. {
  1479. save();
  1480. Parent::write(stream, tabStop, flags);
  1481. }