forked from BachiLi/redner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedge.cpp
2038 lines (1917 loc) · 85.3 KB
/
edge.cpp
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 "edge.h"
#include "line_clip.h"
#include "scene.h"
#include "parallel.h"
#include "thrust_utils.h"
#include "ltc.inc"
#include <memory>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/execution_policy.h>
#include <thrust/sort.h>
#include <thrust/transform_scan.h>
#include <thrust/binary_search.h>
#include <thrust/remove.h>
// Set this to false to fallback to importance resampling if edge tree doesn't work
constexpr bool c_use_edge_tree = true;
constexpr bool c_uniform_sampling = false;
constexpr bool c_use_nee_ray = true;
namespace ltc {
const float *tabMcpu = &tabM_[0];
const float *tabMgpu = nullptr;
const float *tabM = nullptr;
}
void initialize_ltc_table(bool use_gpu) {
ltc::tabM = use_gpu ? ltc::tabMgpu : ltc::tabMcpu;
if (use_gpu && ltc::tabM == nullptr) {
#ifdef __CUDACC__
checkCuda(cudaMallocManaged(<c::tabMgpu, sizeof(ltc::tabM_)));
checkCuda(cudaMemcpy((void*)ltc::tabMgpu,
(void*)ltc::tabM_, sizeof(ltc::tabM_), cudaMemcpyHostToDevice));
ltc::tabM = ltc::tabMgpu;
#else
assert(false);
#endif
}
}
struct edge_collector {
DEVICE inline void operator()(int idx) {
const auto &shape = *shape_ptr;
// For each triangle
auto ind = get_indices(shape, idx / 3);
if ((idx % 3) == 0) {
edges[idx] = Edge{shape_id,
min(ind[0], ind[1]),
max(ind[0], ind[1]),
idx / 3, -1};
} else if ((idx % 3) == 1) {
edges[idx] = Edge{shape_id,
min(ind[1], ind[2]),
max(ind[1], ind[2]),
idx / 3, -1};
} else {
edges[idx] = Edge{shape_id,
min(ind[2], ind[0]),
max(ind[2], ind[0]),
idx / 3, -1};
}
}
int shape_id;
const Shape *shape_ptr;
Edge *edges;
};
struct edge_less_comparer {
DEVICE inline bool operator()(const Edge &e0, const Edge &e1) {
if (e0.v0 == e1.v0) {
return e0.v1 < e1.v1;
}
return e0.v0 < e1.v0;
}
};
struct edge_equal_comparer {
DEVICE inline bool operator()(const Edge &e0, const Edge &e1) {
return e0.v0 == e1.v0 && e0.v1 == e1.v1;
}
};
struct edge_merger {
DEVICE inline Edge operator()(const Edge &e0, const Edge &e1) {
return Edge{e0.shape_id, e0.v0, e0.v1, e0.f0, e1.f0};
}
};
DEVICE inline bool less_than(const Vector3f &v0, const Vector3f &v1) {
if (v0.x != v1.x) {
return v0.x < v1.x;
} else if (v0.y != v1.y) {
return v0.y < v1.y;
} else if (v0.z != v1.z) {
return v0.z < v1.z;
}
return true;
}
struct edge_vertex_comparer {
DEVICE inline bool operator()(const Edge &e0, const Edge &e1) {
// First, locally sort v0 & v1 within e0 & e1
auto v00 = get_vertex(*shape_ptr, e0.v0);
auto v01 = get_vertex(*shape_ptr, e0.v1);
if (less_than(v01, v00)) {
swap_(v00, v01);
}
auto v10 = get_vertex(*shape_ptr, e1.v0);
auto v11 = get_vertex(*shape_ptr, e1.v1);
if (less_than(v11, v10)) {
swap_(v10, v11);
}
// Next, compare and return
if (v00 != v10) {
return less_than(v00, v10);
} else if (v01 != v11) {
return less_than(v01, v11);
}
return true;
}
const Shape *shape_ptr;
};
struct edge_face_assigner {
DEVICE void operator()(int idx) {
auto &edge = edges[idx];
if (edge.f1 != -1) {
return;
}
auto v0 = get_vertex(*shape_ptr, edge.v0);
auto v1 = get_vertex(*shape_ptr, edge.v1);
if (less_than(v1, v0)) {
swap_(v0, v1);
}
if (idx > 0) {
const auto &cmp_edge = edges[idx - 1];
auto cmp_v0 = get_vertex(*shape_ptr, cmp_edge.v0);
auto cmp_v1 = get_vertex(*shape_ptr, cmp_edge.v1);
if (less_than(cmp_v1, cmp_v0)) {
swap_(cmp_v0, cmp_v1);
}
if (v0 == cmp_v0 && v1 == cmp_v1) {
edge.f1 = cmp_edge.f0;
}
}
if (idx < num_edges - 1) {
const auto &cmp_edge = edges[idx + 1];
auto cmp_v0 = get_vertex(*shape_ptr, cmp_edge.v0);
auto cmp_v1 = get_vertex(*shape_ptr, cmp_edge.v1);
if (less_than(cmp_v1, cmp_v0)) {
swap_(cmp_v0, cmp_v1);
}
if (v0 == cmp_v0 && v1 == cmp_v1) {
edge.f1 = cmp_edge.f0;
}
}
}
const Shape *shape_ptr;
Edge *edges;
int num_edges;
};
struct edge_remover {
DEVICE inline bool operator()(const Edge &e) {
if (e.f0 == -1 || e.f1 == -1) {
// Only adjacent to one face
return false;
}
auto v0 = Vector3{get_v0(shapes, e)};
auto v1 = Vector3{get_v1(shapes, e)};
auto ns_v0 = Vector3{get_non_shared_v0(shapes, e)};
auto ns_v1 = Vector3{get_non_shared_v1(shapes, e)};
auto n0 = normalize(cross(v0 - ns_v0, v1 - ns_v0));
auto n1 = normalize(cross(v1 - ns_v1, v0 - ns_v1));
return dot(n0, n1) >= (1 - 1e-6f);
}
const Shape *shapes;
};
struct primary_edge_weighter {
DEVICE void operator()(int idx) {
const auto &edge = edges[idx];
auto &primary_edge_weight = primary_edge_weights[idx];
auto v0 = get_v0(shapes, edge);
auto v1 = get_v1(shapes, edge);
auto v0p = Vector2{};
auto v1p = Vector2{};
primary_edge_weight = 0;
// Project to screen space
if (project(camera, Vector3(v0), Vector3(v1), v0p, v1p)) {
auto v0c = v0p;
auto v1c = v1p;
// Clip against screen boundaries
if (clip_line(v0p, v1p, v0c, v1c)) {
// Reject non-silhouette edges
auto org = xfm_point(camera.cam_to_world, Vector3{0, 0, 0});
if (is_silhouette(shapes, org, edge)) {
primary_edge_weight = distance(v0c, v1c);
}
}
}
}
Camera camera;
const Shape *shapes;
const Edge *edges;
Real *primary_edge_weights;
};
struct secondary_edge_weighter {
DEVICE void operator()(int idx) {
const auto &edge = edges[idx];
// We use the length * (pi - dihedral angle) to sample the edges
// If the dihedral angle is large, it's less likely that the edge would be a silhouette
auto &secondary_edge_weight = secondary_edge_weights[idx];
auto exterior_dihedral = compute_exterior_dihedral_angle(shapes, edge);
auto v0 = get_v0(shapes, edge);
auto v1 = get_v1(shapes, edge);
secondary_edge_weight = distance(v0, v1) * exterior_dihedral;
}
const Shape *shapes;
const Edge *edges;
Real *secondary_edge_weights;
};
EdgeSampler::EdgeSampler(const std::vector<const Shape*> &shapes,
const Scene &scene) {
if (!scene.use_primary_edge_sampling && !scene.use_secondary_edge_sampling) {
// No need to collect edges
return;
}
auto shapes_buffer = scene.shapes.view(0, shapes.size());
// Conservatively allocate a big buffer for all edges
auto num_total_triangles = 0;
for (int shape_id = 0; shape_id < (int)shapes.size(); shape_id++) {
num_total_triangles += shapes[shape_id]->num_triangles;
}
// Collect the edges
// TODO: this assumes each edge is only associated with two triangles
// which may be untrue for some pathological meshes.
// For edges associated to more than two triangles,
// we should just ignore them
edges = Buffer<Edge>(scene.use_gpu, 3 * num_total_triangles);
auto edges_buffer = Buffer<Edge>(scene.use_gpu, 3 * num_total_triangles);
auto current_num_edges = 0;
for (int shape_id = 0; shape_id < (int)shapes.size(); shape_id++) {
parallel_for(edge_collector{
shape_id,
shapes_buffer.begin() + shape_id,
edges.data + current_num_edges
}, 3 * shapes[shape_id]->num_triangles, scene.use_gpu);
// Merge the edges
auto edges_begin = edges.data + current_num_edges;
DISPATCH(scene.use_gpu, thrust::sort,
edges_begin,
edges_begin + 3 * shapes[shape_id]->num_triangles,
edge_less_comparer{});
auto edges_buffer_begin = edges_buffer.data;
auto new_end = DISPATCH(scene.use_gpu, thrust::reduce_by_key,
edges_begin, // input keys
edges_begin + 3 * shapes[shape_id]->num_triangles,
edges_begin, // input values
edges_buffer_begin, // output keys
edges_buffer_begin, // output values
edge_equal_comparer{},
edge_merger{}).first;
auto num_edges = new_end - edges_buffer_begin;
// Sometimes there are duplicated edges that don't get merged
// in the procedure above (e.g. UV seams), here we make sure these edges
// are associated with two faces.
// We do this by sorting the edges again based on vertex positions,
// look at nearby edges and assign faces.
DISPATCH(scene.use_gpu, thrust::sort,
edges_buffer_begin,
edges_buffer_begin + num_edges,
edge_vertex_comparer{shapes_buffer.begin() + shape_id});
parallel_for(edge_face_assigner{
shapes_buffer.begin() + shape_id,
edges_buffer_begin,
(int)num_edges
}, num_edges, scene.use_gpu);
DISPATCH(scene.use_gpu, thrust::copy, edges_buffer_begin, new_end, edges_begin);
current_num_edges += num_edges;
}
// Remove edges with 180 degree dihedral angles
auto edges_end = DISPATCH(scene.use_gpu, thrust::remove_if, edges.begin(),
edges.begin() + current_num_edges, edge_remover{shapes_buffer.begin()});
edges.count = edges_end - edges.begin();
if (scene.use_primary_edge_sampling) {
// Primary edge sampler:
primary_edges_pmf = Buffer<Real>(scene.use_gpu, edges.count);
primary_edges_cdf = Buffer<Real>(scene.use_gpu, edges.count);
// For each edge, if it is a silhouette, we project them on screen
// and compute the screen-space length. We store the length in
// primary_edges_pmf
{
parallel_for(primary_edge_weighter{
scene.camera,
scene.shapes.data,
edges.begin(),
primary_edges_pmf.begin()
}, edges.size(), scene.use_gpu);
// Compute PMF & CDF
// First normalize primary_edges_pmf.
auto total_length = DISPATCH(scene.use_gpu, thrust::reduce,
primary_edges_pmf.begin(),
primary_edges_pmf.end(),
Real(0),
thrust::plus<Real>());
DISPATCH(scene.use_gpu, thrust::transform,
primary_edges_pmf.begin(),
primary_edges_pmf.end(),
thrust::make_constant_iterator(total_length),
primary_edges_pmf.begin(),
thrust::divides<Real>());
// Next we compute a prefix sum
DISPATCH(scene.use_gpu, thrust::transform_exclusive_scan,
primary_edges_pmf.begin(),
primary_edges_pmf.end(),
primary_edges_cdf.begin(),
thrust::identity<Real>(), Real(0), thrust::plus<Real>());
}
}
if (scene.use_secondary_edge_sampling) {
// Secondary edge sampler
if (!c_use_edge_tree) {
// Build a global distribution if we are not using edge tree
secondary_edges_pmf = Buffer<Real>(scene.use_gpu, edges.count);
secondary_edges_cdf = Buffer<Real>(scene.use_gpu, edges.count);
// For each edge we compute the length and store the length in
// secondary_edges_pmf
parallel_for(secondary_edge_weighter{
scene.shapes.data,
edges.begin(),
secondary_edges_pmf.begin()
}, edges.size(), scene.use_gpu);
{
// Compute PMF & CDF
// First normalize secondary_edges_pmf.
auto total_length = DISPATCH(scene.use_gpu, thrust::reduce,
secondary_edges_pmf.begin(),
secondary_edges_pmf.end(),
Real(0),
thrust::plus<Real>());
DISPATCH(scene.use_gpu, thrust::transform,
secondary_edges_pmf.begin(),
secondary_edges_pmf.end(),
thrust::make_constant_iterator(total_length),
secondary_edges_pmf.begin(),
thrust::divides<Real>());
// Next we compute a prefix sum
DISPATCH(scene.use_gpu, thrust::transform_exclusive_scan,
secondary_edges_pmf.begin(),
secondary_edges_pmf.end(),
secondary_edges_cdf.begin(),
thrust::identity<Real>(), Real(0), thrust::plus<Real>());
}
// Build a hierarchical data structure for edge sampling
edge_tree = std::unique_ptr<EdgeTree>(
new EdgeTree(scene.use_gpu,
scene.camera,
shapes_buffer,
edges.view(0, edges.size())));
} else {
// Build a hierarchical data structure for edge sampling
edge_tree = std::unique_ptr<EdgeTree>(
new EdgeTree(scene.use_gpu,
scene.camera,
shapes_buffer,
edges.view(0, edges.size())));
}
}
}
struct primary_edge_sampler {
DEVICE void operator()(int idx) {
// Initialize output
edge_records[idx] = PrimaryEdgeRecord{};
throughputs[2 * idx + 0] = Vector3{0, 0, 0};
throughputs[2 * idx + 1] = Vector3{0, 0, 0};
auto nd = channel_info.num_total_dimensions;
for (int d = 0; d < nd; d++) {
channel_multipliers[2 * nd * idx + d] = 0;
channel_multipliers[2 * nd * idx + d + nd] = 0;
}
rays[2 * idx + 0] = Ray(Vector3{0, 0, 0}, Vector3{0, 0, 0});
rays[2 * idx + 1] = Ray(Vector3{0, 0, 0}, Vector3{0, 0, 0});
// Sample an edge by binary search on cdf
auto sample = samples[idx];
const Real *edge_ptr = thrust::upper_bound(thrust::seq,
edges_cdf, edges_cdf + num_edges,
sample.edge_sel);
auto edge_id = clamp((int)(edge_ptr - edges_cdf - 1),
0, num_edges - 1);
const auto &edge = edges[edge_id];
// Sample a point on the edge
auto v0 = Vector3{get_v0(shapes, edge)};
auto v1 = Vector3{get_v1(shapes, edge)};
// Project the edge onto screen space
auto v0_ss = Vector2{0, 0};
auto v1_ss = Vector2{0, 0};
if (!project(camera, v0, v1, v0_ss, v1_ss)) {
return;
}
if (edges_pmf[edge_id] <= 0.f) {
return;
}
if (camera.camera_type != CameraType::Fisheye) {
// Perspective or Orthographic cameras
// Uniform sample on the edge
auto edge_pt = v0_ss + sample.t * (v1_ss - v0_ss);
// Reject samples outside of image plane
if (!in_screen(camera, edge_pt)) {
return;
}
edge_records[idx].edge = edge;
edge_records[idx].edge_pt = edge_pt;
// Generate two rays at the two sides of the edge
auto half_space_normal = get_normal(normalize(v0_ss - v1_ss));
// The half space normal always points to the upper half-space.
auto offset = 1e-6f;
auto upper_pt = edge_pt + half_space_normal * offset;
auto upper_ray = sample_primary(camera, upper_pt);
auto lower_pt = edge_pt - half_space_normal * offset;
auto lower_ray = sample_primary(camera, lower_pt);
rays[2 * idx + 0] = upper_ray;
rays[2 * idx + 1] = lower_ray;
// Compute the corresponding backprop derivatives
auto xi = clamp(int(edge_pt[0] * camera.width), 0, camera.width - 1);
auto yi = clamp(int(edge_pt[1] * camera.height), 0, camera.height - 1);
auto rd = channel_info.radiance_dimension;
auto d_color = Vector3{
d_rendered_image[nd * (yi * camera.width + xi) + rd + 0],
d_rendered_image[nd * (yi * camera.width + xi) + rd + 1],
d_rendered_image[nd * (yi * camera.width + xi) + rd + 2]
};
// The weight is the length of edge divided by the probability
// of selecting this edge, divided by the length of gradients
// of the edge equation w.r.t. screen coordinate.
// For perspective projection the length of edge and gradients
// cancel each other out.
// For fisheye we need to compute the Jacobians
auto upper_weight = d_color / edges_pmf[edge_id];
auto lower_weight = -d_color / edges_pmf[edge_id];
assert(isfinite(d_color));
assert(isfinite(upper_weight));
throughputs[2 * idx + 0] = upper_weight;
throughputs[2 * idx + 1] = lower_weight;
for (int d = 0; d < nd; d++) {
auto d_channel = d_rendered_image[nd * (yi * camera.width + xi) + d];
channel_multipliers[2 * nd * idx + d] = d_channel / edges_pmf[edge_id];
channel_multipliers[2 * nd * idx + d + nd] = -d_channel / edges_pmf[edge_id];
}
} else {
// In paper we focused on linear projection model.
// However we also support non-linear models such as fisheye
// projection.
// To sample a point on the edge for non-linear models,
// we need to sample in camera space instead of screen space,
// since the edge is no longer a line segment in screen space.
// Therefore we perform an "unprojection" to project the edge
// from screen space to the film in camera space.
// For perspective camera this is equivalent to sample in screen space:
// we unproject (x, y) to (x', y', 1) where x', y' are just individual
// affine transforms of x, y.
// For fisheye camera we unproject from screen-space to the unit
// sphere.
// Therefore the following code also works for perspective camera,
// but to make things more consistent to the paper we provide
// two versions of code.
auto v0_dir = screen_to_camera(camera, v0_ss);
auto v1_dir = screen_to_camera(camera, v1_ss);
// Uniform sample in camera space
auto v_dir3 = v1_dir - v0_dir;
auto edge_pt3 = v0_dir + sample.t * v_dir3;
// Project back to screen space
auto edge_pt = camera_to_screen(camera, edge_pt3);
// Reject samples outside of image plane
if (!in_screen(camera, edge_pt)) {
// In theory this shouldn't happen since we clamp the edges
return;
}
edge_records[idx].edge = edge;
edge_records[idx].edge_pt = edge_pt;
// The edge equation for the fisheye camera is:
// alpha(p) = dot(p, cross(v0_dir, v1_dir))
// Thus the half-space normal is cross(v0_dir, v1_dir)
// Generate two rays at the two sides of the edge
// We choose the ray offset such that the longer the edge is from
// the camera, the smaller the offset is.
auto half_space_normal = normalize(cross(v0_dir, v1_dir));
auto v0_local = xfm_point(camera.world_to_cam, v0);
auto v1_local = xfm_point(camera.world_to_cam, v1);
auto edge_local = v0_local + sample.t * v1_local;
auto offset = 1e-5f / length(edge_local);
auto upper_dir = normalize(edge_pt3 + offset * half_space_normal);
auto upper_pt = camera_to_screen(camera, upper_dir);
auto upper_ray = sample_primary(camera, upper_pt);
auto lower_dir = normalize(edge_pt3 - offset * half_space_normal);
auto lower_pt = camera_to_screen(camera, lower_dir);
auto lower_ray = sample_primary(camera, lower_pt);
rays[2 * idx + 0] = upper_ray;
rays[2 * idx + 1] = lower_ray;
// Compute the corresponding backprop derivatives
auto xi = int(edge_pt[0] * camera.width);
auto yi = int(edge_pt[1] * camera.height);
auto rd = channel_info.radiance_dimension;
auto d_color = Vector3{
d_rendered_image[nd * (yi * camera.width + xi) + rd + 0],
d_rendered_image[nd * (yi * camera.width + xi) + rd + 1],
d_rendered_image[nd * (yi * camera.width + xi) + rd + 2]
};
// The weight is the length of edge divided by the probability
// of selecting this edge, divided by the length of gradients
// of the edge equation w.r.t. screen coordinate.
// For perspective projection the length of edge and gradients
// cancel each other out.
// For fisheye we need to compute the Jacobians
auto upper_weight = d_color / edges_pmf[edge_id];
auto lower_weight = -d_color / edges_pmf[edge_id];
// alpha(p(x, y)) = dot(p(x, y), cross(v0_dir, v1_dir))
// p = screen_to_camera(x, y)
// dp/dx & dp/dy
auto d_edge_dir_x = Vector3{0, 0, 0};
auto d_edge_dir_y = Vector3{0, 0, 0};
d_screen_to_camera(camera, edge_pt, d_edge_dir_x, d_edge_dir_y);
// d alpha / d p = cross(v0_dir, v1_dir)
auto d_alpha_dx = dot(d_edge_dir_x, cross(v0_dir, v1_dir));
auto d_alpha_dy = dot(d_edge_dir_y, cross(v0_dir, v1_dir));
auto dirac_jacobian = 1.f / sqrt(square(d_alpha_dx) + square(d_alpha_dy));
// We use finite difference to compute the Jacobian
// for sampling on the line
auto jac_offset = Real(1e-6);
auto edge_pt3_delta = v0_dir + (sample.t + jac_offset) * v_dir3;
auto edge_pt_delta = camera_to_screen(camera, edge_pt3_delta);
auto line_jacobian = length((edge_pt_delta - edge_pt) / offset);
auto jacobian = line_jacobian * dirac_jacobian;
upper_weight *= jacobian;
lower_weight *= jacobian;
assert(isfinite(upper_weight));
throughputs[2 * idx + 0] = upper_weight;
throughputs[2 * idx + 1] = lower_weight;
for (int d = 0; d < nd; d++) {
auto d_channel = d_rendered_image[nd * (yi * camera.width + xi) + d];
channel_multipliers[2 * nd * idx + d] =
d_channel * jacobian / edges_pmf[edge_id];
channel_multipliers[2 * nd * idx + d + nd] =
-d_channel * jacobian / edges_pmf[edge_id];
}
}
// Ray differential computation
auto screen_pos = edge_records[idx].edge_pt;
auto ray = sample_primary(camera, screen_pos);
auto delta = Real(1e-3);
auto screen_pos_dx = screen_pos + Vector2{delta, Real(0)};
auto ray_dx = sample_primary(camera, screen_pos_dx);
auto screen_pos_dy = screen_pos + Vector2{Real(0), delta};
auto ray_dy = sample_primary(camera, screen_pos_dy);
auto pixel_size_x = Real(0.5) / camera.width;
auto pixel_size_y = Real(0.5) / camera.height;
auto org_dx = pixel_size_x * (ray_dx.org - ray.org) / delta;
auto org_dy = pixel_size_y * (ray_dy.org - ray.org) / delta;
auto dir_dx = pixel_size_x * (ray_dx.dir - ray.dir) / delta;
auto dir_dy = pixel_size_y * (ray_dy.dir - ray.dir) / delta;
primary_ray_differentials[idx] = RayDifferential{org_dx, org_dy, dir_dx, dir_dy};
}
const Camera camera;
const Shape *shapes;
const Edge *edges;
int num_edges;
const Real *edges_pmf;
const Real *edges_cdf;
const PrimaryEdgeSample *samples;
const float *d_rendered_image;
const ChannelInfo channel_info;
PrimaryEdgeRecord *edge_records;
Ray *rays;
RayDifferential *primary_ray_differentials;
Vector3 *throughputs;
Real *channel_multipliers;
};
void sample_primary_edges(const Scene &scene,
const BufferView<PrimaryEdgeSample> &samples,
const float *d_rendered_image,
const ChannelInfo &channel_info,
BufferView<PrimaryEdgeRecord> edge_records,
BufferView<Ray> rays,
BufferView<RayDifferential> primary_ray_differentials,
BufferView<Vector3> throughputs,
BufferView<Real> channel_multipliers) {
parallel_for(primary_edge_sampler{
scene.camera,
scene.shapes.data,
scene.edge_sampler.edges.begin(),
(int)scene.edge_sampler.edges.size(),
scene.edge_sampler.primary_edges_pmf.begin(),
scene.edge_sampler.primary_edges_cdf.begin(),
samples.begin(),
d_rendered_image,
channel_info,
edge_records.begin(),
rays.begin(),
primary_ray_differentials.begin(),
throughputs.begin(),
channel_multipliers.begin()
}, samples.size(), scene.use_gpu);
}
struct primary_edge_weights_updater {
DEVICE void operator()(int idx) {
const auto &edge_record = edge_records[idx];
auto isect_upper = shading_isects[2 * idx + 0];
auto isect_lower = shading_isects[2 * idx + 1];
auto &throughputs_upper = throughputs[2 * idx + 0];
auto &throughputs_lower = throughputs[2 * idx + 1];
// At least one of the intersections should be connected to the edge
bool upper_connected = isect_upper.shape_id == edge_record.edge.shape_id &&
(isect_upper.tri_id == edge_record.edge.f0 || isect_upper.tri_id == edge_record.edge.f1);
bool lower_connected = isect_lower.shape_id == edge_record.edge.shape_id &&
(isect_lower.tri_id == edge_record.edge.f0 || isect_lower.tri_id == edge_record.edge.f1);
if (!upper_connected && !lower_connected) {
throughputs_upper = Vector3{0, 0, 0};
throughputs_lower = Vector3{0, 0, 0};
auto nd = channel_info.num_total_dimensions;
for (int d = 0; d < nd; d++) {
channel_multipliers[2 * nd * idx + d] = 0;
channel_multipliers[2 * nd * idx + d + nd] = 0;
}
}
}
const PrimaryEdgeRecord *edge_records;
const Intersection *shading_isects;
const ChannelInfo channel_info;
Vector3 *throughputs;
Real *channel_multipliers;
};
void update_primary_edge_weights(const Scene &scene,
const BufferView<PrimaryEdgeRecord> &edge_records,
const BufferView<Intersection> &edge_isects,
const ChannelInfo &channel_info,
BufferView<Vector3> throughputs,
BufferView<Real> channel_multipliers) {
// XXX: Disable this at the moment. Not sure if this is more robust or not.
// parallel_for(primary_edge_weights_updater{
// edge_records.begin(),
// edge_isects.begin(),
// channel_info,
// throughputs.begin(),
// channel_multipliers.begin()
// }, edge_records.size(), scene.use_gpu);
}
struct primary_edge_derivatives_computer {
DEVICE void operator()(int idx) {
const auto &edge_record = edge_records[idx];
auto edge_contrib_upper = edge_contribs[2 * idx + 0];
auto edge_contrib_lower = edge_contribs[2 * idx + 1];
auto edge_contrib = edge_contrib_upper + edge_contrib_lower;
// Initialize derivatives
if (edge_record.edge.shape_id < 0) {
return;
}
auto v0 = Vector3{get_v0(shapes, edge_record.edge)};
auto v1 = Vector3{get_v1(shapes, edge_record.edge)};
auto v0_ss = Vector2{0, 0};
auto v1_ss = Vector2{0, 0};
if (!project(camera, v0, v1, v0_ss, v1_ss)) {
return;
}
auto d_v0_ss = Vector2{0, 0};
auto d_v1_ss = Vector2{0, 0};
auto edge_pt = edge_record.edge_pt;
if (camera.camera_type != CameraType::Fisheye) {
// Equation 8 in the paper
d_v0_ss.x = v1_ss.y - edge_pt.y;
d_v0_ss.y = edge_pt.x - v1_ss.x;
d_v1_ss.x = edge_pt.y - v0_ss.y;
d_v1_ss.y = v0_ss.x - edge_pt.x;
} else {
// This also works for perspective camera,
// but for consistency we provide two versions.
// alpha(p) = dot(p, cross(v0_dir, v1_dir))
// v0_dir = screen_to_camera(v0_ss)
// v1_dir = screen_to_camera(v1_ss)
// d alpha / d v0_ss_x = dot(cross(v1_dir, p),
// d_screen_to_camera(v0_ss).x)
auto v0_dir = screen_to_camera(camera, v0_ss);
auto v1_dir = screen_to_camera(camera, v1_ss);
auto edge_dir = screen_to_camera(camera, edge_pt);
auto d_v0_dir_x = Vector3{0, 0, 0};
auto d_v0_dir_y = Vector3{0, 0, 0};
d_screen_to_camera(camera, v0_ss, d_v0_dir_x, d_v0_dir_y);
auto d_v1_dir_x = Vector3{0, 0, 0};
auto d_v1_dir_y = Vector3{0, 0, 0};
d_screen_to_camera(camera, v1_ss, d_v1_dir_x, d_v1_dir_y);
d_v0_ss.x = dot(cross(v1_dir, edge_dir), d_v0_dir_x);
d_v0_ss.y = dot(cross(v1_dir, edge_dir), d_v0_dir_y);
d_v1_ss.x = dot(cross(edge_dir, v0_dir), d_v1_dir_x);
d_v1_ss.y = dot(cross(edge_dir, v0_dir), d_v1_dir_y);
}
d_v0_ss *= edge_contrib;
d_v1_ss *= edge_contrib;
// v0_ss, v1_ss = project(camera, v0, v1)
auto d_v0 = Vector3{0, 0, 0};
auto d_v1 = Vector3{0, 0, 0};
d_project(camera, v0, v1,
d_v0_ss.x, d_v0_ss.y,
d_v1_ss.x, d_v1_ss.y,
d_camera, d_v0, d_v1);
atomic_add(&d_shapes[edge_record.edge.shape_id].vertices[3 * edge_record.edge.v0], d_v0);
atomic_add(&d_shapes[edge_record.edge.shape_id].vertices[3 * edge_record.edge.v1], d_v1);
}
const Camera camera;
const Shape *shapes;
const PrimaryEdgeRecord *edge_records;
const Real *edge_contribs;
DShape *d_shapes;
DCamera d_camera;
};
void compute_primary_edge_derivatives(const Scene &scene,
const BufferView<PrimaryEdgeRecord> &edge_records,
const BufferView<Real> &edge_contribs,
BufferView<DShape> d_shapes,
DCamera d_camera) {
parallel_for(primary_edge_derivatives_computer{
scene.camera,
scene.shapes.data,
edge_records.begin(),
edge_contribs.begin(),
d_shapes.begin(), d_camera
}, edge_records.size(), scene.use_gpu);
}
DEVICE
inline Matrix3x3 get_ltc_matrix(const SurfacePoint &surface_point,
const Vector3 &wi,
Real roughness,
const float *tabM) {
auto cos_theta = dot(wi, surface_point.shading_frame.n);
auto theta = acos(cos_theta);
// search lookup table
auto rid = clamp(int(roughness * (ltc::size - 1)), 0, ltc::size - 1);
auto tid = clamp(int((theta / (M_PI / 2.f)) * (ltc::size - 1)), 0, ltc::size - 1);
// TODO: linear interpolation?
return Matrix3x3(&tabM[9 * (rid + tid * ltc::size)]);
}
struct BVHStackItemH {
BVHNodePtr node_ptr;
int num_samples;
Real pmf;
};
struct BVHStackItemL {
BVHNodePtr node_ptr;
};
struct secondary_edge_sampler {
DEVICE inline Real min_abs_bound(Real min, Real max) {
if (min <= 0.f && max >= 0.f) {
return Real(0);
}
if (min <= 0.f && max <= 0.f) {
return max;
}
assert(min >= 0.f && max >= 0.f);
return min;
}
DEVICE inline Real ltc_bound(const AABB3 &bounds,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
// Due to the linear invariance, the maximum remains
// the same after applying M^{-1}
// Therefore we transform the bounds using M^{-1},
// find the largest possible z and smallest possible
// x, y in terms of magnitude.
auto dir = Vector3{0, 0, 1};
if (!::inside(bounds, p.position)) {
AABB3 b;
for (int i = 0; i < 8; i++) {
b = merge(b, m_inv * (corner(bounds, i) - p.position));
}
if (b.p_max.z < 0) {
return 0;
}
dir.x = min_abs_bound(b.p_min.x, b.p_max.x);
dir.y = min_abs_bound(b.p_min.y, b.p_max.y);
dir.z = b.p_max.z;
auto dir_len = length(dir);
if (dir_len <= 0) {
dir = Vector3{0, 0, 1};
} else {
dir = dir / dir_len;
}
}
auto max_dir = normalize(m * dir);
auto max_dir_local = m_inv * max_dir;
if (max_dir_local.z <= 0) {
return 0;
}
auto n = square(length_squared(max_dir_local));
return max_dir_local.z / n;
}
DEVICE inline Real ltc_bound(const AABB6 &bounds,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
auto p_bounds = AABB3{bounds.p_min, bounds.p_max};
return ltc_bound(p_bounds, p, m, m_inv);
}
DEVICE Real importance(const BVHNode3 &node,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
// importance = BRDF * weighted length / dist
// For BRDF we estimate the bound using linearly transformed cosine distribution
auto brdf_term = ltc_bound(node.bounds, p, m, m_inv);
auto center = 0.5f * (node.bounds.p_min + node.bounds.p_max);
return brdf_term * node.weighted_total_length
/ max(distance(center, p.position), Real(1e-3));
}
DEVICE Real importance(const BVHNode6 &node,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
// importance = BRDF * weighted length / dist
// Except if the sphere centered at 0.5 * (p - cam_org),
// which has radius of 0.5 * distance(p, cam_org)
// does not intersect the directional bounding box of node,
// the importance is zero (see Olson and Zhang 2006)
auto d_bounds = AABB3{node.bounds.d_min, node.bounds.d_max};
if (!intersect(Sphere{0.5f * (p.position - cam_org),
0.5f * distance(p.position, cam_org)}, d_bounds)) {
// Not silhouette
return 0;
}
auto p_bounds = AABB3{node.bounds.p_min, node.bounds.p_max};
auto brdf_term = ltc_bound(p_bounds, p, m, m_inv);
auto center = 0.5f * (p_bounds.p_min + p_bounds.p_max);
return brdf_term * node.weighted_total_length
/ max(distance(center, p.position), Real(1e-3));
}
DEVICE Real importance(const BVHNodePtr &node_ptr,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
if (node_ptr.is_bvh_node3) {
return importance(*node_ptr.ptr3, p, m, m_inv);
} else {
return importance(*node_ptr.ptr6, p, m, m_inv);
}
}
DEVICE bool contains_silhouette(const BVHNodePtr &node_ptr,
const Vector3 &p) {
if (node_ptr.is_bvh_node3) {
return true;
} else {
auto bounds = node_ptr.ptr6->bounds;
auto d_bounds = AABB3{bounds.d_min, bounds.d_max};
return intersect(Sphere{0.5f * (p - cam_org),
0.5f * distance(p, cam_org)}, d_bounds);
}
}
template <typename BVHNodeType>
DEVICE Real leaf_importance(const BVHNodeType &node,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
const auto &edge = edges[node.edge_id];
if (!is_silhouette(scene.shapes, p.position, edge)) {
return 0;
}
auto v0 = Vector3{get_v0(scene.shapes, edge)};
auto v1 = Vector3{get_v1(scene.shapes, edge)};
// If degenerate, the weight is 0
if (length_squared(v1 - v0) > 1e-10f) {
// Transform the vertices to local coordinates
auto v0o = m_inv * (v0 - p.position);
auto v1o = m_inv * (v1 - p.position);
// If below surface, the weight is 0
if (v0o[2] > 0.f || v1o[2] > 0.f) {
// Clip to the surface tangent plane
if (v0o[2] < 0.f) {
v0o = (v0o*v1o[2] - v1o*v0o[2]) / (v1o[2] - v0o[2]);
}
if (v1o[2] < 0.f) {
v1o = (v0o*v1o[2] - v1o*v0o[2]) / (v1o[2] - v0o[2]);
}
// Integrate over the edge using LTC
auto vodir = v1o - v0o;
auto wt = normalize(vodir);
auto l0 = dot(v0o, wt);
auto l1 = dot(v1o, wt);
auto vo = v0o - l0 * wt;
auto d = length(vo);
auto I = [&](Real l) {
return (l/(d*(d*d+l*l))+atan(l/d)/(d*d))*vo[2] +
(l*l/(d*(d*d+l*l)))*wt[2];
};
auto Il0 = I(l0);
auto Il1 = I(l1);
return max(Il1 - Il0, Real(0));
}
}
return 0;
}
DEVICE Real leaf_importance(const BVHNodePtr &node_ptr,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv) {
if (node_ptr.is_bvh_node3) {
return leaf_importance(*node_ptr.ptr3, p, m, m_inv);
} else {
return leaf_importance(*node_ptr.ptr6, p, m, m_inv);
}
}
template <typename BVHNodeType>
DEVICE Real leaf_importance(const BVHNodeType &node,
const SurfacePoint &p,
const Matrix3x3 &m,
const Matrix3x3 &m_inv,
const Ray &nee_ray,
const Intersection &nee_isect,
Real edge_billboard_size) {
const auto &edge = edges[node.edge_id];
if (!is_silhouette(scene.shapes, p.position, edge)) {
return 0;
}
if (nee_isect.valid()) {
auto nee_pt = nee_ray.org + nee_ray.tmax * nee_ray.dir;
if (!is_silhouette(scene.shapes, nee_pt, edge)) {
return 0;
}
} else {
if (!is_silhouette(scene.shapes, nee_ray.dir, edge)) {
return 0;
}
}
// Intersect nee_ray with the edge billboard, reject if
// the intersection is not in edge_billboard_size
auto v0 = Vector3{get_v0(scene.shapes, edge)};
auto v1 = Vector3{get_v1(scene.shapes, edge)};
auto plane_pt = v0;
auto plane_normal = nee_ray.dir;
auto t = -(dot(nee_ray.org, plane_normal) - dot(plane_pt, plane_normal)) /
dot(nee_ray.dir, plane_normal);
auto isect_pt = nee_ray.org + nee_ray.dir * t;
// Project isect_pt to corresponding point on the edge
auto v0_p = v0 - isect_pt;
auto v0_v1 = normalize(v1 - v0);
auto edge_pt = isect_pt + v0_p - (dot(v0_p, v0_v1)) * v0_v1;
if (distance_squared(edge_pt, isect_pt) > square(edge_billboard_size)) {