ImproveCacheLocality.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, 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 Implementation of the post processing to improve the
  35. * cache locality of a mesh.
  36. * <br>
  37. * The algorithm is roughly basing on this paper:
  38. * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf
  39. */
  40. #include "AssimpPCH.h"
  41. // internal headers
  42. #include "ImproveCacheLocality.h"
  43. #include "VertexTriangleAdjacency.h"
  44. using namespace Assimp;
  45. #if _MSC_VER >= 1400
  46. # define sprintf sprintf_s
  47. #endif
  48. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. ImproveCacheLocalityProcess::ImproveCacheLocalityProcess()
  51. {
  52. // nothing to do here
  53. configCacheDepth = 12; // hardcoded to 12 at the moment
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. ImproveCacheLocalityProcess::~ImproveCacheLocalityProcess()
  58. {
  59. // nothing to do here
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Returns whether the processing step is present in the given flag field.
  63. bool ImproveCacheLocalityProcess::IsActive( unsigned int pFlags) const
  64. {
  65. return (pFlags & aiProcess_ImproveCacheLocality) != 0;
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Executes the post processing step on the given imported data.
  69. void ImproveCacheLocalityProcess::Execute( aiScene* pScene)
  70. {
  71. if (!pScene->mNumMeshes)
  72. {
  73. DefaultLogger::get()->debug("ImproveCacheLocalityProcess skipped; there are no meshes");
  74. return;
  75. }
  76. DefaultLogger::get()->debug("ImproveCacheLocalityProcess begin");
  77. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  78. {
  79. this->ProcessMesh( pScene->mMeshes[a],a);
  80. }
  81. DefaultLogger::get()->debug("ImproveCacheLocalityProcess finished. ");
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Improves the cache coherency of a specific mesh
  85. void ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshNum)
  86. {
  87. ai_assert(NULL != pMesh);
  88. // check whether the input data is valid ->
  89. // - there must be vertices and faces (haha)
  90. // - all faces must be triangulated
  91. if (!pMesh->HasFaces() || !pMesh->HasPositions())
  92. return;
  93. if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
  94. {
  95. DefaultLogger::get()->error("This algorithm works on triangle meshes only");
  96. return;
  97. }
  98. // find the input ACMR ...
  99. unsigned int* piFIFOStack = new unsigned int[this->configCacheDepth];
  100. ::memset(piFIFOStack,0xff,this->configCacheDepth*sizeof(unsigned int));
  101. unsigned int* piCur = piFIFOStack;
  102. const unsigned int* const piCurEnd = piFIFOStack + this->configCacheDepth;
  103. // count the number of cache misses
  104. unsigned int iCacheMisses = 0;
  105. const aiFace* const pcEnd = pMesh->mFaces+pMesh->mNumFaces;
  106. for (const aiFace* pcFace = pMesh->mFaces;pcFace != pcEnd;++pcFace)
  107. {
  108. for (unsigned int qq = 0; qq < 3;++qq)
  109. {
  110. bool bInCache = false;
  111. for (unsigned int* pp = piFIFOStack;pp < piCurEnd;++pp)
  112. {
  113. if (*pp == pcFace->mIndices[qq])
  114. {
  115. // the vertex is in cache
  116. bInCache = true;
  117. break;
  118. }
  119. }
  120. if (!bInCache)
  121. {
  122. ++iCacheMisses;
  123. if (piCurEnd == piCur)piCur = piFIFOStack;
  124. *piCur++ = pcFace->mIndices[qq];
  125. }
  126. }
  127. }
  128. delete[] piFIFOStack;
  129. float fACMR = (float)iCacheMisses / pMesh->mNumFaces;
  130. if (3.0 == fACMR)
  131. {
  132. if (!DefaultLogger::isNullLogger())
  133. {
  134. char szBuff[128]; // should be sufficiently large in every case
  135. // the JoinIdenticalVertices process has not been executed on this
  136. // mesh, otherwise this value would normally be at least minimally#
  137. // smaller than 3.0 ...
  138. ::sprintf(szBuff,"Mesh %i: Not suitable for vcache optimization",meshNum);
  139. DefaultLogger::get()->warn(szBuff);
  140. }
  141. return;
  142. }
  143. // first we need to build a vertex-triangle adjacency list
  144. VertexTriangleAdjacency adj(pMesh->mFaces,pMesh->mNumFaces, pMesh->mNumVertices,true);
  145. // build a list to store per-vertex caching time stamps
  146. unsigned int* const piCachingStamps = new unsigned int[pMesh->mNumVertices];
  147. ::memset(piCachingStamps,0x0,pMesh->mNumVertices*sizeof(unsigned int));
  148. // allocate an empty output index buffer. We store the output
  149. // indices in one large array. Since the number of triangles
  150. // won't change the input faces can be reused. This is how we save
  151. // thousands of redundant mini allocations for aiFace::mIndices
  152. const unsigned int iIdxCnt = pMesh->mNumFaces*3;
  153. unsigned int* const piIBOutput = new unsigned int[iIdxCnt];
  154. unsigned int* piCSIter = piIBOutput;
  155. // allocate the flag array to hold the information
  156. // whether a face has already been emitted or not
  157. std::vector<bool> abEmitted(pMesh->mNumFaces,false);
  158. // dead-end vertex index stack
  159. std::stack<unsigned int> sDeadEndVStack;
  160. // create a copy of the piNumTriPtr buffer
  161. unsigned int* const piNumTriPtr = adj.mLiveTriangles;
  162. const unsigned int* const piNumTriPtrNoModify = new unsigned int[pMesh->mNumVertices];
  163. ::memcpy(const_cast<unsigned int* const> (piNumTriPtrNoModify),piNumTriPtr,
  164. pMesh->mNumVertices * sizeof(unsigned int));
  165. // get the largest number of referenced triangles
  166. // and allocate the "candidate buffer"
  167. unsigned int iMaxRefTris = 0;
  168. {
  169. const unsigned int* piCur = adj.mLiveTriangles;
  170. const unsigned int* const piCurEnd = adj.mLiveTriangles+pMesh->mNumVertices;
  171. for (;piCur != piCurEnd;++piCur)
  172. iMaxRefTris = std::max(iMaxRefTris,*piCur);
  173. }
  174. unsigned int* piCandidates = new unsigned int[iMaxRefTris*3];
  175. iCacheMisses = 0;
  176. /** PSEUDOCODE for the algorithm
  177. A = Build-Adjacency(I) Vertex-triangle adjacency
  178. L = Get-Triangle-Counts(A) Per-vertex live triangle counts
  179. C = Zero(Vertex-Count(I)) Per-vertex caching time stamps
  180. D = Empty-Stack() Dead-end vertex stack
  181. E = False(Triangle-Count(I)) Per triangle emitted flag
  182. O = Empty-Index-Buffer() Empty output buffer
  183. f = 0 Arbitrary starting vertex
  184. s = k+1, i = 1 Time stamp and cursor
  185. while f >= 0 For all valid fanning vertices
  186. N = Empty-Set() 1-ring of next candidates
  187. for each Triangle t in Neighbors(A, f)
  188. if !Emitted(E,t)
  189. for each Vertex v in t
  190. Append(O,v) Output vertex
  191. Push(D,v) Add to dead-end stack
  192. Insert(N,v) Register as candidate
  193. L[v] = L[v]-1 Decrease live triangle count
  194. if s-C[v] > k If not in cache
  195. C[v] = s Set time stamp
  196. s = s+1 Increment time stamp
  197. E[t] = true Flag triangle as emitted
  198. Select next fanning vertex
  199. f = Get-Next-Vertex(I,i,k,N,C,s,L,D)
  200. return O
  201. */
  202. int ivdx = 0;
  203. int ics = 1;
  204. int iStampCnt = this->configCacheDepth+1;
  205. while (ivdx >= 0)
  206. {
  207. unsigned int icnt = piNumTriPtrNoModify[ivdx];
  208. unsigned int* piList = adj.GetAdjacentTriangles(ivdx);
  209. unsigned int* piCurCandidate = piCandidates;
  210. // get all triangles in the neighborhood
  211. for (unsigned int tri = 0; tri < icnt;++tri)
  212. {
  213. // if they have not yet been emitted, add them to the output IB
  214. const unsigned int fidx = *piList++;
  215. if (!abEmitted[fidx])
  216. {
  217. // so iterate through all vertices of the current triangle
  218. const aiFace* pcFace = &pMesh->mFaces[ fidx ];
  219. const unsigned int* const p2 = pcFace->mIndices+3;
  220. for (unsigned int* p = pcFace->mIndices;p != p2;++p)
  221. {
  222. const unsigned int dp = *p;
  223. // the current vertex won't have any free triangles after this step
  224. if (ivdx != (int)dp)
  225. {
  226. // append the vertex to the dead-end stack
  227. sDeadEndVStack.push(dp);
  228. // register as candidate for the next step
  229. *piCurCandidate++ = dp;
  230. // decrease the per-vertex triangle counts
  231. piNumTriPtr[dp]--;
  232. }
  233. // append the vertex to the output index buffer
  234. *piCSIter++ = dp;
  235. // if the vertex is not yet in cache, set its cache count
  236. if (iStampCnt-piCachingStamps[dp] > this->configCacheDepth)
  237. {
  238. piCachingStamps[dp] = iStampCnt++;
  239. ++iCacheMisses;
  240. }
  241. }
  242. // flag triangle as emitted
  243. abEmitted[fidx] = true;
  244. }
  245. }
  246. // the vertex has now no living adjacent triangles anymore
  247. piNumTriPtr[ivdx] = 0;
  248. // get next fanning vertex
  249. ivdx = -1;
  250. int max_priority = -1;
  251. for (unsigned int* piCur = piCandidates;piCur != piCurCandidate;++piCur)
  252. {
  253. register const unsigned int dp = *piCur;
  254. // must have live triangles
  255. if (piNumTriPtr[dp] > 0)
  256. {
  257. int priority = 0;
  258. // will the vertex be in cache, even after fanning occurs?
  259. unsigned int tmp;
  260. if ((tmp = iStampCnt-piCachingStamps[dp]) + 2*piNumTriPtr[dp] <= this->configCacheDepth)
  261. priority = tmp;
  262. // keep best candidate
  263. if (priority > max_priority)
  264. {
  265. max_priority = priority;
  266. ivdx = dp;
  267. }
  268. }
  269. }
  270. // did we reach a dead end?
  271. if (-1 == ivdx)
  272. {
  273. // need to get a non-local vertex for which we have a good
  274. // chance that it is still in the cache ...
  275. while (!sDeadEndVStack.empty())
  276. {
  277. unsigned int iCachedIdx = sDeadEndVStack.top();
  278. sDeadEndVStack.pop();
  279. if (piNumTriPtr[ iCachedIdx ] > 0)
  280. {
  281. ivdx = iCachedIdx;
  282. break;
  283. }
  284. }
  285. if (-1 == ivdx)
  286. {
  287. // well, there isn't such a vertex. Simply get the next
  288. // vertex in input order and hope it is not too bad ...
  289. while (ics < (int)pMesh->mNumVertices)
  290. {
  291. ++ics;
  292. if (piNumTriPtr[ics] > 0)
  293. {
  294. ivdx = ics;
  295. break;
  296. }
  297. }
  298. }
  299. }
  300. }
  301. if (!DefaultLogger::isNullLogger())
  302. {
  303. char szBuff[128]; // should be sufficiently large in every case
  304. float fACMR2 = (float)iCacheMisses / pMesh->mNumFaces;
  305. ::sprintf(szBuff,"Mesh %i | ACMR in: %f out: %f | ~%.1f%%",meshNum,fACMR,fACMR2,
  306. ((fACMR - fACMR2) / fACMR) * 100.f);
  307. DefaultLogger::get()->info(szBuff);
  308. }
  309. // sort the output index buffer back to the input array
  310. piCSIter = piIBOutput;
  311. for (aiFace* pcFace = pMesh->mFaces; pcFace != pcEnd;++pcFace)
  312. {
  313. pcFace->mIndices[0] = *piCSIter++;
  314. pcFace->mIndices[1] = *piCSIter++;
  315. pcFace->mIndices[2] = *piCSIter++;
  316. }
  317. // delete temporary storage
  318. delete[] piCachingStamps;
  319. delete[] piIBOutput;
  320. delete[] piCandidates;
  321. delete[] piNumTriPtrNoModify;
  322. }