TriangulateProcess.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2009, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file TriangulateProcess.cpp
  35. * @brief Implementation of the post processing step to split up
  36. * all faces with more than three indices into triangles.
  37. *
  38. *
  39. * The triangulation algorithm will handle concave or convex polygons.
  40. * Self-intersecting or non-planar polygons are not rejected, but
  41. * they're probably not triangulated correctly.
  42. *
  43. * AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  44. * - generates vertex colors to represent the face winding order.
  45. * the first vertex of a polygon becomes red, the last blue.
  46. */
  47. #include "AssimpPCH.h"
  48. #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS
  49. #include "TriangulateProcess.h"
  50. #include "ProcessHelper.h"
  51. //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  52. using namespace Assimp;
  53. // ------------------------------------------------------------------------------------------------
  54. // Constructor to be privately used by Importer
  55. TriangulateProcess::TriangulateProcess()
  56. {
  57. // nothing to do here
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Destructor, private as well
  61. TriangulateProcess::~TriangulateProcess()
  62. {
  63. // nothing to do here
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // Returns whether the processing step is present in the given flag field.
  67. bool TriangulateProcess::IsActive( unsigned int pFlags) const
  68. {
  69. return (pFlags & aiProcess_Triangulate) != 0;
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Executes the post processing step on the given imported data.
  73. void TriangulateProcess::Execute( aiScene* pScene)
  74. {
  75. DefaultLogger::get()->debug("TriangulateProcess begin");
  76. bool bHas = false;
  77. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  78. {
  79. if( TriangulateMesh( pScene->mMeshes[a]))
  80. bHas = true;
  81. }
  82. if (bHas)DefaultLogger::get()->info ("TriangulateProcess finished. All polygons have been triangulated.");
  83. else DefaultLogger::get()->debug("TriangulateProcess finished. There was nothing to be done.");
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Test whether a point p2 is on the left side of the line formed by p0-p1
  87. inline bool OnLeftSideOfLine(const aiVector2D& p0, const aiVector2D& p1,const aiVector2D& p2)
  88. {
  89. return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) ) > 0;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Test whether a point is inside a given triangle in R2
  93. inline bool PointInTriangle2D(const aiVector2D& p0, const aiVector2D& p1,const aiVector2D& p2, const aiVector2D& pp)
  94. {
  95. // Point in triangle test using baryzentric coordinates
  96. const aiVector2D v0 = p1 - p0;
  97. const aiVector2D v1 = p2 - p0;
  98. const aiVector2D v2 = pp - p0;
  99. float dot00 = v0 * v0;
  100. float dot01 = v0 * v1;
  101. float dot02 = v0 * v2;
  102. float dot11 = v1 * v1;
  103. float dot12 = v1 * v2;
  104. const float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  105. dot11 = (dot11 * dot02 - dot01 * dot12) * invDenom;
  106. dot00 = (dot00 * dot12 - dot01 * dot02) * invDenom;
  107. return (dot11 > 0) && (dot00 > 0) && (dot11 + dot00 < 1);
  108. }
  109. // ------------------------------------------------------------------------------------------------
  110. // Triangulates the given mesh.
  111. bool TriangulateProcess::TriangulateMesh( aiMesh* pMesh)
  112. {
  113. // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
  114. if (!pMesh->mPrimitiveTypes) {
  115. bool bNeed = false;
  116. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  117. const aiFace& face = pMesh->mFaces[a];
  118. if( face.mNumIndices != 3) {
  119. bNeed = true;
  120. }
  121. }
  122. if (!bNeed)
  123. return false;
  124. }
  125. else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  126. return false;
  127. }
  128. // the output mesh will contain triangles, but no polys anymore
  129. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  130. pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
  131. // Find out how many output faces we'll get
  132. unsigned int numOut = 0, max_out = 0;
  133. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  134. aiFace& face = pMesh->mFaces[a];
  135. if( face.mNumIndices <= 3)
  136. numOut++;
  137. else {
  138. numOut += face.mNumIndices-2;
  139. max_out = std::max(max_out,face.mNumIndices);
  140. }
  141. }
  142. // Just another check whether aiMesh::mPrimitiveTypes is correct
  143. assert(numOut != pMesh->mNumFaces);
  144. aiVector3D* nor_out = NULL;
  145. if (!pMesh->mNormals && pMesh->mPrimitiveTypes == aiPrimitiveType_POLYGON) {
  146. nor_out = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  147. }
  148. aiFace* out = new aiFace[numOut], *curOut = out;
  149. std::vector<aiVector3D> temp_verts(max_out+2); /* temporary storage for vertices */
  150. // Apply vertex colors to represent the face winding?
  151. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  152. if (!pMesh->mColors[0])
  153. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  154. else
  155. new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices];
  156. aiColor4D* clr = pMesh->mColors[0];
  157. #endif
  158. // use boost::scoped_array to avoid slow std::vector<bool> specialiations
  159. boost::scoped_array<bool> done(new bool[max_out]);
  160. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  161. aiFace& face = pMesh->mFaces[a];
  162. unsigned int* idx = face.mIndices;
  163. int num = (int)face.mNumIndices, ear = 0, tmp, prev = num-1, next = 0, max = num;
  164. // Apply vertex colors to represent the face winding?
  165. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  166. for (unsigned int i = 0; i < face.mNumIndices; ++i) {
  167. aiColor4D& c = clr[idx[i]];
  168. c.r = (i+1) / (float)max;
  169. c.b = 1.f - c.r;
  170. }
  171. #endif
  172. // if it's a simple primitive, just copy it
  173. if( face.mNumIndices <= 3)
  174. {
  175. aiFace& nface = *curOut++;
  176. nface.mNumIndices = face.mNumIndices;
  177. nface.mIndices = face.mIndices;
  178. }
  179. else
  180. {
  181. // A polygon with more than 3 vertices can be either concave or convex.
  182. // Usually everything we're getting is convex and we could easily
  183. // triangulate by trifanning. However, LightWave is probably the only
  184. // modeller making extensive use of highly concave monster polygons ...
  185. // so we need to apply the full 'ear cutting' algorithm.
  186. // RERQUIREMENT: polygon is expected to be simple and *nearly* planar.
  187. // We project it onto a plane to get 2d data. Working in R3 would
  188. // also be possible but it's more difficult to implement.
  189. // Collect all vertices of of the polygon.
  190. aiVector3D* verts = pMesh->mVertices;
  191. for (tmp = 0; tmp < max; ++tmp)
  192. temp_verts[tmp] = verts[idx[tmp]];
  193. // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
  194. aiVector3D n;
  195. NewellNormal<3,3,3>(n,max,&temp_verts.front().x,&temp_verts.front().y,&temp_verts.front().z);
  196. if (nor_out) {
  197. for (tmp = 0; tmp < max; ++tmp)
  198. nor_out[idx[tmp]] = n;
  199. }
  200. // Select largest normal coordinate to ignore for projection
  201. const float ax = (n.x>0 ? n.x : -n.x);
  202. const float ay = (n.y>0 ? n.y : -n.y);
  203. const float az = (n.z>0 ? n.z : -n.z);
  204. unsigned int ac = 0, bc = 1; /* no z coord. projection to xy */
  205. float inv = n.z;
  206. if (ax > ay) {
  207. if (ax > az) { /* no x coord. projection to yz */
  208. ac = 1; bc = 2;
  209. inv = n.x;
  210. }
  211. }
  212. else if (ay > az) { /* no y coord. projection to zy */
  213. ac = 2; bc = 0;
  214. inv = n.y;
  215. }
  216. // Swap projection axes to take the negated projection vector into account
  217. if (inv < 0.f) {
  218. std::swap(ac,bc);
  219. }
  220. for (tmp =0; tmp < max; ++tmp) {
  221. temp_verts[tmp].x = verts[idx[tmp]][ac];
  222. temp_verts[tmp].y = verts[idx[tmp]][bc];
  223. done[tmp] = false;
  224. }
  225. //
  226. // FIXME: currently this is the slow O(kn) variant with a worst case
  227. // complexity of O(n^2) (I think). Can be done in O(n).
  228. while (num > 3) {
  229. // Find the next ear of the polygon
  230. int num_found = 0;
  231. for (ear = next;;prev = ear,ear = next) {
  232. // break after we looped two times without a positive match
  233. for (next=ear+1;done[(next>max-1?next=0:next)];++next);
  234. if (next < ear) {
  235. if (++num_found == 2)
  236. break;
  237. }
  238. const aiVector2D* pnt1 = (const aiVector2D*)&temp_verts[ear],
  239. *pnt0 = (const aiVector2D*)&temp_verts[prev],
  240. *pnt2 = (const aiVector2D*)&temp_verts[next];
  241. // Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1.
  242. if (OnLeftSideOfLine (*pnt0,*pnt2,*pnt1))
  243. continue;
  244. // and no other point may be contained in this triangle
  245. for ( tmp = 0; tmp < max; ++tmp) {
  246. // We need to compare the actual values because it's possible that multiple indexes in
  247. // the polygon are refering to the same position. concave_polygon.obj is a sample
  248. //
  249. // FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in
  250. // PointInTriangle() I'm guessing that it's actually possible to construct
  251. // input data that would cause us to end up with no ears. The problem is,
  252. // which epsilon? If we chose a too large value, we'd get wrong results
  253. const aiVector2D& vtmp = * ((aiVector2D*) &temp_verts[tmp] );
  254. if ( vtmp != *pnt1 && vtmp != *pnt2 && vtmp != *pnt0 && PointInTriangle2D(*pnt0,*pnt1,*pnt2,vtmp))
  255. break;
  256. }
  257. if (tmp != max)
  258. continue;
  259. // this vertex is an ear
  260. break;
  261. }
  262. if (num_found == 2) {
  263. // Due to the 'two ear theorem', every simple polygon with more than three points must
  264. // have 2 'ears'. Here's definitely someting wrong ... but we don't give up yet.
  265. //
  266. // Instead we're continuting with the standard trifanning algorithm which we'd
  267. // use if we had only convex polygons. That's life.
  268. DefaultLogger::get()->error("Failed to triangulate polygon (no ear found). Probably not a simple polygon?");
  269. curOut -= (max-num); /* undo all previous work */
  270. for (tmp = 0; tmp < max-2; ++tmp) {
  271. aiFace& nface = *curOut++;
  272. nface.mNumIndices = 3;
  273. if (!nface.mIndices)
  274. nface.mIndices = new unsigned int[3];
  275. nface.mIndices[0] = idx[0];
  276. nface.mIndices[1] = idx[tmp+1];
  277. nface.mIndices[2] = idx[tmp+2];
  278. }
  279. num = 0;
  280. break;
  281. }
  282. aiFace& nface = *curOut++;
  283. nface.mNumIndices = 3;
  284. if (!nface.mIndices)
  285. nface.mIndices = new unsigned int[3];
  286. // setup indices for the new triangle ...
  287. nface.mIndices[0] = idx[prev];
  288. nface.mIndices[1] = idx[ear];
  289. nface.mIndices[2] = idx[next];
  290. // exclude the ear from most further processing
  291. done[ear] = true;
  292. --num;
  293. }
  294. if (num > 0) {
  295. // We have three indices forming the last 'ear' remaining. Collect them.
  296. aiFace& nface = *curOut++;
  297. nface.mNumIndices = 3;
  298. nface.mIndices = face.mIndices;
  299. for (tmp = 0; done[tmp]; ++tmp);
  300. idx[0] = idx[tmp];
  301. for (++tmp; done[tmp]; ++tmp);
  302. idx[1] = idx[tmp];
  303. for (++tmp; done[tmp]; ++tmp);
  304. idx[2] = idx[tmp];
  305. }
  306. }
  307. face.mIndices = NULL; /* prevent unintended deletion of our awesome results. would be a pity */
  308. }
  309. // kill the old faces
  310. delete [] pMesh->mFaces;
  311. // ... and store the new ones
  312. pMesh->mFaces = out;
  313. pMesh->mNumFaces = (unsigned int)(curOut-out); /* not necessarily equal to numOut */
  314. return true;
  315. }
  316. #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS