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