navMesh.cpp 54 KB

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