navMesh.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  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. #include "T3D/assets/LevelAsset.h"
  39. extern bool gEditingMission;
  40. IMPLEMENT_CO_NETOBJECT_V1(NavMesh);
  41. const U32 NavMesh::mMaxVertsPerPoly = DT_VERTS_PER_POLYGON;
  42. SimObjectPtr<SimSet> NavMesh::smServerSet = NULL;
  43. ImplementEnumType(NavMeshWaterMethod,
  44. "The method used to include water surfaces in the NavMesh.\n")
  45. { NavMesh::Ignore, "Ignore", "Ignore all water surfaces.\n" },
  46. { NavMesh::Solid, "Solid", "Treat water surfaces as solid and walkable.\n" },
  47. { NavMesh::Impassable, "Impassable", "Treat water as an impassable obstacle.\n" },
  48. EndImplementEnumType;
  49. SimSet *NavMesh::getServerSet()
  50. {
  51. if(!smServerSet)
  52. {
  53. SimSet *set = NULL;
  54. if(Sim::findObject("ServerNavMeshSet", set))
  55. smServerSet = set;
  56. else
  57. {
  58. smServerSet = new SimSet();
  59. smServerSet->registerObject("ServerNavMeshSet");
  60. Sim::getRootGroup()->addObject(smServerSet);
  61. }
  62. }
  63. return smServerSet;
  64. }
  65. SimObjectPtr<EventManager> NavMesh::smEventManager = NULL;
  66. EventManager *NavMesh::getEventManager()
  67. {
  68. if(!smEventManager)
  69. {
  70. smEventManager = new EventManager();
  71. smEventManager->registerObject("NavEventManager");
  72. Sim::getRootGroup()->addObject(smEventManager);
  73. smEventManager->setMessageQueue("NavEventManagerQueue");
  74. smEventManager->registerEvent("NavMeshCreated");
  75. smEventManager->registerEvent("NavMeshRemoved");
  76. smEventManager->registerEvent("NavMeshStartUpdate");
  77. smEventManager->registerEvent("NavMeshUpdate");
  78. smEventManager->registerEvent("NavMeshTileUpdate");
  79. smEventManager->registerEvent("NavMeshUpdateBox");
  80. smEventManager->registerEvent("NavMeshObstacleAdded");
  81. smEventManager->registerEvent("NavMeshObstacleRemoved");
  82. }
  83. return smEventManager;
  84. }
  85. DefineEngineFunction(getNavMeshEventManager, S32, (),,
  86. "@brief Get the EventManager object for all NavMesh updates.")
  87. {
  88. return NavMesh::getEventManager()->getId();
  89. }
  90. DefineEngineFunction(NavMeshUpdateAll, void, (S32 objid, bool remove), (0, false),
  91. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  92. {
  93. SceneObject *obj;
  94. if(!Sim::findObject(objid, obj))
  95. return;
  96. obj->mPathfindingIgnore = remove;
  97. SimSet *set = NavMesh::getServerSet();
  98. for(U32 i = 0; i < set->size(); i++)
  99. {
  100. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  101. if (m)
  102. {
  103. m->cancelBuild();
  104. m->buildTiles(obj->getWorldBox());
  105. }
  106. }
  107. }
  108. DefineEngineFunction(NavMeshUpdateAroundObject, void, (S32 objid, bool remove), (0, false),
  109. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  110. {
  111. SceneObject *obj;
  112. if (!Sim::findObject(objid, obj))
  113. return;
  114. obj->mPathfindingIgnore = remove;
  115. SimSet *set = NavMesh::getServerSet();
  116. for (U32 i = 0; i < set->size(); i++)
  117. {
  118. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  119. if (m)
  120. {
  121. m->cancelBuild();
  122. m->buildTiles(obj->getWorldBox());
  123. }
  124. }
  125. }
  126. DefineEngineFunction(NavMeshIgnore, void, (S32 objid, bool _ignore), (0, true),
  127. "@brief Flag this object as not generating a navmesh result.")
  128. {
  129. SceneObject *obj;
  130. if(!Sim::findObject(objid, obj))
  131. return;
  132. obj->mPathfindingIgnore = _ignore;
  133. }
  134. DefineEngineFunction(NavMeshUpdateOne, void, (S32 meshid, S32 objid, bool remove), (0, 0, false),
  135. "@brief Update all tiles in a given NavMesh that intersect the given object's world box.")
  136. {
  137. NavMesh *mesh;
  138. SceneObject *obj;
  139. if(!Sim::findObject(meshid, mesh))
  140. {
  141. Con::errorf("NavMeshUpdateOne: cannot find NavMesh %d", meshid);
  142. return;
  143. }
  144. if(!Sim::findObject(objid, obj))
  145. {
  146. Con::errorf("NavMeshUpdateOne: cannot find SceneObject %d", objid);
  147. return;
  148. }
  149. if(remove)
  150. obj->disableCollision();
  151. mesh->buildTiles(obj->getWorldBox());
  152. if(remove)
  153. obj->enableCollision();
  154. }
  155. NavMesh::NavMesh()
  156. : m_triareas(0),
  157. m_solid(0),
  158. m_chf(0),
  159. m_cset(0),
  160. m_pmesh(0),
  161. m_dmesh(0),
  162. m_drawMode(DRAWMODE_NAVMESH)
  163. {
  164. mTypeMask |= StaticShapeObjectType | MarkerObjectType;
  165. mFileName = StringTable->EmptyString();
  166. mNetFlags.clear(Ghostable);
  167. mSaveIntermediates = false;
  168. nm = NULL;
  169. ctx = NULL;
  170. m_geo = NULL;
  171. mWaterMethod = Ignore;
  172. mCellSize = mCellHeight = 0.2f;
  173. mWalkableHeight = 2.0f;
  174. mWalkableClimb = 0.3f;
  175. mWalkableRadius = 0.5f;
  176. mWalkableSlope = 40.0f;
  177. mBorderSize = 1;
  178. mDetailSampleDist = 6.0f;
  179. mDetailSampleMaxError = 1.0f;
  180. mMaxEdgeLen = 12;
  181. mMaxSimplificationError = 1.3f;
  182. mMinRegionArea = 8;
  183. mMergeRegionArea = 20;
  184. mTileSize = 10.0f;
  185. mMaxPolysPerTile = 128;
  186. mSmallCharacters = false;
  187. mRegularCharacters = true;
  188. mLargeCharacters = false;
  189. mVehicles = false;
  190. mCoverSet = StringTable->EmptyString();
  191. mInnerCover = false;
  192. mCoverDist = 1.0f;
  193. mPeekDist = 0.7f;
  194. mAlwaysRender = false;
  195. mBuilding = false;
  196. mCurLinkID = 0;
  197. mWaterVertStart = 0;
  198. mWaterTriStart = 0;
  199. mQuery = NULL;
  200. }
  201. NavMesh::~NavMesh()
  202. {
  203. dtFreeNavMeshQuery(mQuery);
  204. dtFreeNavMesh(nm);
  205. nm = NULL;
  206. delete ctx;
  207. ctx = NULL;
  208. }
  209. bool NavMesh::setProtectedDetailSampleDist(void *obj, const char *index, const char *data)
  210. {
  211. F32 dist = dAtof(data);
  212. if(dist == 0.0f || dist >= 0.9f)
  213. return true;
  214. if (dist > 0.0f && dist < 0.9f)
  215. {
  216. NavMesh* ptr = static_cast<NavMesh*>(obj);
  217. ptr->mDetailSampleDist = 0.9f;
  218. }
  219. Con::errorf("NavMesh::detailSampleDist must be 0 or greater than 0.9!");
  220. return false;
  221. }
  222. bool NavMesh::setProtectedAlwaysRender(void *obj, const char *index, const char *data)
  223. {
  224. NavMesh *mesh = static_cast<NavMesh*>(obj);
  225. bool always = dAtob(data);
  226. if(always)
  227. {
  228. if(!gEditingMission)
  229. mesh->mNetFlags.set(Ghostable);
  230. }
  231. else
  232. {
  233. if(!gEditingMission)
  234. mesh->mNetFlags.clear(Ghostable);
  235. }
  236. mesh->mAlwaysRender = always;
  237. mesh->setMaskBits(LoadFlag);
  238. return true;
  239. }
  240. FRangeValidator ValidCellSize(0.01f, 10.0f);
  241. void NavMesh::initPersistFields()
  242. {
  243. docsURL;
  244. addGroup("NavMesh Options");
  245. addField("fileName", TypeString, Offset(mFileName, NavMesh),
  246. "Name of the data file to store this navmesh in (relative to engine executable).");
  247. addField("waterMethod", TYPEID<NavMeshWaterMethod>(), Offset(mWaterMethod, NavMesh),
  248. "The method to use to handle water surfaces.");
  249. addFieldV("cellSize", TypeRangedF32, Offset(mCellSize, NavMesh), &ValidCellSize,
  250. "Length/width of a voxel.");
  251. addFieldV("cellHeight", TypeRangedF32, Offset(mCellHeight, NavMesh), &ValidCellSize,
  252. "Height of a voxel.");
  253. addFieldV("tileSize", TypeRangedF32, Offset(mTileSize, NavMesh), &CommonValidators::PositiveNonZeroFloat,
  254. "The horizontal size of tiles.");
  255. addFieldV("actorHeight", TypeRangedF32, Offset(mWalkableHeight, NavMesh), &CommonValidators::PositiveFloat,
  256. "Height of an actor.");
  257. addFieldV("actorClimb", TypeRangedF32, Offset(mWalkableClimb, NavMesh), &CommonValidators::PositiveFloat,
  258. "Maximum climbing height of an actor.");
  259. addFieldV("actorRadius", TypeRangedF32, Offset(mWalkableRadius, NavMesh), &CommonValidators::PositiveFloat,
  260. "Radius of an actor.");
  261. addFieldV("walkableSlope", TypeRangedF32, Offset(mWalkableSlope, NavMesh), &CommonValidators::ValidSlopeAngle,
  262. "Maximum walkable slope in degrees.");
  263. addField("smallCharacters", TypeBool, Offset(mSmallCharacters, NavMesh),
  264. "Is this NavMesh for smaller-than-usual characters?");
  265. addField("regularCharacters", TypeBool, Offset(mRegularCharacters, NavMesh),
  266. "Is this NavMesh for regular-sized characters?");
  267. addField("largeCharacters", TypeBool, Offset(mLargeCharacters, NavMesh),
  268. "Is this NavMesh for larger-than-usual characters?");
  269. addField("vehicles", TypeBool, Offset(mVehicles, NavMesh),
  270. "Is this NavMesh for characters driving vehicles?");
  271. endGroup("NavMesh Options");
  272. addGroup("NavMesh Annotations");
  273. addField("coverGroup", TypeString, Offset(mCoverSet, NavMesh),
  274. "Name of the SimGroup to store cover points in.");
  275. addField("innerCover", TypeBool, Offset(mInnerCover, NavMesh),
  276. "Add cover points everywhere, not just on corners?");
  277. addFieldV("coverDist", TypeRangedF32, Offset(mCoverDist, NavMesh), &CommonValidators::PositiveFloat,
  278. "Distance from the edge of the NavMesh to search for cover.");
  279. addFieldV("peekDist", TypeRangedF32, Offset(mPeekDist, NavMesh), &CommonValidators::PositiveFloat,
  280. "Distance to the side of each cover point that peeking happens.");
  281. endGroup("NavMesh Annotations");
  282. addGroup("NavMesh Rendering");
  283. addProtectedField("alwaysRender", TypeBool, Offset(mAlwaysRender, NavMesh),
  284. &setProtectedAlwaysRender, &defaultProtectedGetFn,
  285. "Display this NavMesh even outside the editor.");
  286. endGroup("NavMesh Rendering");
  287. addGroup("NavMesh Advanced Options");
  288. addFieldV("borderSize", TypeRangedS32, Offset(mBorderSize, NavMesh), &CommonValidators::PositiveInt,
  289. "Size of the non-walkable border around the navigation mesh (in voxels).");
  290. addProtectedFieldV("detailSampleDist", TypeRangedF32, Offset(mDetailSampleDist, NavMesh),
  291. &setProtectedDetailSampleDist, &defaultProtectedGetFn, &CommonValidators::PositiveFloat,
  292. "Sets the sampling distance to use when generating the detail mesh.");
  293. addFieldV("detailSampleError", TypeRangedF32, Offset(mDetailSampleMaxError, NavMesh), &CommonValidators::PositiveFloat,
  294. "The maximum distance the detail mesh surface should deviate from heightfield data.");
  295. addFieldV("maxEdgeLen", TypeRangedS32, Offset(mMaxEdgeLen, NavMesh), &CommonValidators::PositiveInt,
  296. "The maximum allowed length for contour edges along the border of the mesh.");
  297. addFieldV("simplificationError", TypeRangedF32, Offset(mMaxSimplificationError, NavMesh), &CommonValidators::PositiveFloat,
  298. "The maximum distance a simplfied contour's border edges should deviate from the original raw contour.");
  299. addFieldV("minRegionArea", TypeRangedS32, Offset(mMinRegionArea, NavMesh), &CommonValidators::PositiveInt,
  300. "The minimum number of cells allowed to form isolated island areas.");
  301. addFieldV("mergeRegionArea", TypeRangedS32, Offset(mMergeRegionArea, NavMesh), &CommonValidators::PositiveInt,
  302. "Any regions with a span count smaller than this value will, if possible, be merged with larger regions.");
  303. addFieldV("maxPolysPerTile", TypeRangedS32, Offset(mMaxPolysPerTile, NavMesh), &CommonValidators::NaturalNumber,
  304. "The maximum number of polygons allowed in a tile.");
  305. endGroup("NavMesh Advanced Options");
  306. Parent::initPersistFields();
  307. }
  308. bool NavMesh::onAdd()
  309. {
  310. if(!Parent::onAdd())
  311. return false;
  312. mObjBox.set(Point3F(-0.5f, -0.5f, -0.5f),
  313. Point3F( 0.5f, 0.5f, 0.5f));
  314. resetWorldBox();
  315. addToScene();
  316. if(gEditingMission || mAlwaysRender)
  317. {
  318. mNetFlags.set(Ghostable);
  319. if (isClientObject())
  320. renderToDrawer();
  321. }
  322. if(isServerObject())
  323. {
  324. getServerSet()->addObject(this);
  325. ctx = new NavContext();
  326. setProcessTick(true);
  327. if(getEventManager())
  328. getEventManager()->postEvent("NavMeshCreated", getIdString());
  329. }
  330. load();
  331. return true;
  332. }
  333. void NavMesh::onRemove()
  334. {
  335. if(getEventManager())
  336. getEventManager()->postEvent("NavMeshRemoved", getIdString());
  337. removeFromScene();
  338. Parent::onRemove();
  339. }
  340. void NavMesh::setTransform(const MatrixF &mat)
  341. {
  342. Parent::setTransform(mat);
  343. }
  344. void NavMesh::setScale(const VectorF &scale)
  345. {
  346. Parent::setScale(scale);
  347. }
  348. S32 NavMesh::addLink(const Point3F &from, const Point3F &to, bool biDir, F32 rad, U32 flags)
  349. {
  350. Point3F rcFrom = DTStoRC(from), rcTo = DTStoRC(to);
  351. mLinkVerts.push_back(rcFrom.x);
  352. mLinkVerts.push_back(rcFrom.y);
  353. mLinkVerts.push_back(rcFrom.z);
  354. mLinkVerts.push_back(rcTo.x);
  355. mLinkVerts.push_back(rcTo.y);
  356. mLinkVerts.push_back(rcTo.z);
  357. mLinksUnsynced.push_back(true);
  358. mLinkRads.push_back(rad);
  359. mLinkDirs.push_back(biDir ? 1 : 0);
  360. mLinkAreas.push_back(OffMeshArea);
  361. if (flags == 0) {
  362. Point3F dir = to - from;
  363. F32 drop = -dir.z;
  364. dir.z = 0;
  365. // If we drop more than we travel horizontally, we're a drop link.
  366. if(drop > dir.len())
  367. mLinkFlags.push_back(DropFlag);
  368. else
  369. mLinkFlags.push_back(JumpFlag);
  370. }
  371. mLinkIDs.push_back(1000 + mCurLinkID);
  372. mLinkSelectStates.push_back(Unselected);
  373. mDeleteLinks.push_back(false);
  374. mCurLinkID++;
  375. return mLinkIDs.size() - 1;
  376. }
  377. DefineEngineMethod(NavMesh, addLink, S32, (Point3F from, Point3F to, bool biDir, U32 flags), (0),
  378. "Add a link to this NavMesh between two points.\n\n"
  379. "")
  380. {
  381. return object->addLink(from, to, biDir, flags);
  382. }
  383. S32 NavMesh::getLink(const Point3F &pos)
  384. {
  385. for(U32 i = 0; i < mLinkIDs.size(); i++)
  386. {
  387. if(mDeleteLinks[i])
  388. continue;
  389. SphereF start(getLinkStart(i), mLinkRads[i]);
  390. SphereF end(getLinkEnd(i), mLinkRads[i]);
  391. if(start.isContained(pos) || end.isContained(pos))
  392. return i;
  393. }
  394. return -1;
  395. }
  396. DefineEngineMethod(NavMesh, getLink, S32, (Point3F pos),,
  397. "Get the off-mesh link closest to a given world point.")
  398. {
  399. return object->getLink(pos);
  400. }
  401. S32 NavMesh::getLinkCount()
  402. {
  403. return mLinkIDs.size();
  404. }
  405. DefineEngineMethod(NavMesh, getLinkCount, S32, (),,
  406. "Return the number of links this mesh has.")
  407. {
  408. return object->getLinkCount();
  409. }
  410. LinkData NavMesh::getLinkFlags(U32 idx)
  411. {
  412. if(idx < mLinkIDs.size())
  413. {
  414. return LinkData(mLinkFlags[idx]);
  415. }
  416. return LinkData();
  417. }
  418. bool NavMesh::getLinkDir(U32 idx)
  419. {
  420. if (idx < mLinkIDs.size())
  421. {
  422. return mLinkDirs[idx];
  423. }
  424. return false;
  425. }
  426. F32 NavMesh::getLinkRadius(U32 idx)
  427. {
  428. if (idx < mLinkIDs.size())
  429. {
  430. return mLinkRads[idx];
  431. }
  432. return -1.0f;
  433. }
  434. void NavMesh::setLinkDir(U32 idx, bool biDir)
  435. {
  436. if (idx < mLinkIDs.size())
  437. {
  438. mLinkDirs[idx] = biDir ? 1 : 0;
  439. mLinksUnsynced[idx] = true;
  440. }
  441. }
  442. void NavMesh::setLinkRadius(U32 idx, F32 rad)
  443. {
  444. if (idx < mLinkIDs.size())
  445. {
  446. mLinkRads[idx] = rad;
  447. }
  448. }
  449. DefineEngineMethod(NavMesh, getLinkFlags, S32, (U32 id),,
  450. "Get the flags set for a particular off-mesh link.")
  451. {
  452. return object->getLinkFlags(id).getFlags();
  453. }
  454. void NavMesh::setLinkFlags(U32 idx, const LinkData &d)
  455. {
  456. if(idx < mLinkIDs.size())
  457. {
  458. mLinkFlags[idx] = d.getFlags();
  459. mLinksUnsynced[idx] = true;
  460. }
  461. }
  462. DefineEngineMethod(NavMesh, setLinkFlags, void, (U32 id, U32 flags),,
  463. "Set the flags of a particular off-mesh link.")
  464. {
  465. LinkData d(flags);
  466. object->setLinkFlags(id, d);
  467. }
  468. Point3F NavMesh::getLinkStart(U32 idx)
  469. {
  470. return RCtoDTS(Point3F(
  471. mLinkVerts[idx*6],
  472. mLinkVerts[idx*6 + 1],
  473. mLinkVerts[idx*6 + 2]));
  474. }
  475. DefineEngineMethod(NavMesh, getLinkStart, Point3F, (U32 id),,
  476. "Get the starting point of an off-mesh link.")
  477. {
  478. return object->getLinkStart(id);
  479. }
  480. Point3F NavMesh::getLinkEnd(U32 idx)
  481. {
  482. return RCtoDTS(Point3F(
  483. mLinkVerts[idx*6 + 3],
  484. mLinkVerts[idx*6 + 4],
  485. mLinkVerts[idx*6 + 5]));
  486. }
  487. DefineEngineMethod(NavMesh, getLinkEnd, Point3F, (U32 id),,
  488. "Get the ending point of an off-mesh link.")
  489. {
  490. return object->getLinkEnd(id);
  491. }
  492. void NavMesh::selectLink(U32 idx, bool select, bool hover)
  493. {
  494. if(idx < mLinkIDs.size())
  495. {
  496. if(!select)
  497. mLinkSelectStates[idx] = Unselected;
  498. else
  499. mLinkSelectStates[idx] = hover ? Hovered : Selected;
  500. }
  501. }
  502. void NavMesh::eraseLink(U32 i)
  503. {
  504. mLinkVerts.erase(i*6, 6);
  505. mLinksUnsynced.erase(i);
  506. mLinkRads.erase(i);
  507. mLinkDirs.erase(i);
  508. mLinkAreas.erase(i);
  509. mLinkFlags.erase(i);
  510. mLinkIDs.erase(i);
  511. mLinkSelectStates.erase(i);
  512. mDeleteLinks.erase(i);
  513. }
  514. void NavMesh::eraseLinks()
  515. {
  516. mLinkVerts.clear();
  517. mLinksUnsynced.clear();
  518. mLinkRads.clear();
  519. mLinkDirs.clear();
  520. mLinkAreas.clear();
  521. mLinkFlags.clear();
  522. mLinkIDs.clear();
  523. mLinkSelectStates.clear();
  524. mDeleteLinks.clear();
  525. }
  526. void NavMesh::setLinkCount(U32 c)
  527. {
  528. eraseLinks();
  529. mLinkVerts.setSize(c * 6);
  530. mLinksUnsynced.setSize(c);
  531. mLinkRads.setSize(c);
  532. mLinkDirs.setSize(c);
  533. mLinkAreas.setSize(c);
  534. mLinkFlags.setSize(c);
  535. mLinkIDs.setSize(c);
  536. mLinkSelectStates.setSize(c);
  537. mDeleteLinks.setSize(c);
  538. }
  539. void NavMesh::deleteLink(U32 idx)
  540. {
  541. if(idx < mLinkIDs.size())
  542. {
  543. mDeleteLinks[idx] = true;
  544. if(mLinksUnsynced[idx])
  545. eraseLink(idx);
  546. else
  547. mLinksUnsynced[idx] = true;
  548. }
  549. }
  550. DefineEngineMethod(NavMesh, deleteLink, void, (U32 id),,
  551. "Delete a given off-mesh link.")
  552. {
  553. object->deleteLink(id);
  554. }
  555. DefineEngineMethod(NavMesh, deleteLinks, void, (),,
  556. "Deletes all off-mesh links on this NavMesh.")
  557. {
  558. //object->eraseLinks();
  559. }
  560. static void buildCallback(SceneObject* object, void* key)
  561. {
  562. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  563. if (!object->mPathfindingIgnore)
  564. object->buildPolyList(info->context, info->polyList, info->boundingBox, info->boundingSphere);
  565. }
  566. bool NavMesh::build(bool background, bool saveIntermediates)
  567. {
  568. if(mBuilding)
  569. cancelBuild();
  570. else
  571. {
  572. if(getEventManager())
  573. getEventManager()->postEvent("NavMeshStartUpdate", getIdString());
  574. }
  575. mBuilding = true;
  576. m_geo = NULL;
  577. ctx->startTimer(RC_TIMER_TOTAL);
  578. dtFreeNavMesh(nm);
  579. // Allocate a new navmesh.
  580. nm = dtAllocNavMesh();
  581. if(!nm)
  582. {
  583. Con::errorf("Could not allocate dtNavMesh for NavMesh %s", getIdString());
  584. return false;
  585. }
  586. // Needed for the recast config and generation params.
  587. Box3F rc_box = DTStoRC(getWorldBox());
  588. S32 gw = 0, gh = 0;
  589. rcCalcGridSize(rc_box.minExtents, rc_box.maxExtents, mCellSize, &gw, &gh);
  590. const S32 ts = (S32)(mTileSize / mCellSize);
  591. const S32 tw = (gw + ts - 1) / ts;
  592. const S32 th = (gh + ts - 1) / ts;
  593. Con::printf("NavMesh::Build - Tiles %d x %d", tw, th);
  594. U32 tileBits = mMin(getBinLog2(getNextPow2(tw * th)), 14);
  595. if (tileBits > 14) tileBits = 14;
  596. U32 maxTiles = 1 << tileBits;
  597. U32 polyBits = 22 - tileBits;
  598. mMaxPolysPerTile = 1 << polyBits;
  599. // Build navmesh parameters from console members.
  600. dtNavMeshParams params;
  601. rcVcopy(params.orig, rc_box.minExtents);
  602. params.tileWidth = mTileSize;
  603. params.tileHeight = mTileSize;
  604. params.maxTiles = maxTiles;
  605. params.maxPolys = mMaxPolysPerTile;
  606. // Initialise our navmesh.
  607. if(dtStatusFailed(nm->init(&params)))
  608. {
  609. Con::errorf("Could not init dtNavMesh for NavMesh %s", getIdString());
  610. return false;
  611. }
  612. // Update links to be deleted.
  613. for(U32 i = 0; i < mLinkIDs.size();)
  614. {
  615. if(mDeleteLinks[i])
  616. eraseLink(i);
  617. else
  618. i++;
  619. }
  620. mLinksUnsynced.fill(false);
  621. mCurLinkID = 0;
  622. mSaveIntermediates = saveIntermediates;
  623. updateTiles(true);
  624. if(!background)
  625. {
  626. while(!mDirtyTiles.empty())
  627. buildNextTile();
  628. }
  629. return true;
  630. }
  631. DefineEngineMethod(NavMesh, build, bool, (bool background, bool save), (true, false),
  632. "@brief Create a Recast nav mesh.")
  633. {
  634. return object->build(background, save);
  635. }
  636. void NavMesh::cancelBuild()
  637. {
  638. mDirtyTiles.clear();
  639. ctx->stopTimer(RC_TIMER_TOTAL);
  640. mBuilding = false;
  641. }
  642. DefineEngineMethod(NavMesh, cancelBuild, void, (),,
  643. "@brief Cancel the current NavMesh build.")
  644. {
  645. object->cancelBuild();
  646. }
  647. void NavMesh::inspectPostApply()
  648. {
  649. if(mBuilding)
  650. cancelBuild();
  651. }
  652. void NavMesh::createNewFile()
  653. {
  654. // We need to construct a default file name
  655. String levelAssetId(Con::getVariable("$Client::LevelAsset"));
  656. LevelAsset* levelAsset;
  657. if (!Sim::findObject(levelAssetId.c_str(), levelAsset))
  658. {
  659. Con::errorf("NavMesh::createNewFile() - Unable to find current level's LevelAsset. Unable to construct NavMesh filePath");
  660. return;
  661. }
  662. Torque::Path basePath(levelAsset->getNavmeshPath());
  663. if (basePath.isEmpty())
  664. basePath = (Torque::Path)(levelAsset->getLevelPath());
  665. String fileName = Torque::FS::MakeUniquePath(basePath.getPath(), basePath.getFileName(), "nav");
  666. mFileName = StringTable->insert(fileName.c_str());
  667. }
  668. S32 NavMesh::getTile(const Point3F& pos)
  669. {
  670. if(mBuilding)
  671. return -1;
  672. for(U32 i = 0; i < mTiles.size(); i++)
  673. {
  674. if(mTiles[i].box.isContained(pos))
  675. return i;
  676. }
  677. return -1;
  678. }
  679. Box3F NavMesh::getTileBox(U32 id)
  680. {
  681. if(mBuilding || id >= mTiles.size())
  682. return Box3F::Invalid;
  683. return mTiles[id].box;
  684. }
  685. void NavMesh::updateTiles(bool dirty)
  686. {
  687. PROFILE_SCOPE(NavMesh_updateTiles);
  688. if(!isProperlyAdded())
  689. return;
  690. mTiles.clear();
  691. mDirtyTiles.clear();
  692. const Box3F &box = DTStoRC(getWorldBox());
  693. if(box.isEmpty())
  694. return;
  695. // Calculate tile dimensions.
  696. const F32* bmin = box.minExtents;
  697. const F32* bmax = box.maxExtents;
  698. S32 gw = 0, gh = 0;
  699. rcCalcGridSize(bmin, bmax, mCellSize, &gw, &gh);
  700. const S32 ts = (S32)(mTileSize / mCellSize);
  701. const S32 tw = (gw + ts - 1) / ts;
  702. const S32 th = (gh + ts - 1) / ts;
  703. const F32 tcs = mTileSize;
  704. // Iterate over tiles.
  705. F32 tileBmin[3], tileBmax[3];
  706. for(U32 y = 0; y < th; ++y)
  707. {
  708. for(U32 x = 0; x < tw; ++x)
  709. {
  710. tileBmin[0] = bmin[0] + x*tcs;
  711. tileBmin[1] = bmin[1];
  712. tileBmin[2] = bmin[2] + y*tcs;
  713. tileBmax[0] = bmin[0] + (x+1)*tcs;
  714. tileBmax[1] = bmax[1];
  715. tileBmax[2] = bmin[2] + (y+1)*tcs;
  716. mTiles.push_back(
  717. Tile(RCtoDTS(tileBmin, tileBmax),
  718. x, y,
  719. tileBmin, tileBmax));
  720. if(dirty)
  721. mDirtyTiles.push_back_unique(mTiles.size() - 1);
  722. }
  723. }
  724. }
  725. void NavMesh::processTick(const Move *move)
  726. {
  727. buildNextTile();
  728. }
  729. void NavMesh::buildNextTile()
  730. {
  731. PROFILE_SCOPE(NavMesh_buildNextTile);
  732. if(!mDirtyTiles.empty())
  733. {
  734. dtFreeNavMeshQuery(mQuery);
  735. mQuery = NULL;
  736. // Pop a single dirty tile and process it.
  737. U32 i = mDirtyTiles.front();
  738. mDirtyTiles.pop_front();
  739. Tile &tile = mTiles[i];
  740. // Remove any previous data.
  741. nm->removeTile(nm->getTileRefAt(tile.x, tile.y, 0), 0, 0);
  742. // Generate navmesh for this tile.
  743. U32 dataSize = 0;
  744. unsigned char* data = buildTileData(tile, dataSize);
  745. // cache our result (these only exist if keep intermediates is ticked)
  746. if (m_chf)
  747. {
  748. tile.chf = m_chf;
  749. m_chf = 0;
  750. }
  751. if (m_solid)
  752. {
  753. tile.solid = m_solid;
  754. m_solid = 0;
  755. }
  756. if (m_cset)
  757. {
  758. tile.cset = m_cset;
  759. m_cset = 0;
  760. }
  761. if (m_pmesh)
  762. {
  763. tile.pmesh = m_pmesh;
  764. m_pmesh = 0;
  765. }
  766. if (m_dmesh)
  767. {
  768. tile.dmesh = m_dmesh;
  769. m_dmesh = 0;
  770. }
  771. if (m_triareas)
  772. {
  773. tile.triareas = m_triareas;
  774. m_triareas = nullptr;
  775. }
  776. if(data)
  777. {
  778. // Add new data (navmesh owns and deletes the data).
  779. dtStatus status = nm->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0);
  780. int success = 1;
  781. if(dtStatusFailed(status))
  782. {
  783. success = 0;
  784. dtFree(data);
  785. }
  786. if(getEventManager())
  787. {
  788. String str = String::ToString("%d %d %d (%d, %d) %d %.3f %s",
  789. getId(),
  790. i, mTiles.size(),
  791. tile.x, tile.y,
  792. success,
  793. ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f,
  794. castConsoleTypeToString(tile.box));
  795. getEventManager()->postEvent("NavMeshTileUpdate", str.c_str());
  796. setMaskBits(LoadFlag);
  797. }
  798. }
  799. // Did we just build the last tile?
  800. if(mDirtyTiles.empty())
  801. {
  802. mQuery = dtAllocNavMeshQuery();
  803. if (dtStatusFailed(mQuery->init(nm, 2048)))
  804. {
  805. Con::errorf("NavMesh - Failed to create navmesh query");
  806. }
  807. ctx->stopTimer(RC_TIMER_TOTAL);
  808. if(getEventManager())
  809. {
  810. String str = String::ToString("%d", getId());
  811. getEventManager()->postEvent("NavMeshUpdate", str.c_str());
  812. setMaskBits(LoadFlag);
  813. }
  814. mBuilding = false;
  815. }
  816. }
  817. if (mQuery == NULL)
  818. {
  819. mQuery = dtAllocNavMeshQuery();
  820. if (dtStatusFailed(mQuery->init(nm, 2048)))
  821. {
  822. Con::errorf("NavMesh - Failed to create navmesh query");
  823. }
  824. }
  825. }
  826. unsigned char *NavMesh::buildTileData(const Tile &tile, U32 &dataSize)
  827. {
  828. cleanup();
  829. // Push out tile boundaries a bit.
  830. F32 tileBmin[3], tileBmax[3];
  831. rcVcopy(tileBmin, tile.bmin);
  832. rcVcopy(tileBmax, tile.bmax);
  833. // Setup our rcConfig
  834. dMemset(&m_cfg, 0, sizeof(m_cfg));
  835. m_cfg.cs = mCellSize;
  836. m_cfg.ch = mCellHeight;
  837. m_cfg.walkableSlopeAngle = mWalkableSlope;
  838. m_cfg.walkableHeight = (S32)mCeil(mWalkableHeight / m_cfg.ch);
  839. m_cfg.walkableClimb = (S32)mFloor(mWalkableClimb / m_cfg.ch);
  840. m_cfg.walkableRadius = (S32)mCeil(mWalkableRadius / m_cfg.cs);
  841. m_cfg.maxEdgeLen = (S32)(mMaxEdgeLen / mCellSize);
  842. m_cfg.maxSimplificationError = mMaxSimplificationError;
  843. m_cfg.minRegionArea = (S32)mSquared((F32)mMinRegionArea);
  844. m_cfg.mergeRegionArea = (S32)mSquared((F32)mMergeRegionArea);
  845. m_cfg.maxVertsPerPoly = (S32)mMaxVertsPerPoly;
  846. m_cfg.tileSize = (S32)(mTileSize / mCellSize);
  847. m_cfg.borderSize = mMax(m_cfg.walkableRadius + 3, mBorderSize); // use the border size if it is bigger.
  848. m_cfg.width = m_cfg.tileSize + m_cfg.borderSize * 2;
  849. m_cfg.height = m_cfg.tileSize + m_cfg.borderSize * 2;
  850. m_cfg.detailSampleDist = mDetailSampleDist < 0.9f ? 0 : mCellSize * mDetailSampleDist;
  851. m_cfg.detailSampleMaxError = mCellHeight * mDetailSampleMaxError;
  852. rcVcopy(m_cfg.bmin, tileBmin);
  853. rcVcopy(m_cfg.bmax, tileBmax);
  854. m_cfg.bmin[0] -= m_cfg.borderSize * m_cfg.cs;
  855. m_cfg.bmin[2] -= m_cfg.borderSize * m_cfg.cs;
  856. m_cfg.bmax[0] += m_cfg.borderSize * m_cfg.cs;
  857. m_cfg.bmax[2] += m_cfg.borderSize * m_cfg.cs;
  858. Box3F worldBox = RCtoDTS(m_cfg.bmin, m_cfg.bmax);
  859. SceneContainer::CallbackInfo info;
  860. info.context = PLC_Navigation;
  861. info.boundingBox = worldBox;
  862. m_geo = new RecastPolyList;
  863. info.polyList = m_geo;
  864. info.key = this;
  865. getContainer()->findObjects(worldBox, StaticObjectType | DynamicShapeObjectType, buildCallback, &info);
  866. // Parse water objects into the same list, but remember how much geometry was /not/ water.
  867. mWaterVertStart = m_geo->getVertCount();
  868. mWaterTriStart = m_geo->getTriCount();
  869. if (mWaterMethod != Ignore)
  870. {
  871. getContainer()->findObjects(worldBox, WaterObjectType, buildCallback, &info);
  872. }
  873. // Check for no geometry.
  874. if (!m_geo->getVertCount())
  875. {
  876. m_geo->clear();
  877. return NULL;
  878. }
  879. const rcChunkyTriMesh* chunkyMesh = m_geo->getChunkyMesh();
  880. // Create a heightfield to voxelize our input geometry.
  881. m_solid = rcAllocHeightfield();
  882. if(!m_solid)
  883. {
  884. Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString());
  885. return NULL;
  886. }
  887. if (!rcCreateHeightfield(ctx, *m_solid, m_cfg.width, m_cfg.height, m_cfg.bmin, m_cfg.bmax, m_cfg.cs, m_cfg.ch))
  888. {
  889. Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString());
  890. return NULL;
  891. }
  892. m_triareas = new unsigned char[chunkyMesh->maxTrisPerChunk];
  893. if (!m_triareas)
  894. {
  895. Con::errorf("NavMesh::buildTileData: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk);
  896. return NULL;
  897. }
  898. F32 tbmin[2], tbmax[2];
  899. tbmin[0] = m_cfg.bmin[0];
  900. tbmin[1] = m_cfg.bmin[2];
  901. tbmax[0] = m_cfg.bmax[0];
  902. tbmax[1] = m_cfg.bmax[2];
  903. int cid[512];
  904. const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512);
  905. if (!ncid)
  906. return 0;
  907. for (int i = 0; i < ncid; ++i)
  908. {
  909. const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]];
  910. const int* ctris = &chunkyMesh->tris[node.i * 3];
  911. const int nctris = node.n;
  912. memset(m_triareas, 0, nctris * sizeof(unsigned char));
  913. rcMarkWalkableTriangles(ctx, m_cfg.walkableSlopeAngle,
  914. m_geo->getVerts(), m_geo->getVertCount(), ctris, nctris, m_triareas);
  915. // Post-process triangle areas if we need to capture water.
  916. if (mWaterMethod != Ignore)
  917. {
  918. for (int t = 0; t < nctris; ++t)
  919. {
  920. const int* tri = &ctris[t * 3];
  921. bool isWater = false;
  922. for (int j = 0; j < 3; ++j)
  923. {
  924. if (tri[j] >= mWaterVertStart)
  925. {
  926. isWater = true;
  927. break;
  928. }
  929. }
  930. if (isWater)
  931. {
  932. if (mWaterMethod == Solid)
  933. {
  934. m_triareas[t] = WaterArea; // Custom enum you define, like 64
  935. }
  936. else if (mWaterMethod == Impassable)
  937. {
  938. m_triareas[t] = NullArea;
  939. }
  940. }
  941. }
  942. }
  943. if (!rcRasterizeTriangles(ctx, m_geo->getVerts(), m_geo->getVertCount(), ctris, m_triareas, nctris, *m_solid, m_cfg.walkableClimb))
  944. return NULL;
  945. }
  946. if (!mSaveIntermediates)
  947. {
  948. delete[] m_triareas;
  949. m_triareas = 0;
  950. }
  951. // these should be optional.
  952. //if (m_filterLowHangingObstacles)
  953. rcFilterLowHangingWalkableObstacles(ctx, m_cfg.walkableClimb, *m_solid);
  954. //if (m_filterLedgeSpans)
  955. rcFilterLedgeSpans(ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid);
  956. //if (m_filterWalkableLowHeightSpans)
  957. rcFilterWalkableLowHeightSpans(ctx, m_cfg.walkableHeight, *m_solid);
  958. // Compact the heightfield so that it is faster to handle from now on.
  959. // This will result more cache coherent data as well as the neighbours
  960. // between walkable cells will be calculated.
  961. m_chf = rcAllocCompactHeightfield();
  962. if (!m_chf)
  963. {
  964. Con::errorf("NavMesh::buildTileData: Out of memory 'chf'.");
  965. return NULL;
  966. }
  967. if (!rcBuildCompactHeightfield(ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid, *m_chf))
  968. {
  969. Con::errorf("NavMesh::buildTileData: Could not build compact data.");
  970. return NULL;
  971. }
  972. if (!mSaveIntermediates)
  973. {
  974. rcFreeHeightField(m_solid);
  975. m_solid = NULL;
  976. }
  977. // Erode the walkable area by agent radius.
  978. if (!rcErodeWalkableArea(ctx, m_cfg.walkableRadius, *m_chf))
  979. {
  980. Con::errorf("NavMesh::buildTileData: Could not erode.");
  981. return NULL;
  982. }
  983. //--------------------------
  984. // Todo: mark areas here.
  985. //const ConvexVolume* vols = m_geom->getConvexVolumes();
  986. //for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
  987. //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
  988. //--------------------------
  989. // Partition the heightfield so that we can use simple algorithm later to triangulate the walkable areas.
  990. // There are 3 martitioning methods, each with some pros and cons:
  991. // These should be implemented.
  992. // 1) Watershed partitioning
  993. // - the classic Recast partitioning
  994. // - creates the nicest tessellation
  995. // - usually slowest
  996. // - partitions the heightfield into nice regions without holes or overlaps
  997. // - the are some corner cases where this method creates produces holes and overlaps
  998. // - holes may appear when a small obstacles is close to large open area (triangulation can handle this)
  999. // - overlaps may occur if you have narrow spiral corridors (i.e stairs), this make triangulation to fail
  1000. // * generally the best choice if you precompute the nacmesh, use this if you have large open areas
  1001. // 2) Monotone partioning
  1002. // - fastest
  1003. // - partitions the heightfield into regions without holes and overlaps (guaranteed)
  1004. // - creates long thin polygons, which sometimes causes paths with detours
  1005. // * use this if you want fast navmesh generation
  1006. // 3) Layer partitoining
  1007. // - quite fast
  1008. // - partitions the heighfield into non-overlapping regions
  1009. // - relies on the triangulation code to cope with holes (thus slower than monotone partitioning)
  1010. // - produces better triangles than monotone partitioning
  1011. // - does not have the corner cases of watershed partitioning
  1012. // - can be slow and create a bit ugly tessellation (still better than monotone)
  1013. // if you have large open areas with small obstacles (not a problem if you use tiles)
  1014. // * good choice to use for tiled navmesh with medium and small sized tiles
  1015. if (/*m_partitionType == SAMPLE_PARTITION_WATERSHED*/ true)
  1016. {
  1017. // Prepare for region partitioning, by calculating distance field along the walkable surface.
  1018. if (!rcBuildDistanceField(ctx, *m_chf))
  1019. {
  1020. Con::errorf("NavMesh::buildTileData: Could not build distance field.");
  1021. return 0;
  1022. }
  1023. // Partition the walkable surface into simple regions without holes.
  1024. if (!rcBuildRegions(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
  1025. {
  1026. Con::errorf("NavMesh::buildTileData: Could not build watershed regions.");
  1027. return NULL;
  1028. }
  1029. }
  1030. else if (/*m_partitionType == SAMPLE_PARTITION_MONOTONE*/ false)
  1031. {
  1032. // Partition the walkable surface into simple regions without holes.
  1033. // Monotone partitioning does not need distancefield.
  1034. if (!rcBuildRegionsMonotone(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
  1035. {
  1036. Con::errorf("NavMesh::buildTileData: Could not build monotone regions.");
  1037. return NULL;
  1038. }
  1039. }
  1040. else // SAMPLE_PARTITION_LAYERS
  1041. {
  1042. // Partition the walkable surface into simple regions without holes.
  1043. if (!rcBuildLayerRegions(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea))
  1044. {
  1045. Con::errorf("NavMesh::buildTileData: Could not build layer regions.");
  1046. return NULL;
  1047. }
  1048. }
  1049. m_cset = rcAllocContourSet();
  1050. if (!m_cset)
  1051. {
  1052. Con::errorf("NavMesh::buildTileData: Out of memory 'cset'");
  1053. return NULL;
  1054. }
  1055. if (!rcBuildContours(ctx, *m_chf, m_cfg.maxSimplificationError, m_cfg.maxEdgeLen, *m_cset))
  1056. {
  1057. Con::errorf("NavMesh::buildTileData: Could not create contours");
  1058. return NULL;
  1059. }
  1060. if (m_cset->nconts == 0)
  1061. return NULL;
  1062. // Build polygon navmesh from the contours.
  1063. m_pmesh = rcAllocPolyMesh();
  1064. if (!m_pmesh)
  1065. {
  1066. Con::errorf("NavMesh::buildTileData: Out of memory 'pmesh'.");
  1067. return NULL;
  1068. }
  1069. if (!rcBuildPolyMesh(ctx, *m_cset, m_cfg.maxVertsPerPoly, *m_pmesh))
  1070. {
  1071. Con::errorf("NavMesh::buildTileData: Could not triangulate contours.");
  1072. return NULL;
  1073. }
  1074. // Build detail mesh.
  1075. m_dmesh = rcAllocPolyMeshDetail();
  1076. if (!m_dmesh)
  1077. {
  1078. Con::errorf("NavMesh::buildTileData: Out of memory 'dmesh'.");
  1079. return NULL;
  1080. }
  1081. if (!rcBuildPolyMeshDetail(ctx, *m_pmesh, *m_chf, m_cfg.detailSampleDist, m_cfg.detailSampleMaxError, *m_dmesh))
  1082. {
  1083. Con::errorf("NavMesh::buildTileData: Could build polymesh detail.");
  1084. return NULL;
  1085. }
  1086. if (!mSaveIntermediates)
  1087. {
  1088. rcFreeCompactHeightfield(m_chf);
  1089. m_chf = 0;
  1090. rcFreeContourSet(m_cset);
  1091. m_cset = 0;
  1092. }
  1093. unsigned char* navData = 0;
  1094. int navDataSize = 0;
  1095. if (m_cfg.maxVertsPerPoly <= DT_VERTS_PER_POLYGON)
  1096. {
  1097. if (m_pmesh->nverts >= 0xffff)
  1098. {
  1099. // The vertex indices are ushorts, and cannot point to more than 0xffff vertices.
  1100. Con::errorf("NavMesh::buildTileData: Too many vertices per tile %d (max: %d).", m_pmesh->nverts, 0xffff);
  1101. return NULL;
  1102. }
  1103. for (U32 i = 0; i < m_pmesh->npolys; i++)
  1104. {
  1105. if (m_pmesh->areas[i] == RC_WALKABLE_AREA)
  1106. m_pmesh->areas[i] = GroundArea;
  1107. if (m_pmesh->areas[i] == GroundArea)
  1108. m_pmesh->flags[i] |= WalkFlag;
  1109. if (m_pmesh->areas[i] == WaterArea)
  1110. m_pmesh->flags[i] |= SwimFlag;
  1111. }
  1112. dtNavMeshCreateParams params;
  1113. dMemset(&params, 0, sizeof(params));
  1114. params.verts = m_pmesh->verts;
  1115. params.vertCount = m_pmesh->nverts;
  1116. params.polys = m_pmesh->polys;
  1117. params.polyAreas = m_pmesh->areas;
  1118. params.polyFlags = m_pmesh->flags;
  1119. params.polyCount = m_pmesh->npolys;
  1120. params.nvp = m_pmesh->nvp;
  1121. params.detailMeshes = m_dmesh->meshes;
  1122. params.detailVerts = m_dmesh->verts;
  1123. params.detailVertsCount = m_dmesh->nverts;
  1124. params.detailTris = m_dmesh->tris;
  1125. params.detailTriCount = m_dmesh->ntris;
  1126. params.offMeshConVerts = mLinkVerts.address();
  1127. params.offMeshConRad = mLinkRads.address();
  1128. params.offMeshConDir = mLinkDirs.address();
  1129. params.offMeshConAreas = mLinkAreas.address();
  1130. params.offMeshConFlags = mLinkFlags.address();
  1131. params.offMeshConUserID = mLinkIDs.address();
  1132. params.offMeshConCount = mLinkIDs.size();
  1133. params.walkableHeight = mWalkableHeight;
  1134. params.walkableRadius = mWalkableRadius;
  1135. params.walkableClimb = mWalkableClimb;
  1136. params.tileX = tile.x;
  1137. params.tileY = tile.y;
  1138. params.tileLayer = 0;
  1139. rcVcopy(params.bmin, m_pmesh->bmin);
  1140. rcVcopy(params.bmax, m_pmesh->bmax);
  1141. params.cs = m_cfg.cs;
  1142. params.ch = m_cfg.ch;
  1143. params.buildBvTree = true;
  1144. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1145. {
  1146. Con::errorf("NavMesh::buildTileData: Could not build Detour navmesh.");
  1147. return NULL;
  1148. }
  1149. }
  1150. dataSize = navDataSize;
  1151. return navData;
  1152. }
  1153. /// This method should never be called in a separate thread to the rendering
  1154. /// or pathfinding logic. It directly replaces data in the dtNavMesh for
  1155. /// this NavMesh object.
  1156. void NavMesh::buildTiles(const Box3F &box)
  1157. {
  1158. PROFILE_SCOPE(NavMesh_buildTiles);
  1159. // Make sure we've already built or loaded.
  1160. if(!nm)
  1161. return;
  1162. // Iterate over tiles.
  1163. for(U32 i = 0; i < mTiles.size(); i++)
  1164. {
  1165. const Tile &tile = mTiles[i];
  1166. // Check tile box.
  1167. if(!tile.box.isOverlapped(box))
  1168. continue;
  1169. // Mark as dirty.
  1170. mDirtyTiles.push_back_unique(i);
  1171. }
  1172. if(mDirtyTiles.size())
  1173. ctx->startTimer(RC_TIMER_TOTAL);
  1174. }
  1175. DefineEngineMethod(NavMesh, buildTiles, void, (Box3F box),,
  1176. "@brief Rebuild the tiles overlapped by the input box.")
  1177. {
  1178. return object->buildTiles(box);
  1179. }
  1180. void NavMesh::buildTile(const U32 &tile)
  1181. {
  1182. PROFILE_SCOPE(NavMesh_buildTile);
  1183. if(tile < mTiles.size())
  1184. {
  1185. mDirtyTiles.push_back_unique(tile);
  1186. ctx->startTimer(RC_TIMER_TOTAL);
  1187. m_geo = NULL;
  1188. }
  1189. }
  1190. void NavMesh::buildLinks()
  1191. {
  1192. // Make sure we've already built or loaded.
  1193. if(!nm)
  1194. return;
  1195. // Iterate over tiles.
  1196. for(U32 i = 0; i < mTiles.size(); i++)
  1197. {
  1198. const Tile &tile = mTiles[i];
  1199. // Iterate over links
  1200. for(U32 j = 0; j < mLinkIDs.size(); j++)
  1201. {
  1202. if (mLinksUnsynced[j])
  1203. {
  1204. if(tile.box.isContained(getLinkStart(j)) ||
  1205. tile.box.isContained(getLinkEnd(j)))
  1206. {
  1207. // Mark tile for build.
  1208. mDirtyTiles.push_back_unique(i);
  1209. // Delete link if necessary
  1210. if(mDeleteLinks[j])
  1211. {
  1212. eraseLink(j);
  1213. j--;
  1214. }
  1215. else
  1216. mLinksUnsynced[j] = false;
  1217. }
  1218. }
  1219. }
  1220. }
  1221. if(mDirtyTiles.size())
  1222. ctx->startTimer(RC_TIMER_TOTAL);
  1223. }
  1224. DefineEngineMethod(NavMesh, buildLinks, void, (),,
  1225. "@brief Build tiles of this mesh where there are unsynchronised links.")
  1226. {
  1227. object->buildLinks();
  1228. }
  1229. void NavMesh::deleteCoverPoints()
  1230. {
  1231. SimSet *set = NULL;
  1232. if(Sim::findObject(mCoverSet, set))
  1233. set->deleteAllObjects();
  1234. }
  1235. DefineEngineMethod(NavMesh, deleteCoverPoints, void, (),,
  1236. "@brief Remove all cover points for this NavMesh.")
  1237. {
  1238. object->deleteCoverPoints();
  1239. }
  1240. bool NavMesh::createCoverPoints()
  1241. {
  1242. if(!nm || !isServerObject())
  1243. return false;
  1244. SimSet *set = NULL;
  1245. if(Sim::findObject(mCoverSet, set))
  1246. {
  1247. set->deleteAllObjects();
  1248. }
  1249. else
  1250. {
  1251. set = new SimGroup();
  1252. if(set->registerObject(mCoverSet))
  1253. {
  1254. getGroup()->addObject(set);
  1255. }
  1256. else
  1257. {
  1258. delete set;
  1259. set = getGroup();
  1260. }
  1261. }
  1262. dtNavMeshQuery *query = dtAllocNavMeshQuery();
  1263. if(!query || dtStatusFailed(query->init(nm, 1)))
  1264. return false;
  1265. dtQueryFilter f;
  1266. // Iterate over all polys in our navmesh.
  1267. const int MAX_SEGS = 6;
  1268. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1269. {
  1270. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1271. if(!tile->header) continue;
  1272. const dtPolyRef base = nm->getPolyRefBase(tile);
  1273. for(U32 j = 0; j < tile->header->polyCount; ++j)
  1274. {
  1275. const dtPolyRef ref = base | j;
  1276. float segs[MAX_SEGS*6];
  1277. int nsegs = 0;
  1278. query->getPolyWallSegments(ref, &f, segs, NULL, &nsegs, MAX_SEGS);
  1279. for(int segIDx = 0; segIDx < nsegs; ++segIDx)
  1280. {
  1281. const float* sa = &segs[segIDx *6];
  1282. const float* sb = &segs[segIDx *6+3];
  1283. Point3F a = RCtoDTS(sa), b = RCtoDTS(sb);
  1284. F32 len = (b - a).len();
  1285. if(len < mWalkableRadius * 2)
  1286. continue;
  1287. Point3F edge = b - a;
  1288. edge.normalize();
  1289. // Number of points to try placing - for now, one at each end.
  1290. U32 pointCount = (len > mWalkableRadius * 4) ? 2 : 1;
  1291. for(U32 pointIDx = 0; pointIDx < pointCount; pointIDx++)
  1292. {
  1293. MatrixF mat;
  1294. Point3F pos;
  1295. // If we're only placing one point, put it in the middle.
  1296. if(pointCount == 1)
  1297. pos = a + edge * len / 2;
  1298. // Otherwise, stand off from edge ends.
  1299. else
  1300. {
  1301. if(pointIDx % 2)
  1302. pos = a + edge * (pointIDx /2+1) * mWalkableRadius;
  1303. else
  1304. pos = b - edge * (pointIDx /2+1) * mWalkableRadius;
  1305. }
  1306. CoverPointData data;
  1307. if(testEdgeCover(pos, edge, data))
  1308. {
  1309. CoverPoint *m = new CoverPoint();
  1310. if(!m->registerObject())
  1311. delete m;
  1312. else
  1313. {
  1314. m->setTransform(data.trans);
  1315. m->setSize(data.size);
  1316. m->setPeek(data.peek[0], data.peek[1], data.peek[2]);
  1317. if(set)
  1318. set->addObject(m);
  1319. }
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. return true;
  1326. }
  1327. DefineEngineMethod(NavMesh, createCoverPoints, bool, (),,
  1328. "@brief Create cover points for this NavMesh.")
  1329. {
  1330. return object->createCoverPoints();
  1331. }
  1332. bool NavMesh::testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data)
  1333. {
  1334. data.peek[0] = data.peek[1] = data.peek[2] = false;
  1335. // Get the edge normal.
  1336. Point3F norm;
  1337. mCross(dir, Point3F(0, 0, 1), &norm);
  1338. RayInfo ray;
  1339. U32 hits = 0;
  1340. for(U32 j = 0; j < CoverPoint::NumSizes; j++)
  1341. {
  1342. Point3F test = pos + Point3F(0.0f, 0.0f, mWalkableHeight * j / (F32)CoverPoint::NumSizes);
  1343. if(getContainer()->castRay(test, test + norm * mCoverDist, StaticObjectType, &ray))
  1344. {
  1345. // Test peeking.
  1346. Point3F left = test + dir * mPeekDist;
  1347. data.peek[0] = !getContainer()->castRay(test, left, StaticObjectType, &ray)
  1348. && !getContainer()->castRay(left, left + norm * mCoverDist, StaticObjectType, &ray);
  1349. Point3F right = test - dir * mPeekDist;
  1350. data.peek[1] = !getContainer()->castRay(test, right, StaticObjectType, &ray)
  1351. && !getContainer()->castRay(right, right + norm * mCoverDist, StaticObjectType, &ray);
  1352. Point3F over = test + Point3F(0, 0, 1) * 0.2f;
  1353. data.peek[2] = !getContainer()->castRay(test, over, StaticObjectType, &ray)
  1354. && !getContainer()->castRay(over, over + norm * mCoverDist, StaticObjectType, &ray);
  1355. if(mInnerCover || data.peek[0] || data.peek[1] || data.peek[2])
  1356. hits++;
  1357. // If we couldn't peek here, we may be able to peek further up.
  1358. }
  1359. else
  1360. // No cover at this height - break off.
  1361. break;
  1362. }
  1363. if(hits > 0)
  1364. {
  1365. data.size = (CoverPoint::Size)(hits - 1);
  1366. data.trans = MathUtils::createOrientFromDir(norm);
  1367. data.trans.setPosition(pos);
  1368. }
  1369. return hits > 0;
  1370. }
  1371. void NavMesh::renderToDrawer()
  1372. {
  1373. mDbgDraw.clearCache();
  1374. // Recast debug draw
  1375. NetObject* no = getServerObject();
  1376. if (no)
  1377. {
  1378. NavMesh* n = static_cast<NavMesh*>(no);
  1379. mDbgDraw.depthMask(true, true);
  1380. if (n->nm &&
  1381. (m_drawMode == DRAWMODE_NAVMESH ||
  1382. m_drawMode == DRAWMODE_NAVMESH_TRANS ||
  1383. m_drawMode == DRAWMODE_NAVMESH_BVTREE ||
  1384. m_drawMode == DRAWMODE_NAVMESH_NODES ||
  1385. m_drawMode == DRAWMODE_NAVMESH_PORTALS ||
  1386. m_drawMode == DRAWMODE_NAVMESH_INVIS))
  1387. {
  1388. if (m_drawMode != DRAWMODE_NAVMESH_INVIS)
  1389. {
  1390. if (m_drawMode == DRAWMODE_NAVMESH_TRANS)
  1391. mDbgDraw.blend(true);
  1392. duDebugDrawNavMeshWithClosedList(&mDbgDraw, *n->nm, *n->mQuery, 0);
  1393. mDbgDraw.blend(false);
  1394. }
  1395. if(m_drawMode == DRAWMODE_NAVMESH_BVTREE)
  1396. duDebugDrawNavMeshBVTree(&mDbgDraw, *n->nm);
  1397. if(m_drawMode == DRAWMODE_NAVMESH_PORTALS)
  1398. duDebugDrawNavMeshPortals(&mDbgDraw, *n->nm);
  1399. }
  1400. mDbgDraw.depthMask(true, false);
  1401. for (Tile& tile : n->mTiles)
  1402. {
  1403. if (tile.chf && m_drawMode == DRAWMODE_COMPACT)
  1404. {
  1405. duDebugDrawCompactHeightfieldSolid(&mDbgDraw, *tile.chf);
  1406. }
  1407. if (tile.chf && m_drawMode == DRAWMODE_COMPACT_DISTANCE)
  1408. {
  1409. duDebugDrawCompactHeightfieldDistance(&mDbgDraw, *tile.chf);
  1410. }
  1411. if (tile.chf && m_drawMode == DRAWMODE_COMPACT_REGIONS)
  1412. {
  1413. duDebugDrawCompactHeightfieldRegions(&mDbgDraw, *tile.chf);
  1414. }
  1415. if (tile.solid && m_drawMode == DRAWMODE_VOXELS)
  1416. {
  1417. duDebugDrawHeightfieldSolid(&mDbgDraw, *tile.solid);
  1418. }
  1419. if (tile.solid && m_drawMode == DRAWMODE_VOXELS_WALKABLE)
  1420. {
  1421. duDebugDrawHeightfieldWalkable(&mDbgDraw, *tile.solid);
  1422. }
  1423. if (tile.cset && m_drawMode == DRAWMODE_RAW_CONTOURS)
  1424. {
  1425. mDbgDraw.depthMask(false);
  1426. duDebugDrawRawContours(&mDbgDraw, *tile.cset);
  1427. mDbgDraw.depthMask(true);
  1428. }
  1429. if (tile.cset && m_drawMode == DRAWMODE_BOTH_CONTOURS)
  1430. {
  1431. mDbgDraw.depthMask(false);
  1432. duDebugDrawRawContours(&mDbgDraw, *tile.cset);
  1433. duDebugDrawContours(&mDbgDraw, *tile.cset);
  1434. mDbgDraw.depthMask(true);
  1435. }
  1436. if (tile.cset && m_drawMode == DRAWMODE_CONTOURS)
  1437. {
  1438. mDbgDraw.depthMask(false);
  1439. duDebugDrawContours(&mDbgDraw, *tile.cset);
  1440. mDbgDraw.depthMask(true);
  1441. }
  1442. if (tile.chf && tile.cset && m_drawMode == DRAWMODE_REGION_CONNECTIONS)
  1443. {
  1444. duDebugDrawCompactHeightfieldRegions(&mDbgDraw, *tile.chf);
  1445. mDbgDraw.depthMask(false);
  1446. duDebugDrawRegionConnections(&mDbgDraw, *tile.cset);
  1447. mDbgDraw.depthMask(true);
  1448. }
  1449. if (tile.pmesh && m_drawMode == DRAWMODE_POLYMESH)
  1450. {
  1451. mDbgDraw.depthMask(false);
  1452. duDebugDrawPolyMesh(&mDbgDraw, *tile.pmesh);
  1453. mDbgDraw.depthMask(true);
  1454. }
  1455. if (tile.dmesh && m_drawMode == DRAWMODE_POLYMESH_DETAIL)
  1456. {
  1457. mDbgDraw.depthMask(false);
  1458. duDebugDrawPolyMeshDetail(&mDbgDraw, *tile.dmesh);
  1459. mDbgDraw.depthMask(true);
  1460. }
  1461. }
  1462. }
  1463. }
  1464. void NavMesh::cleanup()
  1465. {
  1466. delete[] m_triareas;
  1467. m_triareas = 0;
  1468. rcFreeHeightField(m_solid);
  1469. m_solid = 0;
  1470. rcFreeCompactHeightfield(m_chf);
  1471. m_chf = 0;
  1472. rcFreeContourSet(m_cset);
  1473. m_cset = 0;
  1474. rcFreePolyMesh(m_pmesh);
  1475. m_pmesh = 0;
  1476. rcFreePolyMeshDetail(m_dmesh);
  1477. m_dmesh = 0;
  1478. SAFE_DELETE(m_geo);
  1479. }
  1480. void NavMesh::prepRenderImage(SceneRenderState *state)
  1481. {
  1482. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1483. ri->renderDelegate.bind(this, &NavMesh::render);
  1484. ri->type = RenderPassManager::RIT_Object;
  1485. ri->translucentSort = true;
  1486. ri->defaultKey = 1;
  1487. state->getRenderPass()->addInst(ri);
  1488. }
  1489. void NavMesh::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
  1490. {
  1491. if(overrideMat)
  1492. return;
  1493. if(state->isReflectPass())
  1494. return;
  1495. PROFILE_SCOPE(NavMesh_Render);
  1496. // Recast debug draw
  1497. NetObject *no = getServerObject();
  1498. if(no)
  1499. {
  1500. NavMesh *n = static_cast<NavMesh*>(no);
  1501. if ((!gEditingMission && n->mAlwaysRender) || gEditingMission)
  1502. {
  1503. mDbgDraw.render(state);
  1504. }
  1505. }
  1506. }
  1507. void NavMesh::renderLinks(duDebugDraw &dd)
  1508. {
  1509. if(mBuilding)
  1510. return;
  1511. dd.begin(DU_DRAW_LINES);
  1512. dd.depthMask(false);
  1513. for(U32 i = 0; i < mLinkIDs.size(); i++)
  1514. {
  1515. U32 col = 0;
  1516. switch(mLinkSelectStates[i])
  1517. {
  1518. case Unselected: col = mLinksUnsynced[i] ? duRGBA(255, 0, 0, 200) : duRGBA(0, 0, 255, 255); break;
  1519. case Hovered: col = duRGBA(255, 255, 255, 255); break;
  1520. case Selected: col = duRGBA(0, 255, 0, 255); break;
  1521. }
  1522. F32 *s = &mLinkVerts[i*6];
  1523. F32 *e = &mLinkVerts[i*6 + 3];
  1524. if(!mDeleteLinks[i])
  1525. duAppendCircle(&dd, s[0], s[1], s[2], mLinkRads[i], col);
  1526. duAppendArc(&dd,
  1527. s[0], s[1], s[2],
  1528. e[0], e[1], e[2],
  1529. 0.3f,
  1530. (mLinkDirs[i]&1) ? 0.6f : 0.0f, mLinkFlags[i] == DropFlag ? 0.0f : 0.6f,
  1531. col);
  1532. if(!mDeleteLinks[i])
  1533. duAppendCircle(&dd, e[0], e[1], e[2], mLinkRads[i], col);
  1534. }
  1535. dd.end();
  1536. }
  1537. void NavMesh::renderSearch(duDebugDraw& dd)
  1538. {
  1539. if (mQuery == NULL)
  1540. return;
  1541. if (m_drawMode == DRAWMODE_NAVMESH_NODES)
  1542. duDebugDrawNavMeshNodes(&dd, *mQuery);
  1543. }
  1544. void NavMesh::renderTileData(duDebugDrawTorque &dd, U32 tile)
  1545. {
  1546. if (tile > mTiles.size())
  1547. return;
  1548. if(nm)
  1549. {
  1550. //duDebugDrawNavMesh(&dd, *nm, 0);
  1551. if(mTiles[tile].chf)
  1552. duDebugDrawCompactHeightfieldSolid(&dd, *mTiles[tile].chf);
  1553. duDebugDrawNavMeshPortals(&dd, *nm);
  1554. if (!m_geo)
  1555. return;
  1556. int col = duRGBA(255, 0, 255, 255);
  1557. dd.begin(DU_DRAW_LINES);
  1558. const F32 *verts = m_geo->getVerts();
  1559. const S32 *tris = m_geo->getTris();
  1560. for(U32 t = 0; t < m_geo->getTriCount(); t++)
  1561. {
  1562. dd.vertex(&verts[tris[t*3]*3], col);
  1563. dd.vertex(&verts[tris[t*3+1]*3], col);
  1564. dd.vertex(&verts[tris[t*3+1]*3], col);
  1565. dd.vertex(&verts[tris[t*3+2]*3], col);
  1566. dd.vertex(&verts[tris[t*3+2]*3], col);
  1567. dd.vertex(&verts[tris[t*3]*3], col);
  1568. }
  1569. dd.end();
  1570. }
  1571. }
  1572. void NavMesh::onEditorEnable()
  1573. {
  1574. mNetFlags.set(Ghostable);
  1575. if(isClientObject() && !mAlwaysRender)
  1576. addToScene();
  1577. }
  1578. void NavMesh::onEditorDisable()
  1579. {
  1580. if(!mAlwaysRender)
  1581. {
  1582. mNetFlags.clear(Ghostable);
  1583. if(isClientObject())
  1584. removeFromScene();
  1585. }
  1586. }
  1587. U32 NavMesh::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  1588. {
  1589. U32 retMask = Parent::packUpdate(conn, mask, stream);
  1590. mathWrite(*stream, getTransform());
  1591. mathWrite(*stream, getScale());
  1592. stream->writeFlag(mAlwaysRender);
  1593. stream->write((U32)m_drawMode);
  1594. return retMask;
  1595. }
  1596. void NavMesh::unpackUpdate(NetConnection *conn, BitStream *stream)
  1597. {
  1598. Parent::unpackUpdate(conn, stream);
  1599. mathRead(*stream, &mObjToWorld);
  1600. mathRead(*stream, &mObjScale);
  1601. mAlwaysRender = stream->readFlag();
  1602. setTransform(mObjToWorld);
  1603. U32 draw;
  1604. stream->read(&draw);
  1605. m_drawMode = (DrawMode)draw;
  1606. renderToDrawer();
  1607. }
  1608. static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET';
  1609. static const int NAVMESHSET_VERSION = 1;
  1610. struct NavMeshSetHeader
  1611. {
  1612. int magic;
  1613. int version;
  1614. int numTiles;
  1615. dtNavMeshParams params;
  1616. };
  1617. struct NavMeshTileHeader
  1618. {
  1619. dtTileRef tileRef;
  1620. int dataSize;
  1621. };
  1622. bool NavMesh::load()
  1623. {
  1624. if(!dStrlen(mFileName))
  1625. return false;
  1626. FileStream stream;
  1627. if(!stream.open(mFileName, Torque::FS::File::Read))
  1628. {
  1629. Con::errorf("Could not open file %s when loading navmesh %s.",
  1630. mFileName, getName() ? getName() : getIdString());
  1631. return false;
  1632. }
  1633. // Read header.
  1634. NavMeshSetHeader header;
  1635. stream.read(sizeof(NavMeshSetHeader), (char*)&header);
  1636. if(header.magic != NAVMESHSET_MAGIC)
  1637. {
  1638. stream.close();
  1639. Con::errorf("Navmesh magic incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1640. getName() ? getName() : getIdString(), mFileName);
  1641. return false;
  1642. }
  1643. if(header.version != NAVMESHSET_VERSION)
  1644. {
  1645. stream.close();
  1646. Con::errorf("Navmesh version incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1647. getName() ? getName() : getIdString(), mFileName);
  1648. return false;
  1649. }
  1650. if(nm)
  1651. dtFreeNavMesh(nm);
  1652. nm = dtAllocNavMesh();
  1653. if(!nm)
  1654. {
  1655. stream.close();
  1656. Con::errorf("Out of memory when loading navmesh %s.",
  1657. getName() ? getName() : getIdString());
  1658. return false;
  1659. }
  1660. dtStatus status = nm->init(&header.params);
  1661. if(dtStatusFailed(status))
  1662. {
  1663. stream.close();
  1664. Con::errorf("Failed to initialise navmesh params when loading navmesh %s.",
  1665. getName() ? getName() : getIdString());
  1666. return false;
  1667. }
  1668. // Read tiles.
  1669. for(U32 i = 0; i < header.numTiles; ++i)
  1670. {
  1671. NavMeshTileHeader tileHeader;
  1672. stream.read(sizeof(NavMeshTileHeader), (char*)&tileHeader);
  1673. if(!tileHeader.tileRef || !tileHeader.dataSize)
  1674. break;
  1675. unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
  1676. if(!data) break;
  1677. memset(data, 0, tileHeader.dataSize);
  1678. stream.read(tileHeader.dataSize, (char*)data);
  1679. nm->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
  1680. }
  1681. S32 s;
  1682. stream.read(sizeof(S32), (char*)&s);
  1683. setLinkCount(s);
  1684. if (s > 0)
  1685. {
  1686. stream.read(sizeof(F32) * s * 6, (char*)const_cast<F32*>(mLinkVerts.address()));
  1687. stream.read(sizeof(F32) * s, (char*)const_cast<F32*>(mLinkRads.address()));
  1688. stream.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkDirs.address()));
  1689. stream.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkAreas.address()));
  1690. stream.read(sizeof(U16) * s, (char*)const_cast<U16*>(mLinkFlags.address()));
  1691. stream.read(sizeof(F32) * s, (char*)const_cast<U32*>(mLinkIDs.address()));
  1692. }
  1693. mLinksUnsynced.fill(false);
  1694. mLinkSelectStates.fill(Unselected);
  1695. mDeleteLinks.fill(false);
  1696. stream.close();
  1697. updateTiles();
  1698. if(isServerObject())
  1699. {
  1700. setMaskBits(LoadFlag);
  1701. if(getEventManager())
  1702. getEventManager()->postEvent("NavMeshUpdate", getIdString());
  1703. }
  1704. return true;
  1705. }
  1706. DefineEngineMethod(NavMesh, load, bool, (),,
  1707. "@brief Load this NavMesh from its file.")
  1708. {
  1709. return object->load();
  1710. }
  1711. bool NavMesh::save()
  1712. {
  1713. if (!nm)
  1714. return false;
  1715. if (!dStrlen(mFileName) || !nm)
  1716. {
  1717. createNewFile();
  1718. }
  1719. FileStream stream;
  1720. if(!stream.open(mFileName, Torque::FS::File::Write))
  1721. {
  1722. Con::errorf("Could not open file %s when saving navmesh %s.",
  1723. mFileName, getName() ? getName() : getIdString());
  1724. return false;
  1725. }
  1726. // Store header.
  1727. NavMeshSetHeader header;
  1728. header.magic = NAVMESHSET_MAGIC;
  1729. header.version = NAVMESHSET_VERSION;
  1730. header.numTiles = 0;
  1731. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1732. {
  1733. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1734. if (!tile || !tile->header || !tile->dataSize) continue;
  1735. header.numTiles++;
  1736. }
  1737. memcpy(&header.params, nm->getParams(), sizeof(dtNavMeshParams));
  1738. stream.write(sizeof(NavMeshSetHeader), (const char*)&header);
  1739. // Store tiles.
  1740. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1741. {
  1742. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1743. if(!tile || !tile->header || !tile->dataSize) continue;
  1744. NavMeshTileHeader tileHeader;
  1745. tileHeader.tileRef = nm->getTileRef(tile);
  1746. tileHeader.dataSize = tile->dataSize;
  1747. stream.write(sizeof(tileHeader), (const char*)&tileHeader);
  1748. stream.write(tile->dataSize, (const char*)tile->data);
  1749. }
  1750. S32 s = mLinkIDs.size();
  1751. stream.write(sizeof(S32), (const char*)&s);
  1752. if (s > 0)
  1753. {
  1754. stream.write(sizeof(F32) * s * 6, (const char*)mLinkVerts.address());
  1755. stream.write(sizeof(F32) * s, (const char*)mLinkRads.address());
  1756. stream.write(sizeof(U8) * s, (const char*)mLinkDirs.address());
  1757. stream.write(sizeof(U8) * s, (const char*)mLinkAreas.address());
  1758. stream.write(sizeof(U16) * s, (const char*)mLinkFlags.address());
  1759. stream.write(sizeof(U32) * s, (const char*)mLinkIDs.address());
  1760. }
  1761. stream.close();
  1762. return true;
  1763. }
  1764. DefineEngineMethod(NavMesh, save, void, (),,
  1765. "@brief Save this NavMesh to its file.")
  1766. {
  1767. object->save();
  1768. }
  1769. void NavMesh::write(Stream &stream, U32 tabStop, U32 flags)
  1770. {
  1771. save();
  1772. Parent::write(stream, tabStop, flags);
  1773. }