-
Notifications
You must be signed in to change notification settings - Fork 199
/
PointRenderer.cu
1665 lines (1351 loc) · 57 KB
/
PointRenderer.cu
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
/**
* Copyright (c) 2021 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
//#undef CUDA_DEBUG
//#define CUDA_NDEBUG
//#include "saiga/colorize.h"
#include "saiga/cuda/reduce.h"
#include "saiga/vision/torch/CudaHelper.h"
#include "PointRenderer.h"
#include "PointRendererHelper.h"
#include "cooperative_groups.h"
#ifdef CUDA_DEBUG
# define CUDA_DEBUG_ASSERT(_x) CUDA_KERNEL_ASSERT(_x)
#else
# define CUDA_DEBUG_ASSERT(_x)
#endif
// Blog: https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html
// Code: https://gist.github.com/mikhailov-work/0d177465a8151eb6ede1768d51d476c7
__device__ inline vec3 colorizeTurbo(float x)
{
const vec4 kRedVec4 = vec4(0.13572138, 4.61539260, -42.66032258, 132.13108234);
const vec4 kGreenVec4 = vec4(0.09140261, 2.19418839, 4.84296658, -14.18503333);
const vec4 kBlueVec4 = vec4(0.10667330, 12.64194608, -60.58204836, 110.36276771);
const vec2 kRedVec2 = vec2(-152.94239396, 59.28637943);
const vec2 kGreenVec2 = vec2(4.27729857, 2.82956604);
const vec2 kBlueVec2 = vec2(-89.90310912, 27.34824973);
x = __saturatef(x);
vec4 v4 = vec4(1.0, x, x * x, x * x * x);
// vec2 v2 = v4.zw * v4.z;
vec2 v2 = vec2(v4[2], v4[3]) * v4[2];
return vec3(dot(v4, kRedVec4) + dot(v2, kRedVec2), dot(v4, kGreenVec4) + dot(v2, kGreenVec2),
dot(v4, kBlueVec4) + dot(v2, kBlueVec2));
}
static constexpr int default_block_size = 256;
struct DeviceRenderParams
{
int num_texture_channels;
bool check_normal;
float dropout;
bool ghost_gradients;
float dist_cutoff;
int num_layers;
float depth_accept;
float drop_out_radius_threshold;
bool drop_out_points_by_radius;
int test_backward_mode;
float distortion_gradient_factor;
float K_gradient_factor;
// For every layer a batch of images
// [layers, batches, 1, height_of_layer, width_of_layer]
StaticDeviceTensor<float, 4> depth[max_layers];
StaticDeviceTensor<float, 4> weight[max_layers];
StaticDeviceTensor<float, 2> in_texture;
StaticDeviceTensor<float, 3> tmp_projections;
// for every image one pose
Sophus::SE3d* _poses;
HD inline Sophus::SE3f Pose(int image_index) { return _poses[image_index].cast<float>(); }
// [num_cameras, num_model_params]
StaticDeviceTensor<float, 2> intrinsics;
HD inline thrust::pair<IntrinsicsPinholef, Distortionf> PinholeIntrinsics(int camera_index)
{
float* ptr = &intrinsics(camera_index, 0);
IntrinsicsPinholef K = ((vec5*)ptr)[0];
Distortionf distortion = ((vec8*)(ptr + 5))[0];
return {K, distortion};
}
HD inline thrust::pair<Vector<float, 5>, ArrayView<const float>> OcamIntrinsics(int camera_index)
{
float* ptr = &intrinsics(camera_index, 0);
int count = intrinsics.sizes[1];
Vector<float, 5> aff = ((vec5*)ptr)[0];
ArrayView<const float> poly((ptr + 5), count - 5);
return {aff, poly};
}
// vec5* intrinsics_pinhole;
// vec8* intrinsics_distortion;
DeviceRenderParams() {}
DeviceRenderParams(RenderParams params)
{
num_texture_channels = params.num_texture_channels;
check_normal = params.check_normal;
dropout = params.dropout;
ghost_gradients = params.ghost_gradients;
dist_cutoff = params.dist_cutoff;
depth_accept = params.depth_accept;
drop_out_points_by_radius = params.drop_out_points_by_radius;
drop_out_radius_threshold = params.drop_out_radius_threshold;
test_backward_mode = params.test_backward_mode;
distortion_gradient_factor = params.distortion_gradient_factor;
K_gradient_factor = params.K_gradient_factor;
}
};
struct DeviceForwardParams
{
StaticDeviceTensor<float, 4> neural_out[max_layers];
};
struct DeviceBackwardParams
{
Vec6* out_gradient_pose;
float* out_gradient_pose_count;
vec4* out_gradient_points;
float* out_gradient_points_count;
StaticDeviceTensor<float, 2> out_gradient_intrinsics;
float* out_gradient_intrinsics_count;
StaticDeviceTensor<float, 2> out_gradient_texture;
StaticDeviceTensor<float, 4> in_gradient_image[max_layers];
};
static __device__ __constant__ DeviceRenderParams d_render_params;
static __device__ __constant__ DeviceForwardParams d_forward_params;
static __device__ __constant__ DeviceBackwardParams d_backward_params;
__global__ void Clear(ImageView<Packtype> src, ImageView<float> dsrc)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (gx >= src.width || gy >= src.height) return;
CUDA_DEBUG_ASSERT(dsrc(gy, gx) == 100000);
src(gy, gx) = PackIndex(1000000, 0);
dsrc(gy, gx) = 100000;
}
#ifdef _CG_HAS_MATCH_COLLECTIVE
template <int GROUP_SIZE = 32>
__device__ cooperative_groups::coalesced_group subgroupPartitionNV(ivec2 p)
{
using namespace cooperative_groups;
thread_block block = this_thread_block();
thread_block_tile<GROUP_SIZE> tile32 = tiled_partition<GROUP_SIZE>(block);
coalesced_group g1 = labeled_partition(tile32, p(0));
coalesced_group g2 = labeled_partition(tile32, p(1));
details::_coalesced_group_data_access acc;
return acc.construct_from_mask<coalesced_group>(acc.get_mask(g1) & acc.get_mask(g2));
}
template <typename T, int GROUP_SIZE = 32>
__device__ T subgroupPartitionedAddNV(T value, cooperative_groups::coalesced_group group)
{
int s = group.size();
int r = group.thread_rank();
for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2)
{
auto v = group.template shfl_down(value, offset);
if (r + offset < s) value += v;
}
return value;
}
template <typename T, int GROUP_SIZE = 32>
__device__ T subgroupPartitionedMinNV(T value, cooperative_groups::coalesced_group group)
{
int s = group.size();
int r = group.thread_rank();
for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2)
{
auto v = group.template shfl_down(value, offset);
if (r + offset < s) value = min(value, v);
}
return value;
}
#endif
template <int num_layers, bool opt_test, bool opt_ballot, bool opt_early_z>
__global__ void DepthPrepassMulti(DevicePointCloud point_cloud, ReducedImageInfo cam, int batch)
{
cooperative_groups::grid_group grid = cooperative_groups::this_grid();
for (int point_id = grid.thread_rank(); point_id < point_cloud.Size(); point_id += grid.size())
{
vec2 ip;
float z;
float radius_pixels;
if (opt_test)
{
float* dst = &d_render_params.tmp_projections.Get({batch, point_id, 0});
float4 res = ((float4*)dst)[0];
ip(0) = res.x;
ip(1) = res.y;
z = res.z;
radius_pixels = res.w;
if (z <= 0) continue;
}
else
{
vec3 position;
vec3 normal;
vec2 image_p_a;
float drop_out_radius;
CUDA_KERNEL_ASSERT(cam.image_index >= 0);
Sophus::SE3f V = d_render_params.Pose(cam.image_index);
thrust::tie(position, normal, drop_out_radius) = point_cloud.GetPoint(point_id);
if (cam.camera_model_type == CameraModel::PINHOLE_DISTORTION)
{
CUDA_KERNEL_ASSERT(cam.camera_model_type == CameraModel::PINHOLE_DISTORTION);
auto [K, distortion] = d_render_params.PinholeIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointPinhole(
position, normal, V, K, distortion, d_render_params.check_normal, d_render_params.dist_cutoff);
radius_pixels = K.fx * cam.crop_transform.fx * drop_out_radius / z;
}
else if (cam.camera_model_type == CameraModel::OCAM)
{
auto [aff, poly] = d_render_params.OcamIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointOcam(position, normal, V, aff, poly,
d_render_params.check_normal, d_render_params.dist_cutoff);
radius_pixels = d_render_params.depth[0].Image().w * cam.crop_transform.fx * drop_out_radius / z;
}
if (z == 0) continue;
ip = cam.crop_transform.normalizedToImage(image_p_a);
}
#pragma unroll
for (int layer = 0; layer < num_layers; ++layer, radius_pixels *= 0.5f, ip *= 0.5f)
{
if (d_render_params.drop_out_points_by_radius && radius_pixels < d_render_params.drop_out_radius_threshold)
{
break;
}
ivec2 p_imgi = ivec2(__float2int_rn(ip(0)), __float2int_rn(ip(1)));
// Check in image
if (!d_render_params.depth[layer].Image().inImage2(p_imgi(1), p_imgi(0))) continue;
float* dst_pos = &(d_render_params.depth[layer](batch, 0, p_imgi(1), p_imgi(0)));
if (opt_early_z)
{
// earlyz
if (z >= *dst_pos) continue;
}
int i_depth = reinterpret_cast<int*>(&z)[0];
#ifdef _CG_HAS_MATCH_COLLECTIVE
if constexpr (opt_ballot)
{
auto ballot = subgroupPartitionNV(p_imgi);
int min_depth = subgroupPartitionedMinNV(i_depth, ballot);
if (ballot.thread_rank() == 0)
{
atomicMin((int*)dst_pos, min_depth);
}
}
else
#endif
{
atomicMin((int*)dst_pos, i_depth);
}
}
}
}
template <int num_layers, bool opt_test>
__global__ void RenderForwardMulti(DevicePointCloud point_cloud, float* dropout_p, ReducedImageInfo cam, int batch)
{
cooperative_groups::grid_group grid = cooperative_groups::this_grid();
for (int point_id = grid.thread_rank(); point_id < point_cloud.Size(); point_id += grid.size())
{
// if (point_id == 0)
// {
// printf("dist cutoff %f\n", d_render_params.dist_cutoff);
// }
bool drop_out = dropout_p[point_id] == 1;
if (drop_out) return;
vec2 ip;
float z;
float radius_pixels;
if (opt_test)
{
float* dst = &d_render_params.tmp_projections.Get({batch, point_id, 0});
float4 res = ((float4*)dst)[0];
ip(0) = res.x;
ip(1) = res.y;
z = res.z;
radius_pixels = res.w;
if (z <= 0) continue;
}
else
{
vec3 position;
vec3 normal;
vec2 image_p_a;
float drop_out_radius;
Sophus::SE3f V = d_render_params.Pose(cam.image_index);
thrust::tie(position, normal, drop_out_radius) = point_cloud.GetPoint(point_id);
if (cam.camera_model_type == CameraModel::PINHOLE_DISTORTION)
{
auto [K, distortion] = d_render_params.PinholeIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointPinhole(
position, normal, V, K, distortion, d_render_params.check_normal, d_render_params.dist_cutoff);
radius_pixels = K.fx * cam.crop_transform.fx * drop_out_radius / z;
}
else if (cam.camera_model_type == CameraModel::OCAM)
{
auto [aff, poly] = d_render_params.OcamIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointOcam(position, normal, V, aff, poly,
d_render_params.check_normal, d_render_params.dist_cutoff);
radius_pixels = d_render_params.depth[0].Image().w * cam.crop_transform.fx * drop_out_radius / z;
}
if (z == 0) continue;
ip = cam.crop_transform.normalizedToImage(image_p_a);
}
int texture_index = point_cloud.GetIndex(point_id);
CUDA_KERNEL_ASSERT(texture_index >= 0 && texture_index < d_render_params.in_texture.sizes[1]);
#pragma unroll
for (int layer = 0; layer < num_layers; ++layer, radius_pixels *= 0.5f, ip *= 0.5f)
// for (int layer = num_layers - 1; layer >= 0; --layer, radius_pixels *= 2.f, ip *= 2.f)
{
if (d_render_params.drop_out_points_by_radius && radius_pixels < d_render_params.drop_out_radius_threshold)
{
break;
}
ivec2 p_imgi = ivec2(__float2int_rn(ip(0)), __float2int_rn(ip(1)));
// Check in image
if (!d_render_params.depth[layer].Image().inImage2(p_imgi(1), p_imgi(0))) continue;
float image_depth = d_render_params.depth[layer](batch, 0, p_imgi(1), p_imgi(0));
if (z > image_depth * (d_render_params.depth_accept + 1)) continue;
for (int ci = 0; ci < d_render_params.in_texture.sizes[0]; ++ci)
{
float t = d_render_params.in_texture(ci, texture_index);
atomicAdd(&d_forward_params.neural_out[layer](batch, ci, p_imgi(1), p_imgi(0)), t);
}
auto* dst_pos_weight = &(d_render_params.weight[layer](batch, 0, p_imgi(1), p_imgi(0)));
atomicAdd(dst_pos_weight, 1);
}
}
}
__global__ void RenderBackward(DevicePointCloud point_cloud, float* dropout_p, ReducedImageInfo cam, int layer,
int batch)
{
int point_id = blockIdx.x * blockDim.x + threadIdx.x;
if (point_id >= point_cloud.Size()) return;
bool drop_out = dropout_p[point_id] == 1;
vec2 ip;
float z;
float radius_pixels;
vec3 position;
vec3 normal;
Sophus::SE3f V = d_render_params.Pose(cam.image_index);
{
vec2 image_p_a;
float drop_out_radius;
thrust::tie(position, normal, drop_out_radius) = point_cloud.GetPoint(point_id);
if (cam.camera_model_type == CameraModel::PINHOLE_DISTORTION)
{
CUDA_KERNEL_ASSERT(cam.camera_model_type == CameraModel::PINHOLE_DISTORTION);
auto [K, distortion] = d_render_params.PinholeIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointPinhole(position, normal, V, K, distortion,
d_render_params.check_normal, d_render_params.dist_cutoff);
radius_pixels = K.fx * cam.crop_transform.fx * drop_out_radius / z;
}
else if (cam.camera_model_type == CameraModel::OCAM)
{
auto [aff, poly] = d_render_params.OcamIntrinsics(cam.camera_index);
thrust::tie(image_p_a, z) = ProjectPointOcam(position, normal, V, aff, poly, d_render_params.check_normal,
d_render_params.dist_cutoff);
radius_pixels = d_render_params.depth[0].Image().w * cam.crop_transform.fx * drop_out_radius / z;
}
if (z == 0) return;
ip = cam.crop_transform.normalizedToImage(image_p_a);
}
auto texture_index = point_cloud.GetIndex(point_id);
float scale = 1;
#pragma unroll
for (int layer = 0; layer < max_layers; ++layer, scale *= 0.5f, radius_pixels *= 0.5f, ip *= 0.5f)
{
if (layer < d_render_params.num_layers)
{
// ip = cam.crop_transform.scale(scale).normalizedToImage(image_p_a, nullptr, nullptr);
// radius_pixels = scale * cam.base_K.fx * cam.crop_transform.fx * drop_out_radius / z;
if (d_render_params.drop_out_points_by_radius && radius_pixels < d_render_params.drop_out_radius_threshold)
{
continue;
}
ivec2 p_imgi = ivec2(__float2int_rn(ip(0)), __float2int_rn(ip(1)));
// Check in image
if (!d_render_params.depth[layer].Image().inImage2(p_imgi(1), p_imgi(0))) continue;
float image_depth = d_render_params.depth[layer](batch, 0, p_imgi(1), p_imgi(0));
if (z > image_depth * (d_render_params.depth_accept + 1)) break;
auto* dst_pos_weight = &(d_render_params.weight[layer](batch, 0, p_imgi(1), p_imgi(0)));
float w = *dst_pos_weight;
if (!drop_out)
{
// This is currently necessary because somehow the results cam.crop_transform transformation gives
// different results here compared to the forwrad function even though the inputs are the same.
if (w == 0) continue;
float iw = 1.f / w;
CUDA_DEBUG_ASSERT(w > 0);
for (int ci = 0; ci < d_backward_params.out_gradient_texture.sizes[0]; ++ci)
{
float g = iw * d_backward_params.in_gradient_image[layer](batch, ci, p_imgi.y(), p_imgi.x());
CUDA_KERNEL_ASSERT(isfinite(g));
// g = clamp(g * 100, -10, 10);
atomicAdd(&d_backward_params.out_gradient_texture(ci, texture_index), g);
}
}
bool point_grad =
(d_render_params.ghost_gradients && drop_out) | (!d_render_params.ghost_gradients && !drop_out);
if (point_grad && d_render_params.depth[layer].Image().distanceFromEdge(p_imgi.y(), p_imgi.x()) > 2)
{
// We have the following pixel constellation were p is the pixel of the current point and px0, px1,...
// are the left, right, bottom and top neighbors.
//
// py1
// |
// px0 - p - px1
// |
// py0
//
// The output neural image of the render operation is I.
// The intensity of a pixel in I is for example I(px1). The texture of a point is T(p). The background
// color is B(p). We now compute the gradient of p w.r.t. I.
//
// If the point moves from p to px1 and I(px1) was previously the background color
// then I(px1) is now colored by the texture of p. The new value NV of px1 is then:
// NV(px1) = T(p)
//
// The change of I at px1 is then:
// Motion p -> px1 (positive X):
// dI(x)/dp|x=px1 = NV(px1) - I(px1)
//
// There is a special case that if I(px1) is already colored by one or more points which have a similar
// z-value then the point is blended into the neighbors instead of overriding them. This change is then
// defined using the weight at that pixel W(p).
//
// New value if p -> px1:
// NV(px1) = W(px1)/(W(px1)+1)*I(px1)+1/(W(px1)+1)*T(p)
// The gradient is therefore:
// dI(x)/dp|x=px1 = NV(px1) - I(px1)
//
ivec2 px0 = p_imgi + ivec2(-1, 0);
ivec2 px1 = p_imgi + ivec2(1, 0);
ivec2 py0 = p_imgi + ivec2(0, -1);
ivec2 py1 = p_imgi + ivec2(0, 1);
float iw = 1.f / (w + 1);
float dR_dpx = 0;
float dR_dpy = 0;
auto sample_grad = [&](int ci, ivec2 p) -> float
{ return d_backward_params.in_gradient_image[layer](batch, ci, p.y(), p.x()); };
auto sample_forward = [&](int ci, ivec2 p) -> float
{ return d_forward_params.neural_out[layer](batch, ci, p.y(), p.x()); };
auto sample_tex = [&](int ci, int uv) -> float { return d_render_params.in_texture(ci, uv); };
auto compute_dR_dp_at_x = [&](ivec2 x, int ci, float W_x, float D_x, float T_p) -> float
{
auto I_x = sample_forward(ci, x);
auto G_x = sample_grad(ci, x);
if (d_render_params.test_backward_mode == 4)
{
float dI_dp_at_x;
if (W_x == 0 || z * (d_render_params.depth_accept + 1) < D_x)
{
// Full override
dI_dp_at_x = T_p - I_x;
}
else if (z > D_x * (d_render_params.depth_accept + 1))
{
// Discard
dI_dp_at_x = 0;
// dI_dp_at_x = T_p - I_x;
}
else
{
// Blend
dI_dp_at_x = (W_x / (W_x + 1) * I_x + 1 / (W_x + 1) * T_p - I_x);
// dI_dp_at_x = T_p - I_x;
}
float dR_dp_at_x = dI_dp_at_x * G_x;
return dR_dp_at_x;
}
else
{
float dI_dp_at_x = T_p - I_x;
float dR_dp_at_x = dI_dp_at_x * G_x;
return dR_dp_at_x;
}
};
float W_px0 = d_render_params.weight[layer](batch, 0, px0(1), px0(0));
float W_px1 = d_render_params.weight[layer](batch, 0, px1(1), px1(0));
float W_py0 = d_render_params.weight[layer](batch, 0, py0(1), py0(0));
float W_py1 = d_render_params.weight[layer](batch, 0, py1(1), py1(0));
float D_px0 = d_render_params.depth[layer](batch, 0, px0(1), px0(0));
float D_px1 = d_render_params.depth[layer](batch, 0, px1(1), px1(0));
float D_py0 = d_render_params.depth[layer](batch, 0, py0(1), py0(0));
float D_py1 = d_render_params.depth[layer](batch, 0, py1(1), py1(0));
int texture_channels = d_backward_params.out_gradient_texture.sizes[0];
#pragma unroll
for (int ci = 0; ci < texture_channels; ++ci)
{
auto g = sample_grad(ci, p_imgi);
auto T_p = sample_tex(ci, texture_index);
// The spatial derivatives at the neighboring points.
float dI_dp_at_px0 = 0; //-(T_p - I_px0);
float dI_dp_at_px1 = 0; // T_p - I_px1;
float dI_dp_at_py0 = 0; //-(T_p - I_py0);
float dI_dp_at_py1 = 0; // T_p - I_py1;
dI_dp_at_px0 = -compute_dR_dp_at_x(px0, ci, W_px0, D_px0, T_p);
dI_dp_at_px1 = compute_dR_dp_at_x(px1, ci, W_px1, D_px1, T_p);
dI_dp_at_py0 = -compute_dR_dp_at_x(py0, ci, W_py0, D_py0, T_p);
dI_dp_at_py1 = compute_dR_dp_at_x(py1, ci, W_py1, D_py1, T_p);
// Average between forward and backward diff. to get symmetric central diff.
dR_dpx += 0.5f * (dI_dp_at_px0 + dI_dp_at_px1);
dR_dpy += 0.5f * (dI_dp_at_py0 + dI_dp_at_py1);
}
vec2 dR_dp = vec2(dR_dpx, dR_dpy) / float(texture_channels);
float grad_scale = 1.f;
auto cam2 = cam;
cam2.crop_transform = cam.crop_transform.scale(scale * grad_scale);
if (cam.camera_model_type == CameraModel::PINHOLE_DISTORTION)
{
auto [K, distortion] = d_render_params.PinholeIntrinsics(cam.camera_index);
auto [g_point, g_pose, g_k, g_dis] =
ProjectPointPinholeBackward(position, normal, dR_dp, V, K, cam2.crop_transform, distortion,
d_render_params.check_normal, d_render_params.dist_cutoff);
if (d_backward_params.out_gradient_points)
{
for (int k = 0; k < g_point.rows(); ++k)
{
atomicAdd(&d_backward_params.out_gradient_points[point_id][k], g_point(k));
}
atomicAdd(&d_backward_params.out_gradient_points_count[point_id], 1);
}
if (d_backward_params.out_gradient_pose)
{
// Extrinsics
for (int k = 0; k < g_pose.rows(); ++k)
{
atomicAdd(&d_backward_params.out_gradient_pose[cam.image_index][k], g_pose(k));
}
atomicAdd(&d_backward_params.out_gradient_pose_count[cam.image_index], 1);
}
if (d_backward_params.out_gradient_intrinsics_count)
{
float k_factor = d_render_params.K_gradient_factor;
// Intrinsics
// g_k(2) *= 0.5;
// g_k(3) *= 0.5;
// sheer
g_k(4) *= 0.1;
g_k(4) *= 0; // remove sheer (so that we can use it in colmap)
for (int k = 0; k < 5; ++k)
{
atomicAdd(&d_backward_params.out_gradient_intrinsics(cam.camera_index, k),
k_factor * g_k(k));
}
float distortion_factor = d_render_params.distortion_gradient_factor;
// k3
g_dis(2) *= 0.25;
// k4 - 6
g_dis(3) *= 0.1;
g_dis(4) *= 0.1;
g_dis(5) *= 0.1;
// tangential distortion
g_dis(6) *= 0.1;
g_dis(7) *= 0.1;
for (int k = 0; k < 8; ++k)
{
atomicAdd(&d_backward_params.out_gradient_intrinsics(cam.camera_index, k + 5),
distortion_factor * g_dis(k));
}
// Note we add a value less than 1 to increase float precision
float factor = 1.f / 1024.f;
atomicAdd(&d_backward_params.out_gradient_intrinsics_count[cam.camera_index], factor);
}
}
else if (cam.camera_model_type == CameraModel::OCAM)
{
auto [aff, poly] = d_render_params.OcamIntrinsics(cam.camera_index);
auto [g_point, g_pose, g_affine] =
ProjectPointOcamBackward(position, normal, dR_dp, V, cam2.crop_transform, aff, poly,
d_render_params.check_normal, d_render_params.dist_cutoff);
if (d_backward_params.out_gradient_points)
{
// Points
for (int k = 0; k < g_point.rows(); ++k)
{
atomicAdd(&d_backward_params.out_gradient_points[point_id][k], g_point(k));
}
atomicAdd(&d_backward_params.out_gradient_points_count[point_id], 1);
}
if (d_backward_params.out_gradient_pose)
{
// Extrinsics
for (int k = 0; k < g_pose.rows(); ++k)
{
atomicAdd(&d_backward_params.out_gradient_pose[cam.image_index][k], g_pose(k));
}
atomicAdd(&d_backward_params.out_gradient_pose_count[cam.image_index], 1);
}
if (d_backward_params.out_gradient_intrinsics_count)
{
// Extrinsics
for (int k = 0; k < 5; ++k)
{
atomicAdd(&d_backward_params.out_gradient_intrinsics(cam.camera_index, k), g_affine(k));
}
atomicAdd(&d_backward_params.out_gradient_intrinsics_count[cam.camera_index], 1);
}
}
}
}
}
}
template <typename IndexType>
__global__ void CombineAndFill(float* background_color, ImageView<float> weight,
StaticDeviceTensor<float, 3> out_neural_image)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (gx >= weight.width || gy >= weight.height) return;
auto cou = weight(gy, gx);
auto texture_channels = out_neural_image.sizes[0];
if (cou == 0)
{
// copy background into output
for (int ci = 0; ci < texture_channels; ++ci)
{
out_neural_image(ci, gy, gx) = background_color[ci];
}
}
else
{
// divide by weight
for (int ci = 0; ci < texture_channels; ++ci)
{
out_neural_image(ci, gy, gx) /= cou;
}
}
}
__global__ void DebugWeightToColor(ImageView<float> weight, StaticDeviceTensor<float, 3> out_neural_image,
float debug_max_weight)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (gx >= weight.width || gy >= weight.height) return;
auto cou = weight(gy, gx);
CUDA_DEBUG_ASSERT(out_neural_image.sizes[0] == 4);
if (cou == 0)
{
// copy background into output
for (int ci = 0; ci < 3; ++ci)
{
out_neural_image(ci, gy, gx) = 0;
}
out_neural_image(3, gy, gx) = 1;
}
else
{
float x = cou / debug_max_weight;
// float t = ::saturate(x);
// vec3 c = saturate(vec3(sqrt(t), t * t * t, std::max(sin(3.1415 * 1.75 * t), pow(t, 12.0))));
vec3 c = colorizeTurbo(x);
// divide by weight
for (int ci = 0; ci < 3; ++ci)
{
out_neural_image(ci, gy, gx) = c(ci);
}
out_neural_image(3, gy, gx) = 1;
}
}
__global__ void DebugDepthToColor(ImageView<float> depth, StaticDeviceTensor<float, 3> out_neural_image,
float debug_max_weight)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (gx >= depth.width || gy >= depth.height) return;
auto cou = depth(gy, gx);
CUDA_DEBUG_ASSERT(out_neural_image.sizes[0] == 4);
if (cou == 0)
{
// copy background into output
for (int ci = 0; ci < 3; ++ci)
{
out_neural_image(ci, gy, gx) = 0;
}
out_neural_image(3, gy, gx) = 1;
}
else
{
float x = cou / debug_max_weight;
vec3 c = vec3(x, x, x);
// divide by weight
for (int ci = 0; ci < 3; ++ci)
{
out_neural_image(ci, gy, gx) = c(ci);
}
out_neural_image(3, gy, gx) = 1;
}
}
__global__ void CreateMask(StaticDeviceTensor<float, 4> in_weight, StaticDeviceTensor<float, 4> out_mask,
float background_value, int b)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (!in_weight.Image().template inImage(gy, gx)) return;
auto w = in_weight.At({b, 0, gy, gx});
if (w == 0)
{
out_mask.At({b, 0, gy, gx}) = background_value;
}
else
{
out_mask(b, 0, gy, gx) = 1;
}
}
template <typename IndexType>
__global__ void CombineAndFillBackward(StaticDeviceTensor<float, 3> image_gradient, ImageView<float> weight,
float* out_background_gradient)
{
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
int local_tid = threadIdx.y * blockDim.x + threadIdx.x;
bool in_image = gx < weight.width && gy < weight.height;
// if (!in_image) return;
gx = min(gx, weight.width - 1);
gy = min(gy, weight.height - 1);
__shared__ float bg_grad[20];
int num_channels = image_gradient.sizes[0];
if (local_tid < num_channels)
{
bg_grad[local_tid] = 0;
}
__syncthreads();
auto w = weight(gy, gx);
float factor = (w == 0 & in_image);
// if (w == 0)
{
for (int ci = 0; ci < num_channels; ++ci)
{
float g = factor * image_gradient(ci, gy, gx);
g = CUDA::warpReduceSum<float>(g);
if (local_tid % 32 == 0)
{
atomicAdd(&bg_grad[ci], g);
}
}
}
__syncthreads();
if (local_tid < num_channels)
{
atomicAdd(&out_background_gradient[local_tid], bg_grad[local_tid]);
}
}
void PointRendererCache::Build(NeuralRenderInfo* info, bool forward)
{
this->info = info;
this->num_batches = info->images.size();
SAIGA_OPTIONAL_TIME_MEASURE("Build Cache", info->timer_system);
static_assert(sizeof(Packtype) == 8);
SAIGA_ASSERT(num_batches > 0);
{
SAIGA_OPTIONAL_TIME_MEASURE("Allocate", info->timer_system);
Allocate(info, forward);
}
if (forward)
{
SAIGA_OPTIONAL_TIME_MEASURE("Initialize", info->timer_system);
InitializeData(forward);
}
else
{
output_gradient_texture = torch::zeros_like(info->scene->texture->texture);
output_gradient_background = torch::zeros_like(info->scene->texture->background_color);
if (info->scene->point_cloud_cuda->t_position.requires_grad())
{
output_gradient_points = torch::zeros_like(info->scene->point_cloud_cuda->t_position);
output_gradient_point_count =
torch::zeros({output_gradient_points.size(0)}, output_gradient_points.options());
}
if (info->scene->poses->tangent_poses.requires_grad())
{
output_gradient_pose_tangent = torch::zeros_like(info->scene->poses->tangent_poses);
output_gradient_pose_tangent_count =
torch::zeros({info->scene->poses->tangent_poses.size(0)},
info->scene->poses->tangent_poses.options().dtype(torch::kFloat32));
}
if (info->scene->intrinsics->intrinsics.requires_grad())
{
output_gradient_intrinsics = torch::zeros_like(info->scene->intrinsics->intrinsics);
output_gradient_intrinsics_count = torch::zeros({info->scene->intrinsics->intrinsics.size(0)},
info->scene->intrinsics->intrinsics.options());
}
}
}
void PointRendererCache::Allocate(NeuralRenderInfo* info, bool forward)
{
auto& fd = info->images.front();
int h = fd.h;
int w = fd.w;
SAIGA_ASSERT(info->scene->point_cloud_cuda);
SAIGA_ASSERT(info->scene->texture);
std::vector<int> new_cache_size = {(int)info->scene->texture->texture.size(0),
info->scene->point_cloud_cuda->Size(),
info->num_layers,
num_batches,
h,
w};
bool size_changed = new_cache_size != cache_size;
if (size_changed)
{
cache_has_forward = false;
cache_has_backward = false;
}
bool need_allocate_forward = !cache_has_forward && forward;
bool need_allocate_backward = !cache_has_backward && !forward;
if (!need_allocate_forward && !need_allocate_backward)
{
// std::cout << "skip allocate" << std::endl;
return;
}
// std::cout << "allocate render cache " << need_allocate_forward << " " << need_allocate_backward << " "
// << size_changed << std::endl;
if (size_changed)
{
layers_cuda.resize(info->num_layers);
}
float scale = 1;
for (int i = 0; i < info->num_layers; ++i)
{
SAIGA_ASSERT(w > 0 && h > 0);
auto& l = layers_cuda[i];