navMesh.cpp 48 KB

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