This repository has been archived by the owner on Apr 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathLightScattering.fx
1893 lines (1627 loc) · 87.8 KB
/
LightScattering.fx
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 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
////////////////////////////////////////////////////////////////////////////////
#include "Common.fxh"
#ifndef STAINED_GLASS
# define STAINED_GLASS 1
#endif
#ifndef OPTIMIZE_SAMPLE_LOCATIONS
# define OPTIMIZE_SAMPLE_LOCATIONS 1
#endif
#ifndef LIGHT_TYPE
# define LIGHT_TYPE LIGHT_TYPE_POINT
#endif
#ifndef ANISOTROPIC_PHASE_FUNCTION
# define ANISOTROPIC_PHASE_FUNCTION 1
#endif
#define SHADOW_MAP_DEPTH_BIAS 1e-4
//--------------------------------------------------------------------------------------
// Texture samplers
//--------------------------------------------------------------------------------------
SamplerState samLinearClamp : register( s0 )
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = Clamp;
AddressV = Clamp;
};
SamplerState samLinearBorder0 : register( s1 )
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = Border;
AddressV = Border;
BorderColor = float4(0.0, 0.0, 0.0, 0.0);
};
SamplerState samLinearUClampVWrap : register( s2 )
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = CLAMP;
AddressV = WRAP;
};
SamplerComparisonState samComparison : register( s3 )
{
Filter = COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
AddressU = Border;
AddressV = Border;
ComparisonFunc = GREATER;
BorderColor = float4(0.0, 0.0, 0.0, 0.0);
};
//--------------------------------------------------------------------------------------
// Depth stencil states
//--------------------------------------------------------------------------------------
// Depth stencil state disabling depth test
DepthStencilState DSS_NoDepthTest
{
DepthEnable = false;
DepthWriteMask = ZERO;
};
DepthStencilState DSS_NoDepthTestIncrStencil
{
DepthEnable = false;
DepthWriteMask = ZERO;
STENCILENABLE = true;
FRONTFACESTENCILFUNC = ALWAYS;
BACKFACESTENCILFUNC = ALWAYS;
FRONTFACESTENCILPASS = INCR;
BACKFACESTENCILPASS = INCR;
};
DepthStencilState DSS_NoDepth_StEqual_IncrStencil
{
DepthEnable = false;
DepthWriteMask = ZERO;
STENCILENABLE = true;
FRONTFACESTENCILFUNC = EQUAL;
BACKFACESTENCILFUNC = EQUAL;
FRONTFACESTENCILPASS = INCR;
BACKFACESTENCILPASS = INCR;
FRONTFACESTENCILFAIL = KEEP;
BACKFACESTENCILFAIL = KEEP;
};
//--------------------------------------------------------------------------------------
// Rasterizer states
//--------------------------------------------------------------------------------------
// Rasterizer state for solid fill mode with no culling
RasterizerState RS_SolidFill_NoCull
{
FILLMODE = Solid;
CullMode = NONE;
};
// Blend state disabling blending
BlendState NoBlending
{
BlendEnable[0] = FALSE;
BlendEnable[1] = FALSE;
BlendEnable[2] = FALSE;
};
float2 ProjToUV(in float2 f2ProjSpaceXY)
{
return float2(0.5, 0.5) + float2(0.5, -0.5) * f2ProjSpaceXY;
}
float2 UVToProj(in float2 f2UV)
{
return float2(-1.0, 1.0) + float2(2.0, -2.0) * f2UV;
}
float GetCamSpaceZ(in float2 ScreenSpaceUV)
{
return g_tex2DCamSpaceZ.SampleLevel(samLinearClamp, ScreenSpaceUV, 0);
}
float3 ToneMap(in float3 f3Color)
{
float fExposure = g_PPAttribs.m_fExposure;
return 1.0 - exp(-fExposure * f3Color);
}
float3 ProjSpaceXYToWorldSpace(in float2 f2PosPS)
{
// We can sample camera space z texture using bilinear filtering
float fCamSpaceZ = g_tex2DCamSpaceZ.SampleLevel(samLinearClamp, ProjToUV(f2PosPS), 0);
return ProjSpaceXYZToWorldSpace(float3(f2PosPS, fCamSpaceZ));
}
float4 WorldSpaceToShadowMapUV(in float3 f3PosWS)
{
float4 f4LightProjSpacePos = mul( float4(f3PosWS, 1), g_LightAttribs.mWorldToLightProjSpace );
f4LightProjSpacePos.xyz /= f4LightProjSpacePos.w;
float4 f4UVAndDepthInLightSpace;
f4UVAndDepthInLightSpace.xy = ProjToUV( f4LightProjSpacePos.xy );
// Applying depth bias results in light leaking through the opaque objects when looking directly
// at the light source
f4UVAndDepthInLightSpace.z = f4LightProjSpacePos.z;// * g_DepthBiasMultiplier;
f4UVAndDepthInLightSpace.w = 1/f4LightProjSpacePos.w;
return f4UVAndDepthInLightSpace;
}
struct SScreenSizeQuadVSOutput
{
float4 m_f4Pos : SV_Position;
float2 m_f2PosPS : PosPS; // Position in projection space [-1,1]x[-1,1]
};
SScreenSizeQuadVSOutput GenerateScreenSizeQuadVS(in uint VertexId : SV_VertexID)
{
float4 MinMaxUV = float4(-1, -1, 1, 1);
SScreenSizeQuadVSOutput Verts[4] =
{
{float4(MinMaxUV.xy, 1.0, 1.0), MinMaxUV.xy},
{float4(MinMaxUV.xw, 1.0, 1.0), MinMaxUV.xw},
{float4(MinMaxUV.zy, 1.0, 1.0), MinMaxUV.zy},
{float4(MinMaxUV.zw, 1.0, 1.0), MinMaxUV.zw}
};
return Verts[VertexId];
}
float ReconstructCameraSpaceZPS(SScreenSizeQuadVSOutput In) : SV_Target
{
float fDepth = g_tex2DDepthBuffer.Load( uint3(In.m_f4Pos.xy,0) );
float fCamSpaceZ = g_CameraAttribs.mProj[3][2]/(fDepth - g_CameraAttribs.mProj[2][2]);
return fCamSpaceZ;
};
technique11 ReconstructCameraSpaceZ
{
pass
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
SetDepthStencilState( DSS_NoDepthTest, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, ReconstructCameraSpaceZPS() ) );
}
}
const float4 GetOutermostScreenPixelCoords()
{
// The outermost visible screen pixels centers do not lie exactly on the boundary (+1 or -1), but are biased by
// 0.5 screen pixel size inwards
//
// 2.0
// |<---------------------------------------------------------------------->|
//
// 2.0/Res
// |<--------->|
// | X | X | X | ... | X | X |
// -1 | | +1
// | |
// | |
// -1 + 1.0/Res +1 - 1.0/Res
//
// Using shader macro is much more efficient than using constant buffer variable
// because the compiler is able to optimize the code more aggressively
// return float4(-1,-1,1,1) + float4(1, 1, -1, -1)/g_PPAttribs.m_f2ScreenResolution.xyxy;
return float4(-1,-1,1,1) + float4(1, 1, -1, -1) / SCREEN_RESLOUTION.xyxy;
}
// This function computes entry point of the epipolar line given its exit point
//
// g_LightAttribs.f4LightScreenPos
// *
// \
// \ f2EntryPoint
// __\/___
// | \ |
// | \ |
// |_____\_|
// | |
// | f2ExitPoint
// |
// Exit boundary
float2 GetEpipolarLineEntryPoint(float2 f2ExitPoint)
{
float2 f2EntryPoint;
//if( all( abs(g_LightAttribs.f4LightScreenPos.xy) < 1 ) )
if( g_LightAttribs.bIsLightOnScreen )
{
// If light source is inside the screen, its location is entry point for each epipolar line
f2EntryPoint = g_LightAttribs.f4LightScreenPos.xy;
}
else
{
// If light source is outside the screen, we need to compute intersection of the ray with
// the screen boundaries
// Compute direction from the light source to the exit point
// Note that exit point must be located on shrinked screen boundary
float2 f2RayDir = f2ExitPoint.xy - g_LightAttribs.f4LightScreenPos.xy;
float fDistToExitBoundary = length(f2RayDir);
f2RayDir /= fDistToExitBoundary;
// Compute signed distances along the ray from the light position to all four boundaries
// The distances are computed as follows using vector instructions:
// float fDistToLeftBoundary = abs(f2RayDir.x) > 1e-5 ? (-1 - g_LightAttribs.f4LightScreenPos.x) / f2RayDir.x : -FLT_MAX;
// float fDistToBottomBoundary = abs(f2RayDir.y) > 1e-5 ? (-1 - g_LightAttribs.f4LightScreenPos.y) / f2RayDir.y : -FLT_MAX;
// float fDistToRightBoundary = abs(f2RayDir.x) > 1e-5 ? ( 1 - g_LightAttribs.f4LightScreenPos.x) / f2RayDir.x : -FLT_MAX;
// float fDistToTopBoundary = abs(f2RayDir.y) > 1e-5 ? ( 1 - g_LightAttribs.f4LightScreenPos.y) / f2RayDir.y : -FLT_MAX;
// Note that in fact the outermost visible screen pixels do not lie exactly on the boundary (+1 or -1), but are biased by
// 0.5 screen pixel size inwards. Using these adjusted boundaries improves precision and results in
// smaller number of pixels which require inscattering correction
float4 f4Boundaries = GetOutermostScreenPixelCoords();
bool4 b4IsCorrectIntersectionFlag = abs(f2RayDir.xyxy) > 1e-5;
float4 f4DistToBoundaries = (f4Boundaries - g_LightAttribs.f4LightScreenPos.xyxy) / (f2RayDir.xyxy + !b4IsCorrectIntersectionFlag);
// Addition of !b4IsCorrectIntersectionFlag is required to prevent divison by zero
// Note that such incorrect lanes will be masked out anyway
// We now need to find first intersection BEFORE the intersection with the exit boundary
// This means that we need to find maximum intersection distance which is less than fDistToBoundary
// We thus need to skip all boundaries, distance to which is greater than the distance to exit boundary
// Using -FLT_MAX as the distance to these boundaries will result in skipping them:
b4IsCorrectIntersectionFlag = b4IsCorrectIntersectionFlag && ( f4DistToBoundaries < (fDistToExitBoundary - 1e-4) );
f4DistToBoundaries = b4IsCorrectIntersectionFlag * f4DistToBoundaries +
!b4IsCorrectIntersectionFlag * float4(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX);
float fFirstIntersecDist = 0;
fFirstIntersecDist = max(fFirstIntersecDist, f4DistToBoundaries.x);
fFirstIntersecDist = max(fFirstIntersecDist, f4DistToBoundaries.y);
fFirstIntersecDist = max(fFirstIntersecDist, f4DistToBoundaries.z);
fFirstIntersecDist = max(fFirstIntersecDist, f4DistToBoundaries.w);
// The code above is equivalent to the following lines:
// fFirstIntersecDist = fDistToLeftBoundary < fDistToBoundary-1e-4 ? max(fFirstIntersecDist, fDistToLeftBoundary) : fFirstIntersecDist;
// fFirstIntersecDist = fDistToBottomBoundary < fDistToBoundary-1e-4 ? max(fFirstIntersecDist, fDistToBottomBoundary) : fFirstIntersecDist;
// fFirstIntersecDist = fDistToRightBoundary < fDistToBoundary-1e-4 ? max(fFirstIntersecDist, fDistToRightBoundary) : fFirstIntersecDist;
// fFirstIntersecDist = fDistToTopBoundary < fDistToBoundary-1e-4 ? max(fFirstIntersecDist, fDistToTopBoundary) : fFirstIntersecDist;
// Now we can compute entry point:
f2EntryPoint = g_LightAttribs.f4LightScreenPos.xy + f2RayDir * fFirstIntersecDist;
// For invalid rays, coordinates are outside [-1,1]x[-1,1] area
// and such rays will be discarded
//
// g_LightAttribs.f4LightScreenPos
// *
// \|
// \-f2EntryPoint
// |\
// | \ f2ExitPoint
// |__\/___
// | |
// | |
// |_______|
//
}
return f2EntryPoint;
}
float4 GenerateSliceEndpointsPS(SScreenSizeQuadVSOutput In) : SV_Target
{
float2 f2UV = ProjToUV(In.m_f2PosPS);
// Note that due to the rasterization rules, UV coordinates are biased by 0.5 texel size.
//
// 0.5 1.5 2.5 3.5
// | X | X | X | X | ....
// 0 1 2 3 4 f2UV * TexDim
// X - locations where rasterization happens
//
// We need to remove this offset. Also clamp to [0,1] to fix fp32 precision issues
float fEpipolarSlice = saturate(f2UV.x - 0.5f / (float)NUM_EPIPOLAR_SLICES);
// fEpipolarSlice now lies in the range [0, 1 - 1/NUM_EPIPOLAR_SLICES]
// 0 defines location in exacatly left top corner, 1 - 1/NUM_EPIPOLAR_SLICES defines
// position on the top boundary next to the top left corner
uint uiBoundary = clamp(floor( fEpipolarSlice * 4 ), 0, 3);
float fPosOnBoundary = frac( fEpipolarSlice * 4 );
// <------
// +1 0,1___________0.75
// | 3 |
// | | | A
// | |0 2| |
// V | | |
// -1 |_____1_____|
// 0.25 ------> 0.5
//
// -1 +1
//
// Left Bottom Right Top
float4 f4BoundaryXPos = float4( 0, fPosOnBoundary, 1, 1-fPosOnBoundary);
float4 f4BoundaryYPos = float4( 1-fPosOnBoundary, 0, fPosOnBoundary, 1);
bool4 b4BoundaryFlags = bool4( uiBoundary.xxxx == uint4(0,1,2,3) );
// Select the right coordinates for the boundary
float2 f2ExitPointPosOnBnd = float2( dot(f4BoundaryXPos, b4BoundaryFlags), dot(f4BoundaryYPos, b4BoundaryFlags) );
// Note that in fact the outermost visible screen pixels do not lie exactly on the boundary (+1 or -1), but are biased by
// 0.5 screen pixel size inwards. Using these adjusted boundaries improves precision and results in
// samller number of pixels which require inscattering correction
float4 f4OutermostScreenPixelCoords = GetOutermostScreenPixelCoords();// xyzw = (left, bottom, right, top)
float2 f2ExitPoint = lerp(f4OutermostScreenPixelCoords.xy, f4OutermostScreenPixelCoords.zw, f2ExitPointPosOnBnd);
// GetEpipolarLineEntryPoint() gets exit point on SHRINKED boundary
float2 f2EntryPoint = GetEpipolarLineEntryPoint(f2ExitPoint);
#if OPTIMIZE_SAMPLE_LOCATIONS
// If epipolar slice is not invisible, advance its exit point if necessary
// Recall that all correct entry points are completely inside the [-1,1]x[-1,1] area
if( all(abs(f2EntryPoint) < 1) )
{
// Compute length of the epipolar line in screen pixels:
float fEpipolarSliceScreenLen = length( (f2ExitPoint - f2EntryPoint) * SCREEN_RESLOUTION.xy / 2 );
// If epipolar line is too short, update epipolar line exit point to provide 1:1 texel to screen pixel correspondence:
f2ExitPoint = f2EntryPoint + (f2ExitPoint - f2EntryPoint) * max((float)MAX_SAMPLES_IN_SLICE / fEpipolarSliceScreenLen, 1);
}
#endif
return float4(f2EntryPoint, f2ExitPoint);
}
void GenerateCoordinateTexturePS(SScreenSizeQuadVSOutput In,
out float2 f2XY : SV_Target0,
out float fCamSpaceZ : SV_Target1)
{
float4 f4SliceEndPoints = g_tex2DSliceEndPoints.Load( int3(In.m_f4Pos.y,0,0) );
// If slice entry point is outside [-1,1]x[-1,1] area, the slice is completely invisible
// and we can skip it from further processing.
// Note that slice exit point can lie outside the screen, if sample locations are optimized
// Recall that all correct entry points are completely inside the [-1,1]x[-1,1] area
if( any(abs(f4SliceEndPoints.xy) > 1) )
{
// Discard invalid slices
// Such slices will not be marked in the stencil and as a result will always be skipped
discard;
}
float2 f2UV = ProjToUV(In.m_f2PosPS);
// Note that due to the rasterization rules, UV coordinates are biased by 0.5 texel size.
//
// 0.5 1.5 2.5 3.5
// | X | X | X | X | ....
// 0 1 2 3 4 f2UV * f2TexDim
// X - locations where rasterization happens
//
// We need remove this offset:
float fSamplePosOnEpipolarLine = f2UV.x - 0.5f / (float)MAX_SAMPLES_IN_SLICE;
// fSamplePosOnEpipolarLine is now in the range [0, 1 - 1/MAX_SAMPLES_IN_SLICE]
// We need to rescale it to be in [0, 1]
fSamplePosOnEpipolarLine *= (float)MAX_SAMPLES_IN_SLICE / ((float)MAX_SAMPLES_IN_SLICE-1.f);
fSamplePosOnEpipolarLine = saturate(fSamplePosOnEpipolarLine);
// Compute interpolated position between entry and exit points:
f2XY = lerp(f4SliceEndPoints.xy, f4SliceEndPoints.zw, fSamplePosOnEpipolarLine);
// All correct entry points are completely inside the [-1,1]x[-1,1] area
if( any(abs(f2XY) > 1) )
{
// Discard pixels that fall behind the screen
// This can happen if slice exit point was optimized
discard;
}
// Compute camera space z for current location
fCamSpaceZ = GetCamSpaceZ( ProjToUV(f2XY) );
};
technique11 GenerateCoordinateTexture
{
pass
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
// Increase stencil value for all valid rays
SetDepthStencilState( DSS_NoDepthTestIncrStencil, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, GenerateCoordinateTexturePS() ) );
}
}
static const float4 g_f4IncorrectSliceUVDirAndStart = float4(-10000, -10000, 0, 0);
float4 RenderSliceUVDirInShadowMapTexturePS(SScreenSizeQuadVSOutput In) : SV_Target
{
uint uiSliceInd = In.m_f4Pos.x;
// Load epipolar slice endpoints
float4 f4SliceEndpoints = g_tex2DSliceEndPoints.Load( uint3(uiSliceInd,0,0) );
// All correct entry points are completely inside the [-1,1]x[-1,1] area
if( any( abs(f4SliceEndpoints.xy) > 1 ) )
return g_f4IncorrectSliceUVDirAndStart;
// Reconstruct slice exit point position in world space
float3 f3SliceExitWS = ProjSpaceXYToWorldSpace(f4SliceEndpoints.zw);
float3 f3DirToSliceExitFromCamera = normalize(f3SliceExitWS - g_CameraAttribs.f4CameraPos.xyz);
// Compute epipolar slice normal. If light source is outside the screen, the vectors could be collinear
float3 f3SliceNormal = cross(f3DirToSliceExitFromCamera, g_LightAttribs.f4DirOnLight.xyz);
if( length(f3SliceNormal) < 1e-5 )
return g_f4IncorrectSliceUVDirAndStart;
f3SliceNormal = normalize(f3SliceNormal);
// Intersect epipolar slice plane with the light projection plane.
float3 f3IntersecOrig, f3IntersecDir;
#if LIGHT_TYPE == LIGHT_TYPE_POINT || LIGHT_TYPE == LIGHT_TYPE_SPOT
// We can use any plane parallel to the light furstum near clipping plane. The exact distance from the plane
// to light source does not matter since the projection will always be the same:
float3 f3LightProjPlaneCenter = g_LightAttribs.f4LightWorldPos.xyz + g_LightAttribs.f4SpotLightAxisAndCosAngle.xyz;
#endif
if( !PlanePlaneIntersect(
#if LIGHT_TYPE == LIGHT_TYPE_DIRECTIONAL
// In case light is directional, the matrix is not perspective, so location
// of the light projection plane in space as well as camera position do not matter at all
f3SliceNormal, 0,
-g_LightAttribs.f4DirOnLight.xyz, 0,
#elif LIGHT_TYPE == LIGHT_TYPE_POINT || LIGHT_TYPE == LIGHT_TYPE_SPOT
f3SliceNormal, g_CameraAttribs.f4CameraPos.xyz,
g_LightAttribs.f4SpotLightAxisAndCosAngle.xyz, f3LightProjPlaneCenter,
#endif
f3IntersecOrig, f3IntersecDir ) )
{
// There is no correct intersection between planes in barelly possible case which
// requires that:
// 1. DirOnLight is exacatly parallel to light projection plane
// 2. The slice is parallel to light projection plane
return g_f4IncorrectSliceUVDirAndStart;
}
// Important: ray direction f3IntersecDir is computed as a cross product of
// slice normal and light direction (or spot light axis). As a result, the ray
// direction is always correct for valid slices.
// Now project the line onto the light space UV coordinates.
// Get two points on the line:
float4 f4P0 = float4( f3IntersecOrig, 1 );
float4 f4P1 = float4( f3IntersecOrig + f3IntersecDir * max(1, length(f3IntersecOrig)), 1 );
// Transform the points into the shadow map UV:
f4P0 = mul( f4P0, g_LightAttribs.mWorldToLightProjSpace);
f4P0 /= f4P0.w;
f4P1 = mul( f4P1, g_LightAttribs.mWorldToLightProjSpace);
f4P1 /= f4P1.w;
// Note that division by w is not really necessary because both points lie in the plane
// parallel to light projection and thus have the same w value.
float2 f2SliceDir = ProjToUV(f4P1.xy) - ProjToUV(f4P0.xy);
// The following method also works:
// Since we need direction only, we can use any origin. The most convinient is
// f3LightProjPlaneCenter which projects into (0.5,0.5):
//float4 f4SliceUVDir = mul( float4(f3LightProjPlaneCenter + f3IntersecDir, 1), g_LightAttribs.mWorldToLightProjSpace);
//f4SliceUVDir /= f4SliceUVDir.w;
//float2 f2SliceDir = ProjToUV(f4SliceUVDir.xy) - 0.5;
f2SliceDir /= max(abs(f2SliceDir.x), abs(f2SliceDir.y));
float2 f2SliceOriginUV = g_LightAttribs.f4CameraUVAndDepthInShadowMap.xy;
#if LIGHT_TYPE == LIGHT_TYPE_POINT || LIGHT_TYPE == LIGHT_TYPE_SPOT
bool bIsCamInsideCone = dot( -g_LightAttribs.f4DirOnLight.xyz, g_LightAttribs.f4SpotLightAxisAndCosAngle.xyz) > g_LightAttribs.f4SpotLightAxisAndCosAngle.w;
if( !bIsCamInsideCone )
{
// If camera is outside the cone, all the rays in slice hit the same cone side, which means that they
// all start from projection of this rib onto the shadow map
// Intesect the ray with the light cone:
float2 f2ConeIsecs =
RayConeIntersect(g_LightAttribs.f4LightWorldPos.xyz, g_LightAttribs.f4SpotLightAxisAndCosAngle.xyz, g_LightAttribs.f4SpotLightAxisAndCosAngle.w,
f3IntersecOrig, f3IntersecDir);
if( any(f2ConeIsecs == -FLT_MAX) )
return g_f4IncorrectSliceUVDirAndStart;
// Now select the first intersection with the cone along the ray
float4 f4RayConeIsec = float4( f3IntersecOrig + min(f2ConeIsecs.x, f2ConeIsecs.y) * f3IntersecDir, 1 );
// Project this intersection:
f4RayConeIsec = mul( f4RayConeIsec, g_LightAttribs.mWorldToLightProjSpace);
f4RayConeIsec /= f4RayConeIsec.w;
f2SliceOriginUV = ProjToUV(f4RayConeIsec.xy);
}
#endif
return float4(f2SliceDir, f2SliceOriginUV);
}
technique11 RenderSliceUVDirInShadowMapTexture
{
pass p0
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
// Only interpolation samples will not be discarded and increase the stencil value
SetDepthStencilState( DSS_NoDepthTest, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, RenderSliceUVDirInShadowMapTexturePS() ) );
}
}
// Note that min/max shadow map does not contain finest resolution level
// The first level it contains corresponds to step == 2
MIN_MAX_DATA_FORMAT InitializeMinMaxShadowMapPS(SScreenSizeQuadVSOutput In) : SV_Target
{
uint uiSliceInd = In.m_f4Pos.y;
// Load slice direction in shadow map
float4 f4SliceUVDirAndOrigin = g_tex2DSliceUVDirAndOrigin.Load( uint3(uiSliceInd,0,0) );
// Calculate current sample position on the ray
float2 f2CurrUV = f4SliceUVDirAndOrigin.zw + f4SliceUVDirAndOrigin.xy * floor(In.m_f4Pos.x) * 2.f * g_PPAttribs.m_f2ShadowMapTexelSize;
// Gather 8 depths which will be used for PCF filtering for this sample and its immediate neighbor
// along the epipolar slice
// Note that if the sample is located outside the shadow map, Gather() will return 0 as
// specified by the samLinearBorder0. As a result volumes outside the shadow map will always be lit
float4 f4Depths = g_tex2DLightSpaceDepthMap.Gather(samLinearBorder0, f2CurrUV);
// Shift UV to the next sample along the epipolar slice:
f2CurrUV += f4SliceUVDirAndOrigin.xy * g_PPAttribs.m_f2ShadowMapTexelSize;
float4 f4NeighbDepths = g_tex2DLightSpaceDepthMap.Gather(samLinearBorder0, f2CurrUV);
#if ACCEL_STRUCT == ACCEL_STRUCT_MIN_MAX_TREE
float4 f4MinDepth = min(f4Depths, f4NeighbDepths);
f4MinDepth.xy = min(f4MinDepth.xy, f4MinDepth.zw);
f4MinDepth.x = min(f4MinDepth.x, f4MinDepth.y);
float4 f4MaxDepth = max(f4Depths, f4NeighbDepths);
f4MaxDepth.xy = max(f4MaxDepth.xy, f4MaxDepth.zw);
f4MaxDepth.x = max(f4MaxDepth.x, f4MaxDepth.y);
return float2(f4MinDepth.x, f4MaxDepth.x);
#elif ACCEL_STRUCT == ACCEL_STRUCT_BV_TREE
// Calculate min/max depths for current and next sampling locations
float2 f2MinDepth = min(f4Depths.xy, f4Depths.zw);
float fMinDepth = min(f2MinDepth.x, f2MinDepth.y);
float2 f2MaxDepth = max(f4Depths.xy, f4Depths.zw);
float fMaxDepth = max(f2MaxDepth.x, f2MaxDepth.y);
float2 f2NeighbMinDepth = min(f4NeighbDepths.xy, f4NeighbDepths.zw);
float fNeighbMinDepth = min(f2NeighbMinDepth.x, f2NeighbMinDepth.y);
float2 f2NeighbMaxDepth = max(f4NeighbDepths.xy, f4NeighbDepths.zw);
float fNeighbMaxDepth = max(f2NeighbMaxDepth.x, f2NeighbMaxDepth.y);
return float4( fMinDepth, fMaxDepth, fNeighbMinDepth, fNeighbMaxDepth );
#endif
}
// 1D min max mip map is arranged as follows:
//
// g_MiscParams.ui4SrcDstMinMaxLevelOffset.x
// |
// | g_MiscParams.ui4SrcDstMinMaxLevelOffset.z
// |_______|____ __
// | | | |
// | | | |
// | | | |
// | | | |
// |_______|____|__|
// |<----->|<-->|
// | |
// | uiMinMaxShadowMapResolution/
// uiMinMaxShadowMapResolution/2
//
MIN_MAX_DATA_FORMAT ComputeMinMaxShadowMapLevelPS(SScreenSizeQuadVSOutput In) : SV_Target
{
uint2 uiDstSampleInd = uint2(In.m_f4Pos.xy);
uint2 uiSrcSample0Ind = uint2(g_MiscParams.ui4SrcDstMinMaxLevelOffset.x + (uiDstSampleInd.x - g_MiscParams.ui4SrcDstMinMaxLevelOffset.z)*2, uiDstSampleInd.y);
uint2 uiSrcSample1Ind = uiSrcSample0Ind + uint2(1,0);
MIN_MAX_DATA_FORMAT fnMinMaxDepth0 = g_tex2DMinMaxLightSpaceDepth.Load( uint3(uiSrcSample0Ind,0) );
MIN_MAX_DATA_FORMAT fnMinMaxDepth1 = g_tex2DMinMaxLightSpaceDepth.Load( uint3(uiSrcSample1Ind,0) );
#if ACCEL_STRUCT == ACCEL_STRUCT_MIN_MAX_TREE
float2 f2MinMaxDepth;
f2MinMaxDepth.x = min(fnMinMaxDepth0.x, fnMinMaxDepth1.x);
f2MinMaxDepth.y = max(fnMinMaxDepth0.y, fnMinMaxDepth1.y);
return f2MinMaxDepth;
#elif ACCEL_STRUCT == ACCEL_STRUCT_BV_TREE
float4 f4MinMaxDepth;
//
// fnMinMaxDepth0.z fnMinMaxDepth1.z
// * *
// *
// * fnMinMaxDepth1.x
// fnMinMaxDepth0.x
// Start by drawing line from the first to the last points:
f4MinMaxDepth.x = fnMinMaxDepth0.x;
f4MinMaxDepth.z = fnMinMaxDepth1.z;
// Check if second and first points are above the line and update its ends if required
float fDelta = lerp(f4MinMaxDepth.x, f4MinMaxDepth.z, 1.f/3.f) - fnMinMaxDepth0.z;
f4MinMaxDepth.x -= 3.f/2.f * max(fDelta, 0);
fDelta = lerp(f4MinMaxDepth.x, f4MinMaxDepth.z, 2.f/3.f) - fnMinMaxDepth1.x;
f4MinMaxDepth.z -= 3.f/2.f * max(fDelta, 0);
//
// fnMinMaxDepth0.w fnMinMaxDepth1.w
// * *
// *
// * fnMinMaxDepth1.y
// fnMinMaxDepth0.y
f4MinMaxDepth.y = fnMinMaxDepth0.y;
f4MinMaxDepth.w = fnMinMaxDepth1.w;
fDelta = fnMinMaxDepth0.w - lerp(f4MinMaxDepth.y, f4MinMaxDepth.w, 1.f/3.f);
f4MinMaxDepth.y += 3.f/2.f * max(fDelta, 0);
fDelta = fnMinMaxDepth1.y - lerp(f4MinMaxDepth.y, f4MinMaxDepth.w, 2.f/3.f);
f4MinMaxDepth.w += 3.f/2.f * max(fDelta, 0);
// Check if the horizontal bounding box is better
float2 f2MaxDepth = max(fnMinMaxDepth0.yw, fnMinMaxDepth1.yw);
float fMaxDepth = max(f2MaxDepth.x, f2MaxDepth.y);
float2 f2MinDepth = min(fnMinMaxDepth0.xz, fnMinMaxDepth1.xz);
float fMinDepth = min(f2MinDepth.x, f2MinDepth.y);
float fThreshold = (fMaxDepth-fMinDepth) * 0.01;
if( any(f4MinMaxDepth.yw > fMaxDepth + fThreshold) )
f4MinMaxDepth.yw = fMaxDepth;
if( any(f4MinMaxDepth.xz < fMinDepth - fThreshold) )
f4MinMaxDepth.xz = fMinDepth;
return f4MinMaxDepth;
#endif
}
technique11 BuildMinMaxMipMap
{
pass PInitializeMinMaxShadowMap
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
// Only interpolation samples will not be discarded and increase the stencil value
SetDepthStencilState( DSS_NoDepthTest, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, InitializeMinMaxShadowMapPS() ) );
}
pass PComputeMinMaxShadowMapLevel
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
// Only interpolation samples will not be discarded and increase the stencil value
SetDepthStencilState( DSS_NoDepthTest, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, ComputeMinMaxShadowMapLevelPS() ) );
}
}
void MarkRayMarchingSamplesInStencilPS(SScreenSizeQuadVSOutput In)
{
uint2 ui2InterpolationSources = g_tex2DInterpolationSource.Load( uint3(In.m_f4Pos.xy,0) );
// Ray marching samples are interpolated from themselves, so it is easy to detect them:
if( ui2InterpolationSources.x != ui2InterpolationSources.y )
discard;
}
technique11 MarkRayMarchingSamplesInStencil
{
pass
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
// Only interpolation samples will not be discarded and increase the stencil value
SetDepthStencilState( DSS_NoDepth_StEqual_IncrStencil, 1 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, MarkRayMarchingSamplesInStencilPS() ) );
}
}
float3 InterpolateIrradiancePS(SScreenSizeQuadVSOutput In) : SV_Target
{
uint uiSampleInd = In.m_f4Pos.x;
uint uiSliceInd = In.m_f4Pos.y;
// Get interpolation sources
uint2 ui2InterpolationSources = g_tex2DInterpolationSource.Load( uint3(uiSampleInd, uiSliceInd, 0) );
float fInterpolationPos = float(uiSampleInd - ui2InterpolationSources.x) / float( max(ui2InterpolationSources.y - ui2InterpolationSources.x,1) );
float3 f3Src0 = g_tex2DInitialInsctrIrradiance.Load( uint3(ui2InterpolationSources.x, uiSliceInd, 0) );
float3 f3Src1 = g_tex2DInitialInsctrIrradiance.Load( uint3(ui2InterpolationSources.y, uiSliceInd, 0));
// Ray marching samples are interpolated from themselves
return lerp(f3Src0, f3Src1, fInterpolationPos);
}
technique11 InterpolateIrradiance
{
pass
{
SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( RS_SolidFill_NoCull );
SetDepthStencilState( DSS_NoDepthTest, 0 );
SetVertexShader( CompileShader(vs_5_0, GenerateScreenSizeQuadVS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader(ps_5_0, InterpolateIrradiancePS() ) );
}
}
float3 PerformBilateralInterpolation(in float2 f2BilinearWeights,
in float2 f2LeftBottomSrcTexelUV,
in float4 f4SrcLocationsCamSpaceZ,
in float fFilteringLocationCamSpaceZ,
in Texture2D<float3> tex2DSrcTexture,
in float2 f2SrcTexDim,
in SamplerState Sampler)
{
// Initialize bilateral weights with bilinear:
float4 f4BilateralWeights =
//Offset: (x=0,y=1) (x=1,y=1) (x=1,y=0) (x=0,y=0)
float4(1 - f2BilinearWeights.x, f2BilinearWeights.x, f2BilinearWeights.x, 1 - f2BilinearWeights.x) *
float4( f2BilinearWeights.y, f2BilinearWeights.y, 1-f2BilinearWeights.y, 1 - f2BilinearWeights.y);
// Compute depth weights in a way that if the difference is less than the threshold, the weight is 1 and
// the weights fade out to 0 as the difference becomes larger than the threshold:
float4 f4DepthWeights = saturate( g_PPAttribs.m_fRefinementThreshold / max( abs(fFilteringLocationCamSpaceZ-f4SrcLocationsCamSpaceZ), g_PPAttribs.m_fRefinementThreshold ) );
// Note that if the sample is located outside the [-1,1]x[-1,1] area, the sample is invalid and fCurrCamSpaceZ == fInvalidCoordinate
// Depth weight computed for such sample will be zero
f4DepthWeights = pow(f4DepthWeights, 4);
// Multiply bilinear weights with the depth weights:
f4BilateralWeights *= f4DepthWeights;
// Compute summ weight
float fTotalWeight = dot(f4BilateralWeights, float4(1,1,1,1));
float3 f3ScatteredLight = 0;
[branch]
if( g_PPAttribs.m_bCorrectScatteringAtDepthBreaks && fTotalWeight < 1e-2 )
{
// Discarded pixels will keep 0 value in stencil and will be later
// processed to correct scattering
discard;
}
else
{
// Normalize weights
f4BilateralWeights /= fTotalWeight;
// We now need to compute the following weighted summ:
//f3ScatteredLight =
// f4BilateralWeights.x * tex2DSrcTexture.SampleLevel(samPoint, f2ScatteredColorIJ, 0, int2(0,1)) +
// f4BilateralWeights.y * tex2DSrcTexture.SampleLevel(samPoint, f2ScatteredColorIJ, 0, int2(1,1)) +
// f4BilateralWeights.z * tex2DSrcTexture.SampleLevel(samPoint, f2ScatteredColorIJ, 0, int2(1,0)) +
// f4BilateralWeights.w * tex2DSrcTexture.SampleLevel(samPoint, f2ScatteredColorIJ, 0, int2(0,0));
// We will use hardware to perform bilinear filtering and get these values using just two bilinear fetches:
// Offset: (x=1,y=0) (x=1,y=0) (x=0,y=0)
float fRow0UOffset = f4BilateralWeights.z / max(f4BilateralWeights.z + f4BilateralWeights.w, 0.001);
fRow0UOffset /= f2SrcTexDim.x;
float3 f3Row0WeightedCol =
(f4BilateralWeights.z + f4BilateralWeights.w) *
tex2DSrcTexture.SampleLevel(Sampler, f2LeftBottomSrcTexelUV + float2(fRow0UOffset, 0), 0, int2(0,0));
// Offset: (x=1,y=1) (x=0,y=1) (x=1,y=1)
float fRow1UOffset = f4BilateralWeights.y / max(f4BilateralWeights.x + f4BilateralWeights.y, 0.001);
fRow1UOffset /= f2SrcTexDim.x;
float3 f3Row1WeightedCol =
(f4BilateralWeights.x + f4BilateralWeights.y) *
tex2DSrcTexture.SampleLevel(Sampler, f2LeftBottomSrcTexelUV + float2(fRow1UOffset, 0 ), 0, int2(0,1));
f3ScatteredLight = f3Row0WeightedCol + f3Row1WeightedCol;
}
return f3ScatteredLight;
}
float3 UnwarpEpipolarInsctrImage( SScreenSizeQuadVSOutput In, in float fCamSpaceZ )
{
// Compute direction of the ray going from the light through the pixel
float2 f2RayDir = normalize( In.m_f2PosPS - g_LightAttribs.f4LightScreenPos.xy );
// Find, which boundary the ray intersects. For this, we will
// find which two of four half spaces the f2RayDir belongs to
// Each of four half spaces is produced by the line connecting one of four
// screen corners and the current pixel:
// ________________ _______'________ ________________
// |' . '| | ' | | |
// | ' . ' | | ' | . | |
// | ' . ' | | ' | '|. hs1 |
// | *. | | * hs0 | | '*. |
// | ' ' . | | ' | | ' . |
// | ' ' . | | ' | | ' . |
// |'____________ '_| |'_______________| | ____________ '_.
// ' '
// ________________ . '________________
// | . '| |' |
// | hs2 . ' | | ' |
// | . ' | | ' |
// | . * | | * |
// . ' | | ' |
// | | | hs3 ' |
// |________________| |______'_________|
// '
// The equations for the half spaces are the following:
//bool hs0 = (In.m_f2PosPS.x - (-1)) * f2RayDir.y < f2RayDir.x * (In.m_f2PosPS.y - (-1));
//bool hs1 = (In.m_f2PosPS.x - (1)) * f2RayDir.y < f2RayDir.x * (In.m_f2PosPS.y - (-1));
//bool hs2 = (In.m_f2PosPS.x - (1)) * f2RayDir.y < f2RayDir.x * (In.m_f2PosPS.y - (1));
//bool hs3 = (In.m_f2PosPS.x - (-1)) * f2RayDir.y < f2RayDir.x * (In.m_f2PosPS.y - (1));
// Note that in fact the outermost visible screen pixels do not lie exactly on the boundary (+1 or -1), but are biased by
// 0.5 screen pixel size inwards. Using these adjusted boundaries improves precision and results in
// smaller number of pixels which require inscattering correction
float4 f4Boundaries = GetOutermostScreenPixelCoords();//left, bottom, right, top
float4 f4HalfSpaceEquationTerms = (In.m_f2PosPS.xxyy - f4Boundaries.xzyw/*float4(-1,1,-1,1)*/) * f2RayDir.yyxx;
bool4 b4HalfSpaceFlags = f4HalfSpaceEquationTerms.xyyx < f4HalfSpaceEquationTerms.zzww;
// Now compute mask indicating which of four sectors the f2RayDir belongs to and consiquently
// which border the ray intersects:
// ________________
// |' . '| 0 : hs3 && !hs0
// | ' 3 . ' | 1 : hs0 && !hs1
// | ' . ' | 2 : hs1 && !hs2
// |0 *. 2 | 3 : hs2 && !hs3
// | ' ' . |
// | ' 1 ' . |
// |'____________ '_|
//
bool4 b4SectorFlags = b4HalfSpaceFlags.wxyz && !b4HalfSpaceFlags.xyzw;
// Note that b4SectorFlags now contains true (1) for the exit boundary and false (0) for 3 other
// Compute distances to boundaries according to following lines:
//float fDistToLeftBoundary = abs(f2RayDir.x) > 1e-5 ? ( -1 - g_LightAttribs.f4LightScreenPos.x) / f2RayDir.x : -FLT_MAX;
//float fDistToBottomBoundary = abs(f2RayDir.y) > 1e-5 ? ( -1 - g_LightAttribs.f4LightScreenPos.y) / f2RayDir.y : -FLT_MAX;
//float fDistToRightBoundary = abs(f2RayDir.x) > 1e-5 ? ( 1 - g_LightAttribs.f4LightScreenPos.x) / f2RayDir.x : -FLT_MAX;
//float fDistToTopBoundary = abs(f2RayDir.y) > 1e-5 ? ( 1 - g_LightAttribs.f4LightScreenPos.y) / f2RayDir.y : -FLT_MAX;
float4 f4DistToBoundaries = ( f4Boundaries - g_LightAttribs.f4LightScreenPos.xyxy ) / (f2RayDir.xyxy + float4( abs(f2RayDir.xyxy)<1e-6 ) );
// Select distance to the exit boundary:
float fDistToExitBoundary = dot( b4SectorFlags, f4DistToBoundaries );
// Compute exit point on the boundary:
float2 f2ExitPoint = g_LightAttribs.f4LightScreenPos.xy + f2RayDir * fDistToExitBoundary;
// Compute epipolar slice for each boundary:
//if( LeftBoundary )
// fEpipolarSlice = 0.0 - (LeftBoudaryIntersecPoint.y - 1 )/2 /4;
//else if( BottomBoundary )
// fEpipolarSlice = 0.25 + (BottomBoudaryIntersecPoint.x - (-1))/2 /4;
//else if( RightBoundary )
// fEpipolarSlice = 0.5 + (RightBoudaryIntersecPoint.y - (-1))/2 /4;
//else if( TopBoundary )
// fEpipolarSlice = 0.75 - (TopBoudaryIntersecPoint.x - 1 )/2 /4;
float4 f4EpipolarSlice = float4(0, 0.25, 0.5, 0.75) +
saturate( (f2ExitPoint.yxyx - f4Boundaries.wxyz)*float4(-1, +1, +1, -1) / (f4Boundaries.wzwz - f4Boundaries.yxyx) ) / 4.0;
// Select the right value:
float fEpipolarSlice = dot(b4SectorFlags, f4EpipolarSlice);
// Load epipolar endpoints. Note that slice 0 is stored in the first
// texel which has U coordinate shifted by 0.5 texel size
// (search for "fEpipolarSlice = saturate(f2UV.x - 0.5f / (float)NUM_EPIPOLAR_SLICES)"):
fEpipolarSlice = saturate(fEpipolarSlice + 0.5f/(float)NUM_EPIPOLAR_SLICES);
// Note also that this offset dramatically reduces the number of samples, for which correction pass is
// required (the correction pass becomes more than 2x times faster!!!)
float4 f4SliceEndpoints = g_tex2DSliceEndPoints.SampleLevel( samLinearClamp, float2(fEpipolarSlice, 0.5), 0 );
f2ExitPoint = f4SliceEndpoints.zw;
float2 f2EntryPoint = f4SliceEndpoints.xy;
float2 f2EpipolarSliceDir = f2ExitPoint - f2EntryPoint;
float fEpipolarSliceLen = length(f2EpipolarSliceDir);
f2EpipolarSliceDir /= max(fEpipolarSliceLen, 1e-6);
// Project current pixel onto the epipolar slice
float fSamplePosOnEpipolarLine = dot((In.m_f2PosPS - f2EntryPoint.xy), f2EpipolarSliceDir) / fEpipolarSliceLen;
// Rescale the sample position
// Note that the first sample on slice is exactly the f2EntryPoint.xy, while the last sample is exactly the f2ExitPoint
// (search for "fSamplePosOnEpipolarLine *= (float)MAX_SAMPLES_IN_SLICE / ((float)MAX_SAMPLES_IN_SLICE-1.f)")
// As usual, we also need to add offset by 0.5 texel size
float fScatteredColorU = fSamplePosOnEpipolarLine * ((float)MAX_SAMPLES_IN_SLICE-1) / (float)MAX_SAMPLES_IN_SLICE + 0.5f/(float)MAX_SAMPLES_IN_SLICE;
// We need to manually perform bilateral filtering of the scattered radiance texture to
// eliminate artifacts at depth discontinuities
float2 f2ScatteredColorUV = float2(fScatteredColorU, fEpipolarSlice);
float2 f2ScatteredColorTexDim;
g_tex2DScatteredColor.GetDimensions(f2ScatteredColorTexDim.x, f2ScatteredColorTexDim.y);
// Offset by 0.5 is essential, because texel centers have UV coordinates that are offset by half the texel size
float2 f2ScatteredColorUVScaled = f2ScatteredColorUV.xy * f2ScatteredColorTexDim.xy - float2(0.5, 0.5);
float2 f2ScatteredColorIJ = floor(f2ScatteredColorUVScaled);
// Get bilinear filtering weights
float2 f2BilinearWeights = f2ScatteredColorUVScaled - f2ScatteredColorIJ;
// Get texture coordinates of the left bottom source texel. Again, offset by 0.5 is essential
// to align with texel center
f2ScatteredColorIJ = (f2ScatteredColorIJ + float2(0.5, 0.5)) / f2ScatteredColorTexDim.xy;
// Gather 4 camera space z values
// Note that we need to bias f2ScatteredColorIJ by 0.5 texel size to get the required values
// _______ _______
// | | |
// | | |
// |_______X_______| X gather location
// | | |
// | * | | * f2ScatteredColorIJ
// |_______|_______|
// |<----->|
// 1/f2ScatteredColorTexDim.x
float4 f4SrcLocationsCamSpaceZ = g_tex2DEpipolarCamSpaceZ.Gather(samLinearClamp, f2ScatteredColorIJ + float2(0.5, 0.5) / f2ScatteredColorTexDim.xy);
// The values in f4SrcLocationsCamSpaceZ are arranged as follows:
// f4SrcLocationsCamSpaceZ.x == g_tex2DEpipolarCamSpaceZ.SampleLevel(samPointClamp, f2ScatteredColorIJ, 0, int2(0,1))
// f4SrcLocationsCamSpaceZ.y == g_tex2DEpipolarCamSpaceZ.SampleLevel(samPointClamp, f2ScatteredColorIJ, 0, int2(1,1))
// f4SrcLocationsCamSpaceZ.z == g_tex2DEpipolarCamSpaceZ.SampleLevel(samPointClamp, f2ScatteredColorIJ, 0, int2(1,0))
// f4SrcLocationsCamSpaceZ.w == g_tex2DEpipolarCamSpaceZ.SampleLevel(samPointClamp, f2ScatteredColorIJ, 0, int2(0,0))
return PerformBilateralInterpolation(f2BilinearWeights, f2ScatteredColorIJ, f4SrcLocationsCamSpaceZ, fCamSpaceZ, g_tex2DScatteredColor, f2ScatteredColorTexDim, samLinearClamp /* Do not use wrap mode for epipolar slice! */);
}
float3 GetExtinction(float in_Dist)
{
float3 vExtinction;
// Use analytical expression for extinction (see "Rendering Outdoor Light Scattering in Real Time" by
// Hoffman and Preetham, p.27 and p.51)
vExtinction = exp( -(g_MediaParams.f4TotalRayleighBeta.rgb + g_MediaParams.f4TotalMieBeta.rgb) * in_Dist );
return vExtinction;
}
float3 GetAttenuatedBackgroundColor(SScreenSizeQuadVSOutput In, in float fDistToCamera )
{
float3 f3BackgroundColor = 0;
[branch]
if( !g_PPAttribs.m_bShowLightingOnly )
{
f3BackgroundColor = g_tex2DColorBuffer.Load(int3(In.m_f4Pos.xy,0)).rgb;
float3 f3Extinction = GetExtinction(fDistToCamera);
f3BackgroundColor *= f3Extinction.rgb;
}
return f3BackgroundColor;
}
float3 GetAttenuatedBackgroundColor(SScreenSizeQuadVSOutput In)
{