TriangulateProcess.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp 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 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. * DEBUG SWITCHES - do not enable any of them in release builds:
  44. *
  45. * AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  46. * - generates vertex colors to represent the face winding order.
  47. * the first vertex of a polygon becomes red, the last blue.
  48. * AI_BUILD_TRIANGULATE_DEBUG_POLYS
  49. * - dump all polygons and their triangulation sequences to
  50. * a file
  51. */
  52. #include "AssimpPCH.h"
  53. #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS
  54. #include "TriangulateProcess.h"
  55. #include "ProcessHelper.h"
  56. #include "PolyTools.h"
  57. //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  58. //#define AI_BUILD_TRIANGULATE_DEBUG_POLYS
  59. #define POLY_GRID_Y 40
  60. #define POLY_GRID_X 70
  61. #define POLY_GRID_XPAD 20
  62. #define POLY_OUTPUT_FILE "assimp_polygons_debug.txt"
  63. using namespace Assimp;
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. TriangulateProcess::TriangulateProcess()
  67. {
  68. // nothing to do here
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Destructor, private as well
  72. TriangulateProcess::~TriangulateProcess()
  73. {
  74. // nothing to do here
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns whether the processing step is present in the given flag field.
  78. bool TriangulateProcess::IsActive( unsigned int pFlags) const
  79. {
  80. return (pFlags & aiProcess_Triangulate) != 0;
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Executes the post processing step on the given imported data.
  84. void TriangulateProcess::Execute( aiScene* pScene)
  85. {
  86. DefaultLogger::get()->debug("TriangulateProcess begin");
  87. bool bHas = false;
  88. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  89. {
  90. if( TriangulateMesh( pScene->mMeshes[a]))
  91. bHas = true;
  92. }
  93. if (bHas)DefaultLogger::get()->info ("TriangulateProcess finished. All polygons have been triangulated.");
  94. else DefaultLogger::get()->debug("TriangulateProcess finished. There was nothing to be done.");
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Triangulates the given mesh.
  98. bool TriangulateProcess::TriangulateMesh( aiMesh* pMesh)
  99. {
  100. // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
  101. if (!pMesh->mPrimitiveTypes) {
  102. bool bNeed = false;
  103. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  104. const aiFace& face = pMesh->mFaces[a];
  105. if( face.mNumIndices != 3) {
  106. bNeed = true;
  107. }
  108. }
  109. if (!bNeed)
  110. return false;
  111. }
  112. else if (!(pMesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  113. return false;
  114. }
  115. // Find out how many output faces we'll get
  116. unsigned int numOut = 0, max_out = 0;
  117. bool get_normals = true;
  118. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  119. aiFace& face = pMesh->mFaces[a];
  120. if (face.mNumIndices <= 4) {
  121. get_normals = false;
  122. }
  123. if( face.mNumIndices <= 3) {
  124. numOut++;
  125. }
  126. else {
  127. numOut += face.mNumIndices-2;
  128. max_out = std::max(max_out,face.mNumIndices);
  129. }
  130. }
  131. // Just another check whether aiMesh::mPrimitiveTypes is correct
  132. assert(numOut != pMesh->mNumFaces);
  133. aiVector3D* nor_out = NULL;
  134. // if we don't have normals yet, but expect them to be a cheap side
  135. // product of triangulation anyway, allocate storage for them.
  136. if (!pMesh->mNormals && get_normals) {
  137. // XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals
  138. // nor_out = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  139. }
  140. // the output mesh will contain triangles, but no polys anymore
  141. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  142. pMesh->mPrimitiveTypes &= ~aiPrimitiveType_POLYGON;
  143. aiFace* out = new aiFace[numOut](), *curOut = out;
  144. std::vector<aiVector3D> temp_verts3d(max_out+2); /* temporary storage for vertices */
  145. std::vector<aiVector2D> temp_verts(max_out+2);
  146. // Apply vertex colors to represent the face winding?
  147. #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
  148. if (!pMesh->mColors[0])
  149. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  150. else
  151. new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices];
  152. aiColor4D* clr = pMesh->mColors[0];
  153. #endif
  154. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  155. FILE* fout = fopen(POLY_OUTPUT_FILE,"a");
  156. #endif
  157. const aiVector3D* verts = pMesh->mVertices;
  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. aiFace* const last_face = curOut;
  173. // if it's a simple point,line or triangle: just copy it
  174. if( face.mNumIndices <= 3)
  175. {
  176. aiFace& nface = *curOut++;
  177. nface.mNumIndices = face.mNumIndices;
  178. nface.mIndices = face.mIndices;
  179. face.mIndices = NULL;
  180. continue;
  181. }
  182. // optimized code for quadrilaterals
  183. else if ( face.mNumIndices == 4) {
  184. // quads can have at maximum one concave vertex. Determine
  185. // this vertex (if it exists) and start tri-fanning from
  186. // it.
  187. unsigned int start_vertex = 0;
  188. for (unsigned int i = 0; i < 4; ++i) {
  189. const aiVector3D& v0 = verts[face.mIndices[(i+3) % 4]];
  190. const aiVector3D& v1 = verts[face.mIndices[(i+2) % 4]];
  191. const aiVector3D& v2 = verts[face.mIndices[(i+1) % 4]];
  192. const aiVector3D& v = verts[face.mIndices[i]];
  193. aiVector3D left = (v0-v);
  194. aiVector3D diag = (v1-v);
  195. aiVector3D right = (v2-v);
  196. left.Normalize();
  197. diag.Normalize();
  198. right.Normalize();
  199. const float angle = acos(left*diag) + acos(right*diag);
  200. if (angle > AI_MATH_PI_F) {
  201. // this is the concave point
  202. start_vertex = i;
  203. break;
  204. }
  205. }
  206. const unsigned int temp[] = {face.mIndices[0], face.mIndices[1], face.mIndices[2], face.mIndices[3]};
  207. aiFace& nface = *curOut++;
  208. nface.mNumIndices = 3;
  209. nface.mIndices = face.mIndices;
  210. nface.mIndices[0] = temp[start_vertex];
  211. nface.mIndices[1] = temp[(start_vertex + 1) % 4];
  212. nface.mIndices[2] = temp[(start_vertex + 2) % 4];
  213. aiFace& sface = *curOut++;
  214. sface.mNumIndices = 3;
  215. sface.mIndices = new unsigned int[3];
  216. sface.mIndices[0] = temp[start_vertex];
  217. sface.mIndices[1] = temp[(start_vertex + 2) % 4];
  218. sface.mIndices[2] = temp[(start_vertex + 3) % 4];
  219. // prevent double deletion of the indices field
  220. face.mIndices = NULL;
  221. continue;
  222. }
  223. else
  224. {
  225. // A polygon with more than 3 vertices can be either concave or convex.
  226. // Usually everything we're getting is convex and we could easily
  227. // triangulate by trifanning. However, LightWave is probably the only
  228. // modeling suite to make extensive use of highly concave, monster polygons ...
  229. // so we need to apply the full 'ear cutting' algorithm to get it right.
  230. // RERQUIREMENT: polygon is expected to be simple and *nearly* planar.
  231. // We project it onto a plane to get a 2d triangle.
  232. // Collect all vertices of of the polygon.
  233. for (tmp = 0; tmp < max; ++tmp) {
  234. temp_verts3d[tmp] = verts[idx[tmp]];
  235. }
  236. // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
  237. aiVector3D n;
  238. NewellNormal<3,3,3>(n,max,&temp_verts3d.front().x,&temp_verts3d.front().y,&temp_verts3d.front().z);
  239. if (nor_out) {
  240. for (tmp = 0; tmp < max; ++tmp)
  241. nor_out[idx[tmp]] = n;
  242. }
  243. // Select largest normal coordinate to ignore for projection
  244. const float ax = (n.x>0 ? n.x : -n.x);
  245. const float ay = (n.y>0 ? n.y : -n.y);
  246. const float az = (n.z>0 ? n.z : -n.z);
  247. unsigned int ac = 0, bc = 1; /* no z coord. projection to xy */
  248. float inv = n.z;
  249. if (ax > ay) {
  250. if (ax > az) { /* no x coord. projection to yz */
  251. ac = 1; bc = 2;
  252. inv = n.x;
  253. }
  254. }
  255. else if (ay > az) { /* no y coord. projection to zy */
  256. ac = 2; bc = 0;
  257. inv = n.y;
  258. }
  259. // Swap projection axes to take the negated projection vector into account
  260. if (inv < 0.f) {
  261. std::swap(ac,bc);
  262. }
  263. for (tmp =0; tmp < max; ++tmp) {
  264. temp_verts[tmp].x = verts[idx[tmp]][ac];
  265. temp_verts[tmp].y = verts[idx[tmp]][bc];
  266. done[tmp] = false;
  267. }
  268. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  269. // plot the plane onto which we mapped the polygon to a 2D ASCII pic
  270. aiVector2D bmin,bmax;
  271. ArrayBounds(&temp_verts[0],max,bmin,bmax);
  272. char grid[POLY_GRID_Y][POLY_GRID_X+POLY_GRID_XPAD];
  273. std::fill_n((char*)grid,POLY_GRID_Y*(POLY_GRID_X+POLY_GRID_XPAD),' ');
  274. for (int i =0; i < max; ++i) {
  275. const aiVector2D& v = (temp_verts[i] - bmin) / (bmax-bmin);
  276. const size_t x = static_cast<size_t>(v.x*(POLY_GRID_X-1)), y = static_cast<size_t>(v.y*(POLY_GRID_Y-1));
  277. char* loc = grid[y]+x;
  278. if (grid[y][x] != ' ') {
  279. for(;*loc != ' '; ++loc);
  280. *loc++ = '_';
  281. }
  282. *(loc+sprintf(loc,"%i",i)) = ' ';
  283. }
  284. for(size_t y = 0; y < POLY_GRID_Y; ++y) {
  285. grid[y][POLY_GRID_X+POLY_GRID_XPAD-1] = '\0';
  286. fprintf(fout,"%s\n",grid[y]);
  287. }
  288. fprintf(fout,"\ntriangulation sequence: ");
  289. #endif
  290. //
  291. // FIXME: currently this is the slow O(kn) variant with a worst case
  292. // complexity of O(n^2) (I think). Can be done in O(n).
  293. while (num > 3) {
  294. // Find the next ear of the polygon
  295. int num_found = 0;
  296. for (ear = next;;prev = ear,ear = next) {
  297. // break after we looped two times without a positive match
  298. for (next=ear+1;done[(next>=max?next=0:next)];++next);
  299. if (next < ear) {
  300. if (++num_found == 2) {
  301. break;
  302. }
  303. }
  304. const aiVector2D* pnt1 = &temp_verts[ear],
  305. *pnt0 = &temp_verts[prev],
  306. *pnt2 = &temp_verts[next];
  307. // Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1.
  308. if (OnLeftSideOfLine2D(*pnt0,*pnt2,*pnt1)) {
  309. continue;
  310. }
  311. // and no other point may be contained in this triangle
  312. for ( tmp = 0; tmp < max; ++tmp) {
  313. // We need to compare the actual values because it's possible that multiple indexes in
  314. // the polygon are referring to the same position. concave_polygon.obj is a sample
  315. //
  316. // FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in
  317. // PointInTriangle() I'm guessing that it's actually possible to construct
  318. // input data that would cause us to end up with no ears. The problem is,
  319. // which epsilon? If we chose a too large value, we'd get wrong results
  320. const aiVector2D& vtmp = temp_verts[tmp];
  321. if ( vtmp != *pnt1 && vtmp != *pnt2 && vtmp != *pnt0 && PointInTriangle2D(*pnt0,*pnt1,*pnt2,vtmp)) {
  322. break;
  323. }
  324. }
  325. if (tmp != max) {
  326. continue;
  327. }
  328. // this vertex is an ear
  329. break;
  330. }
  331. if (num_found == 2) {
  332. // Due to the 'two ear theorem', every simple polygon with more than three points must
  333. // have 2 'ears'. Here's definitely someting wrong ... but we don't give up yet.
  334. //
  335. // Instead we're continuting with the standard trifanning algorithm which we'd
  336. // use if we had only convex polygons. That's life.
  337. DefaultLogger::get()->error("Failed to triangulate polygon (no ear found). Probably not a simple polygon?");
  338. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  339. fprintf(fout,"critical error here, no ear found! ");
  340. #endif
  341. num = 0;
  342. break;
  343. curOut -= (max-num); /* undo all previous work */
  344. for (tmp = 0; tmp < max-2; ++tmp) {
  345. aiFace& nface = *curOut++;
  346. nface.mNumIndices = 3;
  347. if (!nface.mIndices)
  348. nface.mIndices = new unsigned int[3];
  349. nface.mIndices[0] = 0;
  350. nface.mIndices[1] = tmp+1;
  351. nface.mIndices[2] = tmp+2;
  352. }
  353. num = 0;
  354. break;
  355. }
  356. aiFace& nface = *curOut++;
  357. nface.mNumIndices = 3;
  358. if (!nface.mIndices) {
  359. nface.mIndices = new unsigned int[3];
  360. }
  361. // setup indices for the new triangle ...
  362. nface.mIndices[0] = prev;
  363. nface.mIndices[1] = ear;
  364. nface.mIndices[2] = next;
  365. // exclude the ear from most further processing
  366. done[ear] = true;
  367. --num;
  368. }
  369. if (num > 0) {
  370. // We have three indices forming the last 'ear' remaining. Collect them.
  371. aiFace& nface = *curOut++;
  372. nface.mNumIndices = 3;
  373. if (!nface.mIndices) {
  374. nface.mIndices = new unsigned int[3];
  375. }
  376. for (tmp = 0; done[tmp]; ++tmp);
  377. nface.mIndices[0] = tmp;
  378. for (++tmp; done[tmp]; ++tmp);
  379. nface.mIndices[1] = tmp;
  380. for (++tmp; done[tmp]; ++tmp);
  381. nface.mIndices[2] = tmp;
  382. }
  383. }
  384. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  385. for(aiFace* f = last_face; f != curOut; ++f) {
  386. unsigned int* i = f->mIndices;
  387. fprintf(fout," (%i %i %i)",i[0],i[1],i[2]);
  388. }
  389. fprintf(fout,"\n*********************************************************************\n");
  390. fflush(fout);
  391. #endif
  392. for(aiFace* f = last_face; f != curOut; ) {
  393. unsigned int* i = f->mIndices;
  394. // drop dumb 0-area triangles
  395. if (fabs(GetArea2D(temp_verts[i[0]],temp_verts[i[1]],temp_verts[i[2]])) < 1e-5f) {
  396. DefaultLogger::get()->debug("Dropping triangle with area 0");
  397. --curOut;
  398. delete[] f->mIndices;
  399. f->mIndices = NULL;
  400. for(aiFace* ff = f; ff != curOut; ++ff) {
  401. ff->mNumIndices = (ff+1)->mNumIndices;
  402. ff->mIndices = (ff+1)->mIndices;
  403. (ff+1)->mIndices = NULL;
  404. }
  405. continue;
  406. }
  407. i[0] = idx[i[0]];
  408. i[1] = idx[i[1]];
  409. i[2] = idx[i[2]];
  410. ++f;
  411. }
  412. delete[] face.mIndices;
  413. face.mIndices = NULL;
  414. }
  415. #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
  416. fclose(fout);
  417. #endif
  418. // kill the old faces
  419. delete [] pMesh->mFaces;
  420. // ... and store the new ones
  421. pMesh->mFaces = out;
  422. pMesh->mNumFaces = (unsigned int)(curOut-out); /* not necessarily equal to numOut */
  423. return true;
  424. }
  425. #endif // !! ASSIMP_BUILD_NO_TRIANGULATE_PROCESS