2
0

ImproveCacheLocality.cpp 13 KB

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