-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlightfieldPlayer.cpp
1591 lines (1413 loc) · 60.8 KB
/
lightfieldPlayer.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 <ArgumentViewer/ArgumentViewer.h>
#include <Simple3DApp/Application.h>
#include <geGL/geGL.h>
#include <BasicCamera/PerspectiveCamera.h>
#include <BasicCamera/OrbitCamera.h>
#include <imguiVars/imguiVars.h>
#include <drawGrid.h>
#include <FunctionPrologue.h>
#include <SDL2CPP/Exception.h>
#include <Timer.h>
#include <gpuDecoder.h>
#include <thread>
#include <mutex>
#include <condition_variable>
//TODO use c++20 barriers when released
//#include <barrier>
#include <fstream>
constexpr float FRAME_LIMIT{1.0f/24};
constexpr uint32_t FOCUSMAP_DIV{1};
constexpr bool MEASURE_TIME{1};
constexpr bool STATISTICS{0};
constexpr bool TEXTURE_STATISTICS{0};
constexpr int WARP_SIZE{32};
constexpr int LOCAL_SIZE_X{WARP_SIZE};
constexpr int LOCAL_SIZE_Y{8};
constexpr int BLOCK_SIZE{32};
class LightFields: public simple3DApp::Application
{
public:
LightFields(int argc, char* argv[]) : Application(argc, argv) {}
virtual ~LightFields(){}
virtual void draw() override;
vars::Vars vars;
virtual void init() override;
virtual void deinit() override {vars.reCreate<bool>("mainRuns", false);}
virtual void mouseMove(SDL_Event const& event) override;
virtual void key(SDL_Event const& e, bool down) override;
virtual void resize(uint32_t x,uint32_t y) override;
};
void addProgram(vars::Vars&vars, std::string name, std::string code1, std::string code2)
{
std::map<std::string, std::string> substitutions ={
{"LSX",std::to_string(LOCAL_SIZE_X)},
{"LSY",std::to_string(LOCAL_SIZE_Y)},
{"BSY",std::to_string(BLOCK_SIZE)},
{"BSX",std::to_string(BLOCK_SIZE)},
{"GSX",std::to_string(vars.get<glm::ivec2>("gridSize")->x)}
};
for(const auto& [key, value] : substitutions)
{
size_t pos = code1.find(key);
if(pos != std::string::npos)
code1.replace(code1.find(key), key.length(), value);
pos = code1.find(key);
if(pos != std::string::npos)
code2.replace(code2.find(key), key.length(), value);
}
if(!code2.empty())
{
auto vs = std::make_shared<ge::gl::Shader>(GL_VERTEX_SHADER, "#version 450\n", code1);
auto fs = std::make_shared<ge::gl::Shader>(GL_FRAGMENT_SHADER, "#version 450\n", code2);
auto program = vars.reCreate<ge::gl::Program>(name,vs,fs);
if(program->getLinkStatus() == GL_FALSE)
throw std::runtime_error("Cannot link shader program.");
}
else
{
auto cs = std::make_shared<ge::gl::Shader>(GL_COMPUTE_SHADER, "#version 450\n", code1);
auto program = vars.reCreate<ge::gl::Program>(name,cs);
if(program->getLinkStatus() == GL_FALSE)
throw std::runtime_error("Cannot link shader program.");
}
}
void createProgram(vars::Vars&vars)
{
std::string const vsSrc = R".(
uniform mat4 mvp;
uniform float aspect = 1.f;
out vec2 vCoord;
void main()
{
vCoord = vec2(gl_VertexID&1,gl_VertexID>>1);
gl_Position = mvp*vec4((-1+2*vCoord)*vec2(aspect,1),0,1);
}
).";
//#################################################################
std::string fsSrc = R".(
#extension GL_ARB_gpu_shader_int64 : require
#extension GL_ARB_bindless_texture : require
uniform sampler2D lf;
out vec4 fColor;
in vec2 vCoord;
void main()
{
fColor = texture(lf, vCoord);
}
).";
//#################################################################
std::string csLfSrc = R".(
#extension GL_ARB_gpu_shader_int64 : require
#extension GL_ARB_bindless_texture : require
const ivec2 gridSize = ivec2(GSX);
const uint lfSize = gridSize.x*gridSize.x;
const uint focusLevels = 32; //warp size
uniform uint64_t lfTextures[lfSize];
layout(bindless_image)uniform layout(r8ui) readonly uimage2D focusMap;
layout(local_size_x=LSX*LSY)in;
layout(bindless_image)uniform layout(rgba8) writeonly image2D lf;
const ivec2 size = imageSize(lf);
TEXTURE_CHECK_INIT
uniform int showFocusMap;
uniform int useMedian;
uniform vec2 viewCoord;
uniform float focusStep;
uniform float focus;
uniform float aspect;
uniform float gridSampleDistanceR;
uniform int searchSubdiv;
vec4 lfTexture(int i, vec2 coord)
{
TEXTURE_CHECK_EXEC
//return texture(sampler2D(lfTextures[i]),coord); //this causes offset in the final image
return texelFetch(sampler2D(lfTextures[i]),ivec2(round(coord*vec2(size))),0);
//return texelFetch(sampler2D(lfTextures[i]),clamp(ivec2(round(coord*vec2(size))),ivec2(0,0), size),0);
}
void loadPixels(in ivec2 dt, out ivec4 e[3])
{
int i = 0;
ivec2 offset;
for (offset.y = -1; offset.y <= 1; ++offset.y)
{
for (offset.x = -1; offset.x <= 1; ++offset.x)
{
e[i / 4][i % 4] = int(imageLoad(focusMap, dt + offset).x);
++i;
}
}
}
void minmax(inout int u, inout int v)
{
int save = u;
u = min(save, v);
v = max(save, v);
}
void minmax(inout ivec2 u, inout ivec2 v)
{
ivec2 save = u;
u = min(save, v);
v = max(save, v);
}
void minmax(inout ivec4 u, inout ivec4 v)
{
ivec4 save = u;
u = min(save, v);
v = max(save, v);
}
void minmax3(inout ivec4 e[3])
{
minmax(e[0].x, e[0].y);
minmax(e[0].x, e[0].z);
minmax(e[0].y, e[0].z);
}
void minmax4(inout ivec4 e[3])
{
minmax(e[0].xy, e[0].zw);
minmax(e[0].xz, e[0].yw);
}
void minmax5(inout ivec4 e[3])
{
minmax(e[0].xy, e[0].zw);
minmax(e[0].xz, e[0].yw);
minmax(e[0].x, e[1].x);
minmax(e[0].w, e[1].x);
}
void minmax6(inout ivec4 e[3])
{
minmax(e[0].xy, e[0].zw);
minmax(e[0].xz, e[0].yw);
minmax(e[1].x, e[1].y);
minmax(e[0].xw, e[1].xy);
}
void main()
{
const ivec2 outCoords = ivec2(gl_GlobalInvocationID.x%size.x, gl_GlobalInvocationID.x/size.x);
const vec2 inCoords = outCoords/vec2(size);
int focusLvl = 0;
if(useMedian != 0)
{
ivec4 e[3];
loadPixels(ivec2(inCoords*imageSize(focusMap)), e);
minmax6(e);
e[0].x = e[2].x;
minmax5(e);
e[0].x = e[1].w;
minmax4(e);
e[0].x = e[1].z;
minmax3(e);
focusLvl = e[0].y;
}
else
focusLvl = int(imageLoad(focusMap, ivec2(inCoords*imageSize(focusMap))).x);
float focusValue = focus+focusLvl*focusStep;
vec4 color = vec4(0,0,0,0);
int n=0;
for(int x=0; x<gridSize.x; x++)
for(int y=0; y<gridSize.y; y++)
{
float dist = distance(viewCoord, vec2(x,y));
if(dist > gridSampleDistanceR) continue;
n++;
int slice = y*int(gridSize.x)+x;
vec2 offset = viewCoord-vec2(x,y);
offset.y *=-1;
vec2 focusedCoords = clamp(inCoords+offset*focusValue*vec2(1.0,aspect), 0.0, 1.0);
color += lfTexture(slice,focusedCoords);
}
color /= n;
color.w = 1.0;
/*range detection test
color = vec4(0);
if(focus > 100.0) color.x = focusStep;
for(int x=0; x<2; x++)
for(int y=0; y<2; y++)
{
vec2 offset = vec2(0.5)-vec2(x,y);
offset.y *=-1;
vec2 focusedCoords = clamp((inCoords+offset*focus)*vec2(1.0,aspect), 0.0, 1.0);
int slice = y*int(gridSize.x)+x;
color.xyz += texelFetch(sampler2D(lfTextures[slice]),ivec2(round(focusedCoords*size)),0).xyz;
}
color /= 4;
color.w = 1.0;
*/
if(showFocusMap != 0)
color = vec4(vec3(focusLvl/float(focusLevels*(searchSubdiv+1))),1.0);
/*if(outCoords.y == 1080-319 && outCoords.x == 894)
color = vec4(1.0,0.0,0.0,1.0);*/
imageStore(lf, outCoords, color);
}
).";
//#################################################################
std::string csMapSrc = R".(
#extension GL_ARB_gpu_shader_int64 : require
#extension GL_NV_shader_thread_shuffle : require
#extension GL_NV_gpu_shader5 : require
#extension GL_ARB_bindless_texture : require
#extension GL_ARB_shader_ballot : require
#extension GL_ARB_shader_image_load_store : require
const ivec2 gridSize = ivec2(GSX);
const uint lfSize = gridSize.x*gridSize.x;
const uint focusLevels = 32; //warp size
const float MAX_M2 = 999999999999999.0;
layout(local_size_x=LSX, local_size_y=LSY)in;
layout(bindless_image)uniform layout(r8ui) writeonly uimage2D focusMap;
STATS_INIT
TEXTURE_CHECK_INIT
uniform uint64_t lfTextures[lfSize];
uniform vec2 viewCoord;
uniform float focusStep;
uniform float focus;
uniform float aspect;
uniform int blockRadius;
uniform float gridSampleDistance;
uniform float saddleImpact;
uniform float saddleLimit;
uniform int colMetric;
uniform int searchSubdiv;
uniform int sampleBlock;
uniform int checkSaddle;
uniform int checkBorders;
uniform int sampleMode;
uniform int borderSize;
vec4 lfTexture(int i, vec2 coord)
{
TEXTURE_CHECK_EXEC
//return texture(sampler2D(lfTextures[i]),coord);
ivec2 resolution = textureSize(sampler2D(lfTextures[0]),0);
return texelFetch(sampler2D(lfTextures[i]),ivec2(round(coord*vec2(resolution))),0);
//return texelFetch(sampler2D(lfTextures[i]),clamp(ivec2(round(coord*vec2(resolution))), ivec2(0,0), resolution),0);
}
const float PI = 3.141592653589793238462643;
vec3 lab2lch(vec3 Lab)
{
return vec3(
Lab[0],
sqrt( ( Lab[1] * Lab[1] ) + ( Lab[2] * Lab[2] ) ),
atan( Lab[1], Lab[2] ));
}
float deltaE2000l( vec3 lch1, vec3 lch2 )
{
float avg_L = ( lch1[0] + lch2[0] ) * 0.5;
float delta_L = lch2[0] - lch1[0];
float avg_C = ( lch1[1] + lch2[1] ) * 0.5;
float delta_C = lch1[1] - lch2[1];
float avg_H = ( lch1[2] + lch2[2] ) * 0.5;
if( abs( lch1[2] - lch2[2] ) > PI )
avg_H += PI;
float delta_H = lch2[2] - lch1[2];
if( abs( delta_H ) > PI )
{
if( lch2[2] <= lch1[2] )
delta_H += PI * 2.0;
else
delta_H -= PI * 2.0;
}
delta_H = sqrt( lch1[1] * lch2[1] ) * sin( delta_H ) * 2.0;
float T = 1.0 -
0.17 * cos( avg_H - PI / 6.0 ) +
0.24 * cos( avg_H * 2.0 ) +
0.32 * cos( avg_H * 3.0 + PI / 30.0 ) -
0.20 * cos( avg_H * 4.0 - PI * 7.0 / 20.0 );
float SL = avg_L - 50.0;
SL *= SL;
SL = SL * 0.015 / sqrt( SL + 20.0 ) + 1.0;
float SC = avg_C * 0.045 + 1.0;
float SH = avg_C * T * 0.015 + 1.0;
float delta_Theta = avg_H / 25.0 - PI * 11.0 / 180.0;
delta_Theta = exp( delta_Theta * -delta_Theta ) * ( PI / 6.0 );
float RT = pow( avg_C, 7.0 );
RT = sqrt( RT / ( RT + 6103515625.0 ) ) * sin( delta_Theta ) * -2.0; // 6103515625 = 25^7
delta_L /= SL;
delta_C /= SC;
delta_H /= SH;
return sqrt( delta_L * delta_L + delta_C * delta_C + delta_H * delta_H + RT * delta_C * delta_H );
}
float deltaE2000( vec3 lab1, vec3 lab2 )
{
vec3 lch1, lch2;
lch1 = lab2lch( lab1);
lch2 = lab2lch( lab2);
return deltaE2000l( lch1, lch2 );
}
vec3 rgb2hsv(vec3 c)
{
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsvTrans(vec3 hsv)
{
float sv = hsv.y*hsv.z;
float pih = hsv.x*2*PI;
return vec3(sv*cos(pih), sv*sin(pih), hsv.z);
}
vec3 rgb2lab(in vec3 rgb){
float R = rgb.x;
float G = rgb.y;
float B = rgb.z;
// threshold
float T = 0.008856;
float X = R * 0.412453 + G * 0.357580 + B * 0.180423;
float Y = R * 0.212671 + G * 0.715160 + B * 0.072169;
float Z = R * 0.019334 + G * 0.119193 + B * 0.950227;
// Normalize for D65 white point
X = X / 0.950456;
Y = Y;
Z = Z / 1.088754;
bool XT, YT, ZT;
XT = false; YT=false; ZT=false;
if(X > T) XT = true;
if(Y > T) YT = true;
if(Z > T) ZT = true;
float Y3 = pow(Y,1.0/3.0);
float fX, fY, fZ;
if(XT){ fX = pow(X, 1.0/3.0);} else{ fX = 7.787 * X + 16.0/116.0; }
if(YT){ fY = Y3; } else{ fY = 7.787 * Y + 16.0/116.0 ; }
if(ZT){ fZ = pow(Z,1.0/3.0); } else{ fZ = 7.787 * Z + 16.0/116.0; }
float L; if(YT){ L = (116.0 * Y3) - 16.0; }else { L = 903.3 * Y; }
float a = 500.0 * ( fX - fY );
float b = 200.0 * ( fY - fZ );
return vec3(L,a,b);
}
vec3 rgb2yuv(vec3 rgba)
{
vec3 yuv = vec3(0.0);
yuv.x = rgba.r * 0.299 + rgba.g * 0.587 + rgba.b * 0.114;
yuv.y = rgba.r * -0.169 + rgba.g * -0.331 + rgba.b * 0.5 + 0.5;
yuv.z = rgba.r * 0.5 + rgba.g * -0.419 + rgba.b * -0.081 + 0.5;
return yuv;
}
float colorDistance(vec3 c1, vec3 c2)
{
if(colMetric == 0)
return distance(c1,c2);
else if(colMetric == 1)
return (abs(c1.r-c2.r)+abs(c1.g-c2.g)+abs(c1.b-c2.b))/(c1.r+c2.r+c1.g+c2.g+c1.b+c2.b); //canberra
else if(colMetric == 2)
return max(max(abs(c1.r-c2.r), abs(c1.g-c2.g)), abs(c1.b-c2.b)); //chebyshev
else if(colMetric == 3)
return pow(pow(abs(c1.r-c2.r),5) + pow(abs(c1.g-c2.g),5) + pow(abs(c1.b-c2.b),5), 1.0/5.0); //minkowski
else if(colMetric == 4)
return distance(hsvTrans(rgb2hsv(c1)), hsvTrans(rgb2hsv(c2)));
else if(colMetric == 5)
return distance(rgb2yuv(c1), rgb2yuv(c2));
else if(colMetric == 6)
return sqrt(3*pow(c1.r-c2.r,2) + 4*pow(c1.g-c2.g,2) + 2*pow(c1.b-c2.b,2)); //weighted euclidan
else if(colMetric == 7)
return abs(c1.r-c2.r)+abs(c1.g-c2.g)+abs(c1.b-c2.b); //manhattan
else if(colMetric == 8)
return deltaE2000(rgb2lab(c1), rgb2lab(c2));
else
return max(max(3*abs(c1.r-c2.r), 4*abs(c1.g-c2.g)), 2*abs(c1.b-c2.b)); //weighted chebyshev
}
void main()
{
const uint pixelId = gl_WorkGroupID.x*gl_WorkGroupSize.y + gl_LocalInvocationID.y;
const ivec2 size = imageSize(focusMap);
const ivec2 outCoords = ivec2(pixelId%size.x, pixelId/size.x);
const vec2 inCoords = outCoords/vec2(size);
const vec2 halfPixelOffset = (vec2(0.5)/textureSize(sampler2D(lfTextures[0]),0))*blockRadius;
const vec2 pixelOffset = (vec2(1.0)/textureSize(sampler2D(lfTextures[0]),0))*blockRadius;
float minM2=MAX_M2;
int subDivLvl = 0;
for(int i=0; i<=searchSubdiv; i++)
{
float m2=0.0;
vec3 mean = vec3(0);
int n=0;
const vec2 focusValue = (focus + (i*focusLevels+gl_LocalInvocationID.x)*focusStep)*vec2(1.0,aspect);
for(int x=0; x<gridSize.x; x++)
for(int y=0; y<gridSize.y; y++)
{
float dist = distance(viewCoord, vec2(x,y));
if(dist > gridSampleDistance) continue;
int slice = y*int(gridSize.x)+x;
vec2 offset = viewCoord-vec2(x,y);
offset.y *=-1;
vec2 focusedCoords = clamp(inCoords+offset*focusValue, 0.0, 1.0);
vec4 color = vec4(0);
if(sampleBlock == 1)
{
if(sampleMode == 0)
{
vec2 offset = halfPixelOffset;
if(gl_GlobalInvocationID.x%2 == 0)
{
color = lfTexture(slice, focusedCoords+offset);
color += lfTexture(slice, focusedCoords-offset);
}
else
{
offset *= vec2(-1,1);
color = lfTexture(slice, focusedCoords+offset);
color += lfTexture(slice, focusedCoords-offset);
}
color /= 2.0;
}
else if(sampleMode == 1)
{
color = lfTexture(slice,focusedCoords);
color += lfTexture(slice,focusedCoords+pixelOffset);
color += lfTexture(slice,focusedCoords-pixelOffset);
color += lfTexture(slice,focusedCoords+vec2(1, -1)*pixelOffset);
color += lfTexture(slice,focusedCoords+vec2(-1, 1)*pixelOffset);
color += lfTexture(slice,focusedCoords+vec2(0,1)*pixelOffset);
color += lfTexture(slice,focusedCoords-vec2(0,1)*pixelOffset);
color += lfTexture(slice,focusedCoords+vec2(1, 0)*pixelOffset);
color += lfTexture(slice,focusedCoords-vec2(1, 0)*pixelOffset);
color /= 9.0;
}
else if(sampleMode == 2)
{
uint modulo = gl_GlobalInvocationID.x%4;
color = lfTexture(slice,focusedCoords);
if(modulo == 0)
{
color += lfTexture(slice,focusedCoords+pixelOffset);
color += lfTexture(slice,focusedCoords-pixelOffset);
}
else if(modulo == 1)
{
color += lfTexture(slice,focusedCoords+vec2(1, -1)*pixelOffset);
color += lfTexture(slice,focusedCoords+vec2(-1, 1)*pixelOffset);
}
else if(modulo == 2)
{
color += lfTexture(slice,focusedCoords+vec2(0,1)*pixelOffset);
color += lfTexture(slice,focusedCoords-vec2(0,1)*pixelOffset);
}
else if(modulo == 3)
{
color += lfTexture(slice,focusedCoords+vec2(1, 0)*pixelOffset);
color += lfTexture(slice,focusedCoords-vec2(1, 0)*pixelOffset);
}
color /= 3.0;
}
}
else
color = lfTexture(slice,focusedCoords);
n++;
vec3 delta = color.xyz-mean;
float d = colorDistance(color.xyz, mean);
mean += delta/n;
m2 += d*colorDistance(color.xyz,mean);
}
m2 /= n-1;
if(m2<minM2)
{
minM2 = m2;
subDivLvl = i;
}
}
if(checkSaddle == 1)
{
//normalize
float maxM2 = minM2;
for (uint offset=focusLevels>>1; offset>0; offset>>=1)
maxM2 = max(maxM2,shuffleDownNV(maxM2,offset,focusLevels));
float totalMax2=readFirstInvocationARB(maxM2);
float originalM2 = minM2;
minM2 /= totalMax2;
//TODO fix when using subdivisions but hopefully subdivs are not needed anymore
vec2 neighbours = vec2(minM2);
if(gl_LocalInvocationID.x != 0)
neighbours.x = shuffleUpNV(minM2,1,focusLevels);
if(gl_LocalInvocationID.x != 31)
neighbours.y = shuffleDownNV(minM2,1,focusLevels);
float saddle = abs(minM2-neighbours.x) + abs(minM2-neighbours.y);
saddle /= totalMax2;
bool saddled = false;
if(minM2 <= neighbours.x && minM2 <= neighbours.y)
{
minM2 -= saddle*saddleImpact*0.1;
saddled = true;
}
if(checkBorders == 1 && anyThreadNV(saddled))
{
float MIN=0.05;
float DIF=0.0000001;
bool same = true;
//TODO determine which is smallest or try both ends and get smaller?
if(gl_LocalInvocationID.x == 0 && minM2 < MIN)
minM2 -= 1+borderSize;
/*float mmmm = minM2;
if(gl_LocalInvocationID.x == 0 && minM2 < MIN)
{
minM2 -= 1+borderSize;
}
if(gl_LocalInvocationID.x == focusLevels-1 && minM2 < MIN)
{
if(minM2 < readFirstInvocationARB(mmmm))
minM2 -= 2+borderSize;
}*/
//if(gl_LocalInvocationID.x == borderSize-1)
/*if(gl_LocalInvocationID.x == focusLevels-1)
{
for(int i=1; i<=borderSize; i++)
same = same && (abs(minM2 - shuffleDownNV(minM2, i, focusLevels)) < DIF);
if(same && minM2 < MIN)
minM2 -= 1;
}
else if(gl_LocalInvocationID.x == 0)
{
for(int i=1; i<=borderSize; i++)
same = same && (abs(minM2 - shuffleUpNV(minM2, i, focusLevels)) < DIF);
if(same && minM2 < MIN)
minM2 -= 1;
} */
}
}
float origM2 = minM2;
for (uint offset=focusLevels>>1; offset>0; offset>>=1)
minM2 = min(minM2,shuffleDownNV(minM2,offset,focusLevels));
float totalMinM2=readFirstInvocationARB(minM2);
if(totalMinM2 == origM2)
imageStore(focusMap, outCoords, uvec4(subDivLvl*focusLevels+gl_LocalInvocationID.x));
STATS_EXEC
}
).";
//#################################################################
std::string csPostSrc = R".(
#extension GL_ARB_gpu_shader_int64 : require
#extension GL_ARB_bindless_texture : require
layout(local_size_x=LSX*LSY)in;
uniform sampler2D lf;
layout(bindless_image)uniform layout(rgba8) writeonly image2D postLf;
layout(bindless_image)uniform layout(r8ui) readonly uimage2D focusMap;
const int focusLevels = 32;
uniform float dofDistance;
uniform float dofRange;
uniform int searchSubdiv;
uniform int pass;
void main()
{
const ivec2 size = textureSize(lf,0);
const ivec2 coords = ivec2(gl_GlobalInvocationID.x%size.x, gl_GlobalInvocationID.x/size.x);
const vec2 normalizedCoords = coords/vec2(size);
vec2 halfPixelOffset = 0.5/size;
int totalLevels = focusLevels*(searchSubdiv+1);
int focusLevel = int(round(dofDistance*totalLevels));
int kernelSize = abs(focusLevel - int(imageLoad(focusMap, ivec2(normalizedCoords*imageSize(focusMap))).x));
kernelSize = int(round(kernelSize*dofRange));
vec4 color = texture(lf, normalizedCoords)*(kernelSize+1);
int weights = kernelSize+1;
for(int i=0; i<kernelSize; i++)
{
vec2 pixelOffset = vec2(3*halfPixelOffset + 4*i*halfPixelOffset);
if(pass==0)
pixelOffset.y = 0;
else
pixelOffset.x = 0;
color += texture(lf, normalizedCoords + pixelOffset)*(kernelSize-i);
color += texture(lf, normalizedCoords - pixelOffset)*(kernelSize-i);
weights += 2*(kernelSize-i);
}
if(kernelSize>0)
color /= float(weights);
color.w = 1.0;
imageStore(postLf, coords, color);
}
).";
std::string csRangeSrc = R".(
#extension GL_ARB_gpu_shader_int64 : require
#extension GL_ARB_bindless_texture : require
#extension GL_NV_shader_atomic_float : require
layout(local_size_x=BSX, local_size_y=BSY)in;
layout(std430, binding = 4) buffer minsBuffer
{
float mins[];
};
const ivec2 gridSize = ivec2(GSX);
const ivec2 gridIndex = gridSize-1;
const uint lfSize = gridSize.x*gridSize.x;
const float DIFFERENCE = 0.00001;
uniform uint64_t lfTextures[lfSize];
uniform float aspect;
uniform float range = 0.5;
uniform float step = 0.002;
shared float bestFocus;
//shared int passedPixels;
//shared int bestPassedPixels;
shared float currentVariance;
shared float bestVariance;
float colorDistance(vec3 c1, vec3 c2)
{
return max(max(abs(c1.r-c2.r), abs(c1.g-c2.g)), abs(c1.b-c2.b));
}
void main()
{
if(gl_LocalInvocationID == uvec3(0))
{
//passedPixels = 0;
//bestPassedPixels = 0;
bestVariance = 9999;
currentVariance = 0;
}
memoryBarrierShared();
barrier();
ivec2 size = textureSize(sampler2D(lfTextures[0]),0);
vec2 coords = vec2(int(gl_GlobalInvocationID.x), int(gl_GlobalInvocationID.y))/size;
const int VIEWS = 4;
vec3 colors[VIEWS];
float minVariance = 99999999.0;
const int sampleCorner = gridIndex.x/2;
for(float f=-range; f<range; f+=step)
{
int i=0;
vec3 color = vec3(0,0,0);
const int po = 1;
//for(int x=0; x<gridSize.x; x+=gridIndex.x)
// for(int y=0; y<gridSize.y; y+=gridIndex.y)
for(int x=sampleCorner; x<sampleCorner+2; x++)
for(int y=sampleCorner; y<sampleCorner+2; y++)
{
//vec2 offset = vec2(gridIndex/2.0)-vec2(x,y);
vec2 offset = vec2(sampleCorner+0.5)-vec2(x,y);
offset.y *=-1;
vec2 focusedCoords = clamp((coords+offset*f)*vec2(1.0,aspect), 0.0, 1.0);
int slice = y*int(gridSize.x)+x;
ivec2 c = ivec2(round(focusedCoords*size));
colors[i] = texelFetch(sampler2D(lfTextures[slice]),c,0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(po,po),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(-po,-po),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(po,-po),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(-po,po),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(0,po),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(po,0),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(-po,0),0).xyz;
colors[i] += texelFetch(sampler2D(lfTextures[slice]),c+ivec2(0,-po),0).xyz;
colors[i] /= 9.0;
color += colors[i];
i++;
}
color /= VIEWS;
float variance = 0;
for(int j=0; j<VIEWS; j++)
//variance += pow(colorDistance(colors[j], color), 2);
variance += colorDistance(colors[j], color);
//variance /= VIEWS;
if(variance < (minVariance + DIFFERENCE))
{
minVariance = variance;
//atomicAdd(passedPixels, 1);
}
atomicAdd(currentVariance, variance);
memoryBarrierShared();
barrier();
if(gl_LocalInvocationID == uvec3(0))
{
/*
if(passedPixels >= bestPassedPixels && f != -range)
{
bestPassedPixels = passedPixels;
//bestFocus = f;
}
passedPixels = 0;
*/
if(currentVariance <= bestVariance)
{
bestVariance = currentVariance;
bestFocus = f;
}
currentVariance = 0;
}
memoryBarrierShared();
barrier();
}
memoryBarrierShared();
barrier();
if(gl_LocalInvocationID == uvec3(0))
mins[gl_WorkGroupID.y*gl_NumWorkGroups.x+gl_WorkGroupID.x] = bestFocus;
memoryBarrierBuffer();
barrier();
if(gl_GlobalInvocationID.x >= size.x || gl_GlobalInvocationID.y >= size.y)
{
mins[gl_WorkGroupID.y*gl_NumWorkGroups.x+gl_WorkGroupID.x] = 0;
}
}
).";
std::string statsInitCode{""};
std::string statsExecCode{""};
if constexpr (STATISTICS)
{
statsInitCode =
R".(layout(std430, binding = 2) buffer statisticsLayout
{
float statistics[];
};).";
statsExecCode =
R".(
//if(pixelId==(1080-319)*1920+894)
if(outCoords.y==1080-320 && outCoords.x == 894)
statistics[gl_LocalInvocationID.x] = origM2;
).";
}
csMapSrc.replace(csMapSrc.find("STATS_INIT"), 10, statsInitCode);
csMapSrc.replace(csMapSrc.find("STATS_EXEC"), 10, statsExecCode);
std::string textureStatsInitCode{""};
std::string textureStatsExecCode{""};
if constexpr (TEXTURE_STATISTICS)
{
textureStatsInitCode =
R".(layout(std430, binding = 3) buffer textureStatisticsLayout
{
int textureStatistics[];
};).";
textureStatsExecCode =
R".(
ivec2 lfSize = textureSize(sampler2D(lfTextures[0]), 0);
ivec2 pixelCoord = ivec2(round(lfSize*coord));
if(isMap)
atomicAdd(textureStatistics[i*lfSize.x*lfSize.y + pixelCoord.y*lfSize.x+pixelCoord.x], 1);
else
atomicAdd(textureStatistics[gridSize.x*gridSize.y*lfSize.x*lfSize.y+i*lfSize.x*lfSize.y + pixelCoord.y*lfSize.x+pixelCoord.x], 1);
).";
}
csMapSrc.replace(csMapSrc.find("TEXTURE_CHECK_INIT"), 18, textureStatsInitCode);
csMapSrc.replace(csMapSrc.find("TEXTURE_CHECK_EXEC"), 18, "bool isMap=true;"+textureStatsExecCode);
csLfSrc.replace(csLfSrc.find("TEXTURE_CHECK_INIT"), 18, textureStatsInitCode);
csLfSrc.replace(csLfSrc.find("TEXTURE_CHECK_EXEC"), 18, "bool isMap=false;"+textureStatsExecCode);
addProgram(vars, "mapProgram", csMapSrc, "");
addProgram(vars, "lfProgram", csLfSrc, "");
addProgram(vars, "postProgram", csPostSrc, "");
addProgram(vars, "drawProgram", vsSrc, fsSrc);
addProgram(vars, "rangeProgram",csRangeSrc, "");
}
void savePGM(int *buffer, int offset, glm::ivec2 resolution, std::string path)
{
std::ofstream fs(path, std::ios::out | std::ios::binary);
fs << "P5" << std::endl;
fs << resolution.x << " " << resolution.y << std::endl;
fs << 255 << std::endl;
int size = resolution.x*resolution.y;
for(int i=0; i<size; i++)
{
char number = static_cast<char>(buffer[offset+i]);
fs.write(&number,1);
}
fs.close();
}
void createView(vars::Vars&vars)
{
if(notChanged(vars,"all",__FUNCTION__, {}))return;
vars.add<basicCamera::OrbitCamera>("view");
}
void createProjection(vars::Vars&vars)
{
if(notChanged(vars,"all",__FUNCTION__, {"windowSize","camera.fovy","camera.near","camera.far"}))return;
auto windowSize = vars.get<glm::uvec2>("windowSize");
auto width = windowSize->x;
auto height = windowSize->y;
auto aspect = (float)width/(float)height;
auto near = vars.getFloat("camera.near");
auto far = vars.getFloat("camera.far" );
auto fovy = vars.getFloat("camera.fovy");
vars.reCreate<basicCamera::PerspectiveCamera>("projection",fovy,aspect,near,far);
}
void createCamera(vars::Vars&vars)
{
createProjection(vars);
createView(vars);
}
std::vector<bool> createFramesMask(vars::Vars&vars)
{
std::vector<bool> mask(vars.getInt32("lfCount"),true);
auto gridSize = vars.get<glm::ivec2>("gridSize");
auto viewCoord = vars.get<glm::vec2>("newViewCoord");
auto gridSampleDistance = vars.getFloat("gridSampleDistance");
for(int x=0; x<gridSize->x; x++)
for(int y=0; y<gridSize->y; y++)
{
int slice = y*int(gridSize->x)+x;
float dist = glm::distance(*viewCoord, glm::vec2(x,y));
if(dist > gridSampleDistance)
mask[slice] = false;
}
return mask;
}
void recalculateViewCoords(vars::Vars&vars)
{
auto newViewCoord = vars.get<glm::vec2>("newViewCoord");
vars.reCreate<glm::vec2>("viewCoord", *newViewCoord);
auto gridIndex = *vars.get<glm::ivec2>("gridSize")-1;
float aspect = vars.getFloat("texture.aspect");
glm::vec3 lfPos(0,0,0);
auto view = vars.get<basicCamera::OrbitCamera>("view");
glm::vec3 camPos(view->getView()[3]);
glm::vec3 centerRay = glm::normalize(lfPos - camPos);
float range = .2;
float coox = (glm::clamp(centerRay.x*-1,-range*aspect,range*aspect)/(range*aspect)+1)/2.;
float cooy = (glm::clamp(centerRay.y,-range,range)/range+1)/2.;
*newViewCoord = glm::vec2(gridIndex)-glm::vec2(glm::clamp(coox*(gridIndex.x),0.0f,static_cast<float>(gridIndex.x)),glm::clamp(cooy*(gridIndex.y),0.0f,static_cast<float>(gridIndex.y)));
auto &newFramesMask = vars.getVector<bool>("newFramesMask");
vars.reCreateVector<bool>("framesMask", newFramesMask);
if(vars.getBool("decodingOptimization"))
newFramesMask = createFramesMask(vars);
}
int mc=0;
void asyncVideoLoading(vars::Vars &vars)
{
SDL_GLContext c = SDL_GL_CreateContext(*vars.get<SDL_Window*>("mainWindow"));
SDL_GL_MakeCurrent(*vars.get<SDL_Window*>("mainWindow"),c);
ge::gl::init(SDL_GL_GetProcAddress);
ge::gl::setHighDebugMessage();
auto decoder = std::make_unique<GpuDecoder>(vars.getString("videoFile").c_str());
auto lfSize = glm::uvec2(*vars.reCreate<unsigned int>("lf.width",decoder->getWidth()), *vars.reCreate<unsigned int>("lf.height", decoder->getHeight()));
vars.reCreate<float>("texture.aspect",decoder->getAspect());
auto length = vars.addUint32("length",static_cast<int>(decoder->getLength()/vars.getInt32("lfCount")));
//Must be here since all textures are created in this context and handles might overlap
auto focusMapSize = glm::uvec2(vars.addUint32("focusMap.width", lfSize.x/FOCUSMAP_DIV), vars.addUint32("focusMap.height", lfSize.y/FOCUSMAP_DIV));
auto focusMapTexture = ge::gl::Texture(GL_TEXTURE_2D,GL_R8UI,1,focusMapSize.x,focusMapSize.y);
auto focusMap = vars.add<GLuint64>("focusMap.image",ge::gl::glGetImageHandleARB(focusMapTexture.getId(), 0, GL_FALSE, 0, GL_R8UI));
auto lfTexture = ge::gl::Texture(GL_TEXTURE_2D,GL_RGBA8,1,lfSize.x,lfSize.y);
vars.add<GLuint64>("lf.image",ge::gl::glGetImageHandleARB(lfTexture.getId(), 0, GL_FALSE, 0, GL_RGBA8));
vars.add<GLuint64>("lf.texture",ge::gl::glGetTextureHandleARB(lfTexture.getId()));
auto postLfTexture = ge::gl::Texture(GL_TEXTURE_2D,GL_RGBA8,1,lfSize.x,lfSize.y);
vars.add<GLuint64>("lf.postTexture",ge::gl::glGetTextureHandleARB(postLfTexture.getId()));
vars.add<GLuint64>("lf.postImage",ge::gl::glGetImageHandleARB(postLfTexture.getId(), 0, GL_FALSE, 0, GL_RGBA8));
auto rdyMutex = vars.get<std::mutex>("rdyMutex");
auto rdyCv = vars.get<std::condition_variable>("rdyCv");
int frameNum = 0;
auto timer = vars.addOrGet<Timer<double>>("decoderTimer");
bool pauseTriggered = false;
while(vars.getBool("mainRuns"))
{
auto seekFrame = vars.getInt32("seekFrame");
if(seekFrame > -1)
{
decoder->seek(seekFrame*vars.getInt32("lfCount"));
frameNum = seekFrame;
vars.getInt32("seekFrame") = -1;
}
if(frameNum > length)
frameNum = 0;
*vars.get<int>("frameNum") = frameNum;
pauseTriggered = vars.getBool("pauseTriggered");
if(!vars.getBool("pause"))
{
int index = decoder->getActiveBufferIndex();
std::string nextTexturesName = "lfTextures" + std::to_string(index);
if constexpr (MEASURE_TIME)
timer->reset();