navMesh.cpp 48 KB

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