NEW CLOUDS NEW CLOUDS NEW CLOUDS WHOOO

Added new clouds shader with improved raymarching loop
Currently only being used in main menu (rest is coming right up!)
Removed WWise (it's nice, but all it's doing is throwing exceptions rn since we ain't about to get a license)
This commit is contained in:
Reinier Vens 2022-07-10 02:53:09 +01:00
commit b08423b936
1066 changed files with 9806 additions and 58766 deletions

View file

@ -0,0 +1,92 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Yangrc.AtmosphereScattering {
public class AerialPerspective : MonoBehaviour {
private new Camera camera;
private void Start() {
camera = GetComponent<Camera>();
if ((camera.depthTextureMode & DepthTextureMode.Depth) == 0)
camera.depthTextureMode |= DepthTextureMode.Depth;
material = new Material(Shader.Find("Hidden/Yangrc/AerialPerspective"));
}
private Material material;
[ImageEffectOpaque]
private void OnRenderImage(RenderTexture source, RenderTexture destination) {
material.SetVector("_ProjectionExtents", camera.GetProjectionExtents());
Graphics.Blit(source, destination, material, 0);
}
private void Update() {
//Control sun intensity.
}
private RenderTexture transmittanceVolume;
private RenderTexture scatteringVolume;
public Vector3Int volumeTexSize = new Vector3Int(128, 128, 32);
Vector3[] _FrustumCorners = new Vector3[4];
//Generate camera volume texture.
private void OnPreRender() {
if (RenderSettings.sun == null)
return;
// get four corners of camera frustom in world space
// bottom left
_FrustumCorners[0] = camera.ViewportToWorldPoint(new Vector3(0, 0, camera.farClipPlane));
// bottom right
_FrustumCorners[1] = camera.ViewportToWorldPoint(new Vector3(1, 0, camera.farClipPlane));
// top left
_FrustumCorners[2] = camera.ViewportToWorldPoint(new Vector3(0, 1, camera.farClipPlane));
// top right
_FrustumCorners[3] = camera.ViewportToWorldPoint(new Vector3(1, 1, camera.farClipPlane));
//Render camera volume texture.
var projection_matrix = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false);
AtmLutHelper.CreateCameraAlignedVolumeTexture(ref transmittanceVolume, ref scatteringVolume, volumeTexSize);
AtmLutHelper.UpdateCameraVolume(
transmittanceVolume,
scatteringVolume,
volumeTexSize,
transform.position,
-RenderSettings.sun.transform.forward,
_FrustumCorners,
new Vector2(camera.nearClipPlane, camera.farClipPlane)
);
//Set it.
Shader.SetGlobalTexture("_CameraVolumeTransmittance", transmittanceVolume);
Shader.SetGlobalTexture("_CameraVolumeScattering", scatteringVolume);
var vp_matrix = projection_matrix * camera.worldToCameraMatrix;
Shader.SetGlobalMatrix("_Camera_VP", vp_matrix);
}
private void OnDisable() {
Shader.SetGlobalTexture("_CameraVolumeTransmittance", null);
Shader.SetGlobalTexture("_CameraVolumeScattering", null);
}
}
public static class CameraExtension {
public static Vector4 GetProjectionExtents(this Camera camera, float texelOffsetX, float texelOffsetY) {
if (camera == null)
return Vector4.zero;
float oneExtentY = camera.orthographic ? camera.orthographicSize : Mathf.Tan(0.5f * Mathf.Deg2Rad * camera.fieldOfView);
float oneExtentX = oneExtentY * camera.aspect;
float texelSizeX = oneExtentX / (0.5f * camera.pixelWidth);
float texelSizeY = oneExtentY / (0.5f * camera.pixelHeight);
float oneJitterX = texelSizeX * texelOffsetX;
float oneJitterY = texelSizeY * texelOffsetY;
return new Vector4(oneExtentX, oneExtentY, oneJitterX, oneJitterY);// xy = frustum extents at distance 1, zw = jitter at distance 1
}
public static Vector4 GetProjectionExtents(this Camera camera) {
return GetProjectionExtents(camera, 0.0f, 0.0f);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b535dacf702e20c4b9ef528e42081835
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,568 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
namespace Yangrc.AtmosphereScattering {
public static class HighResolutionDateTime {
public static bool IsAvailable { get; private set; }
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)]
private static extern void GetSystemTimePreciseAsFileTime(out long filetime);
public static DateTime UtcNow {
get {
if (!IsAvailable) {
throw new InvalidOperationException(
"High resolution clock isn't available.");
}
long filetime;
GetSystemTimePreciseAsFileTime(out filetime);
return DateTime.FromFileTimeUtc(filetime);
}
}
static HighResolutionDateTime() {
try {
long filetime;
GetSystemTimePreciseAsFileTime(out filetime);
IsAvailable = true;
} catch (EntryPointNotFoundException) {
// Not running Windows 8 or higher.
IsAvailable = false;
}
}
}
public class ProgressiveLutUpdater {
public void Cleanup() {
var allTextures = new List<RenderTexture> {
this.groundIrradianceCombine,
this.multiScatteringCombine,
this.multiScatteringDensity,
this.singleMie,
this.singleRayleigh,
this.transmittance,
};
allTextures.AddRange(
this.groundIrradianceTemp);
allTextures.AddRange(
this.multiScatteringTemp);
for (int i = 0; i < allTextures.Count; i++) {
if (allTextures[i] != null && allTextures[i].IsCreated())
allTextures[i].Release();
}
}
public interface ITimeLogger {
void Log(string itemName);
}
public AtmosphereConfig atmConfigToUse { get; set; }
public AtmosphereConfig atmConfigUsedToUpdate { get; private set; }
public AtmLutGenerateConfig lutConfig { get; set; }
ITimeLogger logger;
public ProgressiveLutUpdater(AtmosphereConfig atmConfig, AtmLutGenerateConfig lutConfig, ITimeLogger logger = null) {
this.atmConfigToUse = atmConfig;
this.lutConfig = lutConfig;
this.logger = logger;
working = false;
atmConfigUsedToUpdate = ScriptableObject.CreateInstance<AtmosphereConfig>();
}
public const int k_MultiScatteringOrderDepth = 4;
public RenderTexture[] groundIrradianceTemp = new RenderTexture[k_MultiScatteringOrderDepth + 1];
public RenderTexture multiScatteringDensity;
public RenderTexture[] multiScatteringTemp = new RenderTexture[k_MultiScatteringOrderDepth + 1];
public RenderTexture transmittance;
public RenderTexture singleRayleigh, singleMie;
public RenderTexture multiScatteringCombine, groundIrradianceCombine;
internal string name;
public bool working { get; private set; }
private void Log(string t) {
if (this.logger != null)
logger.Log(t);
}
public IEnumerator UpdateCoroutine() {
working = true;
atmConfigUsedToUpdate.CopyDataFrom(atmConfigToUse);
AtmLutHelper.CreateTransmittanceTexture(ref transmittance, lutConfig);
using (new ConvenientStopwatch("Complete Lut update timecost", Log)) {
//Update transmittance.
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
using (new ConvenientStopwatch("Transmittance ", Log)) {
AtmLutHelper.UpdateTransmittance(
transmittance,
lutConfig,
0.0f,
1.0f
);
yield return null;
}
//Update GroundDirect
using (new ConvenientStopwatch("GroundDirect", Log)) {
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.CreateGroundIrradianceTexture(ref groundIrradianceTemp[0], 0, lutConfig);
AtmLutHelper.UpdateGroundDirectIrradiance(groundIrradianceTemp[0], transmittance, lutConfig, 0.0f, 1.0f);
yield return null;
}
//Update SingleRayleigh/Mie
using (new ConvenientStopwatch("Single Rayleigh/Mie", Log)) {
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.CreateSingleRayleighMieTexture(ref singleRayleigh, ref singleMie, lutConfig);
AtmLutHelper.UpdateSingleRayleighMie(singleRayleigh, singleMie, transmittance, lutConfig);
yield return null;
}
AtmLutHelper.CreateMultiScatteringTexture(ref multiScatteringTemp[1], 1, lutConfig); //This texture is not "Meaningful"(Since the 1-st order should be SingleRayleigh and SingleMie, and this tex won't be used in actual computation either), but we need to make an empty one to avoid shader error.
using (new ConvenientStopwatch("GroundIrradiance 1", Log)) {
//Ground irradiance of 1-st order scattering.
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.CreateGroundIrradianceTexture(ref groundIrradianceTemp[1], 1, lutConfig);
AtmLutHelper.UpdateGroundIrradiance(groundIrradianceTemp[1], singleRayleigh, singleMie, multiScatteringTemp[1], 1, lutConfig, 0.0f, 1.0f);
yield return null;
}
//Real game start.
AtmLutHelper.CreateMultiScatteringDensityTexture(ref multiScatteringDensity, lutConfig);
for (int i = 2; i <= k_MultiScatteringOrderDepth; i++) {
using (new ConvenientStopwatch("Multi Scattering Density" + i, Log)) {
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.UpdateMultiScatteringDensity(multiScatteringDensity, transmittance, singleRayleigh, singleMie, multiScatteringTemp[i - 1], groundIrradianceTemp[i - 2], i, lutConfig);
yield return null;
}
AtmLutHelper.CreateGroundIrradianceTexture(ref groundIrradianceTemp[i], i, lutConfig);
using (new ConvenientStopwatch("Ground Irradiance" + i, Log)) {
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.UpdateGroundIrradiance(groundIrradianceTemp[i], singleRayleigh, singleMie, multiScatteringTemp[i - 1], i - 1, lutConfig);
yield return null;
}
AtmLutHelper.CreateMultiScatteringTexture(ref multiScatteringTemp[i], i, lutConfig);
using (new ConvenientStopwatch("Multi Scattering " + i, Log)) {
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
AtmLutHelper.UpdateMultiScatteringCombineDensity(multiScatteringTemp[i], transmittance, multiScatteringDensity, lutConfig);
yield return null;
}
}
//Combine our multiscattering texture.
AtmLutHelper.CreateFinalCombinedTexture(ref multiScatteringCombine, ref groundIrradianceCombine, lutConfig);
AtmLutHelper.ClearFinalCombinedMultiScatter(multiScatteringCombine, lutConfig);
AtmLutHelper.ClearFinalCombinedIrradiance(groundIrradianceCombine, lutConfig);
AtmLutHelper.ApplyComputeShaderParams(lutConfig, atmConfigUsedToUpdate);
for (int i = 2; i <= k_MultiScatteringOrderDepth; i++) {
AtmLutHelper.UpdateFinalCombinedMultiScatter(multiScatteringCombine, multiScatteringTemp[i], lutConfig);
}
for (int i = 1; i <= k_MultiScatteringOrderDepth; i++) {
AtmLutHelper.UpdateFinalCombinedIrradiance(groundIrradianceCombine, groundIrradianceTemp[i], lutConfig);
}
}
//All calculations are done.
/* DON"T RELEASE TEMP TEXTURES HERE, IT WILL CAUSE GRAPHICS GLITCH(FLASHING) WHEN RENDERING SKYBOX. I DON'T KNOW WHY.(2017.4.11f1) */
/* AND THAT GLITCH COST ME 4 HOURS TO FIND OUT, THANK YOU UNITY */
/* I guess that after combine dispatch call, the process isn't finished immediately, if we release the textures right now, it will blow up. */
/* but I tried to wait for a few frame(yield return null), still doesn't work. */
////Release all temp textures. They won't be used in the future.
//for (int i = 0; i < groundIrradianceTemp.Length; i++) {
// if (groundIrradianceTemp[i] != null) {
// groundIrradianceTemp[i].Release();
// groundIrradianceTemp[i] = null;
// }
//}
//for (int i = 0; i < multiScatteringTemp.Length; i++) {
// if (multiScatteringTemp[i] != null) {
// multiScatteringTemp[i].Release();
// multiScatteringTemp[i] = null;
// }
//}
//Done!
working = false;
yield break;
}
}
[System.Serializable]
public class AtmLutGenerateConfig {
public Vector2Int transmittanceSize = new Vector2Int(512, 512);
public Vector3Int scatteringSize = new Vector3Int(32, 32, 128);
public Vector2Int irradianceSize = new Vector2Int(32, 32);
public Vector3Int cameraVolumeSize = new Vector3Int(128, 128, 32);
private static class Keys {
private static readonly int transmittanceSize = Shader.PropertyToID("TransmittanceSize");
private static readonly int scatteringSize = Shader.PropertyToID("ScatteringSize");
private static readonly int irradianceSize = Shader.PropertyToID("IrradianceSize");
}
public void Apply(ComputeShader shader) {
shader.SetInts("TransmittanceSize", transmittanceSize.x, transmittanceSize.y);
shader.SetInts("ScatteringSize", scatteringSize.x, scatteringSize.y, scatteringSize.z);
shader.SetInts("IrradianceSize", irradianceSize.x, irradianceSize.y);
}
}
public class ConvenientStopwatch : System.IDisposable {
public ConvenientStopwatch(string name, System.Action<string> Log = null) {
this.name = name;
start = HighResolutionDateTime.UtcNow;
this.Log = Log;
}
System.Action<string> Log;
DateTime start;
string name;
public void Dispose() {
var timeSpan = HighResolutionDateTime.UtcNow - start;
if (Log != null)
Log(name + ":" + timeSpan.TotalMilliseconds);
}
}
public static class AtmLutHelper {
public static void Init(ComputeShader shader) {
if (computeShader == null) {
AtmLutHelper.computeShader = shader;
SetupKernals(computeShader);
}
}
public static ComputeShader computeShader;
private static int CalculateTransmittanceLUT;
private static int CalculateSingleScatteringLUT;
private static int CalculateGroundDirectIrradianceLUT;
private static int CalculateGroundIndirectIrradianceLUT;
private static int CalculateMultipleScatteringDensityLUT;
private static int CalculateMultipleScatteringLUT;
private static int SumGroundIrradianceLUT;
private static int SumMultipleScatteringLUT;
private static int ClearCombineGroundIrradianceLUT;
private static int ClearCombineMultipleScatteringLUT;
private static int CalculateCameraScatteringVolume;
/// <summary>
/// These functions help do all the "SetXXX" stuff.
/// So we can focus on how to generate Luts.
/// </summary>
private static void SetupKernals(ComputeShader computeShader) {
CalculateTransmittanceLUT = computeShader.FindKernel("CalculateTransmittanceLUT");
CalculateSingleScatteringLUT = computeShader.FindKernel("CalculateSingleScatteringLUT");
CalculateGroundDirectIrradianceLUT = computeShader.FindKernel("CalculateGroundDirectIrradianceLUT");
CalculateGroundIndirectIrradianceLUT = computeShader.FindKernel("CalculateGroundIndirectIrradianceLUT");
CalculateMultipleScatteringDensityLUT = computeShader.FindKernel("CalculateMultipleScatteringDensityLUT");
CalculateMultipleScatteringLUT = computeShader.FindKernel("CalculateMultipleScatteringLUT");
SumGroundIrradianceLUT = computeShader.FindKernel("CombineGroundIrradianceLUT");
SumMultipleScatteringLUT = computeShader.FindKernel("CombineMultipleScatteringLUT");
ClearCombineGroundIrradianceLUT = computeShader.FindKernel("ClearCombineGroundIrradianceLUT");
ClearCombineMultipleScatteringLUT = computeShader.FindKernel("ClearCombineMultipleScatteringLUT");
CalculateCameraScatteringVolume = computeShader.FindKernel("CalculateCameraScatteringVolume");
}
public static void ApplyComputeShaderParams(AtmLutGenerateConfig lutConfig, AtmosphereConfig atmConfig) {
lutConfig.Apply(computeShader);
atmConfig.Apply(computeShader);
}
private static void CreateLUT(ref RenderTexture result, string name, int width, int height, int zsize, RenderTextureFormat format, bool forceReplace = false) {
if (result != null) {
if (!forceReplace && result.name == name && result.width == width && result.height == height && result.volumeDepth == zsize && result.format == format)
return;
result.Release();
}
result = new RenderTexture(width, height, 0, format, RenderTextureReadWrite.Linear);
result.name = name;
result.enableRandomWrite = true;
if (zsize > 0) {
result.dimension = UnityEngine.Rendering.TextureDimension.Tex3D;
result.volumeDepth = zsize;
} else {
result.dimension = UnityEngine.Rendering.TextureDimension.Tex2D;
}
result.filterMode = FilterMode.Bilinear;
result.wrapMode = TextureWrapMode.Clamp;
result.Create();
}
private static void NormalizeProgressPointer(float start, float end, int length, out int startInt, out int endInt) {
if (end < start) {
var t = start;
start = end;
end = t;
}
start = Mathf.Clamp01(start);
end = Mathf.Clamp01(end);
startInt = Mathf.RoundToInt(length * start);
endInt = Mathf.RoundToInt(length * end);
}
public static void CreateTransmittanceTexture(
ref RenderTexture target,
AtmLutGenerateConfig lutconfig) {
CreateLUT(ref target, "Transmittance", lutconfig.transmittanceSize.x, lutconfig.transmittanceSize.y, 0, RenderTextureFormat.ARGBFloat);
}
public static void CreateSingleRayleighMieTexture(ref RenderTexture rayleigh, ref RenderTexture mie, AtmLutGenerateConfig lutconfig) {
CreateLUT(ref rayleigh, "SingleMie", lutconfig.scatteringSize.x, lutconfig.scatteringSize.y, lutconfig.scatteringSize.z, RenderTextureFormat.ARGBFloat);
CreateLUT(ref mie, "SingleRayleigh", lutconfig.scatteringSize.x, lutconfig.scatteringSize.y, lutconfig.scatteringSize.z, RenderTextureFormat.ARGBFloat);
}
public static void CreateGroundIrradianceTexture(ref RenderTexture target, int order, AtmLutGenerateConfig lutconfig) {
CreateLUT(ref target, "Ground Irrdiance Order " + order, lutconfig.irradianceSize.x, lutconfig.irradianceSize.y, 0, RenderTextureFormat.ARGBFloat);
}
public static void CreateMultiScatteringDensityTexture(
ref RenderTexture result,
AtmLutGenerateConfig lutConfig
) {
CreateLUT(ref result, "MultiScatteringDensity", lutConfig.scatteringSize.x, lutConfig.scatteringSize.y, lutConfig.scatteringSize.z, RenderTextureFormat.ARGBFloat);
}
public static void CreateMultiScatteringTexture(
ref RenderTexture result,
int order,
AtmLutGenerateConfig lutConfig
) {
CreateLUT(ref result, "MultiScattering " + order, lutConfig.scatteringSize.x, lutConfig.scatteringSize.y, lutConfig.scatteringSize.z, RenderTextureFormat.ARGBFloat);
}
public static void CreateFinalCombinedTexture(
ref RenderTexture MultipleScatteringLUT,
ref RenderTexture IrradianceLUT,
AtmLutGenerateConfig lutConfig
) {
CreateLUT(ref MultipleScatteringLUT, "Multiple Scattering Combined Final", lutConfig.scatteringSize.x, lutConfig.scatteringSize.y, lutConfig.scatteringSize.z, RenderTextureFormat.ARGBFloat, true);
CreateLUT(ref IrradianceLUT, "Irradiance Combined Final", lutConfig.irradianceSize.x, lutConfig.irradianceSize.y, 0, RenderTextureFormat.ARGBFloat, true);
}
public static void CreateCameraAlignedVolumeTexture(
ref RenderTexture transmittance,
ref RenderTexture scattering,
Vector3Int volumeTexSize
) {
CreateLUT(ref transmittance,
"CameraVolumeTransmittance",
volumeTexSize.x,
volumeTexSize.y,
volumeTexSize.z,
RenderTextureFormat.ARGBFloat,
false);
CreateLUT(ref scattering,
"CameraVolumeScattering",
volumeTexSize.x,
volumeTexSize.y,
volumeTexSize.z,
RenderTextureFormat.ARGBFloat,
false);
}
public static void UpdateTransmittance(
RenderTexture target,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.transmittanceSize.x / 32, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetTexture(CalculateTransmittanceLUT, "TransmittanceLUTResult", target);
computeShader.Dispatch(CalculateTransmittanceLUT, xEnd - xStart, lutConfig.transmittanceSize.y / 32, 1);
}
public static void UpdateSingleRayleighMie(
RenderTexture rayleightarget,
RenderTexture mietarget,
RenderTexture TransmittanceLUT,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.scatteringSize.x / 8, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetTexture(CalculateSingleScatteringLUT, "TransmittanceLUT", TransmittanceLUT);
computeShader.SetTexture(CalculateSingleScatteringLUT, "SingleScatteringMieLUTResult", mietarget);
computeShader.SetTexture(CalculateSingleScatteringLUT, "SingleScatteringRayleighLUTResult", rayleightarget);
computeShader.Dispatch(CalculateSingleScatteringLUT, xEnd - xStart, lutConfig.scatteringSize.y / 8, lutConfig.scatteringSize.z / 8);
}
public static void UpdateGroundDirectIrradiance(
RenderTexture target,
RenderTexture TransmittanceLUT,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.irradianceSize.x / 32, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetTexture(CalculateGroundDirectIrradianceLUT, "TransmittanceLUT", TransmittanceLUT);
computeShader.SetTexture(CalculateGroundDirectIrradianceLUT, "GroundDirectIrradianceResult", target);
computeShader.Dispatch(CalculateGroundDirectIrradianceLUT, xEnd - xStart, lutConfig.irradianceSize.y / 32, 1);
}
public static void UpdateGroundIrradiance(
RenderTexture target,
RenderTexture singleRayleigh,
RenderTexture singleMie,
RenderTexture multiScattering,
int scatteringOrder,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.irradianceSize.x / 32, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetInt("ScatteringOrder", scatteringOrder);
computeShader.SetTexture(CalculateGroundIndirectIrradianceLUT, "SingleRayleighScatteringLUT", singleRayleigh);
computeShader.SetTexture(CalculateGroundIndirectIrradianceLUT, "SingleMieScatteringLUT", singleMie);
computeShader.SetTexture(CalculateGroundIndirectIrradianceLUT, "MultipleScatteringLUT", multiScattering);
computeShader.SetTexture(CalculateGroundIndirectIrradianceLUT, "GroundIndirectIrradianceResult", target);
computeShader.Dispatch(CalculateGroundIndirectIrradianceLUT, xEnd - xStart, lutConfig.irradianceSize.y / 32, 1);
}
public static void UpdateMultiScatteringDensity(
RenderTexture target,
RenderTexture TransmittanceLUT,
RenderTexture SingleScatteringLUTRayleigh,
RenderTexture SingleScatteringLUTMie,
RenderTexture MultiScatteringOfLastOrder,
RenderTexture GroundDirectIrradianceLUT,
int scatteringOrder,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.scatteringSize.x / 8, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "TransmittanceLUT", TransmittanceLUT);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "SingleRayleighScatteringLUT", SingleScatteringLUTRayleigh);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "SingleMieScatteringLUT", SingleScatteringLUTMie);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "IrradianceLUT", GroundDirectIrradianceLUT);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "MultipleScatteringLUT", MultiScatteringOfLastOrder);
computeShader.SetInt("ScatteringOrder", scatteringOrder);
computeShader.SetTexture(CalculateMultipleScatteringDensityLUT, "MultipleScatteringDensityResult", target);
computeShader.Dispatch(CalculateMultipleScatteringDensityLUT, xEnd - xStart, lutConfig.scatteringSize.y / 8, lutConfig.scatteringSize.z / 8);
}
public static void UpdateMultiScatteringCombineDensity(
RenderTexture target,
RenderTexture TransmittanceLUT,
RenderTexture multipleScatteringDensity,
AtmLutGenerateConfig lutConfig,
float start = 0.0f,
float end = 1.0f
) {
int xStart, xEnd;
NormalizeProgressPointer(start, end, lutConfig.scatteringSize.x / 8, out xStart, out xEnd);
computeShader.SetInts("_ThreadOffset", xStart, 0, 0);
computeShader.SetTexture(CalculateMultipleScatteringLUT, "TransmittanceLUT", TransmittanceLUT);
computeShader.SetTexture(CalculateMultipleScatteringLUT, "MultipleScatteringDensityLUT", multipleScatteringDensity);
computeShader.SetTexture(CalculateMultipleScatteringLUT, "MultipleScatteringResult", target);
computeShader.Dispatch(CalculateMultipleScatteringLUT, xEnd - xStart, lutConfig.scatteringSize.y / 8, lutConfig.scatteringSize.z / 8);
}
public static void ClearFinalCombinedMultiScatter(
RenderTexture multiScatteringTarget,
AtmLutGenerateConfig lutConfig
) {
computeShader.SetTexture(ClearCombineMultipleScatteringLUT, "ScatteringSumTarget", multiScatteringTarget);
computeShader.Dispatch(ClearCombineMultipleScatteringLUT, lutConfig.scatteringSize.x / 8, lutConfig.scatteringSize.y / 8, lutConfig.scatteringSize.z / 8);
}
public static void UpdateFinalCombinedMultiScatter(
RenderTexture multiScatteringTarget,
RenderTexture multiScatteringOfSingleOrder,
AtmLutGenerateConfig lutConfig
) {
computeShader.SetTexture(SumMultipleScatteringLUT, "ScatteringSumTarget", multiScatteringTarget);
computeShader.SetTexture(SumMultipleScatteringLUT, "ScatteringSumAdd", multiScatteringOfSingleOrder);
computeShader.Dispatch(SumMultipleScatteringLUT, lutConfig.scatteringSize.x / 8, lutConfig.scatteringSize.y / 8, lutConfig.scatteringSize.z / 8);
}
public static void ClearFinalCombinedIrradiance(
RenderTexture target,
AtmLutGenerateConfig lutConfig
) {
computeShader.SetTexture(ClearCombineGroundIrradianceLUT, "GroundIrradianceSumTarget", target);
computeShader.Dispatch(ClearCombineGroundIrradianceLUT, lutConfig.irradianceSize.x / 32, lutConfig.irradianceSize.y / 32, 1);
}
public static void UpdateFinalCombinedIrradiance(
RenderTexture target,
RenderTexture irradianceOfSingleOrder,
AtmLutGenerateConfig lutConfig
) {
computeShader.SetTexture(SumGroundIrradianceLUT, "GroundIrradianceSumTarget", target);
computeShader.SetTexture(SumGroundIrradianceLUT, "GroundIrradianceSumAdder", irradianceOfSingleOrder);
computeShader.Dispatch(SumGroundIrradianceLUT, lutConfig.irradianceSize.x / 32, lutConfig.irradianceSize.y / 32, 1);
}
/// <summary>
/// Calculate camera frustrum aligned volume.
/// See frostbite slider for more.
/// </summary>
/// <param name="transmittanceTarget">Target to store transmittance</param>
/// <param name="scatteringTarget">Target to store scattering</param>
/// <param name="volumeSize">Volume tex size, used to determine dispatch call params</param>
/// <param name="cameraPos">Camera world pos</param>
/// <param name="sunDirection">Sun direction(pointing towards sun)</param>
/// <param name="frustrumCorners">four corners of camera frustrum(bl, br, tl, tr). We can't use projection matrix since we divide depth equal range, so we manually interpolate uvw using these corners and near/far plane</param>
/// <param name="nearFarPlane">Near and far plane distance</param>
public static void UpdateCameraVolume(
RenderTexture transmittanceTarget,
RenderTexture scatteringTarget,
Vector3Int volumeSize,
Vector3 cameraPos,
Vector3 sunDirection,
Vector3[] frustrumCorners,
Vector2 nearFarPlane
) {
//Here we need calculated lerpable luts. This kinda break the code sepration. Any better idea?
AtmosphereScatteringLutManager.instance.UpdateComputeShaderValueForLerpedAp(computeShader, CalculateCameraScatteringVolume);
computeShader.SetTexture(CalculateCameraScatteringVolume, "CameraVolumeTransmittance", transmittanceTarget);
computeShader.SetTexture(CalculateCameraScatteringVolume, "CameraVolumeScattering", scatteringTarget);
computeShader.SetVector("_CameraPos", cameraPos);
computeShader.SetVector("_SunDir", sunDirection);
computeShader.SetVector("_CamBotLeft", frustrumCorners[0]);
computeShader.SetVector("_CamBotRight", frustrumCorners[1]);
computeShader.SetVector("_CamTopLeft", frustrumCorners[2]);
computeShader.SetVector("_CamTopRight", frustrumCorners[3]);
computeShader.SetVector("_NearFarPlane", nearFarPlane);
computeShader.Dispatch(CalculateCameraScatteringVolume, volumeSize.x / 8, volumeSize.y / 8, volumeSize.z / 8);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 31d43eddaa5ab52468dfdf0df4f69d6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,111 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Yangrc.AtmosphereScattering {
[CreateAssetMenu]
public class AtmosphereConfig : ScriptableObject {
static readonly Vector3 OZoneConst = 6e-7f * new Vector3(3.426f, 8.298f, 0.356f);
static readonly Vector3 RayleighScatteringConst = 1e-6f * new Vector3(5.8f, 13.5f, 33.1f);
static readonly float MieScatteringConst = 2e-6f;
private static class Keys {
public static int atmosphere_top_radius = Shader.PropertyToID("atmosphere_top_radius");
public static int atmosphere_bot_radius = Shader.PropertyToID("atmosphere_bot_radius");
public static int atmosphere_sun_angular_radius = Shader.PropertyToID("atmosphere_sun_angular_radius");
public static int rayleigh_scattering = Shader.PropertyToID("rayleigh_scattering");
public static int rayleigh_scale_height = Shader.PropertyToID("rayleigh_scale_height");
public static int mie_scattering = Shader.PropertyToID("mie_scattering");
public static int mie_extinction = Shader.PropertyToID("mie_extinction");
public static int mie_scale_height = Shader.PropertyToID("mie_scale_height");
public static int mie_phase_function_g = Shader.PropertyToID("mie_phase_function_g");
public static int absorption_extinction = Shader.PropertyToID("absorption_extinction");
public static int absorption_extinction_scale_height = Shader.PropertyToID("absorption_extinction_scale_height");
public static int lightingScale = Shader.PropertyToID("_LightScale");
public static int sunIrradianceOnAtm = Shader.PropertyToID("_SunIrradianceOnAtm");
}
public void Apply(Material mat) {
Shader.SetGlobalFloat(Keys.atmosphere_top_radius, atmosphere_top_radius);
Shader.SetGlobalFloat(Keys.atmosphere_bot_radius, atmosphere_bot_radius);
Shader.SetGlobalFloat(Keys.atmosphere_sun_angular_radius, atmosphere_sun_angular_radius);
Shader.SetGlobalVector(Keys.rayleigh_scattering, rayleigh_scattering_spectrum);
Shader.SetGlobalFloat(Keys.rayleigh_scale_height, rayleigh_scale_height);
Shader.SetGlobalFloat(Keys.mie_scattering, atmosphereDensity * mie_scattering * MieScatteringConst);
Shader.SetGlobalFloat(Keys.mie_extinction, mie_extinction_spectrum);
Shader.SetGlobalFloat(Keys.mie_scale_height, mie_scale_height);
Shader.SetGlobalFloat(Keys.mie_phase_function_g, mie_phase_function_g);
Shader.SetGlobalVector(Keys.absorption_extinction, ozone_extinction_spectrum);
Shader.SetGlobalFloat(Keys.absorption_extinction_scale_height, ozone_scale_height);
Shader.SetGlobalFloat(Keys.lightingScale, LightingScale);
Shader.SetGlobalVector(Keys.sunIrradianceOnAtm, sunIrradianceOnAtmosphere);
}
public void Apply(ComputeShader shader) {
shader.SetFloat(Keys.atmosphere_top_radius, atmosphere_top_radius);
shader.SetFloat(Keys.atmosphere_bot_radius, atmosphere_bot_radius);
shader.SetFloat(Keys.atmosphere_sun_angular_radius, atmosphere_sun_angular_radius);
shader.SetVector(Keys.rayleigh_scattering, rayleigh_scattering_spectrum);
shader.SetFloat(Keys.rayleigh_scale_height, rayleigh_scale_height);
shader.SetFloat(Keys.mie_scattering, atmosphereDensity * mie_scattering * MieScatteringConst);
shader.SetFloat(Keys.mie_extinction, mie_extinction_spectrum);
shader.SetFloat(Keys.mie_scale_height, mie_scale_height);
shader.SetFloat(Keys.mie_phase_function_g, mie_phase_function_g);
shader.SetVector(Keys.absorption_extinction, ozone_extinction_spectrum);
shader.SetFloat(Keys.absorption_extinction_scale_height, ozone_scale_height);
shader.SetVector(Keys.sunIrradianceOnAtm, sunIrradianceOnAtmosphere);
}
public float atmosphereDensity = 1.0f;
public Vector3 sunIrradianceOnAtmosphere = new Vector3(1.0f, 1.0f, 1.0f);
public float LightingScale = 2.0f * 3.1415926f;
public float atmosphere_top_radius = 6.36e6f + 6e4f;
public float atmosphere_bot_radius = 6.36e6f;
public float atmosphere_sun_angular_radius = 0.0087f;
public float rayleigh_scattering = 1.0f;
public float rayleigh_scale_height = 8000.0f;
public Vector3 rayleigh_scattering_spectrum {
get {
return atmosphereDensity * rayleigh_scattering * RayleighScatteringConst;
}
}
public Vector3 ozone_extinction_spectrum {
get {
return atmosphereDensity * OZoneConst * ozone_extinction;
}
}
public float mie_scattering = 1.0f;
public float mie_extinction {
get {
return mie_scattering * 1.1f;
}
}
public float mie_extinction_spectrum {
get {
return atmosphereDensity * mie_extinction * MieScatteringConst;
}
}
public float mie_scale_height = 1200.0f;
public float mie_phase_function_g = 0.8f;
public float ozone_extinction = 1.0f;
public float ozone_scale_height = 1000.0f;
public void CopyDataFrom(AtmosphereConfig config) {
this.atmosphereDensity = config.atmosphereDensity;
this.LightingScale = config.LightingScale;
this.sunIrradianceOnAtmosphere = config.sunIrradianceOnAtmosphere;
this.atmosphere_top_radius = config.atmosphere_top_radius;
this.atmosphere_bot_radius = config.atmosphere_bot_radius;
this.atmosphere_sun_angular_radius = config.atmosphere_sun_angular_radius;
this.rayleigh_scattering = config.rayleigh_scattering;
this.rayleigh_scale_height = config.rayleigh_scale_height;
this.mie_scattering = config.mie_scattering;
this.mie_scale_height = config.mie_scale_height;
this.mie_phase_function_g = config.mie_phase_function_g;
this.ozone_extinction = config.ozone_extinction;
this.ozone_scale_height = config.ozone_scale_height;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a909801085fa7db47939f4858f8f7a1f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,252 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
namespace Yangrc.AtmosphereScattering {
[ExecuteInEditMode]
public class AtmosphereScatteringLutManager : MonoBehaviour , ProgressiveLutUpdater.ITimeLogger{
public static AtmosphereScatteringLutManager instance {
get {
return _instance;
}
}
private static AtmosphereScatteringLutManager _instance;
public bool progressiveUpdate;
[SerializeField]
private ComputeShader computeShader;
[SerializeField]
private bool outputDebug = false;
public AtmLutGenerateConfig lutConfig;
public AtmosphereConfig atmosphereConfig;
[System.NonSerialized]
public Material skyboxMaterial;
//We prepare 3 updater, the 0-index one is "currently updating", 1-index is "just updated", and 2-index is the oldest one.
//During rendering, we interpolate 1 and 2, and updating 0.
private ProgressiveLutUpdater[] pingPongUpdaters = new ProgressiveLutUpdater[3];
public ProgressiveLutUpdater newestLut { get {
return pingPongUpdaters[1];
} }
public ProgressiveLutUpdater oldLut {
get {
return pingPongUpdaters[2];
}
}
//Shift all updater to one right.
private void RotatePingpongUpdater() {
var temp = pingPongUpdaters[pingPongUpdaters.Length-1];
for (int i = pingPongUpdaters.Length - 1; i > 0; i--) {
pingPongUpdaters[i] = pingPongUpdaters[i - 1];
}
pingPongUpdaters[0] = temp;
}
private void Awake() {
if (_instance != null) {
throw new System.InvalidOperationException("AtmosphereScatteringLutManager already exists!");
}
}
private void OnEnable() {
if (computeShader == null) {
throw new System.InvalidOperationException("Compute shader not set!");
}
_instance = this;
AtmLutHelper.Init(computeShader);
for (int i = 0; i < pingPongUpdaters.Length; i++) {
pingPongUpdaters[i] = new ProgressiveLutUpdater(null, lutConfig, this);
pingPongUpdaters[i].name = "Updater " + i;
}
//Quickly complete two set luts.
for (int i = 1; i <= 2; i++) {
pingPongUpdaters[i].atmConfigToUse = atmosphereConfig;
var t = pingPongUpdaters[i].UpdateCoroutine();
while (t.MoveNext()) ;
}
UpdateSkyboxMaterial(pingPongUpdaters[1], pingPongUpdaters[2]);
KickOffUpdater(pingPongUpdaters[0]);
}
private void KickOffUpdater(ProgressiveLutUpdater updater) {
updater.atmConfigToUse = atmosphereConfig;
StartCoroutine(updater.UpdateCoroutine());
}
private float lerpValue = 0.0f;
private void Update() {
if (!pingPongUpdaters[0].working && progressiveUpdate) {
//Use the finished luts.
UpdateSkyboxMaterial(pingPongUpdaters[0], pingPongUpdaters[1]);
lerpValue = 0.0f;
//Rotate to right.
RotatePingpongUpdater();
//Next updater.
KickOffUpdater(pingPongUpdaters[0]);
}
UpdateLerpValue();
}
private void UpdateLerpValue() {
//We now require 19 frames to update
lerpValue += 1.0f / 19.0f;
if (skyboxMaterial != null)
Shader.SetGlobalFloat("_LerpValue", lerpValue);
}
private void OnDisable() {
for (int i = 0; i < pingPongUpdaters.Length; i++) {
pingPongUpdaters[i].Cleanup();
}
}
public void UpdateComputeShaderValueForLerpedAp(ComputeShader shader, int kernelId) {
newestLut.atmConfigUsedToUpdate.Apply(shader);
shader.SetTexture(kernelId, "_SingleRayleigh_1", oldLut.singleRayleigh);
shader.SetTexture(kernelId, "_SingleMie_1", oldLut.singleMie);
shader.SetTexture(kernelId, "_SingleRayleigh_2", newestLut.singleRayleigh);
shader.SetTexture(kernelId, "_SingleMie_2", newestLut.singleMie);
shader.SetTexture(kernelId, "_MultipleScattering_1", oldLut.multiScatteringCombine);
shader.SetTexture(kernelId, "_MultipleScattering_2", newestLut.multiScatteringCombine);
shader.SetTexture(kernelId, "_Transmittance_1", oldLut.transmittance);
shader.SetTexture(kernelId, "_Transmittance_2", newestLut.transmittance);
shader.SetTexture(kernelId, "_GroundIrradiance_1", oldLut.groundIrradianceCombine);
shader.SetTexture(kernelId, "_GroundIrradiance_2", newestLut.groundIrradianceCombine);
shader.SetVector("_ScatteringSize", (Vector3)lutConfig.scatteringSize);
shader.SetVector("_GroundIrradianceSize", (Vector2)lutConfig.irradianceSize);
shader.SetVector("_TransmittanceSize", (Vector2)lutConfig.transmittanceSize);
}
public void UpdateSkyboxMaterial(ProgressiveLutUpdater updater, ProgressiveLutUpdater oldUpdater) {
if (this.skyboxMaterial==null)
this.skyboxMaterial = new Material(Shader.Find("Skybox/AtmosphereScatteringPrecomputed"));
updater.atmConfigUsedToUpdate.Apply(skyboxMaterial);
Shader.SetGlobalTexture("_SingleRayleigh_1", oldUpdater.singleRayleigh);
Shader.SetGlobalTexture("_SingleMie_1", oldUpdater.singleMie);
Shader.SetGlobalTexture("_SingleRayleigh_2", updater.singleRayleigh);
Shader.SetGlobalTexture("_SingleMie_2", updater.singleMie);
Shader.SetGlobalTexture("_MultipleScattering_1", oldUpdater.multiScatteringCombine);
Shader.SetGlobalTexture("_MultipleScattering_2", updater.multiScatteringCombine);
Shader.SetGlobalTexture("_Transmittance_1", oldUpdater.transmittance);
Shader.SetGlobalTexture("_Transmittance_2", updater.transmittance);
Shader.SetGlobalTexture("_GroundIrradiance_1", oldUpdater.groundIrradianceCombine);
Shader.SetGlobalTexture("_GroundIrradiance_2", updater.groundIrradianceCombine);
Shader.SetGlobalVector("_ScatteringSize", (Vector3)lutConfig.scatteringSize);
Shader.SetGlobalVector("_GroundIrradianceSize", (Vector2)lutConfig.irradianceSize);
Shader.SetGlobalVector("_TransmittanceSize", (Vector2)lutConfig.transmittanceSize);
RenderSettings.skybox = this.skyboxMaterial;
}
public void Log(string itemName) {
if (outputDebug)
Debug.Log(itemName);
}
public Vector3 GetRadianceAt(float mu_s, Vector3 basePosition) {
var t = atmosphereConfig.sunIrradianceOnAtmosphere;
var r = basePosition + new Vector3(0.0f, atmosphereConfig.atmosphere_bot_radius, 0.0f);
var transmittance = TransmittanceCalculate.GetTransmittanceToSun(atmosphereConfig, r.magnitude, mu_s);
t.Scale(transmittance);
return t;
}
}
public static class TransmittanceCalculate {
static float ClampCosine(float mu) {
return Mathf.Clamp(mu, -1.0f, 1.0f);
}
static float ClampDistance(float d) {
return Mathf.Max(d, 0.0f);
}
static float ClampRadius(AtmosphereConfig atmosphere, float r) {
return Mathf.Clamp(r, atmosphere.atmosphere_bot_radius, atmosphere.atmosphere_top_radius);
}
static float SafeSqrt(float a) {
return Mathf.Sqrt(Mathf.Max(a, 0.0f));
}
static float DistanceToTopAtmosphereBoundary(AtmosphereConfig atmosphere,
float r, float mu) {
float discriminant = r * r * (mu * mu - 1.0f) +
atmosphere.atmosphere_top_radius * atmosphere.atmosphere_top_radius;
return ClampDistance(-r * mu + SafeSqrt(discriminant));
}
static float GetScaleHeight(float altitude, float scale_height) {
return Mathf.Exp(-altitude / scale_height);
}
static float ComputeOpticalLengthToTopAtmosphereBoundary(
AtmosphereConfig atmosphere, float r, float mu, float scale_height) {
// Number of intervals for the numerical integration.
const int SAMPLE_COUNT = 500;
// The integration step, i.e. the length of each integration interval.
float dx =
DistanceToTopAtmosphereBoundary(atmosphere, r, mu) / (float)SAMPLE_COUNT;
// Integration loop.
float result = 0.0f;
for (int i = 0; i <= SAMPLE_COUNT; ++i) {
float d_i = (float)i * dx;
// Distance between the current sample point and the planet center.
float r_i = Mathf.Sqrt(d_i * d_i + 2.0f * r * mu * d_i + r * r);
// Number density at the current sample point (divided by the number density
// at the bottom of the atmosphere, yielding a dimensionless number).
float y_i = GetScaleHeight(r_i - atmosphere.atmosphere_bot_radius, scale_height);
// Sample weight (from the trapezoidal rule).
float weight_i = i == 0 || i == SAMPLE_COUNT ? 0.5f : 1.0f;
result += y_i * weight_i * dx;
}
return result;
}
public static Vector3 ComputeTransmittanceToTopAtmosphereBoundary(
AtmosphereConfig atmosphere, float r, float mu) {
Vector3 rayleigh = atmosphere.rayleigh_scattering_spectrum *
ComputeOpticalLengthToTopAtmosphereBoundary(
atmosphere, r, mu, atmosphere.rayleigh_scale_height);
Vector3 mie = Vector3.one * atmosphere.mie_extinction_spectrum *
ComputeOpticalLengthToTopAtmosphereBoundary(
atmosphere, r, mu, atmosphere.mie_scale_height);
Vector3 ozone = atmosphere.ozone_extinction_spectrum *
ComputeOpticalLengthToTopAtmosphereBoundary(
atmosphere, r, mu, atmosphere.ozone_scale_height);
var sum = rayleigh + mie + ozone;
return new Vector3(
Mathf.Exp(-sum.x),
Mathf.Exp(-sum.y),
Mathf.Exp(-sum.z)
);
}
public static Vector3 GetTransmittanceToSun(
AtmosphereConfig atmosphere,
float r, float mu_s) {
float sin_theta_h = atmosphere.atmosphere_bot_radius / r;
float cos_theta_h = -Mathf.Sqrt(Mathf.Max(1.0f - sin_theta_h * sin_theta_h, 0.0f));
var transmittanceToCenter = ComputeTransmittanceToTopAtmosphereBoundary(
atmosphere, r, mu_s);
var lower_bound = -sin_theta_h * atmosphere.atmosphere_sun_angular_radius;
var upper_bound = sin_theta_h * atmosphere.atmosphere_sun_angular_radius;
var fraction = (mu_s - cos_theta_h - lower_bound) / (upper_bound - lower_bound);
fraction = Mathf.Clamp01(fraction);
return transmittanceToCenter * fraction;
}
}
}

View file

@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: e16dd2ddbdfa7ea4f87a3cfb032ffd0f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- computeShader: {fileID: 7200000, guid: 2d4396a54b390d742b84d4bb4a122e54, type: 3}
- atmosphereConfig: {fileID: 11400000, guid: 8e73e89daf00b8447b2410427953df25, type: 2}
- skyboxMaterial: {instanceID: 0}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,46 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour {
public float distance = 10.0f;
public Vector3 center;
private Vector2 lastFrameMouse;
public float scale = 1.0f;
public float distanceSpeed = .1f;
public float rotationSpeed = .1f;
private void Update() {
var mouseDelta = (Vector2)Input.mousePosition - lastFrameMouse;
lastFrameMouse = Input.mousePosition;
if (Input.GetMouseButton(2)) {
//Translate.
center += ((transform.right * mouseDelta.x) + (transform.up * mouseDelta.y)) * scale * distance;
}
if (Input.GetMouseButton(1)) {
distance += mouseDelta.x * distanceSpeed * Mathf.Max(1.0f, 0.1f * distance);
}
if (Input.GetMouseButton(0)) {
//Rotate.
var currentRotation = transform.rotation;
var currentYaw = currentRotation.eulerAngles.y;
var currentPitch = currentRotation.eulerAngles.x;
currentPitch -= mouseDelta.y * rotationSpeed;
currentYaw += mouseDelta.x * rotationSpeed;
currentPitch = Mathf.Max(0, currentPitch);
var newRotation = Quaternion.Euler(currentPitch, currentYaw, 0.0f);
transform.rotation = newRotation;
}
transform.position = transform.rotation * Vector3.forward * -distance + center;
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 45d85419f2e23c540999c1a1fee6ed90
timeCreated: 1547180827
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,16 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraVolumeHelper : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0e8391fcc2d8a5144ace172efd446a95
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,36 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Yangrc.AtmosphereScattering {
[RequireComponent(typeof(Light))]
public class SunIntensityController : MonoBehaviour {
private new Light light;
//This is the "base" position, used to sample transmittance to sun, and set a final intensity.
//
//In real-life, objects at different position are affected by different sun intensity.
//But in Unity all objects share the same sun.
//So we need to set a base position, and assume all objects are at this position when affected by sun.
public Vector3 basePosition = new Vector3(0.0f, 50.0f, 0.0f);
private void Awake() {
light = GetComponent<Light>();
}
// Update is called once per frame
void Update() {
var t = AtmosphereScatteringLutManager.instance;
if (t != null) {
//Sun-zenith cos.
var mu_s = Vector3.Dot(Vector3.down, transform.forward);
var radianceAtZero = t.GetRadianceAt(mu_s, basePosition);
light.intensity = radianceAtZero.magnitude / (2 * Mathf.PI);
var normalized = radianceAtZero.normalized;
light.color = new Color(normalized.x, normalized.y, normalized.z);
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 325c269146dc2ac49b190f730a961573
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: