-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightslice.cc
2454 lines (1888 loc) · 80.6 KB
/
lightslice.cc
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
#include "lightslice.h"
#include "scene.h"
#include "camera.h"
#include "aggregate.h"
#include "shape.h"
#include "concentric_mapping.h"
#include "brdf_point_light.h"
#include "cluster.h"
#include "cluster_builder.h"
#include "stats.h"
#include "vpl.h"
#include "log.h"
#include "image_block_view.h"
#include "mesh_view.h" // debug only
#include <Eigen/Dense>
using namespace Eigen;
namespace Renzoku {
LightSlice::LightSlice() : kdtree(NULL), node_data(NULL), R(LightTransportMatrix(1, 1)) {
num_clusters = 600;
max_slice_size = 256;
num_neighbor_slices = 16;
max_slice_clusters = 2 * num_clusters;
num_brdf_samples = 1024;
incident_radiances.resize(num_brdf_samples);
is_incident_radiance_reliable.resize(num_brdf_samples);
brdf_samples.resize(num_brdf_samples);
use_poly_interpolation = false;
poly_deg = 5;
// cone too small causes numerical error in the uniform sampling
uniform_cone_half_angle = A_PI * 0.05f;
// Metropolis sampling
vector<Float> mutation_dist(Mutation::NUM_MUTATIONS);
mutation_dist[Mutation::UNIFORM] = 0.33f;
mutation_dist[Mutation::VPL] = 0.0f; // this techinique, while biased towards VPLs, is not a problem as long as entire density over entire hemisphere is positive.
mutation_dist[Mutation::CONE_PERTURB] = 0.33f;
mutation_pdf.set_distribution(mutation_dist);
density_radius = 0.1f; // the radius controls bias
num_sum_samples = 100000;
perturb_cone_half_angle = A_PI * 0.05f;
perturb_cos_theta_max = cos(perturb_cone_half_angle);
perturb_cone_pdf = 1.0f / (TWO_PI * (1.0f - perturb_cos_theta_max));
luminance_map_resolution = 32; // map resolution in Jensen's method
same_local_wi = true; // the sampled direction is the same in world or local space.
// Apr 06:
// same local: ensures direction always in upper hemisphere, and therefore avoid splotches
//
// there is no real benefit between the two, but in terms of BRDF evaluation for opaque surface,
// is more efficient because at least the directions do not fail the under-surface test.
view_similarity_cosine_max = cos(A_PI * 0.25f); // this is a loose constraint. In most cases view difference, if not too severe, can still reuse the slice's map for sampling.
metropolis_neighbor_slices = 1; // by default for performance we just want to use the slice that contains the gather point
metropolis_neighbor_slices_when_failed = 32; // only when it's invalid then we look at its neighbors
metropolis_tmp_slice_indices.reserve(metropolis_neighbor_slices_when_failed);
metropolis_tmp_slice_pdf.reserve(metropolis_neighbor_slices_when_failed);
luminance_map_epsilon = 1e-3f; // Jensen's approach: ratio of total illumination for each pixel, in which a direction is selected.
density_epsilon_ratio = 1e-2f; // relative to total incoming radiance by VPLs (without epsilon)
distance_epsilon = 1.0f;
sampling_type = LocalSampler::METROPOLIS;
radius_type = LocalDensity::FIXED_RADIUS;
Log::info() << "LightSlice sampler type: " << sampling_type << endn;
}
bool LightSlice::is_view_similar(const Onb &uvn1, const Onb &uvn2) {
// FIXED:
// Apr 05
//
// View check causes splotches (patchy results) on curvy surfaces
//
// A solution is to simply disable view check as we already cluster gather points into patches
// A point that uses a sampling record that has view difference
// will still remains unbiased because all directions in the hemisphere
// has a chance to be sampled.
// Using such a record is still better than uniform sampling.
//
// Apr 06:
// We set the similarly angle to 45 deg, which is a very loose constraint.
// This avoids splotches, but also ensures more efficiency at extreme cases (where two patches face different directions)
if (dot(uvn1.n(), uvn2.n()) < view_similarity_cosine_max) {
return false;
}
if (same_local_wi) {
if (dot(uvn1.u(), uvn2.u()) < view_similarity_cosine_max) {
return false;
}
} else {
// When we assume world wi is the same, it means we assume the tangent is the same, which leads to
// the local basis are already the same.
// Therefore, it is not necessary to care about right vector at the receiver.
//
// But this will not support anisotropic materials well unless quads are used.
}
return true;
}
inline static Vec6 concat_vec6(const Vec3 &u, const Vec3 &v) {
Vec6 p;
p.p[0] = u.x();
p.p[1] = u.y();
p.p[2] = u.z();
p.p[3] = v.x();
p.p[4] = v.y();
p.p[5] = v.z();
return p;
}
/**
* Mapping from vertex position and normal to 6D space
* as suggested in Multidimensional Lightcuts paper.
*/
inline static Vec6 map_vec6(const Vec3 &v, const Vec3 &n, Material *m, const Vec3 &wo, Float diagonal) {
const Float weight = 1.0f / 16.0f * diagonal;
const Float max_gloss_scale = 4.0f;
const Float max_gloss_exponential = 1000.0f;
Vec3 directionality;
if (m) {
switch (m->get_bsdf()->get_bsdf_type()) {
case Bsdf::PHONG:
case Bsdf::WARD:
{
ISpecular *bsdf = dynamic_cast<ISpecular *>(m->get_bsdf());
Vec3 wr = 2.0f * dot(wo, n) * n - wo;
Float gloss_scale = std::min(max_gloss_scale, std::max(1.0f, bsdf->get_gloss_exponential() / max_gloss_exponential));
directionality = wr * gloss_scale;
break;
}
case Bsdf::MIRROR:
case Bsdf::GLASS:
{
Vec3 wr = 2.0f * dot(wo, n) * n - wo;
directionality = wr * max_gloss_scale;
break;
}
case Bsdf::LAMBERTIAN:
default:
directionality = n;
break;
}
} else {
directionality = n;
}
Vec3 position = v;
Vec6 p;
p.p[0] = position.x();
p.p[1] = position.y();
p.p[2] = position.z();
p.p[3] = directionality.x() * weight;
p.p[4] = directionality.y() * weight;
p.p[5] = directionality.z() * weight;
return p;
}
inline static Vec9 map_vec9(const Vec3 &v, const Vec3 &n, const Vec3 &u, Material *m, const Vec3 &wo, Float diagonal) {
// lower weight ensures smaller patch but normal and tangent constraint becomes loose.
// increase the number of slices if we want smaller patch but keep normal and tangent constraint.
const Float weight = 1.0f / 16.0f * diagonal;
const Float max_gloss_scale = 4.0f;
const Float max_gloss_exponential = 1000.0f;
Vec3 directionality;
Vec3 horizontal;
if (m) {
switch (m->get_bsdf()->get_bsdf_type()) {
case Bsdf::PHONG:
case Bsdf::WARD:
{
ISpecular *bsdf = dynamic_cast<ISpecular *>(m->get_bsdf());
Vec3 wr = 2.0f * dot(wo, n) * n - wo;
Float gloss_scale = std::min(max_gloss_scale, std::max(1.0f, bsdf->get_gloss_exponential() / max_gloss_exponential));
directionality = wr * gloss_scale;
horizontal = u * gloss_scale;
break;
}
case Bsdf::MIRROR:
case Bsdf::GLASS:
{
Vec3 wr = 2.0f * dot(wo, n) * n - wo;
directionality = wr * max_gloss_scale;
horizontal = u * max_gloss_scale;
break;
}
case Bsdf::LAMBERTIAN:
default:
directionality = n;
horizontal = u;
break;
}
} else {
directionality = n;
horizontal = u;
}
Vec3 position = v;
Vec9 p;
p.p[0] = position.x();
p.p[1] = position.y();
p.p[2] = position.z();
p.p[3] = (directionality.x()) * weight;
p.p[4] = (directionality.y()) * weight;
p.p[5] = (directionality.z()) * weight;
p.p[6] = horizontal.x() * weight;
p.p[7] = horizontal.y() * weight;
p.p[8] = horizontal.z() * weight;
return p;
}
void LightSlice::generate_slices() {
Size2 img_size = scene->get_image_size();
int num_pixels = img_size.height * img_size.width;
if (node_data) delete [] node_data;
node_data = new NodeData6[num_pixels];
int num_nodes = 0;
// create shading points
Camera *camera = scene->get_camera();
Aggregate *agg = scene->get_aggregate();
Float tmin = scene->get_tmin();
Float tick = scene->get_tick();
Float max_tmax = scene->get_max_tmax();
for (int i = 0; i < img_size.height; ++i) {
for (int j = 0; j < img_size.width; ++j) {
Ray r = camera->shoot_ray(i, j);
HitRecord rec;
// make sure material is available
if (agg->hit(r, tmin, max_tmax, tick, rec) && rec.material) {
Receiver recv(r, rec);
node_data[num_nodes].p = map_vec6(recv.p, recv.shading_n, recv.m, recv.wo, scene_bb_diag);
node_data[num_nodes].index = i * img_size.width + j;
num_nodes++;
}
}
}
Log::info() << "Surface gather points: " << num_nodes << endn;
// TODO: generate more surface gather points (not from camera) to support multi-bounce tracing
Log::info() << "Building kd-tree for gather points..." << endn;
vector<pair<int, int>> slice_clusters;
if (kdtree) delete kdtree;
kdtree = new KdTree6(max_slice_size, node_data, num_nodes, scene, slice_clusters);
Log::info() << "Slices: " << slice_clusters.size() << endn;
Random &rd = *scene->get_random();
slices.clear();
slices.resize(slice_clusters.size());
for (int i = 0; i < slice_clusters.size(); ++i) {
slices[i].start = slice_clusters[i].first;
slices[i].end = slice_clusters[i].second;
slices[i].representative = slices[i].start + rd() * (slices[i].end - slices[i].start + 1);
slices[i].color = Rgb::from_hsv(rd() * 360.0f, 0.75f, 1.0f);
}
}
static void minus(const vector<Float> &a, const vector<Float> &b, vector<Float> &ab) {
ab.resize(a.size());
for (int i = 0; i < a.size(); ++i)
ab[i] = a[i] - b[i];
}
static Float dot(const vector<Float> &a, const vector<Float> &b) {
Float d = 0.0f;
for (int i = 0; i < a.size(); ++i)
d += a[i] * b[i];
return d;
}
static Float sum(const vector<Float> &a) {
Float s = 0.0f;
for (int i = 0; i < a.size(); ++i)
s += a[i];
return s;
}
static void pick(const vector<Float> &in, const vector<int> &indices, vector<Float> &out) {
out.resize(indices.size());
for (int i = 0; i < indices.size(); ++i) {
out[i] = in[indices[i]];
}
}
/**
* Compute distance from each column to every column in the matrix
*/
static Float compute_distance(MatrixC<Float> &R, vector<Float> &column_norms,
MatrixC<Float> &Rt,
vector<Float> &temp_col, vector<Float> &temp_row) {
int rows = R.get_rows();
int cols = R.get_cols();
// alpha = (n_R^t * n_R - R^t * R) 1
// = (n_R^t * n_R * 1 - R^t * R * 1)
// temp_col u has rows elements
// temp_row v has cols elements
R.row_sum(temp_col); // u = R * 1
Rt.mul(temp_col, temp_row); // v = Rt * u
Float c = sum(column_norms); // n_R * 1
Float cost = 0.0f;
for (int i = 0; i < cols; ++i) {
cost += column_norms[i] * c - temp_row[i];
}
return cost;
}
static Float compute_distance_pos(Cluster &cluster, const BrdfPointLights &vpls) {
Float cost = 0.0f;
for (int i = 0; i < cluster.indices.size(); ++i) {
for (int j = 0; j < cluster.indices.size(); ++j) {
cost += (vpls[cluster.indices[i]].org() - vpls[cluster.indices[j]].org()).squared_length();
}
}
return cost;
}
struct ClusterCost {
int index;
Float cost;
ClusterCost(int index, Float cost) : index(index), cost(cost) {}
};
struct ClusterCostLess {
bool operator()(ClusterCost &a, ClusterCost &b) const {
return a.cost < b.cost;
}
};
typedef priority_queue< ClusterCost, vector<ClusterCost>, ClusterCostLess > ClusterCostHeap;
static void choose_representative(Random &rd, Cluster &c) {
int j;
Float pdf_j;
c.pdf.sample(rd, j, pdf_j);
if (j < 0) {
// NOTE: all norms are zero. Just use the median.
c.representative = c.indices[c.indices.size() / 2];
c.weight = 0.0f;
}
else {
c.representative = c.indices[j];
c.weight = 1.0f / pdf_j;
}
}
static bool pair_less(const pair<int, Float> &a, const pair<int, Float> &b) {
return a.second < b.second;
}
static void split_cluster(Random &rd, const Cluster &cluster, const MatrixC<Float> &matC,
vector<int> &indices1, vector<int> &indices2) {
indices1.clear();
indices2.clear();
if (matC.get_cols() == 1) {
indices1.push_back(cluster.indices[0]);
return;
}
if (matC.get_cols() == 2) {
indices1.push_back(cluster.indices[0]);
indices2.push_back(cluster.indices[1]);
return;
}
vector<Float> a, b;
vector<Float> minus_ab;
int i, j;
Float pdf_i, pdf_j;
cluster.pdf.sample(rd, i, pdf_i);
cluster.pdf.sample(rd, j, pdf_j);
if (i < 0 || j < 0) {
Log::info() << "Split by half due to sampling distribution problems." << endn;
vector<int>::const_iterator mid = cluster.indices.begin() + cluster.indices.size() / 2;
indices1.assign(cluster.indices.begin(), mid);
indices2.assign(mid, cluster.indices.end());
return;
}
matC.get_column(i, a);
matC.get_column(j, b);
minus(a, b, minus_ab);
vector<Float> c;
vector<Float> minus_ac;
vector<pair<int, Float>> line;
line.reserve(matC.get_cols());
for (int k = 0; k < matC.get_cols(); ++k) {
if (k == i || k == j) continue;
matC.get_column(k, c);
minus(a, c, minus_ac);
// Float t = dot(minus_ac, minus_ab) / sqr_ab;
Float t = dot(minus_ac, minus_ab); // no need to divide by square of ab since it does not vary among points
line.push_back(pair<int, Float>(k, t));
}
std::sort(line.begin(), line.end(), pair_less);
Float max_dist = 0.0f;
int max_k = -1;
for (int k = 1; k < line.size(); ++k) {
Float dist = line[k].second - line[k - 1].second;
if (dist > max_dist) {
max_dist = dist;
max_k = k;
}
}
if (max_k == -1) {
// just split by half and return because of degeneracy: ab is not a line, or the dot product is always zero
vector<int>::const_iterator mid = cluster.indices.begin() + cluster.indices.size() / 2;
indices1.assign(cluster.indices.begin(), mid);
indices2.assign(mid, cluster.indices.end());
} else {
indices1.push_back(cluster.indices[i]);
indices2.push_back(cluster.indices[j]);
for (int k = 0; k < max_k; ++k)
indices1.push_back(cluster.indices[line[k].first]);
for (int k = max_k; k < line.size(); ++k) // max_k must be >= 0 otherwise compare -1 with unsigned int will result in false
indices2.push_back(cluster.indices[line[k].first]);
}
}
static void split_cluster_pos(Random &rd, const Cluster &cluster, const BrdfPointLights &vpls,
Float scene_bb_diag,
vector<int> &indices1, vector<int> &indices2) {
indices1.clear();
indices2.clear();
if (cluster.indices.size() == 1) {
indices1.push_back(cluster.indices[0]);
return;
}
if (cluster.indices.size() == 2) {
indices1.push_back(cluster.indices[0]);
indices2.push_back(cluster.indices[1]);
return;
}
// map everything into 6D, find the longest axis, and split into two.
const int dim = 6;
int size = cluster.indices.size();
vector<NodeData6> points(size);
for (int i = 0; i < size; ++i) {
const BrdfPointLight &vpl = vpls[cluster.indices[i]];
points[i].p = map_vec6(vpl.org(), vpl.normal(), vpl.get_material(), vpl.get_wi(), scene_bb_diag);
points[i].index = cluster.indices[i];
}
// take node's bounding box and determine the longest axis
BoundingBoxN<dim> bb;
for (int i = 0; i < size; ++i)
bb.merge(points[i].p);
int axis = bb.get_longest_axis();
// sort the points on the axis
struct ComparePoint {
int axis;
ComparePoint(int axis) : axis(axis) {}
bool operator()(const NodeData<dim> &a, const NodeData<dim> &b) {
return a.p[axis] < b.p[axis];
}
};
ComparePoint compare_point(axis);
std::sort(points.begin(), points.end(), compare_point);
// and split at the longest segment
Float max_dist = 0.0f;
int max_i = -1;
for (int i = 1; i < size; ++i) {
Float dist = points[i].p[axis] - points[i - 1].p[axis];
if (dist > max_dist) {
max_dist = dist;
max_i = i;
}
}
if (max_i == -1) {
// just split by half and return
vector<int>::const_iterator mid = cluster.indices.begin() + cluster.indices.size() / 2;
indices1.assign(cluster.indices.begin(), mid);
indices2.assign(mid, cluster.indices.end());
} else {
for (int i = 0; i < max_i; ++i)
indices1.push_back(points[i].index);
for (int i = max_i; i < size; ++i)
indices2.push_back(points[i].index);
}
}
static FILE *open_ply(const string &name, int num_vertices) {
FILE *f = fopen(name.c_str(), "w");
fprintf(f, "ply\n");
fprintf(f, "format ascii 1.0\n");
fprintf(f, "element vertex %d\n", num_vertices);
fprintf(f, "property float x\n");
fprintf(f, "property float y\n");
fprintf(f, "property float z\n");
fprintf(f, "property uchar red\n");
fprintf(f, "property uchar green\n");
fprintf(f, "property uchar blue\n");
fprintf(f, "end_header\n");
return f;
}
static void close_ply(FILE *f) {
fclose(f);
}
static void write_ply(FILE *f, const Vec3 &p, const Rgb &color) {
fprintf(f, "%f %f %f %d %d %d\n",
p.x(), p.y(), p.z(),
(int)(color.red() * 255), (int)(color.green() * 255), (int)color.blue() * 255);
}
void LightSlice::initialize(Scene *scene,
IVirtualPointLightEvaluator *evaluator,
BrdfPointLights &vpls) {
Stats init_stats;
init_stats.tic();
this->scene = scene;
this->scene_bb_diag = scene->get_bounding_box().diagonal();
this->evaluator = evaluator;
if (scene->get_image_view()) {
scene->get_image_view()->mouse_event.attach_observer(this);
}
all_vpls = &vpls;
// HACK: currently we only work on 2-bounce path tracing due to the slice cluster. Therefore, we should only work with VPL that has bounce at most once.
// guiding directional tracing with deeper bounce VPL should only be used when we are not confined to only able to sample at second bounce.
BrdfPointLights one_bounce_vpls;
for (int i = 0; i < vpls.size(); ++i)
if (vpls[i].get_bounce() <= 1)
one_bounce_vpls.push_back(vpls[i]);
vpls.clear();
vpls.assign(one_bounce_vpls.begin(), one_bounce_vpls.end());
// this hack should be removed when our cache points can be used at multiple bounces
if (vpls.size() == 0) {
Log::info() << "There are no VPLs to cluster." << endn;
return;
}
Random &rd = *scene->get_random();
// slicing
Stats stats;
Log::info() << "Generating slices ..." << endn;
stats.tic();
generate_slices();
/*
MeshView *mesh_view = scene->get_mesh_view();
BoundingBoxes bbs;
kdtree->get_cluster_bounding_boxes(bbs);
mesh_view->set_bounding_boxes(bbs);
return;
*/
sampling_records.resize(slices.size());
// test nearest clusters
/*
Vec9 p = concat_vec6(Vec3(-277.762299, 272.726135, -559.417358), Vec3(0.000000000, 0.191311017, 240.248581));
vector<int> slice_indices;
kdtree->find_nearest_cluster(p, 16, slice_indices);
for (int i = 0; i < slice_indices.size(); ++i) {
int slice_index = slice_indices[i];
slices[slice_index].color = DefaultRgb::red * (Float)(i+1) / slice_indices.size();
}*/
Pixels pixels(slices.size());
Size2 img_size = scene->get_image_size();
for (int i = 0; i < slices.size(); ++i) {
int selected = slices[i].representative;
int pixel_index = node_data[selected].index;
int y = pixel_index / (int)img_size.width;
int x = pixel_index % (int)img_size.width;
pixels[i] = Vec2(x, y);
}
stats.toc();
stats.print_elapsed_milliseconds();
Log::info() << "Tentative reduced matrix: " << pixels.size() << " x " << num_clusters << endn;
// assume the number of clusters does not scale with number of VPLs,
// so have a cap at max VPLs that we should use for finding clustering.
/*
int max_columns = 1000000;
BrdfPointLights reduced_vpls;
if (all_vpls->size() > max_columns) {
Log::info() << "Too large reduced matrix. Downsampling to " << max_columns << " columns." << endn;
vector<Float> power(all_vpls->size());
for (int i = 0; i < all_vpls->size(); ++i) {
power[i] = (*all_vpls)[i].power().avg();
}
DiscretePdf pdf(power);
reduced_vpls.resize(max_columns);
for (int i = 0; i < max_columns; ++i) {
int k;
Float pdf_k;
pdf.sample(rd, k, pdf_k);
reduced_vpls[i] = (*all_vpls)[k];
reduced_vpls[i].set_throughput((*all_vpls)[k].power() / pdf_k / max_columns);
}
} else {
reduced_vpls.resize(all_vpls->size());
for (int i = 0; i < all_vpls->size(); ++i)
reduced_vpls[i] = (*all_vpls)[i];
}
*/
// generate reduced matrix
Log::info() << "Generating reduced matrix: " << pixels.size() << " x " << vpls.size() << endn;
stats.tic();
R.resize(pixels.size(), vpls.size());
MatrixC<Rgb> &matR = R.get_matrix();
//matR.resize(pixels.size(), vpls.size());
//matI.resize(pixels.size(), vpls.size());
matV.resize(pixels.size(), vpls.size());
// initialize matrix entries
matR.set(0.0f);
matV.set(0.0f);
Camera *camera = scene->get_camera();
Aggregate *agg = scene->get_aggregate();
Float tmin = scene->get_tmin();
Float max_tmax = scene->get_max_tmax();
Float tick = scene->get_tick();
Lights &lights = *scene->get_lights();
for (int ridx = 0; ridx < pixels.size(); ++ridx) {
Vec2 pixel = pixels[ridx];
Ray r = camera->shoot_ray(pixel.y(), pixel.x());
HitRecord rec;
if (! agg->hit(r, tmin, max_tmax, tick, rec) || rec.material == NULL) {
Log::info() << "Bad slice representative: " << ridx << endn;
continue;
}
Receiver recv(r, rec);
for (int k = 0; k < vpls.size(); ++k) {
bool visible = (agg->hit(recv.p, vpls[k].org(), tmin, tick) == false);
//Rgb radiance = evaluator->radiance(scene, recv, vpls[k], visible);
// NOTE: should use radiance matrix instead of incident radiance matrix because
// + The matrix clustering is used for out-going radiance evaluation. Clustering with incident radiance causes artifacts in output.
// only cluster incident radiance
Rgb radiance = (Float)visible * evaluator->incident_radiance(scene, recv, vpls[k]);
matR(ridx, k) = radiance;
matV(ridx, k) = (Float)visible;
}
// keep uvn for Metropolis sampling record
sampling_records[ridx].uvn = recv.shading_uvn;
}
stats.toc();
stats.print_elapsed_milliseconds();
// cluster columns of the reduced matrix
Log::info() << "Clustering light transport matrix..." << endn;
stats.tic();
ClusterBuilder builder;
builder.cluster_by_sampling(scene,
evaluator,
R,
num_clusters, mrcs_clusters,
*all_vpls,
pixels);
stats.toc();
stats.print_elapsed_milliseconds();
Log::info() << "MRCS clusters: " << mrcs_clusters.size() << endn;
/*
// NOTE: only for testing. Fake MRCS clusters by making each cluster a VPL
Log::info() << "Using a fake MRCS clustering..." << endn;
max_slice_clusters = all_vpls->size();
vector<float> fake_pdf;
fake_pdf.push_back(1.0f);
mrcs_clusters.resize(all_vpls->size());
for (int i = 0; i < all_vpls->size(); ++i) {
mrcs_clusters[i].weight = 1.0f;
mrcs_clusters[i].indices.clear();
mrcs_clusters[i].indices.push_back(i);
mrcs_clusters[i].representative = i;
mrcs_clusters[i].pdf.set_distribution(fake_pdf);
}*/
// slice refinement
Log::info() << "Slice clustering..." << endn;
Log::info() << "Slice memory allocating..." << endn;
stats.tic();
int max_cols = 0;
for (int i = 0; i < mrcs_clusters.size(); ++i) {
if (max_cols < mrcs_clusters[i].indices.size())
max_cols = mrcs_clusters[i].indices.size();
}
// pre-allocate some temporary memory
vector<int> slice_indices;
slice_indices.reserve(num_neighbor_slices);
MatrixC<Rgb> matL; // matrix that extracts rows from R
matL.reserve(num_neighbor_slices, max_cols);
MatrixC<Rgb> matC; // matrix that extracts rows and cols from R
matC.reserve(num_neighbor_slices, max_cols);
MatrixC<Float> matCf; // flatten version of L
matCf.reserve(num_neighbor_slices * 3, max_cols);
MatrixC<Float> matCfTrans;
matCfTrans.reserve(max_cols, num_neighbor_slices * 3);
matrix_clusters.clear();
matrix_clusters.resize(slices.size()); // store clusters per slice
for (int i = 0; i < slices.size(); ++i) { // memory preallocation - indices still might grow
matrix_clusters[i].reserve(max_slice_clusters);
}
vector<Float> norms;
vector<int> indices1;
vector<int> indices2;
vector<Float> temp_col;
//temp_col.resize(num_neighbor_slices * 3);
vector<Float> temp_row;
//temp_row.resize(max_cols);
vector<Float> norms_R;
R.get_column_norms(norms_R);
stats.toc();
stats.print_elapsed_milliseconds();
Log::info() << "Refining clustering per slice..." << endn;
stats.tic();
global_incident_cache.clear();
for (int s = 0; s < slices.size(); ++s) {
// find neighbor slices and extract the slice matrix L
// take a first point in the slice and look for neighbors
Vec6 &p = node_data[slices[s].representative].p;
kdtree->find_nearest_cluster(p, num_neighbor_slices, slice_indices);
// extract rows from matrix R
matR.subrow(slice_indices, matL);
// determine cost for each current cluster by L and push to heap
Clusters &slice_clusters = matrix_clusters[s];
slice_clusters.assign(mrcs_clusters.begin(), mrcs_clusters.end());
ClusterCostHeap heap;
for (int c = 0; c < slice_clusters.size(); ++c) {
// take all columns that belong to the current cluster
matL.subcol(slice_clusters[c].indices, matC);
matC.flatten(matCf);
matCf.get_column_norm(norms);
matCf.transpose(matCfTrans);
Float cost = compute_distance(matCf, norms, matCfTrans, temp_col, temp_row);
heap.push(ClusterCost(c, cost));
// TODO: test if the cost is the same as brute-force
}
while (heap.size() > 0 && slice_clusters.size() < max_slice_clusters) {
// take the most expensive cluster
ClusterCost cc = heap.top();
// and split it into two
if (slice_clusters[cc.index].indices.size() <= 1) break;
matL.subcol(slice_clusters[cc.index].indices, matC);
matC.flatten(matCf);
split_cluster(rd, slice_clusters[cc.index], matCf, indices1, indices2);
// make two new clusters
Cluster &cluster1 = slice_clusters[cc.index];
matL.subcol(indices1, matC);
matC.flatten(matCf);
matCf.get_column_norm(norms); // since we don't have the full in-memory R
matCf.transpose(matCfTrans);
Float cost1 = compute_distance(matCf, norms, matCfTrans, temp_col, temp_row);
cluster1.indices.assign(indices1.begin(), indices1.end());
pick(norms_R, indices1, norms); // use norms of R for representative sampling
cluster1.pdf.set_distribution(norms);
choose_representative(rd, cluster1);
Cluster cluster2;
matL.subcol(indices2, matC);
matC.flatten(matCf);
matCf.get_column_norm(norms);
matCf.transpose(matCfTrans);
Float cost2 = compute_distance(matCf, norms, matCfTrans, temp_col, temp_row);
cluster2.indices.assign(indices2.begin(), indices2.end());
pick(norms_R, indices2, norms);
cluster2.pdf.set_distribution(norms);
choose_representative(rd, cluster2);
// and insert new costs to heap
int new_index = slice_clusters.size();
ClusterCost cc1(cc.index, cost1);
ClusterCost cc2(new_index, cost2);
heap.pop();
heap.push(cc1);
heap.push(cc2);
slice_clusters.push_back(cluster2);
}
// our method of cluster refinement based on positions
/*
for (int c = 0; c < slice_clusters.size(); ++c) {
Float cost = compute_distance_pos(slice_clusters[c], vpls);
heap.push(ClusterCost(c, cost));
}
while (heap.size() > 0 && slice_clusters.size() < max_slice_clusters) {
// take the most expensive cluster
ClusterCost cc = heap.top();
// and split it into two
if (slice_clusters[cc.index].indices.size() <= 1) break;
split_cluster_pos(rd, slice_clusters[cc.index], vpls, scene_bb_diag, indices1, indices2);
// make two new clusters
Cluster &cluster1 = slice_clusters[cc.index];
cluster1.indices.assign(indices1.begin(), indices1.end());
pick(norms_R, indices1, norms); // use norms of R for representative sampling
cluster1.pdf.set_distribution(norms);
choose_representative(rd, cluster1);
Float cost1 = compute_distance_pos(cluster1, vpls);
Cluster cluster2;
cluster2.indices.assign(indices2.begin(), indices2.end());
pick(norms_R, indices2, norms);
cluster2.pdf.set_distribution(norms);
choose_representative(rd, cluster2);
Float cost2 = compute_distance_pos(cluster2, vpls);
// and insert new costs to heap
int new_index = slice_clusters.size();
ClusterCost cc1(cc.index, cost1);
ClusterCost cc2(new_index, cost2);
heap.pop();
heap.push(cc1);
heap.push(cc2);
slice_clusters.push_back(cluster2);
}*/
// compute average incident radiance and cone bound for each cluster
// get receiver
// IMPROVE: in fact receiver is not needed. Only p and n is needed to compute the incident radiance so this can be cached in node data.
int pixel_index = node_data[slices[s].representative].index;
int y = pixel_index / (int)img_size.width;
int x = pixel_index % (int)img_size.width;
Ray ray = camera->shoot_ray(y, x);
HitRecord rec;
if (! agg->hit(ray, tmin, max_tmax, tick, rec) || rec.material == NULL) {
Log::info() << "Error. Ray should hit and material not null." << endn;
}
Receiver recv(ray, rec);
vector<IncidentLight> cache;
for (int c = 0; c < slice_clusters.size(); ++c) {
Cluster &cluster = slice_clusters[c];
Rgb incident;
Rgb outgoing;
for (int i = 0; i < cluster.indices.size(); ++i) {
BrdfPointLight &vpl = vpls[cluster.indices[i]];
Float visibility = matV(s, cluster.indices[i]);
Rgb incident_power = evaluator->incident_radiance(scene, recv, vpl);
incident += visibility * incident_power;
outgoing += matR(s, cluster.indices[i]);
// only support opaque surface at this moment
Vec3 wi = unit_vector(vpl.org() - recv.p);
if (visibility > 0.0f && dot(recv.shading_n, wi) > ZERO_EPSILON && incident_power != DefaultRgb::black) {
cluster.bc.merge_direction(wi);
//cluster.dirs.push_back(wi);
}