Skip to content
Navigation Menu
{{ message }}
forked from microsoft/DirectXMesh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectXMeshOptimizeLRU.cpp
More file actions
665 lines (536 loc) · 22 KB
/
Copy pathDirectXMeshOptimizeLRU.cpp
File metadata and controls
665 lines (536 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//-------------------------------------------------------------------------------------
// DirectXMeshOptimizeLRU.cpp
//
// DirectX Mesh Geometry Library - Mesh optimization
//
// Forsyth "Linear-Speed Vertex Cache Optimisation"
// https://tomforsyth1000.github.io/papers/fast_vert_cache_opt.html
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=324981
//-------------------------------------------------------------------------------------
#include "DirectXMeshP.h"
using namespace DirectX;
namespace
{
// This code was authored and released into the public domain by Adrian Stone (stone@gameangst.com).
// code for computing vertex score was taken, as much as possible
// directly from the original publication.
float ComputeVertexCacheScore(uint32_t cachePosition, uint32_t vertexCacheSize) noexcept
{
constexpr float FindVertexScore_CacheDecayPower = 1.5f;
constexpr float FindVertexScore_LastTriScore = 0.75f;
float score = 0.0f;
if (cachePosition >= vertexCacheSize)
{
// Vertex is not in FIFO cache - no score.
}
else
{
if (cachePosition < 3)
{
// This vertex was used in the last triangle,
// so it has a fixed score, whichever of the three
// it's in. Otherwise, you can get very different
// answers depending on whether you add
// the triangle 1,2,3 or 3,1,2 - which is silly.
score = FindVertexScore_LastTriScore;
}
else
{
// Points for being high in the cache.
const float scaler = 1.0f / float(vertexCacheSize - 3u);
score = 1.0f - float(cachePosition - 3u) * scaler;
score = powf(score, FindVertexScore_CacheDecayPower);
}
}
return score;
}
float ComputeVertexValenceScore(uint32_t numActiveFaces) noexcept
{
constexpr float FindVertexScore_ValenceBoostScale = 2.0f;
constexpr float FindVertexScore_ValenceBoostPower = 0.5f;
float score = 0.f;
// Bonus points for having a low number of tris still to
// use the vert, so we get rid of lone verts quickly.
const float valenceBoost = powf(static_cast<float>(numActiveFaces),
-FindVertexScore_ValenceBoostPower);
score += FindVertexScore_ValenceBoostScale * valenceBoost;
return score;
}
enum { kMaxVertexCacheSize = 64 };
enum { kMaxPrecomputedVertexValenceScores = 64 };
float s_vertexCacheScores[kMaxVertexCacheSize + 1][kMaxVertexCacheSize];
float s_vertexValenceScores[kMaxPrecomputedVertexValenceScores];
#ifdef _WIN32
static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
BOOL WINAPI ComputeVertexScores(PINIT_ONCE, PVOID, PVOID*) noexcept
#else
std::once_flag s_initOnce;
void ComputeVertexScores() noexcept
#endif
{
for (uint32_t cacheSize = 0; cacheSize <= kMaxVertexCacheSize; ++cacheSize)
{
for (uint32_t cachePos = 0; cachePos < cacheSize; ++cachePos)
{
s_vertexCacheScores[cacheSize][cachePos] = ComputeVertexCacheScore(cachePos, cacheSize);
}
}
for (uint32_t valence = 0; valence < kMaxPrecomputedVertexValenceScores; ++valence)
{
s_vertexValenceScores[valence] = ComputeVertexValenceScore(valence);
}
#ifdef _WIN32
return TRUE;
#endif
}
float FindVertexScore(uint32_t numActiveFaces, uint32_t cachePosition, uint32_t vertexCacheSize) noexcept
{
if (numActiveFaces == 0)
{
// No tri needs this vertex!
return -1.0f;
}
float score = 0.f;
if (cachePosition < vertexCacheSize)
{
score += s_vertexCacheScores[vertexCacheSize][cachePosition];
}
if (numActiveFaces < kMaxPrecomputedVertexValenceScores)
{
score += s_vertexValenceScores[numActiveFaces];
}
else
{
score += ComputeVertexValenceScore(numActiveFaces);
}
return score;
}
template <typename IndexType>
struct OptimizeVertexData
{
float score;
uint32_t activeFaceListStart;
uint32_t activeFaceListSize;
IndexType cachePos0;
IndexType cachePos1;
OptimizeVertexData() noexcept : score(0.f), activeFaceListStart(0), activeFaceListSize(0), cachePos0(0), cachePos1(0) {}
};
template <typename T, typename IndexType>
struct IndexSortCompareIndexed
{
const IndexType *_indexData;
IndexSortCompareIndexed(const IndexType *indexData) noexcept : _indexData(indexData) {}
bool operator()(T a, T b) const noexcept
{
IndexType indexA = _indexData[a];
IndexType indexB = _indexData[b];
if (indexA < indexB)
return true;
return false;
}
};
template <typename T, typename IndexType>
struct FaceValenceSort
{
const OptimizeVertexData<IndexType> *_vertexData;
FaceValenceSort(const OptimizeVertexData<IndexType> *vertexData) noexcept : _vertexData(vertexData) {}
bool operator()(T a, T b) const noexcept
{
const OptimizeVertexData<IndexType> *vA = _vertexData + size_t(a) * 3;
const OptimizeVertexData<IndexType> *vB = _vertexData + size_t(b) * 3;
const uint32_t aValence = vA[0].activeFaceListSize + vA[1].activeFaceListSize + vA[2].activeFaceListSize;
const uint32_t bValence = vB[0].activeFaceListSize + vB[1].activeFaceListSize + vB[2].activeFaceListSize;
// higher scoring faces are those with lower valence totals
// reverse sort (reverse of reverse)
if (aValence < bValence)
return true;
return false;
}
};
template <typename IndexType>
HRESULT OptimizeFacesImpl(
_In_reads_(indexCount) const IndexType* indexList, uint32_t indexCount,
_Out_writes_(indexCount / 3) uint32_t* faceRemap, uint32_t lruCacheSize, uint32_t offset)
{
std::unique_ptr<OptimizeVertexData<IndexType>[]> vertexDataList(new (std::nothrow) OptimizeVertexData<IndexType>[indexCount]);
if (!vertexDataList)
return E_OUTOFMEMORY;
std::unique_ptr<uint32_t[]> vertexRemap(new (std::nothrow) uint32_t[indexCount]);
std::unique_ptr<uint32_t[]> activeFaceList(new (std::nothrow) uint32_t[indexCount]);
if (!vertexRemap || !activeFaceList)
return E_OUTOFMEMORY;
const uint32_t faceCount = indexCount / 3;
std::unique_ptr<uint8_t[]> processedFaceList(new (std::nothrow) uint8_t[faceCount]);
std::unique_ptr<uint32_t[]> faceSorted(new (std::nothrow) uint32_t[faceCount]);
std::unique_ptr<uint32_t[]> faceReverseLookup(new (std::nothrow) uint32_t[faceCount]);
if (!processedFaceList || !faceSorted || !faceReverseLookup)
return E_OUTOFMEMORY;
memset(processedFaceList.get(), 0, sizeof(uint8_t) * faceCount);
// build the vertex remap table
uint32_t uniqueVertexCount = 0;
uint32_t unused = 0;
{
using indexSorter = IndexSortCompareIndexed<uint32_t, IndexType>;
std::unique_ptr<uint32_t[]> indexSorted(new (std::nothrow) uint32_t[indexCount]);
if (!indexSorted)
return E_OUTOFMEMORY;
for (uint32_t i = 0; i < indexCount; i++)
{
indexSorted[i] = i;
}
const indexSorter sortFunc(indexList);
std::sort(indexSorted.get(), indexSorted.get() + indexCount, sortFunc);
bool first = false;
for (uint32_t i = 0; i < indexCount; i++)
{
const uint32_t idx = indexSorted[i];
if (indexList[idx] == IndexType(-1))
{
unused++;
vertexRemap[idx] = UNUSED32;
continue;
}
if (!i || first || sortFunc(indexSorted[i - 1], idx))
{
// it's not a duplicate
vertexRemap[idx] = uniqueVertexCount;
uniqueVertexCount++;
first = false;
}
else
{
vertexRemap[indexSorted[i]] = vertexRemap[indexSorted[i - 1]];
}
}
}
// compute face count per vertex
for (uint32_t i = 0; i < indexCount; ++i)
{
if (vertexRemap[i] == UNUSED32)
continue;
OptimizeVertexData<IndexType>& vertexData = vertexDataList[vertexRemap[i]];
vertexData.activeFaceListSize++;
}
constexpr IndexType kEvictedCacheIndex = std::numeric_limits<IndexType>::max();
{
// allocate face list per vertex
uint32_t curActiveFaceListPos = 0;
for (uint32_t i = 0; i < uniqueVertexCount; ++i)
{
OptimizeVertexData<IndexType>& vertexData = vertexDataList[i];
vertexData.cachePos0 = kEvictedCacheIndex;
vertexData.cachePos1 = kEvictedCacheIndex;
vertexData.activeFaceListStart = curActiveFaceListPos;
curActiveFaceListPos += vertexData.activeFaceListSize;
vertexData.score = FindVertexScore(vertexData.activeFaceListSize, vertexData.cachePos0, lruCacheSize);
vertexData.activeFaceListSize = 0;
}
#ifndef NDEBUG
assert(curActiveFaceListPos == (indexCount - unused));
#else
std::ignore = unused;
#endif
}
// sort unprocessed faces by highest score
for (uint32_t f = 0; f < faceCount; f++)
{
faceSorted[f] = f;
}
const FaceValenceSort<uint32_t, IndexType> faceValenceSort(vertexDataList.get());
std::sort(faceSorted.get(), faceSorted.get() + faceCount, faceValenceSort);
for (uint32_t f = 0; f < faceCount; f++)
{
faceReverseLookup[faceSorted[f]] = f;
}
// fill out face list per vertex
for (uint32_t i = 0; i < indexCount; i += 3)
{
for (uint32_t j = 0; j < 3; ++j)
{
const uint32_t v = vertexRemap[size_t(i) + size_t(j)];
if (v == UNUSED32)
continue;
OptimizeVertexData<IndexType>& vertexData = vertexDataList[v];
activeFaceList[size_t(vertexData.activeFaceListStart) + vertexData.activeFaceListSize] = i;
vertexData.activeFaceListSize++;
}
}
uint32_t vertexCacheBuffer[(kMaxVertexCacheSize + 3) * 2] = {};
uint32_t *cache0 = vertexCacheBuffer;
uint32_t *cache1 = vertexCacheBuffer + (kMaxVertexCacheSize + 3);
uint32_t entriesInCache0 = 0;
uint32_t bestFace = 0;
for (size_t i = 0; i < indexCount; i += 3)
{
if (vertexRemap[i] == UNUSED32
|| vertexRemap[i + 1] == UNUSED32
|| vertexRemap[i + 2] == UNUSED32)
{
++bestFace;
continue;
}
else
break;
}
float bestScore = -1.f;
uint32_t nextBestFace = 0;
uint32_t curFace = 0;
for (size_t i = 0; i < indexCount; i += 3)
{
if (vertexRemap[i] == UNUSED32
|| vertexRemap[i + 1] == UNUSED32
|| vertexRemap[i + 2] == UNUSED32)
{
continue;
}
if (bestScore < 0.f)
{
// no verts in the cache are used by any unprocessed faces so
// search all unprocessed faces for a new starting point
while (nextBestFace < faceCount)
{
const uint32_t faceIndex = faceSorted[nextBestFace++];
if (processedFaceList[faceIndex] == 0)
{
const uint32_t face = faceIndex * 3;
const uint32_t i0 = vertexRemap[face];
const uint32_t i1 = vertexRemap[size_t(face) + 1];
const uint32_t i2 = vertexRemap[size_t(face) + 2];
if (i0 != UNUSED32 && i1 != UNUSED32 && i2 != UNUSED32)
{
// we're searching a pre-sorted list, first one we find will be the best
bestFace = face;
bestScore = vertexDataList[i0].score
+ vertexDataList[i1].score
+ vertexDataList[i2].score;
break;
}
}
}
assert(bestScore >= 0.f);
}
processedFaceList[bestFace / 3] = 1;
uint16_t entriesInCache1 = 0;
faceRemap[curFace] = (bestFace / 3) + offset;
curFace++;
// add bestFace to LRU cache
assert(vertexRemap[bestFace] != UNUSED32);
assert(vertexRemap[size_t(bestFace) + 1] != UNUSED32);
assert(vertexRemap[size_t(bestFace) + 2] != UNUSED32);
for (size_t v = 0; v < 3; ++v)
{
OptimizeVertexData<IndexType>& vertexData = vertexDataList[vertexRemap[bestFace + v]];
if (vertexData.cachePos1 >= entriesInCache1)
{
vertexData.cachePos1 = entriesInCache1;
cache1[entriesInCache1++] = vertexRemap[bestFace + v];
if (vertexData.activeFaceListSize == 1)
{
--vertexData.activeFaceListSize;
continue;
}
}
assert(vertexData.activeFaceListSize > 0);
uint32_t* begin = activeFaceList.get() + vertexData.activeFaceListStart;
uint32_t* end = activeFaceList.get() + (size_t(vertexData.activeFaceListStart) + vertexData.activeFaceListSize);
uint32_t* it = std::find(begin, end, bestFace);
assert(it != end);
std::swap(*it, *(end - 1));
--vertexData.activeFaceListSize;
vertexData.score = FindVertexScore(vertexData.activeFaceListSize, vertexData.cachePos1, lruCacheSize);
// need to re-sort the faces that use this vertex, as their score will change due to activeFaceListSize shrinking
for (const uint32_t *fi = begin; fi != end - 1; ++fi)
{
const uint32_t faceIndex = *fi / 3;
uint32_t n = faceReverseLookup[faceIndex];
assert(faceSorted[n] == faceIndex);
// found it, now move it up
while (n > 0)
{
if (faceValenceSort(n, n - 1))
{
faceReverseLookup[faceSorted[n]] = n - 1;
faceReverseLookup[faceSorted[n - 1]] = n;
std::swap(faceSorted[n], faceSorted[n - 1]);
n--;
}
else
{
break;
}
}
}
}
// move the rest of the old verts in the cache down and compute their new scores
for (uint32_t c0 = 0; c0 < entriesInCache0; ++c0)
{
OptimizeVertexData<IndexType>& vertexData = vertexDataList[cache0[c0]];
if (vertexData.cachePos1 >= entriesInCache1)
{
vertexData.cachePos1 = entriesInCache1;
cache1[entriesInCache1++] = cache0[c0];
vertexData.score = FindVertexScore(vertexData.activeFaceListSize, vertexData.cachePos1, lruCacheSize);
// don't need to re-sort this vertex... once it gets out of the cache, it'll have its original score
}
}
// find the best scoring triangle in the current cache (including up to 3 that were just evicted)
bestScore = -1.f;
for (uint32_t c1 = 0; c1 < entriesInCache1; ++c1)
{
OptimizeVertexData<IndexType>& vertexData = vertexDataList[cache1[c1]];
vertexData.cachePos0 = vertexData.cachePos1;
vertexData.cachePos1 = kEvictedCacheIndex;
for (uint32_t j = 0; j < vertexData.activeFaceListSize; ++j)
{
const uint32_t face = activeFaceList[size_t(vertexData.activeFaceListStart) + j];
float faceScore = 0.f;
for (uint32_t v = 0; v < 3; v++)
{
const OptimizeVertexData<IndexType>& faceVertexData = vertexDataList[vertexRemap[size_t(face) + v]];
faceScore += faceVertexData.score;
}
if (faceScore > bestScore)
{
bestScore = faceScore;
bestFace = face;
}
}
}
std::swap(cache0, cache1);
entriesInCache0 = std::min<uint32_t>(entriesInCache1, lruCacheSize);
}
for (; curFace < faceCount; ++curFace)
{
faceRemap[curFace] = UNUSED32;
}
return S_OK;
}
}
//=====================================================================================
// Entry-points
//=====================================================================================
_Use_decl_annotations_
HRESULT DirectX::OptimizeFacesLRU(
const uint16_t* indices,
size_t nFaces,
uint32_t* faceRemap,
uint32_t lruCacheSize)
{
if (!indices || !nFaces || !faceRemap)
return E_INVALIDARG;
if (!lruCacheSize || lruCacheSize > kMaxVertexCacheSize)
return E_INVALIDARG;
if ((uint64_t(nFaces) * 3) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
#ifdef _WIN32
InitOnceExecuteOnce(&s_initOnce, ComputeVertexScores, nullptr, nullptr);
#else
std::call_once(s_initOnce, ComputeVertexScores);
#endif
return OptimizeFacesImpl<uint16_t>(indices, static_cast<uint32_t>(nFaces * 3), faceRemap, lruCacheSize, 0);
}
_Use_decl_annotations_
HRESULT DirectX::OptimizeFacesLRU(
const uint32_t* indices,
size_t nFaces,
uint32_t* faceRemap,
uint32_t lruCacheSize)
{
if (!indices || !nFaces || !faceRemap)
return E_INVALIDARG;
if (!lruCacheSize || lruCacheSize > kMaxVertexCacheSize)
return E_INVALIDARG;
if ((uint64_t(nFaces) * 3) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
#ifdef _WIN32
InitOnceExecuteOnce(&s_initOnce, ComputeVertexScores, nullptr, nullptr);
#else
std::call_once(s_initOnce, ComputeVertexScores);
#endif
return OptimizeFacesImpl<uint32_t>(indices, static_cast<uint32_t>(nFaces * 3), faceRemap, lruCacheSize, 0);
}
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT DirectX::OptimizeFacesLRUEx(
const uint16_t* indices,
size_t nFaces,
const uint32_t* attributes,
uint32_t* faceRemap,
uint32_t lruCacheSize)
{
if (!indices || !nFaces || !attributes || !faceRemap)
return E_INVALIDARG;
if (!lruCacheSize || lruCacheSize > kMaxVertexCacheSize)
return E_INVALIDARG;
if ((uint64_t(nFaces) * 3) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
#ifdef _WIN32
InitOnceExecuteOnce(&s_initOnce, ComputeVertexScores, nullptr, nullptr);
#else
std::call_once(s_initOnce, ComputeVertexScores);
#endif
auto subsets = ComputeSubsets(attributes, nFaces);
if (subsets.empty())
return E_UNEXPECTED;
memset(faceRemap, 0, sizeof(uint32_t) * nFaces);
for (const auto& it : subsets)
{
if (it.first >= nFaces)
return E_UNEXPECTED;
if ((uint64_t(it.first) + uint64_t(it.second)) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
const uint32_t faceMax = uint32_t(it.first + it.second);
if (faceMax > nFaces)
return E_UNEXPECTED;
HRESULT hr = OptimizeFacesImpl<uint16_t>(
&indices[it.first * 3], static_cast<uint32_t>(it.second * 3),
&faceRemap[it.first], lruCacheSize, uint32_t(it.first));
if (FAILED(hr))
return hr;
}
return S_OK;
}
_Use_decl_annotations_
HRESULT DirectX::OptimizeFacesLRUEx(
const uint32_t* indices,
size_t nFaces,
const uint32_t* attributes,
uint32_t* faceRemap,
uint32_t lruCacheSize)
{
if (!indices || !nFaces || !attributes || !faceRemap)
return E_INVALIDARG;
if (!lruCacheSize || lruCacheSize > kMaxVertexCacheSize)
return E_INVALIDARG;
if ((uint64_t(nFaces) * 3) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
#ifdef _WIN32
InitOnceExecuteOnce(&s_initOnce, ComputeVertexScores, nullptr, nullptr);
#else
std::call_once(s_initOnce, ComputeVertexScores);
#endif
auto subsets = ComputeSubsets(attributes, nFaces);
if (subsets.empty())
return E_UNEXPECTED;
memset(faceRemap, 0, sizeof(uint32_t) * nFaces);
for (const auto& it : subsets)
{
if (it.first >= nFaces)
return E_UNEXPECTED;
if ((uint64_t(it.first) + uint64_t(it.second)) >= UINT32_MAX)
return HRESULT_E_ARITHMETIC_OVERFLOW;
const uint32_t faceMax = uint32_t(it.first + it.second);
if (faceMax > nFaces)
return E_UNEXPECTED;
HRESULT hr = OptimizeFacesImpl<uint32_t>(
&indices[it.first * 3], static_cast<uint32_t>(it.second * 3),
&faceRemap[it.first], lruCacheSize, uint32_t(it.first));
if (FAILED(hr))
return hr;
}
return S_OK;
}
You can’t perform that action at this time.
