navMesh.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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(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. if(!areas)
  748. {
  749. Con::errorf("Out of memory (area flags) for NavMesh %s", getIdString());
  750. return NULL;
  751. }
  752. dMemset(areas, 0, data.geom.getTriCount() * sizeof(unsigned char));
  753. // Mark walkable triangles with the appropriate area flags, and rasterize.
  754. if(mWaterMethod == Solid)
  755. {
  756. // Treat water as solid: i.e. mark areas as walkable based on angle.
  757. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  758. data.geom.getVerts(), data.geom.getVertCount(),
  759. data.geom.getTris(), data.geom.getTriCount(), areas);
  760. }
  761. else
  762. {
  763. // Treat water as impassable: leave all area flags 0.
  764. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  765. data.geom.getVerts(), nonWaterVertCount,
  766. data.geom.getTris(), nonWaterTriCount, areas);
  767. }
  768. rcRasterizeTriangles(ctx,
  769. data.geom.getVerts(), data.geom.getVertCount(),
  770. data.geom.getTris(), areas, data.geom.getTriCount(),
  771. *data.hf, cfg.walkableClimb);
  772. delete[] areas;
  773. // Filter out areas with low ceilings and other stuff.
  774. rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *data.hf);
  775. rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf);
  776. rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *data.hf);
  777. data.chf = rcAllocCompactHeightfield();
  778. if(!data.chf)
  779. {
  780. Con::errorf("Out of memory (rcCompactHeightField) for NavMesh %s", getIdString());
  781. return NULL;
  782. }
  783. if(!rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf, *data.chf))
  784. {
  785. Con::errorf("Could not generate rcCompactHeightField for NavMesh %s", getIdString());
  786. return NULL;
  787. }
  788. if(!rcErodeWalkableArea(ctx, cfg.walkableRadius, *data.chf))
  789. {
  790. Con::errorf("Could not erode walkable area for NavMesh %s", getIdString());
  791. return NULL;
  792. }
  793. //--------------------------
  794. // Todo: mark areas here.
  795. //const ConvexVolume* vols = m_geom->getConvexVolumes();
  796. //for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
  797. //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
  798. //--------------------------
  799. if(false)
  800. {
  801. if(!rcBuildRegionsMonotone(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  802. {
  803. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  804. return NULL;
  805. }
  806. }
  807. else
  808. {
  809. if(!rcBuildDistanceField(ctx, *data.chf))
  810. {
  811. Con::errorf("Could not build distance field for NavMesh %s", getIdString());
  812. return NULL;
  813. }
  814. if(!rcBuildRegions(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  815. {
  816. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  817. return NULL;
  818. }
  819. }
  820. data.cs = rcAllocContourSet();
  821. if(!data.cs)
  822. {
  823. Con::errorf("Out of memory (rcContourSet) for NavMesh %s", getIdString());
  824. return NULL;
  825. }
  826. if(!rcBuildContours(ctx, *data.chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *data.cs))
  827. {
  828. Con::errorf("Could not construct rcContourSet for NavMesh %s", getIdString());
  829. return NULL;
  830. }
  831. if(data.cs->nconts <= 0)
  832. {
  833. Con::errorf("No contours in rcContourSet for NavMesh %s", getIdString());
  834. return NULL;
  835. }
  836. data.pm = rcAllocPolyMesh();
  837. if(!data.pm)
  838. {
  839. Con::errorf("Out of memory (rcPolyMesh) for NavMesh %s", getIdString());
  840. return NULL;
  841. }
  842. if(!rcBuildPolyMesh(ctx, *data.cs, cfg.maxVertsPerPoly, *data.pm))
  843. {
  844. Con::errorf("Could not construct rcPolyMesh for NavMesh %s", getIdString());
  845. return NULL;
  846. }
  847. data.pmd = rcAllocPolyMeshDetail();
  848. if(!data.pmd)
  849. {
  850. Con::errorf("Out of memory (rcPolyMeshDetail) for NavMesh %s", getIdString());
  851. return NULL;
  852. }
  853. if(!rcBuildPolyMeshDetail(ctx, *data.pm, *data.chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *data.pmd))
  854. {
  855. Con::errorf("Could not construct rcPolyMeshDetail for NavMesh %s", getIdString());
  856. return NULL;
  857. }
  858. if(data.pm->nverts >= 0xffff)
  859. {
  860. Con::errorf("Too many vertices in rcPolyMesh for NavMesh %s", getIdString());
  861. return NULL;
  862. }
  863. for(U32 i = 0; i < data.pm->npolys; i++)
  864. {
  865. if(data.pm->areas[i] == RC_WALKABLE_AREA)
  866. data.pm->areas[i] = GroundArea;
  867. if(data.pm->areas[i] == GroundArea)
  868. data.pm->flags[i] |= WalkFlag;
  869. if(data.pm->areas[i] == WaterArea)
  870. data.pm->flags[i] |= SwimFlag;
  871. }
  872. unsigned char* navData = 0;
  873. int navDataSize = 0;
  874. dtNavMeshCreateParams params;
  875. dMemset(&params, 0, sizeof(params));
  876. params.verts = data.pm->verts;
  877. params.vertCount = data.pm->nverts;
  878. params.polys = data.pm->polys;
  879. params.polyAreas = data.pm->areas;
  880. params.polyFlags = data.pm->flags;
  881. params.polyCount = data.pm->npolys;
  882. params.nvp = data.pm->nvp;
  883. params.detailMeshes = data.pmd->meshes;
  884. params.detailVerts = data.pmd->verts;
  885. params.detailVertsCount = data.pmd->nverts;
  886. params.detailTris = data.pmd->tris;
  887. params.detailTriCount = data.pmd->ntris;
  888. params.offMeshConVerts = mLinkVerts.address();
  889. params.offMeshConRad = mLinkRads.address();
  890. params.offMeshConDir = mLinkDirs.address();
  891. params.offMeshConAreas = mLinkAreas.address();
  892. params.offMeshConFlags = mLinkFlags.address();
  893. params.offMeshConUserID = mLinkIDs.address();
  894. params.offMeshConCount = mLinkIDs.size();
  895. params.walkableHeight = mWalkableHeight;
  896. params.walkableRadius = mWalkableRadius;
  897. params.walkableClimb = mWalkableClimb;
  898. params.tileX = tile.x;
  899. params.tileY = tile.y;
  900. params.tileLayer = 0;
  901. rcVcopy(params.bmin, data.pm->bmin);
  902. rcVcopy(params.bmax, data.pm->bmax);
  903. params.cs = cfg.cs;
  904. params.ch = cfg.ch;
  905. params.buildBvTree = true;
  906. if(!dtCreateNavMeshData(&params, &navData, &navDataSize))
  907. {
  908. Con::errorf("Could not create dtNavMeshData for tile (%d, %d) of NavMesh %s",
  909. tile.x, tile.y, getIdString());
  910. return NULL;
  911. }
  912. dataSize = navDataSize;
  913. return navData;
  914. }
  915. /// This method should never be called in a separate thread to the rendering
  916. /// or pathfinding logic. It directly replaces data in the dtNavMesh for
  917. /// this NavMesh object.
  918. void NavMesh::buildTiles(const Box3F &box)
  919. {
  920. // Make sure we've already built or loaded.
  921. if(!nm)
  922. return;
  923. // Iterate over tiles.
  924. for(U32 i = 0; i < mTiles.size(); i++)
  925. {
  926. const Tile &tile = mTiles[i];
  927. // Check tile box.
  928. if(!tile.box.isOverlapped(box))
  929. continue;
  930. // Mark as dirty.
  931. mDirtyTiles.push(i);
  932. }
  933. if(mDirtyTiles.size())
  934. ctx->startTimer(RC_TIMER_TOTAL);
  935. }
  936. DefineEngineMethod(NavMesh, buildTiles, void, (Box3F box),,
  937. "@brief Rebuild the tiles overlapped by the input box.")
  938. {
  939. return object->buildTiles(box);
  940. }
  941. void NavMesh::buildTile(const U32 &tile)
  942. {
  943. if(tile < mTiles.size())
  944. {
  945. mDirtyTiles.push(tile);
  946. ctx->startTimer(RC_TIMER_TOTAL);
  947. }
  948. }
  949. void NavMesh::buildLinks()
  950. {
  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. // Iterate over links
  959. for(U32 j = 0; j < mLinkIDs.size(); j++)
  960. {
  961. if(tile.box.isContained(getLinkStart(j)) ||
  962. tile.box.isContained(getLinkEnd(j)) &&
  963. mLinksUnsynced[j])
  964. {
  965. // Mark tile for build.
  966. mDirtyTiles.push(i);
  967. // Delete link if necessary
  968. if(mDeleteLinks[j])
  969. {
  970. eraseLink(j);
  971. j--;
  972. }
  973. else
  974. mLinksUnsynced[j] = false;
  975. }
  976. }
  977. }
  978. if(mDirtyTiles.size())
  979. ctx->startTimer(RC_TIMER_TOTAL);
  980. }
  981. DefineEngineMethod(NavMesh, buildLinks, void, (),,
  982. "@brief Build tiles of this mesh where there are unsynchronised links.")
  983. {
  984. object->buildLinks();
  985. }
  986. void NavMesh::deleteCoverPoints()
  987. {
  988. SimSet *set = NULL;
  989. if(Sim::findObject(mCoverSet, set))
  990. set->deleteAllObjects();
  991. }
  992. DefineEngineMethod(NavMesh, deleteCoverPoints, void, (),,
  993. "@brief Remove all cover points for this NavMesh.")
  994. {
  995. object->deleteCoverPoints();
  996. }
  997. bool NavMesh::createCoverPoints()
  998. {
  999. if(!nm || !isServerObject())
  1000. return false;
  1001. SimSet *set = NULL;
  1002. if(Sim::findObject(mCoverSet, set))
  1003. {
  1004. set->deleteAllObjects();
  1005. }
  1006. else
  1007. {
  1008. set = new SimGroup();
  1009. if(set->registerObject(mCoverSet))
  1010. {
  1011. getGroup()->addObject(set);
  1012. }
  1013. else
  1014. {
  1015. delete set;
  1016. set = getGroup();
  1017. }
  1018. }
  1019. dtNavMeshQuery *query = dtAllocNavMeshQuery();
  1020. if(!query || dtStatusFailed(query->init(nm, 1)))
  1021. return false;
  1022. dtQueryFilter f;
  1023. // Iterate over all polys in our navmesh.
  1024. const int MAX_SEGS = 6;
  1025. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1026. {
  1027. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1028. if(!tile->header) continue;
  1029. const dtPolyRef base = nm->getPolyRefBase(tile);
  1030. for(U32 j = 0; j < tile->header->polyCount; ++j)
  1031. {
  1032. const dtPolyRef ref = base | j;
  1033. float segs[MAX_SEGS*6];
  1034. int nsegs = 0;
  1035. query->getPolyWallSegments(ref, &f, segs, NULL, &nsegs, MAX_SEGS);
  1036. for(int j = 0; j < nsegs; ++j)
  1037. {
  1038. const float* sa = &segs[j*6];
  1039. const float* sb = &segs[j*6+3];
  1040. Point3F a = RCtoDTS(sa), b = RCtoDTS(sb);
  1041. F32 len = (b - a).len();
  1042. if(len < mWalkableRadius * 2)
  1043. continue;
  1044. Point3F edge = b - a;
  1045. edge.normalize();
  1046. // Number of points to try placing - for now, one at each end.
  1047. U32 pointCount = (len > mWalkableRadius * 4) ? 2 : 1;
  1048. for(U32 i = 0; i < pointCount; i++)
  1049. {
  1050. MatrixF mat;
  1051. Point3F pos;
  1052. // If we're only placing one point, put it in the middle.
  1053. if(pointCount == 1)
  1054. pos = a + edge * len / 2;
  1055. // Otherwise, stand off from edge ends.
  1056. else
  1057. {
  1058. if(i % 2)
  1059. pos = a + edge * (i/2+1) * mWalkableRadius;
  1060. else
  1061. pos = b - edge * (i/2+1) * mWalkableRadius;
  1062. }
  1063. CoverPointData data;
  1064. if(testEdgeCover(pos, edge, data))
  1065. {
  1066. CoverPoint *m = new CoverPoint();
  1067. if(!m->registerObject())
  1068. delete m;
  1069. else
  1070. {
  1071. m->setTransform(data.trans);
  1072. m->setSize(data.size);
  1073. m->setPeek(data.peek[0], data.peek[1], data.peek[2]);
  1074. if(set)
  1075. set->addObject(m);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. return true;
  1083. }
  1084. DefineEngineMethod(NavMesh, createCoverPoints, bool, (),,
  1085. "@brief Create cover points for this NavMesh.")
  1086. {
  1087. return object->createCoverPoints();
  1088. }
  1089. bool NavMesh::testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data)
  1090. {
  1091. data.peek[0] = data.peek[1] = data.peek[2] = false;
  1092. // Get the edge normal.
  1093. Point3F norm;
  1094. mCross(dir, Point3F(0, 0, 1), &norm);
  1095. RayInfo ray;
  1096. U32 hits = 0;
  1097. for(U32 j = 0; j < CoverPoint::NumSizes; j++)
  1098. {
  1099. Point3F test = pos + Point3F(0.0f, 0.0f, mWalkableHeight * j / CoverPoint::NumSizes);
  1100. if(getContainer()->castRay(test, test + norm * mCoverDist, StaticObjectType, &ray))
  1101. {
  1102. // Test peeking.
  1103. Point3F left = test + dir * mPeekDist;
  1104. data.peek[0] = !getContainer()->castRay(test, left, StaticObjectType, &ray)
  1105. && !getContainer()->castRay(left, left + norm * mCoverDist, StaticObjectType, &ray);
  1106. Point3F right = test - dir * mPeekDist;
  1107. data.peek[1] = !getContainer()->castRay(test, right, StaticObjectType, &ray)
  1108. && !getContainer()->castRay(right, right + norm * mCoverDist, StaticObjectType, &ray);
  1109. Point3F over = test + Point3F(0, 0, 1) * 0.2f;
  1110. data.peek[2] = !getContainer()->castRay(test, over, StaticObjectType, &ray)
  1111. && !getContainer()->castRay(over, over + norm * mCoverDist, StaticObjectType, &ray);
  1112. if(mInnerCover || data.peek[0] || data.peek[1] || data.peek[2])
  1113. hits++;
  1114. // If we couldn't peek here, we may be able to peek further up.
  1115. }
  1116. else
  1117. // No cover at this height - break off.
  1118. break;
  1119. }
  1120. if(hits > 0)
  1121. {
  1122. data.size = (CoverPoint::Size)(hits - 1);
  1123. data.trans = MathUtils::createOrientFromDir(norm);
  1124. data.trans.setPosition(pos);
  1125. }
  1126. return hits > 0;
  1127. }
  1128. void NavMesh::renderToDrawer()
  1129. {
  1130. dd.clear();
  1131. // Recast debug draw
  1132. NetObject *no = getServerObject();
  1133. if(no)
  1134. {
  1135. NavMesh *n = static_cast<NavMesh*>(no);
  1136. if(n->nm)
  1137. {
  1138. dd.beginGroup(0);
  1139. duDebugDrawNavMesh (&dd, *n->nm, 0);
  1140. dd.beginGroup(1);
  1141. duDebugDrawNavMeshPortals(&dd, *n->nm);
  1142. dd.beginGroup(2);
  1143. duDebugDrawNavMeshBVTree (&dd, *n->nm);
  1144. }
  1145. }
  1146. }
  1147. void NavMesh::prepRenderImage(SceneRenderState *state)
  1148. {
  1149. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1150. ri->renderDelegate.bind(this, &NavMesh::render);
  1151. ri->type = RenderPassManager::RIT_Object;
  1152. ri->translucentSort = true;
  1153. ri->defaultKey = 1;
  1154. state->getRenderPass()->addInst(ri);
  1155. }
  1156. void NavMesh::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
  1157. {
  1158. if(overrideMat)
  1159. return;
  1160. if(state->isReflectPass())
  1161. return;
  1162. PROFILE_SCOPE(NavMesh_Render);
  1163. // Recast debug draw
  1164. NetObject *no = getServerObject();
  1165. if(no)
  1166. {
  1167. NavMesh *n = static_cast<NavMesh*>(no);
  1168. if(n->isSelected())
  1169. {
  1170. GFXDrawUtil *drawer = GFX->getDrawUtil();
  1171. GFXStateBlockDesc desc;
  1172. desc.setZReadWrite(true, false);
  1173. desc.setBlend(true);
  1174. desc.setCullMode(GFXCullNone);
  1175. drawer->drawCube(desc, getWorldBox(), n->mBuilding
  1176. ? ColorI(255, 0, 0, 80)
  1177. : ColorI(136, 228, 255, 45));
  1178. desc.setFillModeWireframe();
  1179. drawer->drawCube(desc, getWorldBox(), ColorI::BLACK);
  1180. }
  1181. if(n->mBuilding)
  1182. {
  1183. int alpha = 80;
  1184. if(!n->isSelected() || !Con::getBoolVariable("$Nav::EditorOpen"))
  1185. alpha = 20;
  1186. dd.overrideColor(duRGBA(255, 0, 0, alpha));
  1187. }
  1188. else
  1189. {
  1190. dd.cancelOverride();
  1191. }
  1192. if((!gEditingMission && n->mAlwaysRender) || (gEditingMission && Con::getBoolVariable("$Nav::Editor::renderMesh", 1))) dd.renderGroup(0);
  1193. if(Con::getBoolVariable("$Nav::Editor::renderPortals")) dd.renderGroup(1);
  1194. if(Con::getBoolVariable("$Nav::Editor::renderBVTree")) dd.renderGroup(2);
  1195. }
  1196. }
  1197. void NavMesh::renderLinks(duDebugDraw &dd)
  1198. {
  1199. if(mBuilding)
  1200. return;
  1201. dd.depthMask(true);
  1202. dd.begin(DU_DRAW_LINES);
  1203. for(U32 i = 0; i < mLinkIDs.size(); i++)
  1204. {
  1205. U32 col = 0;
  1206. switch(mLinkSelectStates[i])
  1207. {
  1208. case Unselected: col = mLinksUnsynced[i] ? duRGBA(255, 0, 0, 200) : duRGBA(0, 0, 255, 255); break;
  1209. case Hovered: col = duRGBA(255, 255, 255, 255); break;
  1210. case Selected: col = duRGBA(0, 255, 0, 255); break;
  1211. }
  1212. F32 *s = &mLinkVerts[i*6];
  1213. F32 *e = &mLinkVerts[i*6 + 3];
  1214. if(!mDeleteLinks[i])
  1215. duAppendCircle(&dd, s[0], s[1], s[2], mLinkRads[i], col);
  1216. duAppendArc(&dd,
  1217. s[0], s[1], s[2],
  1218. e[0], e[1], e[2],
  1219. 0.3f,
  1220. 0.0f, mLinkFlags[i] == DropFlag ? 0.0f : 0.4f,
  1221. col);
  1222. if(!mDeleteLinks[i])
  1223. duAppendCircle(&dd, e[0], e[1], e[2], mLinkRads[i], col);
  1224. }
  1225. dd.end();
  1226. }
  1227. void NavMesh::renderTileData(duDebugDrawTorque &dd, U32 tile)
  1228. {
  1229. if(tile >= mTileData.size())
  1230. return;
  1231. if(nm)
  1232. {
  1233. dd.beginGroup(0);
  1234. if(mTileData[tile].chf) duDebugDrawCompactHeightfieldSolid(&dd, *mTileData[tile].chf);
  1235. dd.beginGroup(1);
  1236. int col = duRGBA(255, 0, 255, 255);
  1237. RecastPolyList &in = mTileData[tile].geom;
  1238. dd.begin(DU_DRAW_LINES);
  1239. const F32 *verts = in.getVerts();
  1240. const S32 *tris = in.getTris();
  1241. for(U32 t = 0; t < in.getTriCount(); t++)
  1242. {
  1243. dd.vertex(&verts[tris[t*3]*3], col);
  1244. dd.vertex(&verts[tris[t*3+1]*3], col);
  1245. dd.vertex(&verts[tris[t*3+1]*3], col);
  1246. dd.vertex(&verts[tris[t*3+2]*3], col);
  1247. dd.vertex(&verts[tris[t*3+2]*3], col);
  1248. dd.vertex(&verts[tris[t*3]*3], col);
  1249. }
  1250. dd.end();
  1251. }
  1252. }
  1253. void NavMesh::onEditorEnable()
  1254. {
  1255. mNetFlags.set(Ghostable);
  1256. if(isClientObject() && !mAlwaysRender)
  1257. addToScene();
  1258. }
  1259. void NavMesh::onEditorDisable()
  1260. {
  1261. if(!mAlwaysRender)
  1262. {
  1263. mNetFlags.clear(Ghostable);
  1264. if(isClientObject())
  1265. removeFromScene();
  1266. }
  1267. }
  1268. U32 NavMesh::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  1269. {
  1270. U32 retMask = Parent::packUpdate(conn, mask, stream);
  1271. mathWrite(*stream, getTransform());
  1272. mathWrite(*stream, getScale());
  1273. stream->writeFlag(mAlwaysRender);
  1274. return retMask;
  1275. }
  1276. void NavMesh::unpackUpdate(NetConnection *conn, BitStream *stream)
  1277. {
  1278. Parent::unpackUpdate(conn, stream);
  1279. mathRead(*stream, &mObjToWorld);
  1280. mathRead(*stream, &mObjScale);
  1281. mAlwaysRender = stream->readFlag();
  1282. setTransform(mObjToWorld);
  1283. renderToDrawer();
  1284. }
  1285. static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET';
  1286. static const int NAVMESHSET_VERSION = 1;
  1287. struct NavMeshSetHeader
  1288. {
  1289. int magic;
  1290. int version;
  1291. int numTiles;
  1292. dtNavMeshParams params;
  1293. };
  1294. struct NavMeshTileHeader
  1295. {
  1296. dtTileRef tileRef;
  1297. int dataSize;
  1298. };
  1299. bool NavMesh::load()
  1300. {
  1301. if(!dStrlen(mFileName))
  1302. return false;
  1303. File file;
  1304. if(file.open(mFileName, File::Read) != File::Ok)
  1305. {
  1306. file.close();
  1307. Con::errorf("Could not open file %s when loading navmesh %s.",
  1308. mFileName, getName() ? getName() : getIdString());
  1309. return false;
  1310. }
  1311. // Read header.
  1312. NavMeshSetHeader header;
  1313. file.read(sizeof(NavMeshSetHeader), (char*)&header);
  1314. if(header.magic != NAVMESHSET_MAGIC)
  1315. {
  1316. file.close();
  1317. Con::errorf("Navmesh magic incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1318. getName() ? getName() : getIdString(), mFileName);
  1319. return false;
  1320. }
  1321. if(header.version != NAVMESHSET_VERSION)
  1322. {
  1323. file.close();
  1324. Con::errorf("Navmesh version incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1325. getName() ? getName() : getIdString(), mFileName);
  1326. return false;
  1327. }
  1328. if(nm)
  1329. dtFreeNavMesh(nm);
  1330. nm = dtAllocNavMesh();
  1331. if(!nm)
  1332. {
  1333. file.close();
  1334. Con::errorf("Out of memory when loading navmesh %s.",
  1335. getName() ? getName() : getIdString());
  1336. return false;
  1337. }
  1338. dtStatus status = nm->init(&header.params);
  1339. if(dtStatusFailed(status))
  1340. {
  1341. file.close();
  1342. Con::errorf("Failed to initialise navmesh params when loading navmesh %s.",
  1343. getName() ? getName() : getIdString());
  1344. return false;
  1345. }
  1346. // Read tiles.
  1347. for(U32 i = 0; i < header.numTiles; ++i)
  1348. {
  1349. NavMeshTileHeader tileHeader;
  1350. file.read(sizeof(NavMeshTileHeader), (char*)&tileHeader);
  1351. if(!tileHeader.tileRef || !tileHeader.dataSize)
  1352. break;
  1353. unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
  1354. if(!data) break;
  1355. memset(data, 0, tileHeader.dataSize);
  1356. file.read(tileHeader.dataSize, (char*)data);
  1357. nm->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
  1358. }
  1359. S32 s;
  1360. file.read(sizeof(S32), (char*)&s);
  1361. setLinkCount(s);
  1362. file.read(sizeof(F32) * s * 6, (char*)const_cast<F32*>(mLinkVerts.address()));
  1363. file.read(sizeof(F32) * s, (char*)const_cast<F32*>(mLinkRads.address()));
  1364. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkDirs.address()));
  1365. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkAreas.address()));
  1366. file.read(sizeof(U16) * s, (char*)const_cast<U16*>(mLinkFlags.address()));
  1367. file.read(sizeof(F32) * s, (char*)const_cast<U32*>(mLinkIDs.address()));
  1368. mLinksUnsynced.fill(false);
  1369. mLinkSelectStates.fill(Unselected);
  1370. mDeleteLinks.fill(false);
  1371. file.close();
  1372. updateTiles();
  1373. if(isServerObject())
  1374. {
  1375. setMaskBits(LoadFlag);
  1376. if(getEventManager())
  1377. getEventManager()->postEvent("NavMeshUpdate", getIdString());
  1378. }
  1379. return true;
  1380. }
  1381. DefineEngineMethod(NavMesh, load, bool, (),,
  1382. "@brief Load this NavMesh from its file.")
  1383. {
  1384. return object->load();
  1385. }
  1386. bool NavMesh::save()
  1387. {
  1388. if(!dStrlen(mFileName) || !nm)
  1389. return false;
  1390. File file;
  1391. if(file.open(mFileName, File::Write) != File::Ok)
  1392. {
  1393. file.close();
  1394. Con::errorf("Could not open file %s when saving navmesh %s.",
  1395. mFileName, getName() ? getName() : getIdString());
  1396. return false;
  1397. }
  1398. // Store header.
  1399. NavMeshSetHeader header;
  1400. header.magic = NAVMESHSET_MAGIC;
  1401. header.version = NAVMESHSET_VERSION;
  1402. header.numTiles = 0;
  1403. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1404. {
  1405. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1406. if (!tile || !tile->header || !tile->dataSize) continue;
  1407. header.numTiles++;
  1408. }
  1409. memcpy(&header.params, nm->getParams(), sizeof(dtNavMeshParams));
  1410. file.write(sizeof(NavMeshSetHeader), (const char*)&header);
  1411. // Store tiles.
  1412. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1413. {
  1414. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1415. if(!tile || !tile->header || !tile->dataSize) continue;
  1416. NavMeshTileHeader tileHeader;
  1417. tileHeader.tileRef = nm->getTileRef(tile);
  1418. tileHeader.dataSize = tile->dataSize;
  1419. file.write(sizeof(tileHeader), (const char*)&tileHeader);
  1420. file.write(tile->dataSize, (const char*)tile->data);
  1421. }
  1422. S32 s = mLinkIDs.size();
  1423. file.write(sizeof(S32), (const char*)&s);
  1424. file.write(sizeof(F32) * s * 6, (const char*)mLinkVerts.address());
  1425. file.write(sizeof(F32) * s, (const char*)mLinkRads.address());
  1426. file.write(sizeof(U8) * s, (const char*)mLinkDirs.address());
  1427. file.write(sizeof(U8) * s, (const char*)mLinkAreas.address());
  1428. file.write(sizeof(U16) * s, (const char*)mLinkFlags.address());
  1429. file.write(sizeof(U32) * s, (const char*)mLinkIDs.address());
  1430. file.close();
  1431. return true;
  1432. }
  1433. DefineEngineMethod(NavMesh, save, void, (),,
  1434. "@brief Save this NavMesh to its file.")
  1435. {
  1436. object->save();
  1437. }
  1438. void NavMesh::write(Stream &stream, U32 tabStop, U32 flags)
  1439. {
  1440. save();
  1441. Parent::write(stream, tabStop, flags);
  1442. }