navMesh.cpp 53 KB

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