navMesh.cpp 47 KB

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