-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathSEGICascaded.cs
1505 lines (1183 loc) · 47.8 KB
/
SEGICascaded.cs
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
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Sonic Ether/SEGI (Cascaded)")]
public class SEGICascaded : MonoBehaviour
{
#region Parameters
[Serializable]
public enum VoxelResolution
{
low = 64,
high = 128
}
public VoxelResolution voxelResolution = VoxelResolution.high;
public bool visualizeSunDepthTexture = false;
public bool visualizeGI = false;
public Light sun;
public LayerMask giCullingMask = 2147483647;
public float shadowSpaceSize = 50.0f;
[Range(0.01f, 1.0f)]
public float temporalBlendWeight = 0.1f;
public bool visualizeVoxels = false;
public bool updateGI = true;
public Color skyColor;
public float voxelSpaceSize = 25.0f;
public bool useBilateralFiltering = false;
[Range(0, 2)]
public int innerOcclusionLayers = 1;
public bool halfResolution = false;
public bool stochasticSampling = true;
public bool infiniteBounces = false;
public Transform followTransform;
[Range(1, 128)]
public int cones = 4;
[Range(1, 32)]
public int coneTraceSteps = 10;
[Range(0.1f, 2.0f)]
public float coneLength = 1.0f;
[Range(0.5f, 6.0f)]
public float coneWidth = 3.9f;
[Range(0.0f, 2.0f)]
public float occlusionStrength = 0.15f;
[Range(0.0f, 4.0f)]
public float nearOcclusionStrength = 0.5f;
[Range(0.001f, 4.0f)]
public float occlusionPower = 0.65f;
[Range(0.0f, 4.0f)]
public float coneTraceBias = 2.8f;
[Range(0.0f, 4.0f)]
public float nearLightGain = 0.36f;
[Range(0.0f, 4.0f)]
public float giGain = 1.0f;
[Range(0.0f, 4.0f)]
public float secondaryBounceGain = 0.9f;
[Range(0.0f, 16.0f)]
public float softSunlight = 0.0f;
[Range(0.0f, 8.0f)]
public float skyIntensity = 1.0f;
[HideInInspector]
public bool doReflections
{
get
{
return false; //Locked to keep reflections disabled since they're in a broken state with cascades at the moment
}
set
{
value = false;
}
}
[Range(12, 128)]
public int reflectionSteps = 64;
[Range(0.001f, 4.0f)]
public float reflectionOcclusionPower = 1.0f;
[Range(0.0f, 1.0f)]
public float skyReflectionIntensity = 1.0f;
[Range(0.1f, 4.0f)]
public float farOcclusionStrength = 1.0f;
[Range(0.1f, 4.0f)]
public float farthestOcclusionStrength = 1.0f;
[Range(3, 16)]
public int secondaryCones = 6;
[Range(0.1f, 2.0f)]
public float secondaryOcclusionStrength = 0.27f;
public bool sphericalSkylight = false;
#endregion
#region InternalVariables
object initChecker;
Material material;
Camera attachedCamera;
Transform shadowCamTransform;
Camera shadowCam;
GameObject shadowCamGameObject;
Texture2D[] blueNoise;
int sunShadowResolution = 128;
int prevSunShadowResolution;
Shader sunDepthShader;
float shadowSpaceDepthRatio = 10.0f;
int frameCounter = 0;
RenderTexture sunDepthTexture;
RenderTexture previousGIResult;
RenderTexture previousDepth;
///<summary>This is a volume texture that is immediately written to in the voxelization shader. The RInt format enables atomic writes to avoid issues where multiple fragments are trying to write to the same voxel in the volume.</summary>
RenderTexture integerVolume;
///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture scales depending on whether Voxel AA is enabled to ensure correct voxelization.</summary>
RenderTexture dummyVoxelTextureAAScaled;
///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture is always the same size whether Voxel AA is enabled or not.</summary>
RenderTexture dummyVoxelTextureFixed;
///<summary>The main GI data clipmaps that hold GI data referenced during GI tracing</summary>
Clipmap[] clipmaps;
///<summary>The secondary clipmaps that hold irradiance data for infinite bounces</summary>
Clipmap[] irradianceClipmaps;
bool notReadyToRender = false;
Shader voxelizationShader;
Shader voxelTracingShader;
ComputeShader clearCompute;
ComputeShader transferIntsCompute;
ComputeShader mipFilterCompute;
const int numClipmaps = 6;
int clipmapCounter = 0;
int currentClipmapIndex = 0;
Camera voxelCamera;
GameObject voxelCameraGO;
GameObject leftViewPoint;
GameObject topViewPoint;
float voxelScaleFactor
{
get
{
return (float)voxelResolution / 256.0f;
}
}
Quaternion rotationFront = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
Quaternion rotationLeft = new Quaternion(0.0f, 0.7f, 0.0f, 0.7f);
Quaternion rotationTop = new Quaternion(0.7f, 0.0f, 0.0f, 0.7f);
int giRenderRes
{
get
{
return halfResolution ? 2 : 1;
}
}
enum RenderState
{
Voxelize,
Bounce
}
RenderState renderState = RenderState.Voxelize;
#endregion
#region SupportingObjectsAndProperties
struct Pass
{
public static int DiffuseTrace = 0;
public static int BilateralBlur = 1;
public static int BlendWithScene = 2;
public static int TemporalBlend = 3;
public static int SpecularTrace = 4;
public static int GetCameraDepthTexture = 5;
public static int GetWorldNormals = 6;
public static int VisualizeGI = 7;
public static int WriteBlack = 8;
public static int VisualizeVoxels = 10;
public static int BilateralUpsample = 11;
}
public struct SystemSupported
{
public bool hdrTextures;
public bool rIntTextures;
public bool dx11;
public bool volumeTextures;
public bool postShader;
public bool sunDepthShader;
public bool voxelizationShader;
public bool tracingShader;
public bool fullFunctionality
{
get
{
return hdrTextures && rIntTextures && dx11 && volumeTextures && postShader && sunDepthShader && voxelizationShader && tracingShader;
}
}
}
/// <summary>
/// Contains info on system compatibility of required hardware functionality
/// </summary>
public SystemSupported systemSupported;
/// <summary>
/// Estimates the VRAM usage of all the render textures used to render GI.
/// </summary>
public float vramUsage //TODO: Update vram usage calculation
{
get
{
if (!enabled)
{
return 0.0f;
}
long v = 0;
if (sunDepthTexture != null)
v += sunDepthTexture.width * sunDepthTexture.height * 16;
if (previousGIResult != null)
v += previousGIResult.width * previousGIResult.height * 16 * 4;
if (previousDepth != null)
v += previousDepth.width * previousDepth.height * 32;
if (integerVolume != null)
v += integerVolume.width * integerVolume.height * integerVolume.volumeDepth * 32;
if (dummyVoxelTextureAAScaled != null)
v += dummyVoxelTextureAAScaled.width * dummyVoxelTextureAAScaled.height * 8;
if (dummyVoxelTextureFixed != null)
v += dummyVoxelTextureFixed.width * dummyVoxelTextureFixed.height * 8;
if (clipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (clipmaps[i] != null)
{
v += clipmaps[i].volumeTexture0.width * clipmaps[i].volumeTexture0.height * clipmaps[i].volumeTexture0.volumeDepth * 16 * 4;
}
}
}
if (irradianceClipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (irradianceClipmaps[i] != null)
{
v += irradianceClipmaps[i].volumeTexture0.width * irradianceClipmaps[i].volumeTexture0.height * irradianceClipmaps[i].volumeTexture0.volumeDepth * 16 * 4;
}
}
}
float vram = (v / 8388608.0f);
return vram;
}
}
class Clipmap
{
public Vector3 origin;
public Vector3 originDelta;
public Vector3 previousOrigin;
public float localScale;
public int resolution;
public RenderTexture volumeTexture0;
public FilterMode filterMode = FilterMode.Bilinear;
public RenderTextureFormat renderTextureFormat = RenderTextureFormat.ARGBHalf;
public void UpdateTextures()
{
if (volumeTexture0)
{
volumeTexture0.DiscardContents();
volumeTexture0.Release();
DestroyImmediate(volumeTexture0);
}
volumeTexture0 = new RenderTexture(resolution, resolution, 0, renderTextureFormat, RenderTextureReadWrite.Linear);
volumeTexture0.wrapMode = TextureWrapMode.Clamp;
#if UNITY_5_4_OR_NEWER
volumeTexture0.dimension = TextureDimension.Tex3D;
#else
volumeTexture0.isVolume = true;
#endif
volumeTexture0.volumeDepth = resolution;
volumeTexture0.enableRandomWrite = true;
volumeTexture0.filterMode = filterMode;
#if UNITY_5_4_OR_NEWER
volumeTexture0.autoGenerateMips = false;
#else
volumeTexture0.generateMips = false;
#endif
volumeTexture0.useMipMap = false;
volumeTexture0.Create();
volumeTexture0.hideFlags = HideFlags.HideAndDontSave;
}
public void CleanupTextures()
{
if (volumeTexture0)
{
volumeTexture0.DiscardContents();
volumeTexture0.Release();
DestroyImmediate(volumeTexture0);
}
}
}
public bool gaussianMipFilter
{
get
{
return false;
}
set
{
value = false;
}
}
int mipFilterKernel
{
get
{
return gaussianMipFilter ? 1 : 0;
}
}
public bool voxelAA = false;
int dummyVoxelResolution
{
get
{
return (int)voxelResolution * (voxelAA ? 4 : 1);
}
}
#endregion
public void ApplyPreset(SEGICascadedPreset preset)
{
voxelResolution = preset.voxelResolution;
voxelAA = preset.voxelAA;
innerOcclusionLayers = preset.innerOcclusionLayers;
infiniteBounces = preset.infiniteBounces;
temporalBlendWeight = preset.temporalBlendWeight;
useBilateralFiltering = preset.useBilateralFiltering;
halfResolution = preset.halfResolution;
stochasticSampling = preset.stochasticSampling;
doReflections = preset.doReflections;
cones = preset.cones;
coneTraceSteps = preset.coneTraceSteps;
coneLength = preset.coneLength;
coneWidth = preset.coneWidth;
coneTraceBias = preset.coneTraceBias;
occlusionStrength = preset.occlusionStrength;
nearOcclusionStrength = preset.nearOcclusionStrength;
occlusionPower = preset.occlusionPower;
nearLightGain = preset.nearLightGain;
giGain = preset.giGain;
secondaryBounceGain = preset.secondaryBounceGain;
reflectionSteps = preset.reflectionSteps;
reflectionOcclusionPower = preset.reflectionOcclusionPower;
skyReflectionIntensity = preset.skyReflectionIntensity;
gaussianMipFilter = preset.gaussianMipFilter;
farOcclusionStrength = preset.farOcclusionStrength;
farthestOcclusionStrength = preset.farthestOcclusionStrength;
secondaryCones = preset.secondaryCones;
secondaryOcclusionStrength = preset.secondaryOcclusionStrength;
}
void Start()
{
InitCheck();
}
void InitCheck()
{
if (initChecker == null)
{
Init();
}
}
void CreateVolumeTextures()
{
if (integerVolume)
{
integerVolume.DiscardContents();
integerVolume.Release();
DestroyImmediate(integerVolume);
}
integerVolume = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.RInt, RenderTextureReadWrite.Linear);
#if UNITY_5_4_OR_NEWER
integerVolume.dimension = TextureDimension.Tex3D;
#else
integerVolume.isVolume = true;
#endif
integerVolume.volumeDepth = (int)voxelResolution;
integerVolume.enableRandomWrite = true;
integerVolume.filterMode = FilterMode.Point;
integerVolume.Create();
integerVolume.hideFlags = HideFlags.HideAndDontSave;
ResizeDummyTexture();
}
void BuildClipmaps()
{
if (clipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (clipmaps[i] != null)
{
clipmaps[i].CleanupTextures();
}
}
}
clipmaps = new Clipmap[numClipmaps];
for (int i = 0; i < numClipmaps; i++)
{
clipmaps[i] = new Clipmap();
clipmaps[i].localScale = Mathf.Pow(2.0f, (float)i);
clipmaps[i].resolution = (int)voxelResolution;
clipmaps[i].filterMode = FilterMode.Bilinear;
clipmaps[i].renderTextureFormat = RenderTextureFormat.ARGBHalf;
clipmaps[i].UpdateTextures();
}
if (irradianceClipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (irradianceClipmaps[i] != null)
{
irradianceClipmaps[i].CleanupTextures();
}
}
}
irradianceClipmaps = new Clipmap[numClipmaps];
for (int i = 0; i < numClipmaps; i++)
{
irradianceClipmaps[i] = new Clipmap();
irradianceClipmaps[i].localScale = Mathf.Pow(2.0f, i);
irradianceClipmaps[i].resolution = (int)voxelResolution;
irradianceClipmaps[i].filterMode = FilterMode.Point;
irradianceClipmaps[i].renderTextureFormat = RenderTextureFormat.ARGBHalf;
irradianceClipmaps[i].UpdateTextures();
}
}
void ResizeDummyTexture()
{
if (dummyVoxelTextureAAScaled)
{
dummyVoxelTextureAAScaled.DiscardContents();
dummyVoxelTextureAAScaled.Release();
DestroyImmediate(dummyVoxelTextureAAScaled);
}
dummyVoxelTextureAAScaled = new RenderTexture(dummyVoxelResolution, dummyVoxelResolution, 0, RenderTextureFormat.R8);
dummyVoxelTextureAAScaled.Create();
dummyVoxelTextureAAScaled.hideFlags = HideFlags.HideAndDontSave;
if (dummyVoxelTextureFixed)
{
dummyVoxelTextureFixed.DiscardContents();
dummyVoxelTextureFixed.Release();
DestroyImmediate(dummyVoxelTextureFixed);
}
dummyVoxelTextureFixed = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.R8);
dummyVoxelTextureFixed.Create();
dummyVoxelTextureFixed.hideFlags = HideFlags.HideAndDontSave;
}
void GetBlueNoiseTextures()
{
blueNoise = null;
blueNoise = new Texture2D[64];
for (int i = 0; i < 64; i++)
{
string filename = "LDR_RGBA_" + i.ToString();
Texture2D blueNoiseTexture = Resources.Load("Noise Textures/" + filename) as Texture2D;
if (blueNoiseTexture == null)
{
Debug.LogWarning("Unable to find noise texture \"Assets/SEGI/Resources/Noise Textures/" + filename + "\" for SEGI!");
}
blueNoise[i] = blueNoiseTexture;
}
}
void Init()
{
//Setup shaders and materials
sunDepthShader = Shader.Find("Hidden/SEGIRenderSunDepth_C");
clearCompute = Resources.Load("SEGIClear_C") as ComputeShader;
transferIntsCompute = Resources.Load("SEGITransferInts_C") as ComputeShader;
mipFilterCompute = Resources.Load("SEGIMipFilter_C") as ComputeShader;
voxelizationShader = Shader.Find("Hidden/SEGIVoxelizeScene_C");
voxelTracingShader = Shader.Find("Hidden/SEGITraceScene_C");
if (!material) {
material = new Material(Shader.Find("Hidden/SEGI_C"));
material.hideFlags = HideFlags.HideAndDontSave;
}
//Get the camera attached to this game object
attachedCamera = this.GetComponent<Camera>();
attachedCamera.depthTextureMode |= DepthTextureMode.Depth;
attachedCamera.depthTextureMode |= DepthTextureMode.DepthNormals;
#if UNITY_5_4_OR_NEWER
attachedCamera.depthTextureMode |= DepthTextureMode.MotionVectors;
#endif
//Find the proxy shadow rendering camera if it exists
GameObject scgo = GameObject.Find("SEGI_SHADOWCAM");
//If not, create it
if (!scgo)
{
shadowCamGameObject = new GameObject("SEGI_SHADOWCAM");
shadowCam = shadowCamGameObject.AddComponent<Camera>();
shadowCamGameObject.hideFlags = HideFlags.HideAndDontSave;
shadowCam.enabled = false;
shadowCam.depth = attachedCamera.depth - 1;
shadowCam.orthographic = true;
shadowCam.orthographicSize = shadowSpaceSize;
shadowCam.clearFlags = CameraClearFlags.SolidColor;
shadowCam.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
shadowCam.farClipPlane = shadowSpaceSize * 2.0f * shadowSpaceDepthRatio;
shadowCam.cullingMask = giCullingMask;
shadowCam.useOcclusionCulling = false;
shadowCamTransform = shadowCamGameObject.transform;
}
else //Otherwise, it already exists, just get it
{
shadowCamGameObject = scgo;
shadowCam = scgo.GetComponent<Camera>();
shadowCamTransform = shadowCamGameObject.transform;
}
//Create the proxy camera objects responsible for rendering the scene to voxelize the scene. If they already exist, destroy them
GameObject vcgo = GameObject.Find("SEGI_VOXEL_CAMERA");
if (!vcgo) {
voxelCameraGO = new GameObject("SEGI_VOXEL_CAMERA");
voxelCameraGO.hideFlags = HideFlags.HideAndDontSave;
voxelCamera = voxelCameraGO.AddComponent<Camera>();
voxelCamera.enabled = false;
voxelCamera.orthographic = true;
voxelCamera.orthographicSize = voxelSpaceSize * 0.5f;
voxelCamera.nearClipPlane = 0.0f;
voxelCamera.farClipPlane = voxelSpaceSize;
voxelCamera.depth = -2;
voxelCamera.renderingPath = RenderingPath.Forward;
voxelCamera.clearFlags = CameraClearFlags.Color;
voxelCamera.backgroundColor = Color.black;
voxelCamera.useOcclusionCulling = false;
}
else
{
voxelCameraGO = vcgo;
voxelCamera = vcgo.GetComponent<Camera>();
}
GameObject lvp = GameObject.Find("SEGI_LEFT_VOXEL_VIEW");
if (!lvp) {
leftViewPoint = new GameObject("SEGI_LEFT_VOXEL_VIEW");
leftViewPoint.hideFlags = HideFlags.HideAndDontSave;
}
else
{
leftViewPoint = lvp;
}
GameObject tvp = GameObject.Find("SEGI_TOP_VOXEL_VIEW");
if (!tvp) {
topViewPoint = new GameObject("SEGI_TOP_VOXEL_VIEW");
topViewPoint.hideFlags = HideFlags.HideAndDontSave;
}
else
{
topViewPoint = tvp;
}
//Setup sun depth texture
if (sunDepthTexture)
{
sunDepthTexture.DiscardContents();
sunDepthTexture.Release();
DestroyImmediate(sunDepthTexture);
}
sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear);
sunDepthTexture.wrapMode = TextureWrapMode.Clamp;
sunDepthTexture.filterMode = FilterMode.Point;
sunDepthTexture.Create();
sunDepthTexture.hideFlags = HideFlags.HideAndDontSave;
CreateVolumeTextures();
BuildClipmaps();
GetBlueNoiseTextures();
initChecker = new object();
}
void CheckSupport()
{
systemSupported.hdrTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
systemSupported.rIntTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RInt);
systemSupported.dx11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
systemSupported.volumeTextures = SystemInfo.supports3DTextures;
systemSupported.postShader = material.shader.isSupported;
systemSupported.sunDepthShader = sunDepthShader.isSupported;
systemSupported.voxelizationShader = voxelizationShader.isSupported;
systemSupported.tracingShader = voxelTracingShader.isSupported;
if (!systemSupported.fullFunctionality)
{
Debug.LogWarning("SEGI is not supported on the current platform. Check for shader compile errors in SEGI/Resources");
enabled = false;
}
}
void OnDrawGizmosSelected()
{
if (!enabled)
return;
Color prevColor = Gizmos.color;
Gizmos.color = new Color(1.0f, 0.25f, 0.0f, 0.5f);
float scale = clipmaps[numClipmaps - 1].localScale;
Gizmos.DrawCube(clipmaps[0].origin, new Vector3(voxelSpaceSize * scale, voxelSpaceSize * scale, voxelSpaceSize * scale));
Gizmos.color = new Color(1.0f, 0.0f, 0.0f, 0.1f);
Gizmos.color = prevColor;
}
void CleanupTexture(ref RenderTexture texture)
{
if (texture)
{
texture.DiscardContents();
texture.Release();
DestroyImmediate(texture);
}
}
void CleanupTextures()
{
CleanupTexture(ref sunDepthTexture);
CleanupTexture(ref previousGIResult);
CleanupTexture(ref previousDepth);
CleanupTexture(ref integerVolume);
CleanupTexture(ref dummyVoxelTextureAAScaled);
CleanupTexture(ref dummyVoxelTextureFixed);
if (clipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (clipmaps[i] != null)
{
clipmaps[i].CleanupTextures();
}
}
}
if (irradianceClipmaps != null)
{
for (int i = 0; i < numClipmaps; i++)
{
if (irradianceClipmaps[i] != null)
{
irradianceClipmaps[i].CleanupTextures();
}
}
}
}
void Cleanup()
{
DestroyImmediate(material);
DestroyImmediate(voxelCameraGO);
DestroyImmediate(leftViewPoint);
DestroyImmediate(topViewPoint);
DestroyImmediate(shadowCamGameObject);
initChecker = null;
CleanupTextures();
}
void OnEnable()
{
InitCheck();
ResizeRenderTextures();
CheckSupport();
}
void OnDisable()
{
Cleanup();
}
void ResizeRenderTextures()
{
if (previousGIResult)
{
previousGIResult.DiscardContents();
previousGIResult.Release();
DestroyImmediate(previousGIResult);
}
int width = attachedCamera.pixelWidth == 0 ? 2 : attachedCamera.pixelWidth;
int height = attachedCamera.pixelHeight == 0 ? 2 : attachedCamera.pixelHeight;
previousGIResult = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBHalf);
previousGIResult.wrapMode = TextureWrapMode.Clamp;
previousGIResult.filterMode = FilterMode.Bilinear;
previousGIResult.Create();
previousGIResult.hideFlags = HideFlags.HideAndDontSave;
if (previousDepth)
{
previousDepth.DiscardContents();
previousDepth.Release();
DestroyImmediate(previousDepth);
}
previousDepth = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
previousDepth.wrapMode = TextureWrapMode.Clamp;
previousDepth.filterMode = FilterMode.Bilinear;
previousDepth.Create();
previousDepth.hideFlags = HideFlags.HideAndDontSave;
}
void ResizeSunShadowBuffer()
{
if (sunDepthTexture)
{
sunDepthTexture.DiscardContents();
sunDepthTexture.Release();
DestroyImmediate(sunDepthTexture);
}
sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear);
sunDepthTexture.wrapMode = TextureWrapMode.Clamp;
sunDepthTexture.filterMode = FilterMode.Point;
sunDepthTexture.Create();
sunDepthTexture.hideFlags = HideFlags.HideAndDontSave;
}
void Update()
{
if (notReadyToRender)
return;
if (previousGIResult == null)
{
ResizeRenderTextures();
}
if (previousGIResult.width != attachedCamera.pixelWidth || previousGIResult.height != attachedCamera.pixelHeight)
{
ResizeRenderTextures();
}
if ((int)sunShadowResolution != prevSunShadowResolution)
{
ResizeSunShadowBuffer();
}
prevSunShadowResolution = (int)sunShadowResolution;
if (clipmaps[0].resolution != (int)voxelResolution)
{
clipmaps[0].resolution = (int)voxelResolution;
clipmaps[0].UpdateTextures();
}
if (dummyVoxelTextureAAScaled.width != dummyVoxelResolution)
{
ResizeDummyTexture();
}
}
Matrix4x4 TransformViewMatrix(Matrix4x4 mat)
{
#if UNITY_5_5_OR_NEWER
if (SystemInfo.usesReversedZBuffer)
{
mat[2, 0] = -mat[2, 0];
mat[2, 1] = -mat[2, 1];
mat[2, 2] = -mat[2, 2];
mat[2, 3] = -mat[2, 3];
// mat[3, 2] += 0.0f;
}
#endif
return mat;
}
int SelectCascadeBinary(int c)
{
float counter = c + 0.01f;
int result = 0;
for (int i = 1; i < numClipmaps; i++)
{
float level = Mathf.Pow(2.0f, i);
result += Mathf.CeilToInt( ((counter / level) % 1.0f) - ((level - 1.0f) / level) );
}
return result;
}
void OnPreRender()
{
//Force reinitialization to make sure that everything is working properly if one of the cameras was unexpectedly destroyed
if (!voxelCamera || !shadowCam)
initChecker = null;
InitCheck();
if (notReadyToRender)
return;
if (!updateGI)
{
return;
}
//Cache the previous active render texture to avoid issues with other Unity rendering going on
RenderTexture previousActive = RenderTexture.active;
Shader.SetGlobalInt("SEGIVoxelAA", voxelAA ? 3 : 0);
//Temporarily disable rendering of shadows on the directional light during voxelization pass. Cache the result to set it back to what it was after voxelization is done
LightShadows prevSunShadowSetting = LightShadows.None;
if (sun != null)
{
prevSunShadowSetting = sun.shadows;
sun.shadows = LightShadows.None;
}
//Main voxelization work
if (renderState == RenderState.Voxelize)
{
currentClipmapIndex = SelectCascadeBinary(clipmapCounter); //Determine which clipmap to update during this frame
Clipmap activeClipmap = clipmaps[currentClipmapIndex]; //Set the active clipmap based on which one is determined to render this frame
//If we're not updating the base level 0 clipmap, get the previous clipmap
Clipmap prevClipmap = null;
if (currentClipmapIndex != 0)
{
prevClipmap = clipmaps[currentClipmapIndex - 1];
}
float clipmapShadowSize = shadowSpaceSize * activeClipmap.localScale;
float clipmapSize = voxelSpaceSize * activeClipmap.localScale; //Determine the current clipmap's size in world units based on its scale
//float voxelTexel = (1.0f * clipmapSize) / activeClipmap.resolution * 0.5f; //Calculate the size of a voxel texel in world-space units
//Setup the voxel volume origin position
float interval = (clipmapSize) / 8.0f; //The interval at which the voxel volume will be "locked" in world-space
Vector3 origin;
if (followTransform)
{
origin = followTransform.position;
}
else
{
//GI is still flickering a bit when the scene view and the game view are opened at the same time
origin = transform.position + transform.forward * clipmapSize / 4.0f;
}
//Lock the voxel volume origin based on the interval
activeClipmap.previousOrigin = activeClipmap.origin;
activeClipmap.origin = new Vector3(Mathf.Round(origin.x / interval) * interval, Mathf.Round(origin.y / interval) * interval, Mathf.Round(origin.z / interval) * interval);
//Clipmap delta movement for scrolling secondary bounce irradiance volume when this clipmap has changed origin
activeClipmap.originDelta = activeClipmap.origin - activeClipmap.previousOrigin;
Shader.SetGlobalVector("SEGIVoxelSpaceOriginDelta", activeClipmap.originDelta / (voxelSpaceSize * activeClipmap.localScale));
//Calculate the relative origin and overlap/size of the previous cascade as compared to the active cascade. This is used to avoid voxelizing areas that have already been voxelized by previous (smaller) cascades
Vector3 prevClipmapRelativeOrigin = Vector3.zero;
float prevClipmapOccupance = 0.0f;
if (currentClipmapIndex != 0)
{
prevClipmapRelativeOrigin = (prevClipmap.origin - activeClipmap.origin) / clipmapSize;
prevClipmapOccupance = prevClipmap.localScale / activeClipmap.localScale;
}
Shader.SetGlobalVector("SEGIClipmapOverlap", new Vector4(prevClipmapRelativeOrigin.x, prevClipmapRelativeOrigin.y, prevClipmapRelativeOrigin.z, prevClipmapOccupance));
//Calculate the relative origin and scale of this cascade as compared to the first (level 0) cascade. This is used during GI tracing/data lookup to ensure tracing is done in the correct space
for (int i = 1; i < numClipmaps; i++)
{
Vector3 clipPosFromMaster = Vector3.zero;
float clipScaleFromMaster = 1.0f;
clipPosFromMaster = (clipmaps[i].origin - clipmaps[0].origin) / (voxelSpaceSize * clipmaps[i].localScale);
clipScaleFromMaster = clipmaps[0].localScale / clipmaps[i].localScale;
Shader.SetGlobalVector("SEGIClipTransform" + i.ToString(), new Vector4(clipPosFromMaster.x, clipPosFromMaster.y, clipPosFromMaster.z, clipScaleFromMaster));
}