ImproveCacheLocality.cpp 15 KB

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