TriangulateProcess.cpp 19 KB

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