Repository navigation
Expand file tree
/
Copy pathclusterizer.cpp
More file actions
1771 lines (1359 loc) · 60 KB
/
Copy pathclusterizer.cpp
File metadata and controls
1771 lines (1359 loc) · 60 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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"
#include <assert.h>
#include <float.h>
#include <math.h>
#include <string.h>
// The block below auto-detects SIMD ISA that can be used on the target platform
#ifndef MESHOPTIMIZER_NO_SIMD
#if defined(__SSE2__) || (defined(_MSC_VER) && defined(_M_X64))
#define SIMD_SSE
#include <emmintrin.h>
#elif defined(__aarch64__) || (defined(_MSC_VER) && defined(_M_ARM64) && _MSC_VER >= 1922)
#define SIMD_NEON
#include <arm_neon.h>
#endif
#endif // !MESHOPTIMIZER_NO_SIMD
// This work is based on:
// Graham Wihlidal. Optimizing the Graphics Pipeline with Compute. 2016
// Matthaeus Chajdas. GeometryFX 1.2 - Cluster Culling. 2016
// Jack Ritter. An Efficient Bounding Sphere. 1990
// Thomas Larsson. Fast and Tight Fitting Bounding Spheres. 2008
// Ingo Wald, Vlastimil Havran. On building fast kd-Trees for Ray Tracing, and on doing that in O(N log N). 2006
namespace meshopt
{
// This must be <= 256 since meshlet indices are stored as bytes
const size_t kMeshletMaxVertices = 256;
// A reasonable limit is around 2*max_vertices or less
const size_t kMeshletMaxTriangles = 512;
// We keep a limited number of seed triangles and add a few triangles per finished meshlet
const size_t kMeshletMaxSeeds = 256;
const size_t kMeshletAddSeeds = 4;
// To avoid excessive recursion for malformed inputs, we limit the maximum depth of the tree
const int kMeshletMaxTreeDepth = 50;
struct TriangleAdjacency2
{
unsigned int* counts;
unsigned int* offsets;
unsigned int* data;
};
static void buildTriangleAdjacency(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
{
size_t face_count = index_count / 3;
// allocate arrays
adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
adjacency.data = allocator.allocate<unsigned int>(index_count);
// fill triangle counts
memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
for (size_t i = 0; i < index_count; ++i)
{
assert(indices[i] < vertex_count);
adjacency.counts[indices[i]]++;
}
// fill offset table
unsigned int offset = 0;
for (size_t i = 0; i < vertex_count; ++i)
{
adjacency.offsets[i] = offset;
offset += adjacency.counts[i];
}
assert(offset == index_count);
// fill triangle data
for (size_t i = 0; i < face_count; ++i)
{
unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
adjacency.data[adjacency.offsets[a]++] = unsigned(i);
adjacency.data[adjacency.offsets[b]++] = unsigned(i);
adjacency.data[adjacency.offsets[c]++] = unsigned(i);
}
// fix offsets that have been disturbed by the previous pass
for (size_t i = 0; i < vertex_count; ++i)
{
assert(adjacency.offsets[i] >= adjacency.counts[i]);
adjacency.offsets[i] -= adjacency.counts[i];
}
}
static void buildTriangleAdjacencySparse(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
{
size_t face_count = index_count / 3;
// sparse mode can build adjacency more quickly by ignoring unused vertices, using a bit to mark visited vertices
const unsigned int sparse_seen = 1u << 31;
assert(index_count < sparse_seen);
// allocate arrays
adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
adjacency.data = allocator.allocate<unsigned int>(index_count);
// fill triangle counts
for (size_t i = 0; i < index_count; ++i)
assert(indices[i] < vertex_count);
for (size_t i = 0; i < index_count; ++i)
adjacency.counts[indices[i]] = 0;
for (size_t i = 0; i < index_count; ++i)
adjacency.counts[indices[i]]++;
// fill offset table; uses sparse_seen bit to tag visited vertices
unsigned int offset = 0;
for (size_t i = 0; i < index_count; ++i)
{
unsigned int v = indices[i];
if ((adjacency.counts[v] & sparse_seen) == 0)
{
adjacency.offsets[v] = offset;
offset += adjacency.counts[v];
adjacency.counts[v] |= sparse_seen;
}
}
assert(offset == index_count);
// fill triangle data
for (size_t i = 0; i < face_count; ++i)
{
unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
adjacency.data[adjacency.offsets[a]++] = unsigned(i);
adjacency.data[adjacency.offsets[b]++] = unsigned(i);
adjacency.data[adjacency.offsets[c]++] = unsigned(i);
}
// fix offsets that have been disturbed by the previous pass
// also fix counts (that were marked with sparse_seen by the first pass)
for (size_t i = 0; i < index_count; ++i)
{
unsigned int v = indices[i];
if (adjacency.counts[v] & sparse_seen)
{
adjacency.counts[v] &= ~sparse_seen;
assert(adjacency.offsets[v] >= adjacency.counts[v]);
adjacency.offsets[v] -= adjacency.counts[v];
}
}
}
static void clearUsed(short* used, size_t vertex_count, const unsigned int* indices, size_t index_count)
{
// for sparse inputs, it's faster to only clear vertices referenced by the index buffer
if (vertex_count <= index_count)
memset(used, -1, vertex_count * sizeof(short));
else
for (size_t i = 0; i < index_count; ++i)
{
assert(indices[i] < vertex_count);
used[indices[i]] = -1;
}
}
static void computeBoundingSphere(float result[4], const float* points, size_t count, size_t points_stride, const float* radii, size_t radii_stride, size_t axis_count)
{
static const float kAxes[7][3] = {
// X, Y, Z
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
// XYZ, -XYZ, X-YZ, XY-Z; normalized to unit length
{0.57735026f, 0.57735026f, 0.57735026f},
{-0.57735026f, 0.57735026f, 0.57735026f},
{0.57735026f, -0.57735026f, 0.57735026f},
{0.57735026f, 0.57735026f, -0.57735026f},
};
assert(count > 0);
assert(axis_count <= sizeof(kAxes) / sizeof(kAxes[0]));
size_t points_stride_float = points_stride / sizeof(float);
size_t radii_stride_float = radii_stride / sizeof(float);
// find extremum points along all axes; for each axis we get a pair of points with min/max coordinates
size_t pmin[7], pmax[7];
float tmin[7], tmax[7];
for (size_t axis = 0; axis < axis_count; ++axis)
{
pmin[axis] = pmax[axis] = 0;
tmin[axis] = FLT_MAX;
tmax[axis] = -FLT_MAX;
}
for (size_t i = 0; i < count; ++i)
{
const float* p = points + i * points_stride_float;
float r = radii[i * radii_stride_float];
for (size_t axis = 0; axis < axis_count; ++axis)
{
const float* ax = kAxes[axis];
float tp = ax[0] * p[0] + ax[1] * p[1] + ax[2] * p[2];
float tpmin = tp - r, tpmax = tp + r;
pmin[axis] = (tpmin < tmin[axis]) ? i : pmin[axis];
pmax[axis] = (tpmax > tmax[axis]) ? i : pmax[axis];
tmin[axis] = (tpmin < tmin[axis]) ? tpmin : tmin[axis];
tmax[axis] = (tpmax > tmax[axis]) ? tpmax : tmax[axis];
}
}
// find the pair of points with largest distance
size_t paxis = 0;
float paxisdr = 0;
for (size_t axis = 0; axis < axis_count; ++axis)
{
const float* p1 = points + pmin[axis] * points_stride_float;
const float* p2 = points + pmax[axis] * points_stride_float;
float r1 = radii[pmin[axis] * radii_stride_float];
float r2 = radii[pmax[axis] * radii_stride_float];
float d2 = (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2]);
float dr = sqrtf(d2) + r1 + r2;
if (dr > paxisdr)
{
paxisdr = dr;
paxis = axis;
}
}
// use the longest segment as the initial sphere diameter
const float* p1 = points + pmin[paxis] * points_stride_float;
const float* p2 = points + pmax[paxis] * points_stride_float;
float r1 = radii[pmin[paxis] * radii_stride_float];
float r2 = radii[pmax[paxis] * radii_stride_float];
float paxisd = sqrtf((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2]));
float paxisk = paxisd > 0 ? (paxisd + r2 - r1) / (2 * paxisd) : 0.f;
float center[3] = {p1[0] + (p2[0] - p1[0]) * paxisk, p1[1] + (p2[1] - p1[1]) * paxisk, p1[2] + (p2[2] - p1[2]) * paxisk};
float radius = paxisdr / 2;
// iteratively adjust the sphere up until all points fit
for (size_t i = 0; i < count; ++i)
{
const float* p = points + i * points_stride_float;
float r = radii[i * radii_stride_float];
float d2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]) + (p[2] - center[2]) * (p[2] - center[2]);
float d = sqrtf(d2);
if (d + r > radius)
{
float k = d > 0 ? (d + r - radius) / (2 * d) : 0.f;
center[0] += k * (p[0] - center[0]);
center[1] += k * (p[1] - center[1]);
center[2] += k * (p[2] - center[2]);
radius = (radius + d + r) / 2;
}
}
result[0] = center[0];
result[1] = center[1];
result[2] = center[2];
result[3] = radius;
}
struct Cone
{
float px, py, pz;
float nx, ny, nz;
};
static float getMeshletScore(float distance, float spread, float cone_weight, float expected_radius)
{
float cone = 1.f - spread * cone_weight;
float cone_clamped = cone < 1e-3f ? 1e-3f : cone;
return (1 + distance / expected_radius * (1 - cone_weight)) * cone_clamped;
}
static Cone getMeshletCone(const Cone& acc, unsigned int triangle_count)
{
Cone result = acc;
float center_scale = triangle_count == 0 ? 0.f : 1.f / float(triangle_count);
result.px *= center_scale;
result.py *= center_scale;
result.pz *= center_scale;
float axis_length = result.nx * result.nx + result.ny * result.ny + result.nz * result.nz;
float axis_scale = axis_length == 0.f ? 0.f : 1.f / sqrtf(axis_length);
result.nx *= axis_scale;
result.ny *= axis_scale;
result.nz *= axis_scale;
return result;
}
static float computeTriangleCones(Cone* triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
{
(void)vertex_count;
size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
size_t face_count = index_count / 3;
float mesh_area = 0;
for (size_t i = 0; i < face_count; ++i)
{
unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
assert(a < vertex_count && b < vertex_count && c < vertex_count);
const float* p0 = vertex_positions + vertex_stride_float * a;
const float* p1 = vertex_positions + vertex_stride_float * b;
const float* p2 = vertex_positions + vertex_stride_float * c;
float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
float normalx = p10[1] * p20[2] - p10[2] * p20[1];
float normaly = p10[2] * p20[0] - p10[0] * p20[2];
float normalz = p10[0] * p20[1] - p10[1] * p20[0];
float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz);
float invarea = (area == 0.f) ? 0.f : 1.f / area;
triangles[i].px = (p0[0] + p1[0] + p2[0]) / 3.f;
triangles[i].py = (p0[1] + p1[1] + p2[1]) / 3.f;
triangles[i].pz = (p0[2] + p1[2] + p2[2]) / 3.f;
triangles[i].nx = normalx * invarea;
triangles[i].ny = normaly * invarea;
triangles[i].nz = normalz * invarea;
mesh_area += area;
}
return mesh_area;
}
static bool appendMeshlet(meshopt_Meshlet& meshlet, unsigned int a, unsigned int b, unsigned int c, short* used, meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t meshlet_offset, size_t max_vertices, size_t max_triangles, bool split = false)
{
short& av = used[a];
short& bv = used[b];
short& cv = used[c];
bool result = false;
int used_extra = (av < 0) + (bv < 0) + (cv < 0);
if (meshlet.vertex_count + used_extra > max_vertices || meshlet.triangle_count >= max_triangles || split)
{
meshlets[meshlet_offset] = meshlet;
for (size_t j = 0; j < meshlet.vertex_count; ++j)
used[meshlet_vertices[meshlet.vertex_offset + j]] = -1;
meshlet.vertex_offset += meshlet.vertex_count;
meshlet.triangle_offset += meshlet.triangle_count * 3;
meshlet.vertex_count = 0;
meshlet.triangle_count = 0;
result = true;
}
if (av < 0)
{
av = short(meshlet.vertex_count);
meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = a;
}
if (bv < 0)
{
bv = short(meshlet.vertex_count);
meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = b;
}
if (cv < 0)
{
cv = short(meshlet.vertex_count);
meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = c;
}
meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 0] = (unsigned char)av;
meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 1] = (unsigned char)bv;
meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 2] = (unsigned char)cv;
meshlet.triangle_count++;
return result;
}
static unsigned int getNeighborTriangle(const meshopt_Meshlet& meshlet, const Cone& meshlet_cone, const unsigned int* meshlet_vertices, const unsigned int* indices, const TriangleAdjacency2& adjacency, const Cone* triangles, const unsigned int* live_triangles, const short* used, float meshlet_expected_radius, float cone_weight)
{
unsigned int best_triangle = ~0u;
int best_priority = 5;
float best_score = FLT_MAX;
for (size_t i = 0; i < meshlet.vertex_count; ++i)
{
unsigned int index = meshlet_vertices[meshlet.vertex_offset + i];
unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index];
size_t neighbors_size = adjacency.counts[index];
for (size_t j = 0; j < neighbors_size; ++j)
{
unsigned int triangle = neighbors[j];
unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2];
int extra = (used[a] < 0) + (used[b] < 0) + (used[c] < 0);
assert(extra <= 2);
int priority = -1;
// triangles that don't add new vertices to meshlets are max. priority
if (extra == 0)
priority = 0;
// artificially increase the priority of dangling triangles as they're expensive to add to new meshlets
else if (live_triangles[a] == 1 || live_triangles[b] == 1 || live_triangles[c] == 1)
priority = 1;
// if two vertices have live count of 2, removing this triangle will make another triangle dangling which is good for overall flow
else if ((live_triangles[a] == 2) + (live_triangles[b] == 2) + (live_triangles[c] == 2) >= 2)
priority = 1 + extra;
// otherwise adjust priority to be after the above cases, 3 or 4 based on used[] count
else
priority = 2 + extra;
// since topology-based priority is always more important than the score, we can skip scoring in some cases
if (priority > best_priority)
continue;
const Cone& tri_cone = triangles[triangle];
float dx = tri_cone.px - meshlet_cone.px, dy = tri_cone.py - meshlet_cone.py, dz = tri_cone.pz - meshlet_cone.pz;
float distance = sqrtf(dx * dx + dy * dy + dz * dz);
float spread = tri_cone.nx * meshlet_cone.nx + tri_cone.ny * meshlet_cone.ny + tri_cone.nz * meshlet_cone.nz;
float score = getMeshletScore(distance, spread, cone_weight, meshlet_expected_radius);
// note that topology-based priority is always more important than the score
// this helps maintain reasonable effectiveness of meshlet data and reduces scoring cost
if (priority < best_priority || score < best_score)
{
best_triangle = triangle;
best_priority = priority;
best_score = score;
}
}
}
return best_triangle;
}
static size_t appendSeedTriangles(unsigned int* seeds, const meshopt_Meshlet& meshlet, const unsigned int* meshlet_vertices, const unsigned int* indices, const TriangleAdjacency2& adjacency, const Cone* triangles, const unsigned int* live_triangles, float cornerx, float cornery, float cornerz)
{
unsigned int best_seeds[kMeshletAddSeeds];
unsigned int best_live[kMeshletAddSeeds];
float best_score[kMeshletAddSeeds];
for (size_t i = 0; i < kMeshletAddSeeds; ++i)
{
best_seeds[i] = ~0u;
best_live[i] = ~0u;
best_score[i] = FLT_MAX;
}
for (size_t i = 0; i < meshlet.vertex_count; ++i)
{
unsigned int index = meshlet_vertices[meshlet.vertex_offset + i];
unsigned int best_neighbor = ~0u;
unsigned int best_neighbor_live = ~0u;
// find the neighbor with the smallest live metric
unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index];
size_t neighbors_size = adjacency.counts[index];
for (size_t j = 0; j < neighbors_size; ++j)
{
unsigned int triangle = neighbors[j];
unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2];
unsigned int live = live_triangles[a] + live_triangles[b] + live_triangles[c];
if (live < best_neighbor_live)
{
best_neighbor = triangle;
best_neighbor_live = live;
}
}
// add the neighbor to the list of seeds; the list is unsorted and the replacement criteria is approximate
if (best_neighbor == ~0u)
continue;
float dx = triangles[best_neighbor].px - cornerx, dy = triangles[best_neighbor].py - cornery, dz = triangles[best_neighbor].pz - cornerz;
float best_neighbor_score = sqrtf(dx * dx + dy * dy + dz * dz);
for (size_t j = 0; j < kMeshletAddSeeds; ++j)
{
// non-strict comparison reduces the number of duplicate seeds (triangles adjacent to multiple vertices)
if (best_neighbor_live < best_live[j] || (best_neighbor_live == best_live[j] && best_neighbor_score <= best_score[j]))
{
best_seeds[j] = best_neighbor;
best_live[j] = best_neighbor_live;
best_score[j] = best_neighbor_score;
break;
}
}
}
// add surviving seeds to the meshlet
size_t seed_count = 0;
for (size_t i = 0; i < kMeshletAddSeeds; ++i)
if (best_seeds[i] != ~0u)
seeds[seed_count++] = best_seeds[i];
return seed_count;
}
static size_t pruneSeedTriangles(unsigned int* seeds, size_t seed_count, const unsigned char* emitted_flags)
{
size_t result = 0;
for (size_t i = 0; i < seed_count; ++i)
{
unsigned int index = seeds[i];
seeds[result] = index;
result += emitted_flags[index] == 0;
}
return result;
}
static unsigned int selectSeedTriangle(const unsigned int* seeds, size_t seed_count, const unsigned int* indices, const Cone* triangles, const unsigned int* live_triangles, float cornerx, float cornery, float cornerz)
{
unsigned int best_seed = ~0u;
unsigned int best_live = ~0u;
float best_score = FLT_MAX;
for (size_t i = 0; i < seed_count; ++i)
{
unsigned int index = seeds[i];
unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2];
unsigned int live = live_triangles[a] + live_triangles[b] + live_triangles[c];
float dx = triangles[index].px - cornerx, dy = triangles[index].py - cornery, dz = triangles[index].pz - cornerz;
float score = sqrtf(dx * dx + dy * dy + dz * dz);
if (live < best_live || (live == best_live && score < best_score))
{
best_seed = index;
best_live = live;
best_score = score;
}
}
return best_seed;
}
struct KDNode
{
union
{
float split;
unsigned int index;
};
// leaves: axis = 3, children = number of points including this one
// branches: axis != 3, left subtree = skip 1, right subtree = skip 1+children
unsigned int axis : 2;
unsigned int children : 30;
};
static size_t kdtreePartition(unsigned int* indices, size_t count, const float* points, size_t stride, unsigned int axis, float pivot)
{
size_t m = 0;
// invariant: elements in range [0, m) are < pivot, elements in range [m, i) are >= pivot
for (size_t i = 0; i < count; ++i)
{
float v = points[indices[i] * stride + axis];
// swap(m, i) unconditionally
unsigned int t = indices[m];
indices[m] = indices[i];
indices[i] = t;
// when v >= pivot, we swap i with m without advancing it, preserving invariants
m += v < pivot;
}
return m;
}
static size_t kdtreeBuildLeaf(size_t offset, KDNode* nodes, size_t node_count, unsigned int* indices, size_t count)
{
assert(offset + count <= node_count);
(void)node_count;
KDNode& result = nodes[offset];
result.index = indices[0];
result.axis = 3;
result.children = unsigned(count);
// all remaining points are stored in nodes immediately following the leaf
for (size_t i = 1; i < count; ++i)
{
KDNode& tail = nodes[offset + i];
tail.index = indices[i];
tail.axis = 3;
tail.children = ~0u >> 2; // bogus value to prevent misuse
}
return offset + count;
}
static size_t kdtreeBuild(size_t offset, KDNode* nodes, size_t node_count, const float* points, size_t stride, unsigned int* indices, size_t count, size_t leaf_size)
{
assert(count > 0);
assert(offset < node_count);
if (count <= leaf_size)
return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
float mean[3] = {};
float vars[3] = {};
float runc = 1, runs = 1;
// gather statistics on the points in the subtree using Welford's algorithm
for (size_t i = 0; i < count; ++i, runc += 1.f, runs = 1.f / runc)
{
const float* point = points + indices[i] * stride;
for (int k = 0; k < 3; ++k)
{
float delta = point[k] - mean[k];
mean[k] += delta * runs;
vars[k] += delta * (point[k] - mean[k]);
}
}
// split axis is one where the variance is largest
unsigned int axis = (vars[0] >= vars[1] && vars[0] >= vars[2]) ? 0 : (vars[1] >= vars[2] ? 1 : 2);
float split = mean[axis];
size_t middle = kdtreePartition(indices, count, points, stride, axis, split);
// when the partition is degenerate simply consolidate the points into a single node
if (middle <= leaf_size / 2 || middle >= count - leaf_size / 2)
return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
KDNode& result = nodes[offset];
result.split = split;
result.axis = axis;
// left subtree is right after our node
size_t next_offset = kdtreeBuild(offset + 1, nodes, node_count, points, stride, indices, middle, leaf_size);
// distance to the right subtree is represented explicitly
assert(next_offset - offset > 1);
result.children = unsigned(next_offset - offset - 1);
return kdtreeBuild(next_offset, nodes, node_count, points, stride, indices + middle, count - middle, leaf_size);
}
static void kdtreeNearest(KDNode* nodes, unsigned int root, const float* points, size_t stride, const unsigned char* emitted_flags, const float* position, unsigned int& result, float& limit)
{
const KDNode& node = nodes[root];
if (node.children == 0)
return;
if (node.axis == 3)
{
// leaf
bool inactive = true;
for (unsigned int i = 0; i < node.children; ++i)
{
unsigned int index = nodes[root + i].index;
if (emitted_flags[index])
continue;
inactive = false;
const float* point = points + index * stride;
float dx = point[0] - position[0], dy = point[1] - position[1], dz = point[2] - position[2];
float distance = sqrtf(dx * dx + dy * dy + dz * dz);
if (distance < limit)
{
result = index;
limit = distance;
}
}
// deactivate leaves that no longer have items to emit
if (inactive)
nodes[root].children = 0;
}
else
{
// branch; we order recursion to process the node that search position is in first
float delta = position[node.axis] - node.split;
unsigned int first = (delta <= 0) ? 0 : node.children;
unsigned int second = first ^ node.children;
// deactivate branches that no longer have items to emit to accelerate traversal
// note that we do this *before* recursing which delays deactivation but keeps tail calls
if ((nodes[root + 1 + first].children | nodes[root + 1 + second].children) == 0)
nodes[root].children = 0;
kdtreeNearest(nodes, root + 1 + first, points, stride, emitted_flags, position, result, limit);
// only process the other node if it can have a match based on closest distance so far
if (fabsf(delta) <= limit)
kdtreeNearest(nodes, root + 1 + second, points, stride, emitted_flags, position, result, limit);
}
}
struct BVHBoxT
{
float min[4];
float max[4];
};
struct BVHBox
{
float min[3];
float max[3];
};
#if defined(SIMD_SSE)
static float boxMerge(BVHBoxT& box, const BVHBox& other)
{
__m128 min = _mm_loadu_ps(box.min);
__m128 max = _mm_loadu_ps(box.max);
min = _mm_min_ps(min, _mm_loadu_ps(other.min));
max = _mm_max_ps(max, _mm_loadu_ps(other.max));
_mm_storeu_ps(box.min, min);
_mm_storeu_ps(box.max, max);
__m128 size = _mm_sub_ps(max, min);
__m128 size_yzx = _mm_shuffle_ps(size, size, _MM_SHUFFLE(0, 0, 2, 1));
__m128 mul = _mm_mul_ps(size, size_yzx);
__m128 sum_xy = _mm_add_ss(mul, _mm_shuffle_ps(mul, mul, _MM_SHUFFLE(1, 1, 1, 1)));
__m128 sum_xyz = _mm_add_ss(sum_xy, _mm_shuffle_ps(mul, mul, _MM_SHUFFLE(2, 2, 2, 2)));
return _mm_cvtss_f32(sum_xyz);
}
#elif defined(SIMD_NEON)
static float boxMerge(BVHBoxT& box, const BVHBox& other)
{
float32x4_t min = vld1q_f32(box.min);
float32x4_t max = vld1q_f32(box.max);
min = vminq_f32(min, vld1q_f32(other.min));
max = vmaxq_f32(max, vld1q_f32(other.max));
vst1q_f32(box.min, min);
vst1q_f32(box.max, max);
float32x4_t size = vsubq_f32(max, min);
float32x4_t size_yzx = vextq_f32(vextq_f32(size, size, 3), size, 2);
float32x4_t mul = vmulq_f32(size, size_yzx);
float sum_xy = vgetq_lane_f32(mul, 0) + vgetq_lane_f32(mul, 1);
float sum_xyz = sum_xy + vgetq_lane_f32(mul, 2);
return sum_xyz;
}
#else
static float boxMerge(BVHBoxT& box, const BVHBox& other)
{
for (int k = 0; k < 3; ++k)
{
box.min[k] = other.min[k] < box.min[k] ? other.min[k] : box.min[k];
box.max[k] = other.max[k] > box.max[k] ? other.max[k] : box.max[k];
}
float sx = box.max[0] - box.min[0], sy = box.max[1] - box.min[1], sz = box.max[2] - box.min[2];
return sx * sy + sx * sz + sy * sz;
}
#endif
inline unsigned int radixFloat(unsigned int v)
{
// if sign bit is 0, flip sign bit
// if sign bit is 1, flip everything
unsigned int mask = (int(v) >> 31) | 0x80000000;
return v ^ mask;
}
static void computeHistogram(unsigned int (&hist)[1024][3], const float* data, size_t count)
{
memset(hist, 0, sizeof(hist));
const unsigned int* bits = reinterpret_cast<const unsigned int*>(data);
// compute 3 10-bit histograms in parallel (dropping 2 LSB)
for (size_t i = 0; i < count; ++i)
{
unsigned int id = radixFloat(bits[i]);
hist[(id >> 2) & 1023][0]++;
hist[(id >> 12) & 1023][1]++;
hist[(id >> 22) & 1023][2]++;
}
unsigned int sum0 = 0, sum1 = 0, sum2 = 0;
// replace histogram data with prefix histogram sums in-place
for (int i = 0; i < 1024; ++i)
{
unsigned int hx = hist[i][0], hy = hist[i][1], hz = hist[i][2];
hist[i][0] = sum0;
hist[i][1] = sum1;
hist[i][2] = sum2;
sum0 += hx;
sum1 += hy;
sum2 += hz;
}
assert(sum0 == count && sum1 == count && sum2 == count);
}
static void radixPass(unsigned int* destination, const unsigned int* source, const float* keys, size_t count, unsigned int (&hist)[1024][3], int pass)
{
const unsigned int* bits = reinterpret_cast<const unsigned int*>(keys);
int bitoff = pass * 10 + 2; // drop 2 LSB to be able to use 3 10-bit passes
for (size_t i = 0; i < count; ++i)
{
unsigned int id = (radixFloat(bits[source[i]]) >> bitoff) & 1023;
destination[hist[id][pass]++] = source[i];
}
}
static void bvhPrepare(BVHBox* boxes, float* centroids, const unsigned int* indices, size_t face_count, const float* vertex_positions, size_t vertex_count, size_t vertex_stride_float)
{
(void)vertex_count;
for (size_t i = 0; i < face_count; ++i)
{
unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
assert(a < vertex_count && b < vertex_count && c < vertex_count);
const float* va = vertex_positions + vertex_stride_float * a;
const float* vb = vertex_positions + vertex_stride_float * b;
const float* vc = vertex_positions + vertex_stride_float * c;
BVHBox& box = boxes[i];
for (int k = 0; k < 3; ++k)
{
box.min[k] = va[k] < vb[k] ? va[k] : vb[k];
box.min[k] = vc[k] < box.min[k] ? vc[k] : box.min[k];
box.max[k] = va[k] > vb[k] ? va[k] : vb[k];
box.max[k] = vc[k] > box.max[k] ? vc[k] : box.max[k];
centroids[i + face_count * k] = (box.min[k] + box.max[k]) / 2.f;
}
}
}
static size_t bvhCountVertices(const unsigned int* order, size_t count, short* used, const unsigned int* indices, unsigned int* out = NULL)
{
// count number of unique vertices
size_t used_vertices = 0;
for (size_t i = 0; i < count; ++i)
{
unsigned int index = order[i];
unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2];
used_vertices += (used[a] < 0) + (used[b] < 0) + (used[c] < 0);
used[a] = used[b] = used[c] = 1;
if (out)
out[i] = unsigned(used_vertices);
}
// reset used[] for future invocations
for (size_t i = 0; i < count; ++i)
{
unsigned int index = order[i];
unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2];
used[a] = used[b] = used[c] = -1;
}
return used_vertices;
}
static void bvhPackLeaf(unsigned char* boundary, size_t count)
{
// mark meshlet boundary for future reassembly
assert(count > 0);
boundary[0] = 1;
memset(boundary + 1, 0, count - 1);
}
static void bvhPackTail(unsigned char* boundary, const unsigned int* order, size_t count, short* used, const unsigned int* indices, size_t max_vertices, size_t max_triangles)
{
for (size_t i = 0; i < count;)
{
size_t chunk = i + max_triangles <= count ? max_triangles : count - i;
if (bvhCountVertices(order + i, chunk, used, indices) <= max_vertices)
{
bvhPackLeaf(boundary + i, chunk);
i += chunk;
continue;
}
// chunk is vertex bound, split it into smaller meshlets
assert(chunk > max_vertices / 3);
bvhPackLeaf(boundary + i, max_vertices / 3);
i += max_vertices / 3;
}
}
static bool bvhDivisible(size_t count, size_t min, size_t max)
{
// count is representable as a sum of values in [min..max] if if it in range of [k*min..k*min+k*(max-min)]
// equivalent to ceil(count / max) <= floor(count / min), but the form below allows using idiv (see nv_cluster_builder)
// we avoid expensive integer divisions in the common case where min is <= max/2
return min * 2 <= max ? count >= min : count % min <= (count / min) * (max - min);
}
static void bvhComputeArea(float* areas, const BVHBox* boxes, const unsigned int* order, size_t count)
{
BVHBoxT accuml = {{FLT_MAX, FLT_MAX, FLT_MAX, 0}, {-FLT_MAX, -FLT_MAX, -FLT_MAX, 0}};
BVHBoxT accumr = accuml;
for (size_t i = 0; i < count; ++i)
{
float larea = boxMerge(accuml, boxes[order[i]]);
float rarea = boxMerge(accumr, boxes[order[count - 1 - i]]);
areas[i] = larea;
areas[i + count] = rarea;
}
}
static size_t bvhPivot(const float* areas, const unsigned int* vertices, size_t count, size_t step, size_t min, size_t max, float fill, size_t maxfill, float* out_cost)
{
bool aligned = count >= min * 2 && bvhDivisible(count, min, max);
size_t end = aligned ? count - min : count - 1;
float rmaxfill = 1.f / float(int(maxfill));
// find best split that minimizes SAH
size_t bestsplit = 0;
float bestcost = FLT_MAX;
for (size_t i = min - 1; i < end; i += step)
{
size_t lsplit = i + 1, rsplit = count - (i + 1);
if (!bvhDivisible(lsplit, min, max))
continue;
if (aligned && !bvhDivisible(rsplit, min, max))
continue;