vrshoot

view libs/assimp/ImproveCacheLocality.cpp @ 0:b2f14e535253

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 01 Feb 2014 19:58:19 +0200
parents
children
line source
1 /*
2 ---------------------------------------------------------------------------
3 Open Asset Import Library (assimp)
4 ---------------------------------------------------------------------------
6 Copyright (c) 2006-2012, assimp team
8 All rights reserved.
10 Redistribution and use of this software in source and binary forms,
11 with or without modification, are permitted provided that the following
12 conditions are met:
14 * Redistributions of source code must retain the above
15 copyright notice, this list of conditions and the
16 following disclaimer.
18 * Redistributions in binary form must reproduce the above
19 copyright notice, this list of conditions and the
20 following disclaimer in the documentation and/or other
21 materials provided with the distribution.
23 * Neither the name of the assimp team, nor the names of its
24 contributors may be used to endorse or promote products
25 derived from this software without specific prior
26 written permission of the assimp team.
28 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 ---------------------------------------------------------------------------
40 */
42 /** @file Implementation of the post processing step to improve the cache locality of a mesh.
43 * <br>
44 * The algorithm is roughly basing on this paper:
45 * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf
46 * .. although overdraw rduction isn't implemented yet ...
47 */
49 #include "AssimpPCH.h"
51 // internal headers
52 #include "ImproveCacheLocality.h"
53 #include "VertexTriangleAdjacency.h"
55 using namespace Assimp;
57 // ------------------------------------------------------------------------------------------------
58 // Constructor to be privately used by Importer
59 ImproveCacheLocalityProcess::ImproveCacheLocalityProcess() {
60 configCacheDepth = PP_ICL_PTCACHE_SIZE;
61 }
63 // ------------------------------------------------------------------------------------------------
64 // Destructor, private as well
65 ImproveCacheLocalityProcess::~ImproveCacheLocalityProcess()
66 {
67 // nothing to do here
68 }
70 // ------------------------------------------------------------------------------------------------
71 // Returns whether the processing step is present in the given flag field.
72 bool ImproveCacheLocalityProcess::IsActive( unsigned int pFlags) const
73 {
74 return (pFlags & aiProcess_ImproveCacheLocality) != 0;
75 }
77 // ------------------------------------------------------------------------------------------------
78 // Setup configuration
79 void ImproveCacheLocalityProcess::SetupProperties(const Importer* pImp)
80 {
81 // AI_CONFIG_PP_ICL_PTCACHE_SIZE controls the target cache size for the optimizer
82 configCacheDepth = pImp->GetPropertyInteger(AI_CONFIG_PP_ICL_PTCACHE_SIZE,PP_ICL_PTCACHE_SIZE);
83 }
85 // ------------------------------------------------------------------------------------------------
86 // Executes the post processing step on the given imported data.
87 void ImproveCacheLocalityProcess::Execute( aiScene* pScene)
88 {
89 if (!pScene->mNumMeshes) {
90 DefaultLogger::get()->debug("ImproveCacheLocalityProcess skipped; there are no meshes");
91 return;
92 }
94 DefaultLogger::get()->debug("ImproveCacheLocalityProcess begin");
96 float out = 0.f;
97 unsigned int numf = 0, numm = 0;
98 for( unsigned int a = 0; a < pScene->mNumMeshes; a++){
99 const float res = ProcessMesh( pScene->mMeshes[a],a);
100 if (res) {
101 numf += pScene->mMeshes[a]->mNumFaces;
102 out += res;
103 ++numm;
104 }
105 }
106 if (!DefaultLogger::isNullLogger()) {
107 char szBuff[128]; // should be sufficiently large in every case
108 ::sprintf(szBuff,"Cache relevant are %i meshes (%i faces). Average output ACMR is %f",
109 numm,numf,out/numf);
111 DefaultLogger::get()->info(szBuff);
112 DefaultLogger::get()->debug("ImproveCacheLocalityProcess finished. ");
113 }
114 }
116 // ------------------------------------------------------------------------------------------------
117 // Improves the cache coherency of a specific mesh
118 float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshNum)
119 {
120 // TODO: rewrite this to use std::vector or boost::shared_array
121 ai_assert(NULL != pMesh);
123 // Check whether the input data is valid
124 // - there must be vertices and faces
125 // - all faces must be triangulated or we can't operate on them
126 if (!pMesh->HasFaces() || !pMesh->HasPositions())
127 return 0.f;
129 if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) {
130 DefaultLogger::get()->error("This algorithm works on triangle meshes only");
131 return 0.f;
132 }
134 if(pMesh->mNumVertices <= configCacheDepth) {
135 return 0.f;
136 }
138 float fACMR = 3.f;
139 const aiFace* const pcEnd = pMesh->mFaces+pMesh->mNumFaces;
141 // Input ACMR is for logging purposes only
142 if (!DefaultLogger::isNullLogger()) {
144 unsigned int* piFIFOStack = new unsigned int[configCacheDepth];
145 memset(piFIFOStack,0xff,configCacheDepth*sizeof(unsigned int));
146 unsigned int* piCur = piFIFOStack;
147 const unsigned int* const piCurEnd = piFIFOStack + configCacheDepth;
149 // count the number of cache misses
150 unsigned int iCacheMisses = 0;
151 for (const aiFace* pcFace = pMesh->mFaces;pcFace != pcEnd;++pcFace) {
153 for (unsigned int qq = 0; qq < 3;++qq) {
154 bool bInCache = false;
156 for (unsigned int* pp = piFIFOStack;pp < piCurEnd;++pp) {
157 if (*pp == pcFace->mIndices[qq]) {
158 // the vertex is in cache
159 bInCache = true;
160 break;
161 }
162 }
163 if (!bInCache) {
164 ++iCacheMisses;
165 if (piCurEnd == piCur) {
166 piCur = piFIFOStack;
167 }
168 *piCur++ = pcFace->mIndices[qq];
169 }
170 }
171 }
172 delete[] piFIFOStack;
173 fACMR = (float)iCacheMisses / pMesh->mNumFaces;
174 if (3.0 == fACMR) {
175 char szBuff[128]; // should be sufficiently large in every case
177 // the JoinIdenticalVertices process has not been executed on this
178 // mesh, otherwise this value would normally be at least minimally
179 // smaller than 3.0 ...
180 sprintf(szBuff,"Mesh %i: Not suitable for vcache optimization",meshNum);
181 DefaultLogger::get()->warn(szBuff);
182 return 0.f;
183 }
184 }
186 // first we need to build a vertex-triangle adjacency list
187 VertexTriangleAdjacency adj(pMesh->mFaces,pMesh->mNumFaces, pMesh->mNumVertices,true);
189 // build a list to store per-vertex caching time stamps
190 unsigned int* const piCachingStamps = new unsigned int[pMesh->mNumVertices];
191 memset(piCachingStamps,0x0,pMesh->mNumVertices*sizeof(unsigned int));
193 // allocate an empty output index buffer. We store the output indices in one large array.
194 // Since the number of triangles won't change the input faces can be reused. This is how
195 // we save thousands of redundant mini allocations for aiFace::mIndices
196 const unsigned int iIdxCnt = pMesh->mNumFaces*3;
197 unsigned int* const piIBOutput = new unsigned int[iIdxCnt];
198 unsigned int* piCSIter = piIBOutput;
200 // allocate the flag array to hold the information
201 // whether a face has already been emitted or not
202 std::vector<bool> abEmitted(pMesh->mNumFaces,false);
204 // dead-end vertex index stack
205 std::stack<unsigned int, std::vector<unsigned int> > sDeadEndVStack;
207 // create a copy of the piNumTriPtr buffer
208 unsigned int* const piNumTriPtr = adj.mLiveTriangles;
209 const std::vector<unsigned int> piNumTriPtrNoModify(piNumTriPtr, piNumTriPtr + pMesh->mNumVertices);
211 // get the largest number of referenced triangles and allocate the "candidate buffer"
212 unsigned int iMaxRefTris = 0; {
213 const unsigned int* piCur = adj.mLiveTriangles;
214 const unsigned int* const piCurEnd = adj.mLiveTriangles+pMesh->mNumVertices;
215 for (;piCur != piCurEnd;++piCur) {
216 iMaxRefTris = std::max(iMaxRefTris,*piCur);
217 }
218 }
219 unsigned int* piCandidates = new unsigned int[iMaxRefTris*3];
220 unsigned int iCacheMisses = 0;
222 // ...................................................................................
223 /** PSEUDOCODE for the algorithm
225 A = Build-Adjacency(I) Vertex-triangle adjacency
226 L = Get-Triangle-Counts(A) Per-vertex live triangle counts
227 C = Zero(Vertex-Count(I)) Per-vertex caching time stamps
228 D = Empty-Stack() Dead-end vertex stack
229 E = False(Triangle-Count(I)) Per triangle emitted flag
230 O = Empty-Index-Buffer() Empty output buffer
231 f = 0 Arbitrary starting vertex
232 s = k+1, i = 1 Time stamp and cursor
233 while f >= 0 For all valid fanning vertices
234 N = Empty-Set() 1-ring of next candidates
235 for each Triangle t in Neighbors(A, f)
236 if !Emitted(E,t)
237 for each Vertex v in t
238 Append(O,v) Output vertex
239 Push(D,v) Add to dead-end stack
240 Insert(N,v) Register as candidate
241 L[v] = L[v]-1 Decrease live triangle count
242 if s-C[v] > k If not in cache
243 C[v] = s Set time stamp
244 s = s+1 Increment time stamp
245 E[t] = true Flag triangle as emitted
246 Select next fanning vertex
247 f = Get-Next-Vertex(I,i,k,N,C,s,L,D)
248 return O
249 */
250 // ...................................................................................
252 int ivdx = 0;
253 int ics = 1;
254 int iStampCnt = configCacheDepth+1;
255 while (ivdx >= 0) {
257 unsigned int icnt = piNumTriPtrNoModify[ivdx];
258 unsigned int* piList = adj.GetAdjacentTriangles(ivdx);
259 unsigned int* piCurCandidate = piCandidates;
261 // get all triangles in the neighborhood
262 for (unsigned int tri = 0; tri < icnt;++tri) {
264 // if they have not yet been emitted, add them to the output IB
265 const unsigned int fidx = *piList++;
266 if (!abEmitted[fidx]) {
268 // so iterate through all vertices of the current triangle
269 const aiFace* pcFace = &pMesh->mFaces[ fidx ];
270 for (unsigned int* p = pcFace->mIndices, *p2 = pcFace->mIndices+3;p != p2;++p) {
271 const unsigned int dp = *p;
273 // the current vertex won't have any free triangles after this step
274 if (ivdx != (int)dp) {
275 // append the vertex to the dead-end stack
276 sDeadEndVStack.push(dp);
278 // register as candidate for the next step
279 *piCurCandidate++ = dp;
281 // decrease the per-vertex triangle counts
282 piNumTriPtr[dp]--;
283 }
285 // append the vertex to the output index buffer
286 *piCSIter++ = dp;
288 // if the vertex is not yet in cache, set its cache count
289 if (iStampCnt-piCachingStamps[dp] > configCacheDepth) {
290 piCachingStamps[dp] = iStampCnt++;
291 ++iCacheMisses;
292 }
293 }
294 // flag triangle as emitted
295 abEmitted[fidx] = true;
296 }
297 }
299 // the vertex has now no living adjacent triangles anymore
300 piNumTriPtr[ivdx] = 0;
302 // get next fanning vertex
303 ivdx = -1;
304 int max_priority = -1;
305 for (unsigned int* piCur = piCandidates;piCur != piCurCandidate;++piCur) {
306 register const unsigned int dp = *piCur;
308 // must have live triangles
309 if (piNumTriPtr[dp] > 0) {
310 int priority = 0;
312 // will the vertex be in cache, even after fanning occurs?
313 unsigned int tmp;
314 if ((tmp = iStampCnt-piCachingStamps[dp]) + 2*piNumTriPtr[dp] <= configCacheDepth) {
315 priority = tmp;
316 }
318 // keep best candidate
319 if (priority > max_priority) {
320 max_priority = priority;
321 ivdx = dp;
322 }
323 }
324 }
325 // did we reach a dead end?
326 if (-1 == ivdx) {
327 // need to get a non-local vertex for which we have a good chance that it is still
328 // in the cache ...
329 while (!sDeadEndVStack.empty()) {
330 unsigned int iCachedIdx = sDeadEndVStack.top();
331 sDeadEndVStack.pop();
332 if (piNumTriPtr[ iCachedIdx ] > 0) {
333 ivdx = iCachedIdx;
334 break;
335 }
336 }
338 if (-1 == ivdx) {
339 // well, there isn't such a vertex. Simply get the next vertex in input order and
340 // hope it is not too bad ...
341 while (ics < (int)pMesh->mNumVertices) {
342 ++ics;
343 if (piNumTriPtr[ics] > 0) {
344 ivdx = ics;
345 break;
346 }
347 }
348 }
349 }
350 }
351 float fACMR2 = 0.0f;
352 if (!DefaultLogger::isNullLogger()) {
353 fACMR2 = (float)iCacheMisses / pMesh->mNumFaces;
355 // very intense verbose logging ... prepare for much text if there are many meshes
356 if ( DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
357 char szBuff[128]; // should be sufficiently large in every case
359 ::sprintf(szBuff,"Mesh %i | ACMR in: %f out: %f | ~%.1f%%",meshNum,fACMR,fACMR2,
360 ((fACMR - fACMR2) / fACMR) * 100.f);
361 DefaultLogger::get()->debug(szBuff);
362 }
364 fACMR2 *= pMesh->mNumFaces;
365 }
366 // sort the output index buffer back to the input array
367 piCSIter = piIBOutput;
368 for (aiFace* pcFace = pMesh->mFaces; pcFace != pcEnd;++pcFace) {
369 pcFace->mIndices[0] = *piCSIter++;
370 pcFace->mIndices[1] = *piCSIter++;
371 pcFace->mIndices[2] = *piCSIter++;
372 }
374 // delete temporary storage
375 delete[] piCachingStamps;
376 delete[] piIBOutput;
377 delete[] piCandidates;
379 return fACMR2;
380 }