navMesh.cpp 47 KB

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