tsMeshFit.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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 "platform/platform.h"
  23. #include "console/consoleTypes.h"
  24. #include "core/resourceManager.h"
  25. #include "ts/tsShapeConstruct.h"
  26. #include "console/engineAPI.h"
  27. #define ENABLE_VHACD_IMPLEMENTATION 1
  28. #define VHACD_DISABLE_THREADING 0
  29. #include <VHACD.H>
  30. #include <FloatMath.h>
  31. //-----------------------------------------------------------------------------
  32. static const Point3F sFacePlanes[] = {
  33. Point3F( -1.0f, 0.0f, 0.0f ),
  34. Point3F( 1.0f, 0.0f, 0.0f ),
  35. Point3F( 0.0f, -1.0f, 0.0f ),
  36. Point3F( 0.0f, 1.0f, 0.0f ),
  37. Point3F( 0.0f, 0.0f, -1.0f ),
  38. Point3F( 0.0f, 0.0f, 1.0f ),
  39. };
  40. static const Point3F sXEdgePlanes[] = {
  41. Point3F( 0.0f, -0.7071f, -0.7071f ),
  42. Point3F( 0.0f, -0.7071f, 0.7071f ),
  43. Point3F( 0.0f, 0.7071f, -0.7071f ),
  44. Point3F( 0.0f, 0.7071f, 0.7071f ),
  45. };
  46. static const Point3F sYEdgePlanes[] = {
  47. Point3F( -0.7071f, 0.0f, -0.7071f ),
  48. Point3F( -0.7071f, 0.0f, 0.7071f ),
  49. Point3F( 0.7071f, 0.0f, -0.7071f ),
  50. Point3F( 0.7071f, 0.0f, 0.7071f ),
  51. };
  52. static const Point3F sZEdgePlanes[] = {
  53. Point3F( -0.7071f, -0.7071f, 0.0f ),
  54. Point3F( -0.7071f, 0.7071f, 0.0f ),
  55. Point3F( 0.7071f, -0.7071f, 0.0f ),
  56. Point3F( 0.7071f, 0.7071f, 0.0f ),
  57. };
  58. static const Point3F sCornerPlanes[] = {
  59. Point3F( -0.5774f, -0.5774f, -0.5774f ),
  60. Point3F( -0.5774f, -0.5774f, 0.5774f ),
  61. Point3F( -0.5774f, 0.5774f, -0.5774f ),
  62. Point3F( -0.5774f, 0.5774f, 0.5774f ),
  63. Point3F( 0.5774f, -0.5774f, -0.5774f ),
  64. Point3F( 0.5774f, -0.5774f, 0.5774f ),
  65. Point3F( 0.5774f, 0.5774f, -0.5774f ),
  66. Point3F( 0.5774f, 0.5774f, 0.5774f ),
  67. };
  68. //-----------------------------------------------------------------------------
  69. /** A helper class for fitting primitives (Box, Sphere, Capsule) to a triangulated mesh */
  70. struct PrimFit
  71. {
  72. MatrixF mBoxTransform;
  73. Point3F mBoxSides;
  74. Point3F mSphereCenter;
  75. F32 mSphereRadius;
  76. MatrixF mCapTransform;
  77. F32 mCapRadius;
  78. F32 mCapHeight;
  79. public:
  80. PrimFit() :
  81. mBoxTransform(true), mBoxSides(1,1,1),
  82. mSphereCenter(0,0,0), mSphereRadius(1),
  83. mCapTransform(true), mCapRadius(1), mCapHeight(1)
  84. {
  85. }
  86. inline F32 getBoxVolume() const { return mBoxSides.x * mBoxSides.y * mBoxSides.z; }
  87. inline F32 getSphereVolume() const { return 4.0f / 3.0f * M_PI * mPow( mSphereRadius, 3 ); }
  88. inline F32 getCapsuleVolume() const { return 2 * M_PI * mPow( mCapRadius, 2 ) * (4.0f / 3.0f * mCapRadius + mCapHeight); }
  89. void fitBox( U32 vertCount, const F32* verts )
  90. {
  91. FLOAT_MATH::fm_computeBestFitOBB( vertCount, verts, sizeof(F32)*3, (F32*)mBoxSides, (F32*)mBoxTransform, false );
  92. mBoxTransform.transpose();
  93. }
  94. void fitSphere( U32 vertCount, const F32* verts )
  95. {
  96. mSphereRadius = FLOAT_MATH::fm_computeBestFitSphere( vertCount, verts, sizeof(F32)*3, (F32*)mSphereCenter );
  97. }
  98. void fitCapsule( U32 vertCount, const F32* verts )
  99. {
  100. FLOAT_MATH::fm_computeBestFitCapsule( vertCount, verts, sizeof(F32)*3, mCapRadius, mCapHeight, (F32*)mCapTransform );
  101. mCapTransform.transpose();
  102. }
  103. };
  104. class MeshFit
  105. {
  106. public:
  107. enum eMeshType
  108. {
  109. Box = 0,
  110. Sphere,
  111. Capsule,
  112. Hull,
  113. };
  114. struct Mesh
  115. {
  116. eMeshType type;
  117. MatrixF transform;
  118. TSMesh *tsmesh;
  119. };
  120. private:
  121. TSShape *mShape; ///!< Source geometry shape
  122. Vector<Point3F> mVerts; ///!< Source geometry verts (all meshes)
  123. Vector<U32> mIndices; ///!< Source geometry indices (triangle lists, all meshes)
  124. bool mIsReady; ///!< Flag indicating whether we are ready to fit/create meshes
  125. Vector<Mesh> mMeshes; ///!< Fitted meshes
  126. void addSourceMesh( const TSShape::Object& obj, const TSMesh* mesh );
  127. TSMesh* initMeshFromFile( const String& filename ) const;
  128. TSMesh* createTriMesh( F32* verts, S32 numVerts, U32* indices, S32 numTris ) const;
  129. F32 maxDot( const VectorF& v ) const;
  130. void fitK_DOP( const Vector<Point3F>& planes );
  131. public:
  132. MeshFit(TSShape* shape) : mShape(shape), mIsReady(false) { }
  133. void setReady() { mIsReady = true; }
  134. bool isReady() const { return mIsReady; }
  135. void initSourceGeometry( const String& target );
  136. S32 getMeshCount() const { return mMeshes.size(); }
  137. Mesh* getMesh( S32 index ) { return &(mMeshes[index]); }
  138. // Box
  139. void addBox( const Point3F& sides, const MatrixF& mat );
  140. void fitOBB();
  141. // Sphere
  142. void addSphere( F32 radius, const Point3F& center );
  143. void fitSphere();
  144. // Capsule
  145. void addCapsule( F32 radius, F32 height, const MatrixF& mat );
  146. void fitCapsule();
  147. // k-DOP
  148. void fit10_DOP_X();
  149. void fit10_DOP_Y();
  150. void fit10_DOP_Z();
  151. void fit18_DOP();
  152. void fit26_DOP();
  153. // Convex Hulls
  154. void fitConvexHulls( U32 depth, F32 mergeThreshold, F32 concavityThreshold, U32 maxHullVerts,
  155. F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError );
  156. };
  157. void MeshFit::initSourceGeometry( const String& target )
  158. {
  159. mMeshes.clear();
  160. mVerts.clear();
  161. mIndices.clear();
  162. if ( target.equal( "bounds", String::NoCase ) )
  163. {
  164. // Add all geometry in the highest detail level
  165. S32 dl = 0;
  166. S32 ss = mShape->details[dl].subShapeNum;
  167. if ( ss < 0 )
  168. return;
  169. S32 od = mShape->details[dl].objectDetailNum;
  170. S32 start = mShape->subShapeFirstObject[ss];
  171. S32 end = start + mShape->subShapeNumObjects[ss];
  172. for ( S32 i = start; i < end; i++ )
  173. {
  174. const TSShape::Object &obj = mShape->objects[i];
  175. const TSMesh* mesh = ( od < obj.numMeshes ) ? mShape->meshes[obj.startMeshIndex + od] : NULL;
  176. if ( mesh )
  177. addSourceMesh( obj, mesh );
  178. }
  179. }
  180. else
  181. {
  182. // Add highest detail mesh from this object
  183. S32 objIndex = mShape->findObject( target );
  184. if ( objIndex == -1 )
  185. return;
  186. const TSShape::Object &obj = mShape->objects[objIndex];
  187. for ( S32 i = 0; i < obj.numMeshes; i++ )
  188. {
  189. const TSMesh* mesh = mShape->meshes[obj.startMeshIndex + i];
  190. if ( mesh )
  191. {
  192. addSourceMesh( obj, mesh );
  193. break;
  194. }
  195. }
  196. }
  197. mIsReady = ( !mVerts.empty() && !mIndices.empty() );
  198. }
  199. void MeshFit::addSourceMesh( const TSShape::Object& obj, const TSMesh* mesh )
  200. {
  201. // Add indices
  202. S32 indicesBase = mIndices.size();
  203. for ( S32 i = 0; i < mesh->mPrimitives.size(); i++ )
  204. {
  205. const TSDrawPrimitive& draw = mesh->mPrimitives[i];
  206. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  207. {
  208. mIndices.merge( &mesh->mIndices[draw.start], draw.numElements );
  209. }
  210. else
  211. {
  212. U32 idx0 = mesh->mIndices[draw.start + 0];
  213. U32 idx1;
  214. U32 idx2 = mesh->mIndices[draw.start + 1];
  215. U32 *nextIdx = &idx1;
  216. for ( S32 j = 2; j < draw.numElements; j++ )
  217. {
  218. *nextIdx = idx2;
  219. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  220. idx2 = mesh->mIndices[draw.start + j];
  221. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  222. continue;
  223. mIndices.push_back( idx0 );
  224. mIndices.push_back( idx1 );
  225. mIndices.push_back( idx2 );
  226. }
  227. }
  228. }
  229. // Offset indices for already added verts
  230. for ( S32 j = indicesBase; j < mIndices.size(); j++ )
  231. mIndices[j] += mVerts.size();
  232. // Add verts
  233. S32 count, stride;
  234. U8* pVert;
  235. if ( mesh->mVertexData.isReady() && mesh->mVerts.size() == 0 )
  236. {
  237. count = mesh->mVertexData.size();
  238. stride = mesh->mVertexData.vertSize();
  239. pVert = (U8*)mesh->mVertexData.address();
  240. }
  241. else
  242. {
  243. count = mesh->mVerts.size();
  244. stride = sizeof(Point3F);
  245. pVert = (U8*)mesh->mVerts.address();
  246. }
  247. MatrixF objMat;
  248. mShape->getNodeWorldTransform( obj.nodeIndex, &objMat );
  249. mVerts.reserve( mVerts.size() + count );
  250. for ( S32 j = 0; j < count; j++, pVert += stride )
  251. {
  252. mVerts.increment();
  253. objMat.mulP( *(Point3F*)pVert, &mVerts.last() );
  254. }
  255. }
  256. TSMesh* MeshFit::initMeshFromFile( const String& filename ) const
  257. {
  258. // Open the source shape file and make a copy of the mesh
  259. Resource<TSShape> hShape = ResourceManager::get().load(filename);
  260. if (!bool(hShape) || !((TSShape*)hShape)->meshes.size())
  261. {
  262. Con::errorf("TSShape::createMesh: Could not load source mesh from %s", filename.c_str());
  263. return NULL;
  264. }
  265. TSMesh* srcMesh = ((TSShape*)hShape)->meshes[0];
  266. return mShape->copyMesh( srcMesh );
  267. }
  268. TSMesh* MeshFit::createTriMesh( F32* verts, S32 numVerts, U32* indices, S32 numTris ) const
  269. {
  270. TSMesh* mesh = mShape->copyMesh( NULL );
  271. mesh->numFrames = 1;
  272. mesh->numMatFrames = 1;
  273. mesh->vertsPerFrame = numVerts;
  274. mesh->setFlags(0);
  275. mesh->mNumVerts = numVerts;
  276. mesh->mIndices.reserve( numTris * 3 );
  277. for ( S32 i = 0; i < numTris; i++ )
  278. {
  279. mesh->mIndices.push_back( indices[i*3 + 0] );
  280. mesh->mIndices.push_back( indices[i*3 + 2] );
  281. mesh->mIndices.push_back( indices[i*3 + 1] );
  282. }
  283. mesh->mVerts.set( verts, numVerts );
  284. // Compute mesh normals
  285. mesh->mNorms.setSize( mesh->mVerts.size() );
  286. for (S32 iNorm = 0; iNorm < mesh->mNorms.size(); iNorm++)
  287. mesh->mNorms[iNorm] = Point3F::Zero;
  288. // Sum triangle normals for each vertex
  289. for (S32 iInd = 0; iInd < mesh->mIndices.size(); iInd += 3)
  290. {
  291. // Compute the normal for this triangle
  292. S32 idx0 = mesh->mIndices[iInd + 0];
  293. S32 idx1 = mesh->mIndices[iInd + 1];
  294. S32 idx2 = mesh->mIndices[iInd + 2];
  295. const Point3F& v0 = mesh->mVerts[idx0];
  296. const Point3F& v1 = mesh->mVerts[idx1];
  297. const Point3F& v2 = mesh->mVerts[idx2];
  298. Point3F n;
  299. mCross(v2 - v0, v1 - v0, &n);
  300. n.normalize(); // remove this to use 'weighted' normals (large triangles will have more effect)
  301. mesh->mNorms[idx0] += n;
  302. mesh->mNorms[idx1] += n;
  303. mesh->mNorms[idx2] += n;
  304. }
  305. // Normalize the vertex normals (this takes care of averaging the triangle normals)
  306. for (S32 iNorm = 0; iNorm < mesh->mNorms.size(); iNorm++)
  307. mesh->mNorms[iNorm].normalize();
  308. // Set some dummy UVs
  309. mesh->mTverts.setSize( numVerts );
  310. for ( S32 j = 0; j < mesh->mTverts.size(); j++ )
  311. mesh->mTverts[j].set( 0, 0 );
  312. // Add a single triangle-list primitive
  313. mesh->mPrimitives.increment();
  314. mesh->mPrimitives.last().start = 0;
  315. mesh->mPrimitives.last().numElements = mesh->mIndices.size();
  316. mesh->mPrimitives.last().matIndex = TSDrawPrimitive::Triangles |
  317. TSDrawPrimitive::Indexed |
  318. TSDrawPrimitive::NoMaterial;
  319. mesh->createTangents( mesh->mVerts, mesh->mNorms);
  320. mesh->mEncodedNorms.set( NULL,0 );
  321. return mesh;
  322. }
  323. F32 MeshFit::maxDot( const VectorF& v ) const
  324. {
  325. F32 maxDot = -FLT_MAX;
  326. for ( S32 i = 0; i < mVerts.size(); i++ )
  327. maxDot = getMax( maxDot, mDot( v, mVerts[i] ) );
  328. return maxDot;
  329. }
  330. //---------------------------
  331. // Best-fit oriented bounding box
  332. void MeshFit::addBox( const Point3F& sides, const MatrixF& mat )
  333. {
  334. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getCubeShapePath() );
  335. if ( !mesh )
  336. return;
  337. if (mesh->mVerts.size() > 0)
  338. {
  339. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  340. {
  341. Point3F v = mesh->mVerts[i];
  342. v.convolve(sides);
  343. mesh->mVerts[i] = v;
  344. }
  345. mesh->mVertexData.setReady(false);
  346. }
  347. else
  348. {
  349. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  350. {
  351. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  352. Point3F v = vdata.vert();
  353. v.convolve(sides);
  354. vdata.vert(v);
  355. }
  356. }
  357. mesh->computeBounds();
  358. mMeshes.increment();
  359. mMeshes.last().type = MeshFit::Box;
  360. mMeshes.last().transform = mat;
  361. mMeshes.last().tsmesh = mesh;
  362. }
  363. void MeshFit::fitOBB()
  364. {
  365. PrimFit primFitter;
  366. primFitter.fitBox( mVerts.size(), (F32*)mVerts.address() );
  367. addBox( primFitter.mBoxSides, primFitter.mBoxTransform );
  368. }
  369. //---------------------------
  370. // Best-fit sphere
  371. void MeshFit::addSphere( F32 radius, const Point3F& center )
  372. {
  373. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getSphereShapePath() );
  374. if ( !mesh )
  375. return;
  376. for ( S32 i = 0; i < mesh->mVertexData.size(); i++ )
  377. {
  378. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  379. Point3F v = vdata.vert();
  380. vdata.vert( v * radius );
  381. }
  382. mesh->computeBounds();
  383. mMeshes.increment();
  384. MeshFit::Mesh& lastMesh = mMeshes.last();
  385. lastMesh.type = MeshFit::Sphere;
  386. lastMesh.transform.identity();
  387. lastMesh.transform.setPosition(center);
  388. lastMesh.tsmesh = mesh;
  389. }
  390. void MeshFit::fitSphere()
  391. {
  392. PrimFit primFitter;
  393. primFitter.fitSphere( mVerts.size(), (F32*)mVerts.address() );
  394. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  395. }
  396. //---------------------------
  397. // Best-fit capsule
  398. void MeshFit::addCapsule( F32 radius, F32 height, const MatrixF& mat )
  399. {
  400. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getCapsuleShapePath() );
  401. if ( !mesh )
  402. return;
  403. // Translate and scale the mesh verts
  404. height = mMax( 0, height );
  405. F32 offset = ( height / ( 2 * radius ) ) - 0.5f;
  406. for ( S32 i = 0; i < mesh->mVertexData.size(); i++ )
  407. {
  408. Point3F v = mesh->mVertexData.getBase(i).vert();
  409. v.y += ( ( v.y > 0 ) ? offset : -offset );
  410. mesh->mVertexData.getBase(i).vert( v * radius );
  411. }
  412. mesh->computeBounds();
  413. mMeshes.increment();
  414. mMeshes.last().type = MeshFit::Capsule;
  415. mMeshes.last().transform = mat;
  416. mMeshes.last().tsmesh = mesh;
  417. }
  418. void MeshFit::fitCapsule()
  419. {
  420. PrimFit primFitter;
  421. primFitter.fitCapsule( mVerts.size(), (F32*)mVerts.address() );
  422. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  423. }
  424. //---------------------------
  425. // Best-fit k-discrete-oriented-polytope (where k is the number of axis-aligned planes)
  426. // All faces + 4 edges (aligned to X axis) of the unit cube
  427. void MeshFit::fit10_DOP_X()
  428. {
  429. Vector<Point3F> planes;
  430. planes.setSize( 10 );
  431. dCopyArray( planes.address(), sFacePlanes, 6 );
  432. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  433. fitK_DOP( planes );
  434. }
  435. // All faces + 4 edges (aligned to Y axis) of the unit cube
  436. void MeshFit::fit10_DOP_Y()
  437. {
  438. Vector<Point3F> planes;
  439. planes.setSize( 10 );
  440. dCopyArray( planes.address(), sFacePlanes, 6 );
  441. dCopyArray( planes.address()+6, sYEdgePlanes, 4 );
  442. fitK_DOP( planes );
  443. }
  444. // All faces + 4 edges (aligned to Z axis) of the unit cube
  445. void MeshFit::fit10_DOP_Z()
  446. {
  447. Vector<Point3F> planes;
  448. planes.setSize( 10 );
  449. dCopyArray( planes.address(), sFacePlanes, 6 );
  450. dCopyArray( planes.address()+6, sZEdgePlanes, 4 );
  451. fitK_DOP( planes );
  452. }
  453. // All faces and edges of the unit cube
  454. void MeshFit::fit18_DOP()
  455. {
  456. Vector<Point3F> planes;
  457. planes.setSize( 18 );
  458. dCopyArray( planes.address(), sFacePlanes, 6 );
  459. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  460. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  461. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  462. fitK_DOP( planes );
  463. }
  464. // All faces, edges and corners of the unit cube
  465. void MeshFit::fit26_DOP()
  466. {
  467. Vector<Point3F> planes;
  468. planes.setSize( 26 );
  469. dCopyArray( planes.address(), sFacePlanes, 6 );
  470. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  471. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  472. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  473. dCopyArray( planes.address()+18, sCornerPlanes, 8 );
  474. fitK_DOP( planes );
  475. }
  476. void MeshFit::fitK_DOP( const Vector<Point3F>& planes )
  477. {
  478. // Push the planes up against the mesh
  479. Vector<F32> planeDs;
  480. for ( S32 i = 0; i < planes.size(); i++ )
  481. planeDs.push_back( maxDot( planes[i] ) );
  482. // Collect the intersection points of any 3 planes that lie inside
  483. // the maximum distances found above
  484. Vector<Point3F> points;
  485. Vector<U32> pointIndices;
  486. for ( S32 i = 0; i < planes.size()-2; i++ )
  487. {
  488. for ( S32 j = i+1; j < planes.size()-1; j++ )
  489. {
  490. for ( S32 k = j+1; k < planes.size(); k++ )
  491. {
  492. Point3F v23 = mCross( planes[j], planes[k] );
  493. F32 denom = mDot( planes[i], v23 );
  494. if ( denom == 0 )
  495. continue;
  496. Point3F v31 = mCross( planes[k], planes[i] );
  497. Point3F v12 = mCross( planes[i], planes[j] );
  498. Point3F p = ( planeDs[i]*v23 + planeDs[j]*v31 + planeDs[k]*v12 ) / denom;
  499. // Ignore intersection points outside the volume
  500. // described by the planes
  501. bool addPoint = true;
  502. for ( S32 n = 0; n < planes.size(); n++ )
  503. {
  504. if ( ( mDot( p, planes[n] ) - planeDs[n] ) > 0.005f )
  505. {
  506. addPoint = false;
  507. break;
  508. }
  509. }
  510. if (addPoint)
  511. {
  512. points.push_back(p);
  513. pointIndices.push_back(points.size() - 1);
  514. }
  515. }
  516. }
  517. }
  518. VHACD::IVHACD::Parameters p;
  519. p.m_fillMode = VHACD::FillMode::FLOOD_FILL;
  520. p.m_maxNumVerticesPerCH = 64;
  521. p.m_shrinkWrap = true;
  522. p.m_maxRecursionDepth = 64;
  523. p.m_minimumVolumePercentErrorAllowed = 10;
  524. p.m_resolution = 10000;
  525. p.m_maxConvexHulls = 1;
  526. VHACD::IVHACD* iface = VHACD::CreateVHACD();
  527. iface->Compute((F32*)points.address(), points.size(), (U32*)pointIndices.address(), pointIndices.size() / 3, p);
  528. // safety loop.
  529. while (!iface->IsReady())
  530. {
  531. Platform::sleep(1000);
  532. }
  533. // we only get the 1 in dop?
  534. VHACD::IVHACD::ConvexHull ch;
  535. iface->GetConvexHull(0, ch);
  536. // Create TSMesh from convex hull
  537. mMeshes.increment();
  538. MeshFit::Mesh& lastMesh = mMeshes.last();
  539. lastMesh.type = MeshFit::Hull;
  540. lastMesh.transform.identity();
  541. U32* indices = new U32[ch.m_triangles.size() * 3];
  542. for (U32 i = 0; i < ch.m_triangles.size(); i++)
  543. {
  544. indices[i * 3 + 0] = ch.m_triangles[i].mI0;
  545. indices[i * 3 + 1] = ch.m_triangles[i].mI1;
  546. indices[i * 3 + 2] = ch.m_triangles[i].mI2;
  547. }
  548. F32* resultPts = new F32[ch.m_points.size() * 3];
  549. for (U32 i = 0; i < ch.m_points.size(); i++)
  550. {
  551. resultPts[i * 3 + 0] = ch.m_points[i].mX;
  552. resultPts[i * 3 + 1] = ch.m_points[i].mY;
  553. resultPts[i * 3 + 2] = ch.m_points[i].mZ;
  554. }
  555. lastMesh.tsmesh = createTriMesh(resultPts, ch.m_points.size(),
  556. indices, ch.m_triangles.size());
  557. lastMesh.tsmesh->computeBounds();
  558. iface->Release();
  559. delete[] resultPts;
  560. delete[] indices;
  561. }
  562. //---------------------------
  563. // Best-fit set of convex hulls
  564. void MeshFit::fitConvexHulls( U32 depth, F32 mergeThreshold, F32 concavityThreshold, U32 maxHullVerts,
  565. F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError )
  566. {
  567. const F32 SkinWidth = 0.0f;
  568. const F32 SplitThreshold = 2.0f;
  569. VHACD::IVHACD::Parameters p;
  570. p.m_fillMode = VHACD::FillMode::FLOOD_FILL;
  571. p.m_maxNumVerticesPerCH = maxHullVerts;
  572. p.m_shrinkWrap = true;
  573. p.m_maxRecursionDepth = 64;
  574. p.m_minimumVolumePercentErrorAllowed = 10;
  575. p.m_resolution = 10000;
  576. p.m_maxConvexHulls = depth;
  577. VHACD::IVHACD* iface = VHACD::CreateVHACD_ASYNC();
  578. iface->Compute((F32*)mVerts.address(), mVerts.size(), mIndices.address(), mIndices.size() / 3, p);
  579. // safety loop.
  580. while (!iface->IsReady())
  581. {
  582. Platform::sleep(1000);
  583. }
  584. // Add a TSMesh for each hull
  585. for ( S32 i = 0; i < iface->GetNConvexHulls(); i++ )
  586. {
  587. VHACD::IVHACD::ConvexHull ch;
  588. iface->GetConvexHull(i, ch);
  589. eMeshType meshType = MeshFit::Hull;
  590. // Check if we can use a box, sphere or capsule primitive for this hull
  591. if (( boxMaxError > 0 ) || ( sphereMaxError > 0 ) || ( capsuleMaxError > 0 ))
  592. {
  593. // Compute error between actual mesh and fitted primitives
  594. F32* points = new F32[ch.m_points.size() * 3];
  595. for (U32 i = 0; i < ch.m_points.size(); i++)
  596. {
  597. points[i * 3 + 0] = ch.m_points[i].mX;
  598. points[i * 3 + 1] = ch.m_points[i].mY;
  599. points[i * 3 + 2] = ch.m_points[i].mZ;
  600. }
  601. U32* indices = new U32[ch.m_triangles.size() * 3];
  602. for (U32 i = 0; i < ch.m_triangles.size(); i++)
  603. {
  604. indices[i * 3 + 0] = ch.m_triangles[i].mI0;
  605. indices[i * 3 + 1] = ch.m_triangles[i].mI1;
  606. indices[i * 3 + 2] = ch.m_triangles[i].mI2;
  607. }
  608. F32 meshVolume = FLOAT_MATH::fm_computeMeshVolume(points, ch.m_triangles.size(), indices);
  609. PrimFit primFitter;
  610. F32 boxError = 100.0f, sphereError = 100.0f, capsuleError = 100.0f;
  611. if ( boxMaxError > 0 )
  612. {
  613. primFitter.fitBox(ch.m_points.size(), points);
  614. boxError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getBoxVolume() ) );
  615. }
  616. if ( sphereMaxError > 0 )
  617. {
  618. primFitter.fitSphere(ch.m_points.size(), points);
  619. sphereError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getSphereVolume() ) );
  620. }
  621. if ( capsuleMaxError > 0 )
  622. {
  623. primFitter.fitCapsule(ch.m_points.size(), points);
  624. capsuleError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getCapsuleVolume() ) );
  625. }
  626. // Use the primitive type with smallest error less than the respective
  627. // max error, or Hull if none
  628. F32 minError = FLT_MAX;
  629. if ( ( boxError < boxMaxError ) && ( boxError < minError ) )
  630. {
  631. meshType = MeshFit::Box;
  632. minError = boxError;
  633. }
  634. if ( ( sphereError < sphereMaxError ) && ( sphereError < minError ) )
  635. {
  636. meshType = MeshFit::Sphere;
  637. minError = sphereError;
  638. }
  639. if ( ( capsuleError < capsuleMaxError ) && ( capsuleError < minError ) )
  640. {
  641. meshType = MeshFit::Capsule;
  642. minError = capsuleError;
  643. }
  644. if ( meshType == MeshFit::Box )
  645. addBox( primFitter.mBoxSides, primFitter.mBoxTransform );
  646. else if ( meshType == MeshFit::Sphere )
  647. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  648. else if ( meshType == MeshFit::Capsule )
  649. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  650. // else fall through to Hull processing
  651. }
  652. if ( meshType == MeshFit::Hull )
  653. {
  654. // Create TSMesh from convex hull
  655. mMeshes.increment();
  656. MeshFit::Mesh& lastMesh = mMeshes.last();
  657. lastMesh.type = MeshFit::Hull;
  658. lastMesh.transform.identity();
  659. U32* indices = new U32[ch.m_triangles.size() * 3];
  660. for (U32 i = 0; i < ch.m_triangles.size(); i++)
  661. {
  662. indices[i * 3 + 0] = ch.m_triangles[i].mI0;
  663. indices[i * 3 + 1] = ch.m_triangles[i].mI1;
  664. indices[i * 3 + 2] = ch.m_triangles[i].mI2;
  665. }
  666. F32* points = new F32[ch.m_points.size() * 3];
  667. for (U32 i = 0; i < ch.m_points.size(); i++)
  668. {
  669. points[i * 3 + 0] = ch.m_points[i].mX;
  670. points[i * 3 + 1] = ch.m_points[i].mY;
  671. points[i * 3 + 2] = ch.m_points[i].mZ;
  672. }
  673. lastMesh.tsmesh = createTriMesh(points, ch.m_points.size(), indices, ch.m_triangles.size());
  674. lastMesh.tsmesh->computeBounds();
  675. delete[] points;
  676. delete[] indices;
  677. }
  678. }
  679. iface->Release();
  680. }
  681. //-----------------------------------------------------------------------------
  682. DefineTSShapeConstructorMethod( addPrimitive, bool, ( const char* meshName, const char* type, const char* params, TransformF txfm, const char* nodeName ),,
  683. ( meshName, type, params, txfm, nodeName ), false,
  684. "Add a new mesh primitive to the shape.\n"
  685. "@param meshName full name (object name + detail size) of the new mesh. If "
  686. "no detail size is present at the end of the name, a value of 2 is used.<br>"
  687. "An underscore before the number at the end of the name will be interpreted as "
  688. "a negative sign. eg. \"MyMesh_4\" will be interpreted as \"MyMesh-4\".\n"
  689. "@param type one of: \"box\", \"sphere\", \"capsule\"\n"
  690. "@param params mesh primitive parameters:\n"
  691. "<ul>"
  692. "<li>for box: \"size_x size_y size_z\"</li>"
  693. "<li>for sphere: \"radius\"</li>"
  694. "<li>for capsule: \"height radius\"</li>"
  695. "</ul>"
  696. "</ul>\n"
  697. "@param txfm local transform offset from the node for this mesh\n"
  698. "@param nodeName name of the node to attach the new mesh to (will change the "
  699. "object's node if adding a new mesh to an existing object)\n"
  700. "@return true if successful, false otherwise\n\n"
  701. "@tsexample\n"
  702. "%this.addMesh( \"Box4\", \"box\", \"2 4 2\", \"0 2 0 0 0 1 0\", \"eye\" );\n"
  703. "%this.addMesh( \"Sphere256\", \"sphere\", \"2\", \"0 0 0 0 0 1 0\", \"root\" );\n"
  704. "%this.addMesh( \"MyCapsule-1\", \"capsule\", \"2 5\", \"0 0 2 0 0 1 0\", \"base01\" );\n"
  705. "@endtsexample\n" )
  706. {
  707. MeshFit fit( mShape );
  708. if ( !dStricmp( type, "box" ) )
  709. {
  710. // Parse box parameters
  711. Point3F sides;
  712. if ( dSscanf( params, "%g %g %g", &sides.x, &sides.y, &sides.z ) == 3 )
  713. {
  714. fit.addBox( sides, MatrixF::Identity );
  715. fit.setReady();
  716. }
  717. }
  718. else if ( !dStricmp( type, "sphere" ) )
  719. {
  720. // Parse sphere parameters
  721. F32 radius;
  722. if ( dSscanf( params, "%g", &radius ) == 1)
  723. {
  724. fit.addSphere( radius, Point3F::Zero );
  725. fit.setReady();
  726. }
  727. }
  728. else if ( !dStricmp( type, "capsule" ) )
  729. {
  730. // Parse capsule parameters
  731. F32 radius, height;
  732. if ( dSscanf( params, "%g %g", &radius, &height ) == 1)
  733. {
  734. fit.addCapsule( radius, height, MatrixF::Identity );
  735. fit.setReady();
  736. }
  737. }
  738. if ( !fit.isReady() )
  739. {
  740. Con::errorf( "TSShapeConstructor::addPrimitive: Invalid params: '%s' for type '%s'",
  741. params, type );
  742. return false;
  743. }
  744. TSMesh* mesh = fit.getMesh( 0 )->tsmesh;
  745. MatrixF mat( txfm.getMatrix() );
  746. // Transform the mesh vertices
  747. if ( mesh->mVertexData.isReady() && mesh->mVerts.size() == 0 )
  748. {
  749. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  750. {
  751. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  752. Point3F v;
  753. mat.mulP( vdata.vert(), &v );
  754. vdata.vert( v );
  755. }
  756. }
  757. else
  758. {
  759. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  760. {
  761. Point3F v(mesh->mVerts[i]);
  762. mat.mulP( v, &mesh->mVerts[i] );
  763. }
  764. }
  765. // Add the mesh to the shape at the right node
  766. mShape->addMesh( mesh, meshName );
  767. S32 dummy;
  768. String objName = String::GetTrailingNumber( meshName, dummy );
  769. setObjectNode( objName, nodeName );
  770. mShape->init();
  771. ADD_TO_CHANGE_SET();
  772. return true;
  773. }}
  774. DefineTSShapeConstructorMethod( addCollisionDetail, bool, ( S32 size, const char* type, const char* target, S32 depth, F32 merge, F32 concavity, S32 maxVerts, F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError ), ( 4, 30, 30, 32, 0, 0, 0 ),
  775. ( size, type, target, depth, merge, concavity, maxVerts, boxMaxError, sphereMaxError, capsuleMaxError ), false,
  776. "Autofit a mesh primitive or set of convex hulls to the shape geometry. Hulls "
  777. "may optionally be converted to boxes, spheres and/or capsules based on their "
  778. "volume.\n"
  779. "@param size size for this detail level\n"
  780. "@param type one of: box, sphere, capsule, 10-dop x, 10-dop y, 10-dop z, 18-dop, "
  781. "26-dop, convex hulls. See the Shape Editor documentation for more details "
  782. "about these types.\n"
  783. "@param target geometry to fit collision mesh(es) to; either \"bounds\" (for the "
  784. "whole shape), or the name of an object in the shape\n"
  785. "@param depth maximum split recursion depth (hulls only)\n"
  786. "@param merge volume % threshold used to merge hulls together (hulls only)\n"
  787. "@param concavity volume % threshold used to detect concavity (hulls only)\n"
  788. "@param maxVerts maximum number of vertices per hull (hulls only)\n"
  789. "@param boxMaxError max % volume difference for a hull to be converted to a "
  790. "box (hulls only)\n"
  791. "@param sphereMaxError max % volume difference for a hull to be converted to "
  792. "a sphere (hulls only)\n"
  793. "@param capsuleMaxError max % volume difference for a hull to be converted to "
  794. "a capsule (hulls only)\n"
  795. "@return true if successful, false otherwise\n\n"
  796. "@tsexample\n"
  797. "%this.addCollisionDetail( -1, \"box\", \"bounds\" );\n"
  798. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 0, 0, 0 );\n"
  799. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 50, 50, 50 );\n"
  800. "@endtsexample\n" )
  801. {
  802. MeshFit fit( mShape );
  803. fit.initSourceGeometry( target );
  804. if ( !fit.isReady() )
  805. {
  806. Con::errorf( "TSShapeConstructor::addCollisionDetail: Failed to initialise mesh fitter "
  807. "using target: %s", target );
  808. return false;
  809. }
  810. if ( !dStricmp( type, "box" ) )
  811. fit.fitOBB();
  812. else if ( !dStricmp( type, "sphere" ) )
  813. fit.fitSphere();
  814. else if ( !dStricmp( type, "capsule" ) )
  815. fit.fitCapsule();
  816. else if ( !dStricmp( type, "10-dop x" ) )
  817. fit.fit10_DOP_X();
  818. else if ( !dStricmp( type, "10-dop y" ) )
  819. fit.fit10_DOP_Y();
  820. else if ( !dStricmp( type, "10-dop z" ) )
  821. fit.fit10_DOP_Z();
  822. else if ( !dStricmp( type, "18-dop" ) )
  823. fit.fit18_DOP();
  824. else if ( !dStricmp( type, "26-dop" ) )
  825. fit.fit26_DOP();
  826. else if ( !dStricmp( type, "convex hulls" ) )
  827. {
  828. fit.fitConvexHulls( depth, merge, concavity, maxVerts,
  829. boxMaxError, sphereMaxError, capsuleMaxError );
  830. }
  831. else
  832. {
  833. Con::errorf( "TSShape::addCollisionDetail: Invalid type: '%s'", type );
  834. return false;
  835. }
  836. // Now add the fitted meshes to the shape:
  837. // - primitives (box, sphere, capsule) need their own node (with appropriate
  838. // transform set) so that we can use the mesh bounds to compute the real
  839. // collision primitive at load time without having to examine the geometry.
  840. // - convex meshes may be added at the default node, with identity transform
  841. // - since all meshes are in the same detail level, they all get a unique
  842. // object name
  843. const String colNodeName( String::ToString( "Col%d", size ) );
  844. // Add the default node with identity transform
  845. S32 nodeIndex = mShape->findNode( colNodeName );
  846. if ( nodeIndex == -1 )
  847. {
  848. addNode( colNodeName, "" );
  849. }
  850. else
  851. {
  852. MatrixF mat;
  853. mShape->getNodeWorldTransform( nodeIndex, &mat );
  854. if ( !mat.isIdentity() )
  855. setNodeTransform( colNodeName, TransformF::Identity );
  856. }
  857. // Add the meshes to the shape =>
  858. for ( S32 i = 0; i < fit.getMeshCount(); i++ )
  859. {
  860. MeshFit::Mesh* mesh = fit.getMesh( i );
  861. // Determine a unique name for this mesh
  862. String objName;
  863. switch ( mesh->type )
  864. {
  865. case MeshFit::Box: objName = "ColBox"; break;
  866. case MeshFit::Sphere: objName = "ColSphere"; break;
  867. case MeshFit::Capsule: objName = "ColCapsule"; break;
  868. default: objName = "ColConvex"; break;
  869. }
  870. for ( S32 suffix = i; suffix != 0; suffix /= 26 )
  871. objName += ('A' + ( suffix % 26 ) );
  872. String meshName = objName + String::ToString( "%d", size );
  873. mShape->addMesh( mesh->tsmesh, meshName );
  874. // Add a node for this object if needed (non-identity transform)
  875. if ( mesh->transform.isIdentity() )
  876. {
  877. mShape->setObjectNode( objName, colNodeName );
  878. }
  879. else
  880. {
  881. addNode( meshName, colNodeName, TransformF( mesh->transform ) );
  882. mShape->setObjectNode( objName, meshName );
  883. }
  884. }
  885. mShape->init();
  886. ADD_TO_CHANGE_SET();
  887. return true;
  888. }}