initial commit

This commit is contained in:
2026-05-29 18:21:53 +03:00
commit 66ddf0ead0
2184 changed files with 1384338 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4b15f777774297b4f91455d3353a0c40
folderAsset: yes
timeCreated: 1454589502
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,96 @@
using UnityEngine;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Cinematic/Anti-aliasing")]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
public class AntiAliasing : MonoBehaviour
{
public enum Method
{
Smaa,
Fxaa
}
[SerializeField]
private SMAA m_SMAA = new SMAA();
[SerializeField]
private FXAA m_FXAA = new FXAA();
[SerializeField, HideInInspector]
private int m_Method = (int)Method.Smaa;
public int method
{
get { return m_Method; }
set
{
if (m_Method == value)
return;
m_Method = value;
}
}
public IAntiAliasing current
{
get
{
if (method == (int)Method.Smaa)
return m_SMAA;
else
return m_FXAA;
}
}
private Camera m_Camera;
public Camera cameraComponent
{
get
{
if (m_Camera == null)
m_Camera = GetComponent<Camera>();
return m_Camera;
}
}
private void Awake()
{
m_SMAA.Awake();
m_FXAA.Awake();
}
private void OnEnable()
{
m_SMAA.OnEnable(this);
m_FXAA.OnEnable(this);
}
private void OnDisable()
{
m_SMAA.OnDisable();
m_FXAA.OnDisable();
}
private void OnPreCull()
{
current.OnPreCull(cameraComponent);
}
private void OnPostRender()
{
current.OnPostRender(cameraComponent);
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
current.OnRenderImage(cameraComponent, source, destination);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: fdc35e0180670ab4e8d2f9439137791f
timeCreated: 1454589503
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 738f82ccf57b5974cb672f8032c72169
folderAsset: yes
timeCreated: 1454595975
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,64 @@
using System;
using UnityEditor;
namespace UnityStandardAssets.CinematicEffects
{
[CustomEditor(typeof(AntiAliasing))]
public class AntiAliasingEditor : Editor
{
private string[] methodNames =
{
"Subpixel Morphological Anti-aliasing",
"Fast Approximate Anti-aliasing"
};
private int m_SelectedMethod;
private SMAAEditor m_SMAAEditor = new SMAAEditor();
private FXAAEditor m_FXAAEditor = new FXAAEditor();
IAntiAliasingEditor m_AntiAliasingEditor;
private void OnEnable()
{
m_SMAAEditor.OnEnable(serializedObject, "m_SMAA");
m_FXAAEditor.OnEnable(serializedObject, "m_FXAA");
}
public override void OnInspectorGUI()
{
var antiAliasingTarget = (AntiAliasing)target;
m_SelectedMethod = antiAliasingTarget.method;
EditorGUI.BeginChangeCheck();
m_SelectedMethod = EditorGUILayout.Popup("Method", m_SelectedMethod, methodNames);
bool dirty = false;
if (EditorGUI.EndChangeCheck())
{
if (m_SelectedMethod < 0)
m_SelectedMethod = 0;
else if (m_SelectedMethod > 1)
m_SelectedMethod = 1;
antiAliasingTarget.method = m_SelectedMethod;
dirty = true;
}
if (m_SelectedMethod == 0)
m_AntiAliasingEditor = m_SMAAEditor;
else
m_AntiAliasingEditor = m_FXAAEditor;
dirty |= m_AntiAliasingEditor.OnInspectorGUI(antiAliasingTarget.current);
if (dirty)
{
EditorUtility.SetDirty(antiAliasingTarget);
serializedObject.ApplyModifiedProperties();
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6bd9375ab74a65448b556b0452e8c6af
timeCreated: 1454593885
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,10 @@
using UnityEditor;
namespace UnityStandardAssets.CinematicEffects
{
public interface IAntiAliasingEditor
{
void OnEnable(SerializedObject serializedObject, string path);
bool OnInspectorGUI(IAntiAliasing target);
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 015ee83e537e9e4438f403e2149c69ae
timeCreated: 1454595240
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 7629f5693f26f34448aa9c713d257e26
folderAsset: yes
timeCreated: 1453733554
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 880813d23951c624d9d5c3e6d2a4e93c
folderAsset: yes
timeCreated: 1454331861
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,57 @@
using UnityEditor;
namespace UnityStandardAssets.CinematicEffects
{
public class FXAAEditor : IAntiAliasingEditor
{
private string[] presetNames =
{
"Extreme performance",
"Performance",
"Default",
"Quality",
"Extreme quality"
};
public void OnEnable(SerializedObject serializedObject, string path)
{
}
public bool OnInspectorGUI(IAntiAliasing target)
{
var fxaaTarget = (FXAA)target;
if (!fxaaTarget.validSourceFormat)
EditorGUILayout.HelpBox("FXAA should be used at the end of the post-processing stack after conversion to LDR (after Tonemapping) to maximize quality and avoid artifacts.", MessageType.Warning);
int selectedPreset = 2;
if (fxaaTarget.preset.Equals(FXAA.Preset.extremePerformancePreset))
selectedPreset = 0;
else if (fxaaTarget.preset.Equals(FXAA.Preset.performancePreset))
selectedPreset = 1;
else if (fxaaTarget.preset.Equals(FXAA.Preset.defaultPreset))
selectedPreset = 2;
else if (fxaaTarget.preset.Equals(FXAA.Preset.qualityPreset))
selectedPreset = 3;
else if (fxaaTarget.preset.Equals(FXAA.Preset.extremeQualityPreset))
selectedPreset = 4;
EditorGUI.BeginChangeCheck();
selectedPreset = EditorGUILayout.Popup("Preset", selectedPreset, presetNames);
if (EditorGUI.EndChangeCheck())
{
if (selectedPreset < 0)
selectedPreset = 0;
else if (selectedPreset > 4)
selectedPreset = 4;
fxaaTarget.preset = FXAA.availablePresets[selectedPreset];
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 60bfb637c85e3e04ea76962349fee327
timeCreated: 1454331861
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,264 @@
using UnityEngine;
using System;
using Object = UnityEngine.Object;
namespace UnityStandardAssets.CinematicEffects
{
[Serializable]
public class FXAA : IAntiAliasing
{
private Shader m_Shader;
private Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/Fast Approximate Anti-aliasing");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("The amount of desired sub-pixel aliasing removal. Effects the sharpeness of the output.")]
[Range(0.0f, 1.0f)]
public float subpixelAliasingRemovalAmount;
[Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")]
[Range(0.063f, 0.333f)]
public float edgeDetectionThreshold;
[Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")]
[Range(0.0f, 0.0833f)]
public float minimumRequiredLuminance;
}
[Serializable]
public struct ConsoleSettings
{
[Tooltip("The amount of spread applied to the sampling coordinates while sampling for subpixel information.")]
[Range(0.33f, 0.5f)]
public float subpixelSpreadAmount;
[Tooltip("This value dictates how sharp the edges in the image are kept; a higher value implies sharper edges.")]
[Range(2.0f, 8.0f)]
public float edgeSharpnessAmount;
[Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")]
[Range(0.125f, 0.25f)]
public float edgeDetectionThreshold;
[Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")]
[Range(0.04f, 0.06f)]
public float minimumRequiredLuminance;
}
[Serializable]
public struct Preset
{
[AttributeUsage(AttributeTargets.Field)]
public class LayoutAttribute : PropertyAttribute
{}
[Layout]
public QualitySettings qualitySettings;
[Layout]
public ConsoleSettings consoleSettings;
private static readonly Preset s_ExtremePerformance = new Preset
{
qualitySettings = new QualitySettings
{
subpixelAliasingRemovalAmount = 0.0f,
edgeDetectionThreshold = 0.333f,
minimumRequiredLuminance = 0.0833f
},
consoleSettings = new ConsoleSettings
{
subpixelSpreadAmount = 0.33f,
edgeSharpnessAmount = 8.0f,
edgeDetectionThreshold = 0.25f,
minimumRequiredLuminance = 0.06f
}
};
private static readonly Preset s_Performance = new Preset
{
qualitySettings = new QualitySettings
{
subpixelAliasingRemovalAmount = 0.25f,
edgeDetectionThreshold = 0.25f,
minimumRequiredLuminance = 0.0833f
},
consoleSettings = new ConsoleSettings
{
subpixelSpreadAmount = 0.33f,
edgeSharpnessAmount = 8.0f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.06f
}
};
private static readonly Preset s_Default = new Preset
{
qualitySettings = new QualitySettings
{
subpixelAliasingRemovalAmount = 0.75f,
edgeDetectionThreshold = 0.166f,
minimumRequiredLuminance = 0.0833f
},
consoleSettings = new ConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 8.0f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.05f
}
};
private static readonly Preset s_Quality = new Preset
{
qualitySettings = new QualitySettings
{
subpixelAliasingRemovalAmount = 1.0f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.0625f
},
consoleSettings = new ConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 4.0f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.04f
}
};
private static readonly Preset s_ExtremeQuality = new Preset
{
qualitySettings = new QualitySettings
{
subpixelAliasingRemovalAmount = 1.0f,
edgeDetectionThreshold = 0.063f,
minimumRequiredLuminance = 0.0312f
},
consoleSettings = new ConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 2.0f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.04f
}
};
public static Preset extremePerformancePreset
{
get { return s_ExtremePerformance; }
}
public static Preset performancePreset
{
get { return s_Performance; }
}
public static Preset defaultPreset
{
get { return s_Default; }
}
public static Preset qualityPreset
{
get { return s_Quality; }
}
public static Preset extremeQualityPreset
{
get { return s_ExtremeQuality; }
}
}
[SerializeField, HideInInspector]
public Preset preset = Preset.defaultPreset;
public static Preset[] availablePresets =
{
Preset.extremePerformancePreset,
Preset.performancePreset,
Preset.defaultPreset,
Preset.qualityPreset,
Preset.extremeQualityPreset
};
public bool validSourceFormat { get; private set; }
private int m_QualitySettings;
private int m_ConsoleSettings;
public void Awake()
{
m_QualitySettings = Shader.PropertyToID("_QualitySettings");
m_ConsoleSettings = Shader.PropertyToID("_ConsoleSettings");
}
public void OnEnable(AntiAliasing owner)
{
if (!ImageEffectHelper.IsSupported(shader, true, false, owner))
owner.enabled = false;
}
public void OnDisable()
{
if (m_Material != null)
Object.DestroyImmediate(m_Material);
}
public void OnPreCull(Camera camera)
{
}
public void OnPostRender(Camera camera)
{
}
public void OnRenderImage(Camera camera, RenderTexture source, RenderTexture destination)
{
#if UNITY_EDITOR
validSourceFormat = true;
if (source.format == RenderTextureFormat.ARGBHalf
|| source.format == RenderTextureFormat.ARGBFloat
|| source.format == RenderTextureFormat.ARGB2101010)
validSourceFormat = false;
#endif
material.SetVector(m_QualitySettings, new Vector3(preset.qualitySettings.subpixelAliasingRemovalAmount,
preset.qualitySettings.edgeDetectionThreshold, preset.qualitySettings.minimumRequiredLuminance));
material.SetVector(m_ConsoleSettings, new Vector4(preset.consoleSettings.subpixelSpreadAmount,
preset.consoleSettings.edgeSharpnessAmount, preset.consoleSettings.edgeDetectionThreshold,
preset.consoleSettings.minimumRequiredLuminance));
Graphics.Blit(source, destination, material, 0);
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8ca0fe85db4ef594fb0771b250c00e23
timeCreated: 1453738651
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences:
- shader: {fileID: 4800000, guid: 3eaaee164ee0fed4d9a0bbe8434805a6, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 3f7cc4a9005f5f846957997471c28f2b
folderAsset: yes
timeCreated: 1455022968
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,106 @@
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Hidden/Fast Approximate Anti-aliasing"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
CGINCLUDE
#pragma fragmentoption ARB_precision_hint_fastest
#if defined(SHADER_API_PS3)
#define FXAA_PS3 1
// Shaves off 2 cycles from the shader
#define FXAA_EARLY_EXIT 0
#elif defined(SHADER_API_XBOX360)
#define FXAA_360 1
// Shaves off 10ms from the shader's execution time
#define FXAA_EARLY_EXIT 1
#else
#define FXAA_PC 1
#endif
#define FXAA_HLSL_3 1
#define FXAA_QUALITY__PRESET 39
#define FXAA_GREEN_AS_LUMA 1
#pragma target 3.0
#include "FXAA3.cginc"
float4 _MainTex_TexelSize;
float3 _QualitySettings;
float4 _ConsoleSettings;
struct Input
{
float4 position : POSITION;
float2 uv : TEXCOORD0;
};
struct Varying
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
};
Varying vertex(Input input)
{
Varying output;
output.position = UnityObjectToClipPos(input.position);
output.uv = input.uv;
return output;
}
sampler2D _MainTex;
float calculateLuma(float4 color)
{
return color.g * 1.963211 + color.r;
}
fixed4 fragment(Varying input) : SV_Target
{
const float4 consoleUV = input.uv.xyxy + .5 * float4(-_MainTex_TexelSize.xy, _MainTex_TexelSize.xy);
const float4 consoleSubpixelFrame = _ConsoleSettings.x * float4(-1., -1., 1., 1.) *
_MainTex_TexelSize.xyxy;
const float4 consoleSubpixelFramePS3 = float4(-2., -2., 2., 2.) * _MainTex_TexelSize.xyxy;
const float4 consoleSubpixelFrameXBOX = float4(8., 8., -4., -4.) * _MainTex_TexelSize.xyxy;
#if defined(SHADER_API_XBOX360)
const float4 consoleConstants = float4(1., -1., .25, -.25);
#else
const float4 consoleConstants = float4(0., 0., 0., 0.);
#endif
return FxaaPixelShader(input.uv, consoleUV, _MainTex, _MainTex, _MainTex, _MainTex_TexelSize.xy,
consoleSubpixelFrame, consoleSubpixelFramePS3, consoleSubpixelFrameXBOX,
_QualitySettings.x, _QualitySettings.y, _QualitySettings.z, _ConsoleSettings.y, _ConsoleSettings.z,
_ConsoleSettings.w, consoleConstants);
}
ENDCG
SubShader
{
ZTest Always Cull Off ZWrite Off
Fog { Mode off }
Pass
{
CGPROGRAM
#pragma vertex vertex
#pragma fragment fragment
#include "UnityCG.cginc"
ENDCG
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 3eaaee164ee0fed4d9a0bbe8434805a6
timeCreated: 1453736553
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b44d2ca11a7157e4db9f1e02f5249f95
timeCreated: 1453990603
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
using UnityEngine;
namespace UnityStandardAssets.CinematicEffects
{
public interface IAntiAliasing
{
void Awake();
void OnEnable(AntiAliasing owner);
void OnDisable();
void OnPreCull(Camera camera);
void OnPostRender(Camera camera);
void OnRenderImage(Camera camera, RenderTexture source, RenderTexture destination);
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 90329fa7c7a616243a47de84e6e5c041
timeCreated: 1454590083
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: d958f8498dd28db459dc41b661331fc8
folderAsset: yes
timeCreated: 1446717353
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 3ab9eab0d04085b4abd47b6b0657143c
folderAsset: yes
timeCreated: 1430588699
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,106 @@
using UnityEditor;
using System.Collections.Generic;
using System;
using System.Linq;
using UnityEngine;
using System.Reflection;
using UnityEngine.Serialization;
namespace UnityStandardAssets.CinematicEffects
{
public class SMAAEditor : IAntiAliasingEditor
{
private List<SerializedProperty> m_TopLevelFields = new List<SerializedProperty>();
[Serializable]
class InfoMap
{
public string name;
public bool experimental;
public bool quality;
public List<SerializedProperty> properties;
}
private List<InfoMap> m_GroupFields = new List<InfoMap>();
public void OnEnable(SerializedObject serializedObject, string path)
{
var topLevelSettings = typeof(SMAA).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(SMAA.TopLevelSettings), false).Any());
var settingsGroups = typeof(SMAA).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(SMAA.SettingsGroup), false).Any());
foreach (var group in topLevelSettings)
{
var searchPath = path + "." + group.Name + ".";
foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
var property = serializedObject.FindProperty(searchPath + setting.Name);
if (property != null)
m_TopLevelFields.Add(property);
}
}
foreach (var group in settingsGroups)
{
var searchPath = path + "." + group.Name + ".";
foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
var infoGroup = m_GroupFields.FirstOrDefault(x => x.name == group.Name);
if (infoGroup == null)
{
infoGroup = new InfoMap();
infoGroup.properties = new List<SerializedProperty>();
infoGroup.name = group.Name;
infoGroup.quality = group.FieldType == typeof(SMAA.QualitySettings);
infoGroup.experimental = group.GetCustomAttributes(typeof(SMAA.ExperimentalGroup), false).Length > 0;
m_GroupFields.Add(infoGroup);
}
var property = serializedObject.FindProperty(searchPath + setting.Name);
if (property != null)
{
infoGroup.properties.Add(property);
}
}
}
}
public bool OnInspectorGUI(IAntiAliasing target)
{
EditorGUI.BeginChangeCheck();
foreach (var setting in m_TopLevelFields)
EditorGUILayout.PropertyField(setting);
foreach (var group in m_GroupFields)
{
if (group.quality && (target as SMAA).settings.quality != SMAA.QualityPreset.Custom)
{
continue;
}
string title = ObjectNames.NicifyVariableName(group.name);
if (group.experimental)
title += " (Experimental)";
EditorGUILayout.Space();
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
var enabledField = group.properties.FirstOrDefault(x => x.propertyPath == "m_SMAA." + group.name + ".enabled");
if (enabledField != null && !enabledField.boolValue)
{
EditorGUILayout.PropertyField(enabledField);
EditorGUI.indentLevel--;
continue;
}
foreach (var field in group.properties)
EditorGUILayout.PropertyField(field);
EditorGUI.indentLevel--;
}
return EditorGUI.EndChangeCheck();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5c2ffc06b5a6ee64d8e1d9bdf074732c
timeCreated: 1430643832
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 9362798305520c448b294dd314a7daff
folderAsset: yes
timeCreated: 1430505545
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 KiB

View File

@@ -0,0 +1,57 @@
fileFormatVersion: 2
guid: e62aa7035ea66c94b90b2d8774d02cca
timeCreated: 1432601000
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 1
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: -3
maxTextureSize: 2048
textureSettings:
filterMode: 1
aniso: 0
mipBias: -1
wrapMode: 1
nPOTScale: 0
lightmap: 0
rGBM: 2
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 74597699f47d8ae458dca68f79f1b21f
timeCreated: 1430504573
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,384 @@
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Hidden/Subpixel Morphological Anti-aliasing"
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {}
}
CGINCLUDE
#pragma fragmentoption ARB_precision_hint_fastest
#pragma target 3.0
#pragma glsl
#pragma exclude_renderers flash
sampler2D _MainTex;
sampler2D _BlendTex;
sampler2D _AreaTex;
sampler2D _SearchTex;
sampler2D _AccumulationTex;
sampler2D _CameraDepthTexture;
float4 _MainTex_TexelSize;
float4 _Metrics; // 1f / width, 1f / height, width, height
float4 _Params1; // SMAA_THRESHOLD, SMAA_DEPTH_THRESHOLD, SMAA_MAX_SEARCH_STEPS, SMAA_MAX_SEARCH_STEPS_DIAG
float2 _Params2; // SMAA_CORNER_ROUNDING, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
float3 _Params3; // SMAA_PREDICATION_THRESHOLD, SMAA_PREDICATION_SCALE, SMAA_PREDICATION_STRENGTH
float4x4 _ReprojectionMatrix;
float4 _SubsampleIndices;
#define SMAA_RT_METRICS _Metrics
#define SMAA_THRESHOLD _Params1.x
#define SMAA_DEPTH_THRESHOLD _Params1.y
#define SMAA_MAX_SEARCH_STEPS _Params1.z
#define SMAA_MAX_SEARCH_STEPS_DIAG _Params1.w
#define SMAA_CORNER_ROUNDING _Params2.x
#define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR _Params2.y
#define SMAA_PREDICATION_THRESHOLD _Params3.x
#define SMAA_PREDICATION_SCALE _Params3.y
#define SMAA_PREDICATION_STRENGTH _Params3.z
// Can't use SMAA_HLSL_3 as it won't compile with OpenGL, so lets make our own set of defines for Unity
#define SMAA_CUSTOM_SL
#define mad(a, b, c) (a * b + c)
#define SMAATexture2D(tex) sampler2D tex
#define SMAATexturePass2D(tex) tex
#define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
#define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
#define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0))
#define SMAASample(tex, coord) tex2D(tex, coord)
#define SMAASamplePoint(tex, coord) tex2D(tex, coord)
#define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy)
#define SMAA_FLATTEN UNITY_FLATTEN
#define SMAA_BRANCH UNITY_BRANCH
// SMAA_CUSTOM_SL
#define SMAA_AREATEX_SELECT(sample) sample.rg
#define SMAA_SEARCHTEX_SELECT(sample) sample.a
#define SMAA_INCLUDE_VS 0
struct vInput
{
float4 pos : POSITION;
float2 uv : TEXCOORD0;
};
struct fInput_edge
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float4 offset[3] : TEXCOORD1;
};
fInput_edge vert_edge(vInput i)
{
fInput_edge o;
o.pos = UnityObjectToClipPos(i.pos);
o.uv = i.uv;
#if UNITY_UV_STARTS_AT_TOP
if (_MainTex_TexelSize.y < 0)
o.uv.y = 1.0 - i.uv.y;
#endif
o.offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), o.uv.xyxy);
o.offset[1] = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), o.uv.xyxy);
o.offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), o.uv.xyxy);
return o;
}
ENDCG
SubShader
{
ZTest Always Cull Off ZWrite Off
Fog { Mode off }
// (0) Clear
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#include "UnityCG.cginc"
float4 frag(v2f_img i) : SV_Target
{
return float4(0.0, 0.0, 0.0, 0.0);
}
ENDCG
}
// -----------------------------------------------------------------------------
// Edge Detection
// (1) Luma
Pass
{
// TODO: Stencil not working
// Stencil
// {
// Pass replace
// Ref 1
// }
CGPROGRAM
#pragma vertex vert_edge
#pragma fragment frag
#pragma multi_compile __ USE_PREDICATION
#if USE_PREDICATION
#define SMAA_PREDICATION 1
#else
#define SMAA_PREDICATION 0
#endif
#include "UnityCG.cginc"
#include "SMAA.cginc"
float4 frag(fInput_edge i) : SV_Target
{
#if SMAA_PREDICATION
return float4(SMAALumaEdgeDetectionPS(i.uv, i.offset, _MainTex, _CameraDepthTexture), 0.0, 0.0);
#else
return float4(SMAALumaEdgeDetectionPS(i.uv, i.offset, _MainTex), 0.0, 0.0);
#endif
}
ENDCG
}
// (2) Color
Pass
{
// TODO: Stencil not working
// Stencil
// {
// Pass replace
// Ref 1
// }
CGPROGRAM
#pragma vertex vert_edge
#pragma fragment frag
#pragma multi_compile __ USE_PREDICATION
#if USE_PREDICATION
#define SMAA_PREDICATION 1
#else
#define SMAA_PREDICATION 0
#endif
#include "UnityCG.cginc"
#include "SMAA.cginc"
float4 frag(fInput_edge i) : SV_Target
{
#if SMAA_PREDICATION
return float4(SMAAColorEdgeDetectionPS(i.uv, i.offset, _MainTex, _CameraDepthTexture), 0.0, 0.0);
#else
return float4(SMAAColorEdgeDetectionPS(i.uv, i.offset, _MainTex), 0.0, 0.0);
#endif
}
ENDCG
}
// (3) Depth
Pass
{
// TODO: Stencil not working
// Stencil
// {
// Pass replace
// Ref 1
// }
CGPROGRAM
#pragma vertex vert_edge
#pragma fragment frag
#define SMAA_PREDICATION 0
#include "UnityCG.cginc"
#include "SMAA.cginc"
float4 frag(fInput_edge i) : SV_Target
{
return float4(SMAADepthEdgeDetectionPS(i.uv, i.offset, _CameraDepthTexture), 0.0, 0.0);
}
ENDCG
}
// -----------------------------------------------------------------------------
// Blend Weights Calculation
// (4)
Pass
{
// TODO: Stencil not working
// Stencil
// {
// Pass keep
// Comp equal
// Ref 1
// }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ USE_DIAG_SEARCH
#pragma multi_compile __ USE_CORNER_DETECTION
#if !defined(USE_DIAG_SEARCH)
#define SMAA_DISABLE_DIAG_DETECTION
#endif
#if !defined(USE_CORNER_DETECTION)
#define SMAA_DISABLE_CORNER_DETECTION
#endif
#include "UnityCG.cginc"
#include "SMAA.cginc"
struct fInput
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float2 pixcoord : TEXCOORD1;
float4 offset[3] : TEXCOORD2;
};
fInput vert(vInput i)
{
fInput o;
o.pos = UnityObjectToClipPos(i.pos);
o.uv = i.uv;
o.pixcoord = o.uv * SMAA_RT_METRICS.zw;
// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
o.offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), o.uv.xyxy);
o.offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), o.uv.xyxy);
// And these for the searches, they indicate the ends of the loops:
o.offset[2] = mad(SMAA_RT_METRICS.xxyy, float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
float4(o.offset[0].xz, o.offset[1].yw));
return o;
}
float4 frag(fInput i) : SV_Target
{
return SMAABlendingWeightCalculationPS(i.uv, i.pixcoord, i.offset, _MainTex, _AreaTex, _SearchTex,
_SubsampleIndices);
}
ENDCG
}
// -----------------------------------------------------------------------------
// Neighborhood Blending
// (5)
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ USE_UV_BASED_REPROJECTION
#if defined (USE_UV_BASED_REPROJECTION)
#define SMAA_UV_BASED_REPROJECTION 1
#endif
#include "UnityCG.cginc"
#include "SMAA.cginc"
struct fInput
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float4 offset : TEXCOORD1;
};
fInput vert(vInput i)
{
fInput o;
o.pos = UnityObjectToClipPos(i.pos);
o.uv = i.uv;
o.offset = mad(SMAA_RT_METRICS.xyxy, float4(1.0, 0.0, 0.0, 1.0), o.uv.xyxy);
return o;
}
float4 frag(fInput i) : SV_Target
{
return SMAANeighborhoodBlendingPS(i.uv, i.offset, _MainTex, _BlendTex);
}
ENDCG
}
// -----------------------------------------------------------------------------
// Accumulation Resolve
// (6)
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ USE_UV_BASED_REPROJECTION
#if defined (USE_UV_BASED_REPROJECTION)
#define SMAA_UV_BASED_REPROJECTION 1
#endif
#include "UnityCG.cginc"
#include "SMAA.cginc"
struct fInput
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
fInput vert(vInput i)
{
fInput o;
o.pos = UnityObjectToClipPos(i.pos);
o.uv = i.uv;
return o;
}
float4 frag(fInput i) : SV_Target
{
return SMAAResolvePS(i.uv, _MainTex, _AccumulationTex);
}
ENDCG
}
}
FallBack off
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4505fec7a81214243b8e59edf89e3a53
timeCreated: 1432603500
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@@ -0,0 +1,57 @@
fileFormatVersion: 2
guid: 387ed7c38eb63554db846987adb98e68
timeCreated: 1432601000
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 1
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 1
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
filterMode: 0
aniso: -1
mipBias: -1
wrapMode: 1
nPOTScale: 0
lightmap: 0
rGBM: 2
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,507 @@
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using Object = UnityEngine.Object;
namespace UnityStandardAssets.CinematicEffects
{
[Serializable]
public class SMAA : IAntiAliasing
{
[AttributeUsage(AttributeTargets.Field)]
public class SettingsGroup : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class TopLevelSettings : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class ExperimentalGroup : Attribute
{}
public enum DebugPass
{
Off,
Edges,
Weights,
Accumulation
}
public enum QualityPreset
{
Low = 0,
Medium = 1,
High = 2,
Ultra = 3,
Custom
}
public enum EdgeDetectionMethod
{
Luma = 1,
Color = 2,
Depth = 3
}
[Serializable]
public struct GlobalSettings
{
[Tooltip("Use this to fine tune your settings when working in Custom quality mode. \"Accumulation\" only works when \"Temporal Filtering\" is enabled.")]
public DebugPass debugPass;
[Tooltip("Low: 60% of the quality.\nMedium: 80% of the quality.\nHigh: 95% of the quality.\nUltra: 99% of the quality (overkill).")]
public QualityPreset quality;
[Tooltip("You've three edge detection methods to choose from: luma, color or depth.\nThey represent different quality/performance and anti-aliasing/sharpness tradeoffs, so our recommendation is for you to choose the one that best suits your particular scenario:\n\n- Depth edge detection is usually the fastest but it may miss some edges.\n- Luma edge detection is usually more expensive than depth edge detection, but catches visible edges that depth edge detection can miss.\n- Color edge detection is usually the most expensive one but catches chroma-only edges.")]
public EdgeDetectionMethod edgeDetectionMethod;
public static GlobalSettings defaultSettings
{
get
{
return new GlobalSettings
{
debugPass = DebugPass.Off,
quality = QualityPreset.High,
edgeDetectionMethod = EdgeDetectionMethod.Color
};
}
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("Enables/Disables diagonal processing.")]
public bool diagonalDetection;
[Tooltip("Enables/Disables corner detection. Leave this on to avoid blurry corners.")]
public bool cornerDetection;
[Range(0f, 0.5f)]
[Tooltip("Specifies the threshold or sensitivity to edges. Lowering this value you will be able to detect more edges at the expense of performance.\n0.1 is a reasonable value, and allows to catch most visible edges. 0.05 is a rather overkill value, that allows to catch 'em all.")]
public float threshold;
[Min(0.0001f)]
[Tooltip("Specifies the threshold for depth edge detection. Lowering this value you will be able to detect more edges at the expense of performance.")]
public float depthThreshold;
[Range(0, 112)]
[Tooltip("Specifies the maximum steps performed in the horizontal/vertical pattern searches, at each side of the pixel.\nIn number of pixels, it's actually the double. So the maximum line length perfectly handled by, for example 16, is 64 (by perfectly, we meant that longer lines won't look as good, but still antialiased).")]
public int maxSearchSteps;
[Range(0, 20)]
[Tooltip("Specifies the maximum steps performed in the diagonal pattern searches, at each side of the pixel. In this case we jump one pixel at time, instead of two.\nOn high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 steps), but it can have a significant impact on older machines.")]
public int maxDiagonalSearchSteps;
[Range(0, 100)]
[Tooltip("Specifies how much sharp corners will be rounded.")]
public int cornerRounding;
[Min(0f)]
[Tooltip("If there is an neighbor edge that has a local contrast factor times bigger contrast than current edge, current edge will be discarded.\nThis allows to eliminate spurious crossing edges, and is based on the fact that, if there is too much contrast in a direction, that will hide perceptually contrast in the other neighbors.")]
public float localContrastAdaptationFactor;
public static QualitySettings[] presetQualitySettings =
{
// Low
new QualitySettings
{
diagonalDetection = false,
cornerDetection = false,
threshold = 0.15f,
depthThreshold = 0.01f,
maxSearchSteps = 4,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// Medium
new QualitySettings
{
diagonalDetection = false,
cornerDetection = false,
threshold = 0.1f,
depthThreshold = 0.01f,
maxSearchSteps = 8,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// High
new QualitySettings
{
diagonalDetection = true,
cornerDetection = true,
threshold = 0.1f,
depthThreshold = 0.01f,
maxSearchSteps = 16,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// Ultra
new QualitySettings
{
diagonalDetection = true,
cornerDetection = true,
threshold = 0.05f,
depthThreshold = 0.01f,
maxSearchSteps = 32,
maxDiagonalSearchSteps = 16,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
};
}
[Serializable]
public struct TemporalSettings
{
[Tooltip("Temporal filtering makes it possible for the SMAA algorithm to benefit from minute subpixel information available that has been accumulated over many frames.")]
public bool enabled;
public bool UseTemporal()
{
#if UNITY_EDITOR
return enabled && EditorApplication.isPlayingOrWillChangePlaymode;
#else
return enabled;
#endif
}
[Range(0.5f, 10.0f)]
[Tooltip("The size of the fuzz-displacement (jitter) in pixels applied to the camera's perspective projection matrix.\nUsed for 2x temporal anti-aliasing.")]
public float fuzzSize;
public static TemporalSettings defaultSettings
{
get
{
return new TemporalSettings
{
enabled = false,
fuzzSize = 2f
};
}
}
}
[Serializable]
public struct PredicationSettings
{
[Tooltip("Predicated thresholding allows to better preserve texture details and to improve performance, by decreasing the number of detected edges using an additional buffer (the detph buffer).\nIt locally decreases the luma or color threshold if an edge is found in an additional buffer (so the global threshold can be higher).")]
public bool enabled;
[Min(0.0001f)]
[Tooltip("Threshold to be used in the additional predication buffer.")]
public float threshold;
[Range(1f, 5f)]
[Tooltip("How much to scale the global threshold used for luma or color edge detection when using predication.")]
public float scale;
[Range(0f, 1f)]
[Tooltip("How much to locally decrease the threshold.")]
public float strength;
public static PredicationSettings defaultSettings
{
get
{
return new PredicationSettings
{
enabled = false,
threshold = 0.01f,
scale = 2f,
strength = 0.4f
};
}
}
}
[TopLevelSettings]
public GlobalSettings settings = GlobalSettings.defaultSettings;
[SettingsGroup]
public QualitySettings quality = QualitySettings.presetQualitySettings[2];
[SettingsGroup]
public PredicationSettings predication = PredicationSettings.defaultSettings;
[SettingsGroup, ExperimentalGroup]
public TemporalSettings temporal = TemporalSettings.defaultSettings;
private Matrix4x4 m_ProjectionMatrix;
private Matrix4x4 m_PreviousViewProjectionMatrix;
private float m_FlipFlop = 1.0f;
private RenderTexture m_Accumulation;
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/Subpixel Morphological Anti-aliasing");
return m_Shader;
}
}
private Texture2D m_AreaTexture;
private Texture2D areaTexture
{
get
{
if (m_AreaTexture == null)
m_AreaTexture = Resources.Load<Texture2D>("AreaTex");
return m_AreaTexture;
}
}
private Texture2D m_SearchTexture;
private Texture2D searchTexture
{
get
{
if (m_SearchTexture == null)
m_SearchTexture = Resources.Load<Texture2D>("SearchTex");
return m_SearchTexture;
}
}
private Material m_Material;
private Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private int m_AreaTex;
private int m_SearchTex;
private int m_Metrics;
private int m_Params1;
private int m_Params2;
private int m_Params3;
private int m_ReprojectionMatrix;
private int m_SubsampleIndices;
private int m_BlendTex;
private int m_AccumulationTex;
public void Awake()
{
m_AreaTex = Shader.PropertyToID("_AreaTex");
m_SearchTex = Shader.PropertyToID("_SearchTex");
m_Metrics = Shader.PropertyToID("_Metrics");
m_Params1 = Shader.PropertyToID("_Params1");
m_Params2 = Shader.PropertyToID("_Params2");
m_Params3 = Shader.PropertyToID("_Params3");
m_ReprojectionMatrix = Shader.PropertyToID("_ReprojectionMatrix");
m_SubsampleIndices = Shader.PropertyToID("_SubsampleIndices");
m_BlendTex = Shader.PropertyToID("_BlendTex");
m_AccumulationTex = Shader.PropertyToID("_AccumulationTex");
}
public void OnEnable(AntiAliasing owner)
{
if (!ImageEffectHelper.IsSupported(shader, true, false, owner))
owner.enabled = false;
}
public void OnDisable()
{
// Cleanup
if (m_Material != null)
Object.DestroyImmediate(m_Material);
if (m_Accumulation != null)
Object.DestroyImmediate(m_Accumulation);
m_Material = null;
m_Accumulation = null;
}
public void OnPreCull(Camera camera)
{
if (temporal.UseTemporal())
{
m_ProjectionMatrix = camera.projectionMatrix;
m_FlipFlop -= (2.0f * m_FlipFlop);
Matrix4x4 fuzz = Matrix4x4.identity;
fuzz.m03 = (0.25f * m_FlipFlop) * temporal.fuzzSize / camera.pixelWidth;
fuzz.m13 = (-0.25f * m_FlipFlop) * temporal.fuzzSize / camera.pixelHeight;
camera.projectionMatrix = fuzz * camera.projectionMatrix;
}
}
public void OnPostRender(Camera camera)
{
if (temporal.UseTemporal())
camera.ResetProjectionMatrix();
}
public void OnRenderImage(Camera camera, RenderTexture source, RenderTexture destination)
{
int width = camera.pixelWidth;
int height = camera.pixelHeight;
bool isFirstFrame = false;
QualitySettings preset = quality;
if (settings.quality != QualityPreset.Custom)
preset = QualitySettings.presetQualitySettings[(int)settings.quality];
// Pass IDs
int passEdgeDetection = (int)settings.edgeDetectionMethod;
int passBlendWeights = 4;
int passNeighborhoodBlending = 5;
int passResolve = 6;
// Reprojection setup
var viewProjectionMatrix = GL.GetGPUProjectionMatrix(m_ProjectionMatrix, true) * camera.worldToCameraMatrix;
// Uniforms
material.SetTexture(m_AreaTex, areaTexture);
material.SetTexture(m_SearchTex, searchTexture);
material.SetVector(m_Metrics, new Vector4(1f / width, 1f / height, width, height));
material.SetVector(m_Params1, new Vector4(preset.threshold, preset.depthThreshold, preset.maxSearchSteps, preset.maxDiagonalSearchSteps));
material.SetVector(m_Params2, new Vector2(preset.cornerRounding, preset.localContrastAdaptationFactor));
material.SetMatrix(m_ReprojectionMatrix, m_PreviousViewProjectionMatrix * Matrix4x4.Inverse(viewProjectionMatrix));
float subsampleIndex = (m_FlipFlop < 0.0f) ? 2.0f : 1.0f;
material.SetVector(m_SubsampleIndices, new Vector4(subsampleIndex, subsampleIndex, subsampleIndex, 0.0f));
// Handle predication & depth-based edge detection
Shader.DisableKeyword("USE_PREDICATION");
if (settings.edgeDetectionMethod == EdgeDetectionMethod.Depth)
{
camera.depthTextureMode |= DepthTextureMode.Depth;
}
else if (predication.enabled)
{
camera.depthTextureMode |= DepthTextureMode.Depth;
Shader.EnableKeyword("USE_PREDICATION");
material.SetVector(m_Params3, new Vector3(predication.threshold, predication.scale, predication.strength));
}
// Diag search & corner detection
Shader.DisableKeyword("USE_DIAG_SEARCH");
Shader.DisableKeyword("USE_CORNER_DETECTION");
if (preset.diagonalDetection)
Shader.EnableKeyword("USE_DIAG_SEARCH");
if (preset.cornerDetection)
Shader.EnableKeyword("USE_CORNER_DETECTION");
// UV-based reprojection (up to Unity 5.x)
Shader.DisableKeyword("USE_UV_BASED_REPROJECTION");
if (temporal.UseTemporal())
Shader.EnableKeyword("USE_UV_BASED_REPROJECTION");
// Persistent textures and lazy-initializations
if (m_Accumulation == null || (m_Accumulation.width != width || m_Accumulation.height != height))
{
if (m_Accumulation)
RenderTexture.ReleaseTemporary(m_Accumulation);
m_Accumulation = RenderTexture.GetTemporary(width, height, 0, source.format, RenderTextureReadWrite.Linear);
m_Accumulation.hideFlags = HideFlags.HideAndDontSave;
isFirstFrame = true;
}
RenderTexture rt1 = TempRT(width, height, source.format);
Graphics.Blit(null, rt1, material, 0); // Clear
// Edge Detection
Graphics.Blit(source, rt1, material, passEdgeDetection);
if (settings.debugPass == DebugPass.Edges)
{
Graphics.Blit(rt1, destination);
}
else
{
RenderTexture rt2 = TempRT(width, height, source.format);
Graphics.Blit(null, rt2, material, 0); // Clear
// Blend Weights
Graphics.Blit(rt1, rt2, material, passBlendWeights);
if (settings.debugPass == DebugPass.Weights)
{
Graphics.Blit(rt2, destination);
}
else
{
// Neighborhood Blending
material.SetTexture(m_BlendTex, rt2);
if (temporal.UseTemporal())
{
// Temporal filtering
Graphics.Blit(source, rt1, material, passNeighborhoodBlending);
if (settings.debugPass == DebugPass.Accumulation)
{
Graphics.Blit(m_Accumulation, destination);
}
else if (!isFirstFrame)
{
material.SetTexture(m_AccumulationTex, m_Accumulation);
Graphics.Blit(rt1, destination, material, passResolve);
}
else
{
Graphics.Blit(rt1, destination);
}
//Graphics.Blit(rt1, m_Accumulation);
Graphics.Blit(destination, m_Accumulation);
RenderTexture.active = null;
}
else
{
Graphics.Blit(source, destination, material, passNeighborhoodBlending);
}
}
RenderTexture.ReleaseTemporary(rt2);
}
RenderTexture.ReleaseTemporary(rt1);
// Store the future-previous frame's view-projection matrix
m_PreviousViewProjectionMatrix = viewProjectionMatrix;
}
private RenderTexture TempRT(int width, int height, RenderTextureFormat format)
{
// Skip the depth & stencil buffer creation when DebugPass is set to avoid flickering
// int depthStencilBits = DebugPass == DebugPass.Off ? 24 : 0;
int depthStencilBits = 0;
return RenderTexture.GetTemporary(width, height, depthStencilBits, format, RenderTextureReadWrite.Linear);
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 9c2502951f8f3e743917c441eba57d1c
timeCreated: 1454511067
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences:
- m_Shader: {fileID: 4800000, guid: 4505fec7a81214243b8e59edf89e3a53, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 88d2f1c604c7f6d4bb80a72b2f0219a7
folderAsset: yes
timeCreated: 1449044555
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e862ecde714eb154ca2d86a9a0809732
folderAsset: yes
timeCreated: 1453372226
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,62 @@
using UnityEngine;
using UnityEditor;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace UnityStandardAssets.CinematicEffects
{
public static class EditorGUIHelper
{
private static Styles s_Styles;
private class Styles
{
public GUIStyle header = "ShurikenModuleTitle";
public GUIStyle headerCheckbox = "ShurikenCheckMark";
internal Styles()
{
header.font = (new GUIStyle("Label")).font;
header.border = new RectOffset(15, 7, 4, 4);
header.fixedHeight = 22;
header.contentOffset = new Vector2(20f, -2f);
}
}
static EditorGUIHelper()
{
s_Styles = new Styles();
}
public static bool Header(SerializedProperty group, SerializedProperty enabledField)
{
var display = group == null || group.isExpanded;
var enabled = enabledField != null && enabledField.boolValue;
var title = group == null ? "Unknown Group" : ObjectNames.NicifyVariableName(group.displayName);
Rect rect = GUILayoutUtility.GetRect(16f, 22f, s_Styles.header);
GUI.Box(rect, title, s_Styles.header);
Rect toggleRect = new Rect(rect.x + 4f, rect.y + 4f, 13f, 13f);
if (Event.current.type == EventType.Repaint)
s_Styles.headerCheckbox.Draw(toggleRect, false, false, enabled, false);
Event e = Event.current;
if (e.type == EventType.MouseDown)
{
if (toggleRect.Contains(e.mousePosition) && enabledField != null)
{
enabledField.boolValue = !enabledField.boolValue;
e.Use();
}
else if (rect.Contains(e.mousePosition) && group != null)
{
display = !display;
group.isExpanded = !group.isExpanded;
e.Use();
}
}
return display;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5b995f06a3ed14d449823cf7ab1c5a58
timeCreated: 1454681943
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,25 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace UnityStandardAssets.CinematicEffects
{
public static class FieldFinder<T>
{
public static FieldInfo GetField<TValue>(Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (FieldInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 39e54cb37a3a81a40b248f1cc25c4619
timeCreated: 1454073160
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,29 @@
using UnityEditor;
using UnityEngine;
namespace UnityStandardAssets.CinematicEffects
{
[CustomPropertyDrawer(typeof(MinAttribute))]
internal sealed class MinDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MinAttribute attribute = (MinAttribute) base.attribute;
if (property.propertyType == SerializedPropertyType.Integer)
{
int v = EditorGUI.IntField(position, label, property.intValue);
property.intValue = (int)Mathf.Max(v, attribute.min);
}
else if (property.propertyType == SerializedPropertyType.Float)
{
float v = EditorGUI.FloatField(position, label, property.floatValue);
property.floatValue = Mathf.Max(v, attribute.min);
}
else
{
EditorGUI.LabelField(position, label.text, "Use Min with float or int.");
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 9c615a85f13c6764fa4496d1d7f75f52
timeCreated: 1453220014
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,67 @@
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityStandardAssets.CinematicEffects
{
public static class ImageEffectHelper
{
public static bool IsSupported(Shader s, bool needDepth, bool needHdr, MonoBehaviour effect)
{
#if UNITY_EDITOR
// Don't check for shader compatibility while it's building as it would disable most effects
// on build farms without good-enough gaming hardware.
if (!BuildPipeline.isBuildingPlayer)
{
#endif
if (s == null || !s.isSupported)
{
Debug.LogWarningFormat("Missing shader for image effect {0}", effect);
return false;
}
#if UNITY_5_5_OR_NEWER
if (!SystemInfo.supportsImageEffects)
#else
if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures)
#endif
{
Debug.LogWarningFormat("Image effects aren't supported on this device ({0})", effect);
return false;
}
if (needDepth && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth))
{
Debug.LogWarningFormat("Depth textures aren't supported on this device ({0})", effect);
return false;
}
if (needHdr && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
{
Debug.LogWarningFormat("Floating point textures aren't supported on this device ({0})", effect);
return false;
}
#if UNITY_EDITOR
}
#endif
return true;
}
public static Material CheckShaderAndCreateMaterial(Shader s)
{
if (s == null || !s.isSupported)
return null;
var material = new Material(s);
material.hideFlags = HideFlags.DontSave;
return material;
}
public static bool supportsDX11
{
get { return SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; }
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ab6a3f50deeee984c88794eeeb901226
timeCreated: 1448544124
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
namespace UnityStandardAssets.CinematicEffects
{
using UnityEngine;
public sealed class MinAttribute : PropertyAttribute
{
public readonly float min;
public MinAttribute(float min)
{
this.min = min;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b07292ae638766047a6751da7552e566
timeCreated: 1453220005
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,44 @@
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.CinematicEffects
{
public class RenderTextureUtility
{
//Temporary render texture handling
private List<RenderTexture> m_TemporaryRTs = new List<RenderTexture>();
public RenderTexture GetTemporaryRenderTexture(int width, int height, int depthBuffer = 0, RenderTextureFormat format = RenderTextureFormat.ARGBHalf, FilterMode filterMode = FilterMode.Bilinear)
{
var rt = RenderTexture.GetTemporary(width, height, depthBuffer, format);
rt.filterMode = filterMode;
rt.wrapMode = TextureWrapMode.Clamp;
rt.name = "RenderTextureUtilityTempTexture";
m_TemporaryRTs.Add(rt);
return rt;
}
public void ReleaseTemporaryRenderTexture(RenderTexture rt)
{
if (rt == null)
return;
if (!m_TemporaryRTs.Contains(rt))
{
Debug.LogErrorFormat("Attempting to remove texture that was not allocated: {0}", rt);
return;
}
m_TemporaryRTs.Remove(rt);
RenderTexture.ReleaseTemporary(rt);
}
public void ReleaseAllTemporaryRenderTextures()
{
for (int i = 0; i < m_TemporaryRTs.Count; ++i)
RenderTexture.ReleaseTemporary(m_TemporaryRTs[i]);
m_TemporaryRTs.Clear();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 054e694bae00c374a97c2bc495fca66b
timeCreated: 1449148391
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,6 @@
fileFormatVersion: 2
guid: d6e0c95a128e14227939c51b5d9ad74e
folderAsset: yes
DefaultImporter:
userData:
assetBundleName:

View File

@@ -0,0 +1,6 @@
fileFormatVersion: 2
guid: cd3e1490c3d9a7a498538315414d5129
folderAsset: yes
DefaultImporter:
userData:
assetBundleName:

View File

@@ -0,0 +1,362 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")]
public class Bloom : PostEffectsBase
{
public enum LensFlareStyle
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
public enum BloomQuality
{
Cheap = 0,
High = 1,
}
public TweakMode tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 2.5f;
public BloomQuality quality = BloomQuality.High;
public float bloomIntensity = 0.5f;
public float bloomThreshold = 0.5f;
public Color bloomThresholdColor = Color.white;
public int bloomBlurIterations = 2;
public int hollywoodFlareBlurIterations = 2;
public float flareRotation = 0.0f;
public LensFlareStyle lensflareMode = (LensFlareStyle) 1;
public float hollyStretchWidth = 2.5f;
public float lensflareIntensity = 0.0f;
public float lensflareThreshold = 0.3f;
public float lensFlareSaturation = 0.75f;
public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f);
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader blurAndFlaresShader;
private Material blurAndFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources ()
{
CheckSupport (false);
screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial);
blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
public void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources()==false)
{
Graphics.Blit (source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
#if UNITY_5_6_OR_NEWER
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR;
#else
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
#endif
else {
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
var rtW2= source.width/2;
var rtH2= source.height/2;
var rtW4= source.width/4;
var rtH4= source.height/4;
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
if (quality > BloomQuality.Cheap) {
Graphics.Blit (source, halfRezColorDown, screenBlend, 2);
RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2);
Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6);
RenderTexture.ReleaseTemporary(rtDown4);
}
else {
Graphics.Blit (source, halfRezColorDown);
Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6);
}
RenderTexture.ReleaseTemporary (halfRezColorDown);
// cut colors (thresholding)
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor);
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
else if (bloomBlurIterations > 10) bloomBlurIterations = 10;
for (int iter = 0; iter < bloomBlurIterations; iter++)
{
float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread;
// vertical blur
RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
secondQuarterRezColor = blur4;
// horizontal blur
blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
secondQuarterRezColor = blur4;
if (quality > BloomQuality.Cheap)
{
if (iter == 0)
{
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (secondQuarterRezColor, quarterRezColor);
}
else
{
quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected
Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10);
}
}
}
if (quality > BloomQuality.Cheap)
{
Graphics.SetRenderTarget(secondQuarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6);
}
// lens flares: ghosting, anamorphic or both (ghosted anamorphic flares)
if (lensflareIntensity > Mathf.Epsilon)
{
RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
if (lensflareMode == 0)
{
// ghosting only
BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4);
if (quality > BloomQuality.Cheap)
{
// smooth a little
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
Graphics.SetRenderTarget(rtFlares4);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
}
// no ugly edges!
Vignette (0.975f, rtFlares4, rtFlares4);
BlendFlares (rtFlares4, secondQuarterRezColor);
}
else
{
//Vignette (0.975ff, rtFlares4, rtFlares4);
//DrawBorder(rtFlares4, screenBlend, 8);
float flareXRot = 1.0f * Mathf.Cos(flareRotation);
float flareyRot = 1.0f * Mathf.Sin(flareRotation);
float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation);
// "pre and cut"
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2);
// "post"
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f));
// stretch 1st
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// stretch 2nd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f);
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1);
// stretch 3rd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// additional blur passes
for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++)
{
stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
}
if (lensflareMode == (LensFlareStyle) 1)
// anamorphic lens flares
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
else
{
// "combined" lens flares
Vignette (1.0f, quarterRezColor, rtFlares4);
BlendFlares (rtFlares4, quarterRezColor);
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
}
}
RenderTexture.ReleaseTemporary (rtFlares4);
}
int blendPass = (int) realBlendMode;
//if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon)
// blendPass += 4;
screenBlend.SetFloat ("_Intensity", bloomIntensity);
screenBlend.SetTexture ("_ColorBuffer", source);
if (quality > BloomQuality.Cheap)
{
RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
Graphics.Blit (secondQuarterRezColor, halfRezColorUp);
Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (halfRezColorUp);
}
else
Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (quarterRezColor);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
}
private void AddTo (float intensity_, RenderTexture from, RenderTexture to)
{
screenBlend.SetFloat ("_Intensity", intensity_);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, screenBlend, 9);
}
private void BlendFlares (RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, lensFlareMaterial);
}
private void BrightFilter (float thresh, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh));
Graphics.Blit (from, to, brightPassFilterMaterial, 0);
}
private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", threshColor);
Graphics.Blit (from, to, brightPassFilterMaterial, 1);
}
private void Vignette (float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask);
to.MarkRestoreExpected(); // using blending, RT restore expected
Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3);
}
else if (from != to)
{
Graphics.SetRenderTarget (to);
GL.Clear(false, true, Color.black); // clear destination to avoid RT restore
Graphics.Blit (from, to);
}
}
}
}

View File

@@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: 7fceaeb339b971b429c4cc600acabd13
MonoImporter:
serializedVersion: 2
defaultReferences:
- lensFlareVignetteMask: {fileID: 2800000, guid: 95ef4804fe0be4c999ddaa383536cde8,
type: 3}
- lensFlareShader: {fileID: 4800000, guid: 459fe69d2f6d74ddb92f04dbf45a866b, type: 3}
- screenBlendShader: {fileID: 4800000, guid: 7856cbff0a0ca45c787d5431eb805bb0, type: 3}
- blurAndFlaresShader: {fileID: 4800000, guid: be6e39cf196f146d5be72fbefb18ed75,
type: 3}
- brightPassFilterShader: {fileID: 4800000, guid: 0aeaa4cb29f5d4e9c8455f04c8575c8c,
type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,318 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
public enum LensflareStyle34
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode34
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Bloom and Glow/BloomAndFlares (3.5, Deprecated)")]
public class BloomAndFlares : PostEffectsBase
{
public TweakMode34 tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 1.5f;
public float useSrcAlphaAsMask = 0.5f;
public float bloomIntensity = 1.0f;
public float bloomThreshold = 0.5f;
public int bloomBlurIterations = 2;
public bool lensflares = false;
public int hollywoodFlareBlurIterations = 2;
public LensflareStyle34 lensflareMode = (LensflareStyle34)1;
public float hollyStretchWidth = 3.5f;
public float lensflareIntensity = 1.0f;
public float lensflareThreshold = 0.3f;
public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f);
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader vignetteShader;
private Material vignetteMaterial;
public Shader separableBlurShader;
private Material separableBlurMaterial;
public Shader addBrightStuffOneOneShader;
private Material addBrightStuffBlendOneOneMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader hollywoodFlaresShader;
private Material hollywoodFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources()
{
CheckSupport(false);
screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial);
vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial);
separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial);
addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial);
hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
#if UNITY_5_6_OR_NEWER
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR;
#else
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
#endif
else
{
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat);
RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample
RenderTexture.ReleaseTemporary(halfRezColor);
// cut colors (thresholding)
BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
quarterRezColor.DiscardContents();
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
for (int iter = 0; iter < bloomBlurIterations; iter++)
{
float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread;
separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial);
src.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
// lens flares: ghosting, anamorphic or a combination
if (lensflares)
{
if (lensflareMode == 0)
{
BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor);
quarterRezColor.DiscardContents();
// smooth a little, this needs to be resolution dependent
/*
separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
*/
// no ugly edges!
Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
BlendFlares(secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
// (b) hollywood/anamorphic flares?
else
{
// thirdQuarter has the brightcut unblurred colors
// quarterRezColor is the blurred, brightcut buffer that will end up as bloom
hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f));
hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
thirdQuarterRezColor.DiscardContents();
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f);
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
if (lensflareMode == (LensflareStyle34)1)
{
for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
else
{
// (c) combined
for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor);
secondQuarterRezColor.DiscardContents();
BlendFlares(thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
}
}
// screen blend bloom results to color buffer
screenBlend.SetFloat("_Intensity", bloomIntensity);
screenBlend.SetTexture("_ColorBuffer", source);
Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode);
RenderTexture.ReleaseTemporary(quarterRezColor);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
RenderTexture.ReleaseTemporary(thirdQuarterRezColor);
}
private void AddTo(float intensity_, RenderTexture from, RenderTexture to)
{
addBrightStuffBlendOneOneMaterial.SetFloat("_Intensity", intensity_);
Graphics.Blit(from, to, addBrightStuffBlendOneOneMaterial);
}
private void BlendFlares(RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
Graphics.Blit(from, to, lensFlareMaterial);
}
private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to)
{
if (doHdr)
brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f, 0.0f, 0.0f));
else
brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f));
brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask);
Graphics.Blit(from, to, brightPassFilterMaterial);
}
private void Vignette(float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask);
Graphics.Blit(from, to, screenBlend, 3);
}
else
{
vignetteMaterial.SetFloat("vignetteIntensity", amount);
Graphics.Blit(from, to, vignetteMaterial);
}
}
}
}

View File

@@ -0,0 +1,22 @@
fileFormatVersion: 2
guid: 02536f33053638549ab5c50ff3ecc0de
MonoImporter:
serializedVersion: 2
defaultReferences:
- lensFlareVignetteMask: {fileID: 2800000, guid: 95ef4804fe0be4c999ddaa383536cde8,
type: 3}
- lensFlareShader: {fileID: 4800000, guid: 459fe69d2f6d74ddb92f04dbf45a866b, type: 3}
- vignetteShader: {fileID: 4800000, guid: 627943dc7a9a74286b70a4f694a0acd5, type: 3}
- separableBlurShader: {fileID: 4800000, guid: a9df009a214e24a5ebbf271595f8d5b6,
type: 3}
- addBrightStuffOneOneShader: {fileID: 4800000, guid: f7898d203e9b94c0dbe2bf9dd5cb32c0,
type: 3}
- screenBlendShader: {fileID: 4800000, guid: 53b3960ee3d3d4a5caa8d5473d120187, type: 3}
- hollywoodFlaresShader: {fileID: 4800000, guid: e2baf3cae8edc4daf94c9adc2154be00,
type: 3}
- brightPassFilterShader: {fileID: 4800000, guid: 186c4c0d31e314f049595dcbaf4ca129,
type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,109 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Bloom and Glow/Bloom (Optimized)")]
public class BloomOptimized : PostEffectsBase
{
public enum Resolution
{
Low = 0,
High = 1,
}
public enum BlurType
{
Standard = 0,
Sgx = 1,
}
[Range(0.0f, 1.5f)]
public float threshold = 0.25f;
[Range(0.0f, 2.5f)]
public float intensity = 0.75f;
[Range(0.25f, 5.5f)]
public float blurSize = 1.0f;
Resolution resolution = Resolution.Low;
[Range(1, 4)]
public int blurIterations = 1;
public BlurType blurType= BlurType.Standard;
public Shader fastBloomShader = null;
private Material fastBloomMaterial = null;
public override bool CheckResources ()
{
CheckSupport (false);
fastBloomMaterial = CheckShaderAndCreateMaterial (fastBloomShader, fastBloomMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnDisable ()
{
if (fastBloomMaterial)
DestroyImmediate (fastBloomMaterial);
}
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit (source, destination);
return;
}
int divider = resolution == Resolution.Low ? 4 : 2;
float widthMod = resolution == Resolution.Low ? 0.5f : 1.0f;
fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod, 0.0f, threshold, intensity));
source.filterMode = FilterMode.Bilinear;
var rtW= source.width/divider;
var rtH= source.height/divider;
// downsample
RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
rt.filterMode = FilterMode.Bilinear;
Graphics.Blit (source, rt, fastBloomMaterial, 1);
var passOffs= blurType == BlurType.Standard ? 0 : 2;
for(int i = 0; i < blurIterations; i++)
{
fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + (i*1.0f), 0.0f, threshold, intensity));
// vertical blur
RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
rt2.filterMode = FilterMode.Bilinear;
Graphics.Blit (rt, rt2, fastBloomMaterial, 2 + passOffs);
RenderTexture.ReleaseTemporary (rt);
rt = rt2;
// horizontal blur
rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
rt2.filterMode = FilterMode.Bilinear;
Graphics.Blit (rt, rt2, fastBloomMaterial, 3 + passOffs);
RenderTexture.ReleaseTemporary (rt);
rt = rt2;
}
fastBloomMaterial.SetTexture ("_Bloom", rt);
Graphics.Blit (source, destination, fastBloomMaterial, 0);
RenderTexture.ReleaseTemporary (rt);
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 4975a6e437fc3b149a8cd508ce5bdd69
MonoImporter:
serializedVersion: 2
defaultReferences:
- fastBloomShader: {fileID: 4800000, guid: 68a00c837b82e4c6d92e7da765dc5f1d, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,55 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[RequireComponent(typeof (Camera))]
[AddComponentMenu("")]
public class ImageEffectBase : MonoBehaviour
{
/// Provides a shader property that is set in the inspector
/// and a material instantiated from the shader
public Shader shader;
private Material m_Material;
protected virtual void Start()
{
// Disable if we don't support image effects
if (!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
// Disable the image effect if the shader can't
// run on the users graphics card
if (!shader || !shader.isSupported)
enabled = false;
}
protected Material material
{
get
{
if (m_Material == null)
{
m_Material = new Material(shader);
m_Material.hideFlags = HideFlags.HideAndDontSave;
}
return m_Material;
}
}
protected virtual void OnDisable()
{
if (m_Material)
{
DestroyImmediate(m_Material);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f6469eb0ad1119d6d00011d98d76c639
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,42 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
/// A Utility class for performing various image based rendering tasks.
[AddComponentMenu("")]
public class ImageEffects
{
public static void RenderDistortion(Material material, RenderTexture source, RenderTexture destination, float angle, Vector2 center, Vector2 radius)
{
bool invertY = source.texelSize.y < 0.0f;
if (invertY)
{
center.y = 1.0f - center.y;
angle = -angle;
}
Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one);
material.SetMatrix("_RotationMatrix", rotationMatrix);
material.SetVector("_CenterRadius", new Vector4(center.x, center.y, radius.x, radius.y));
material.SetFloat("_Angle", angle*Mathf.Deg2Rad);
Graphics.Blit(source, destination, material);
}
[Obsolete("Use Graphics.Blit(source,dest) instead")]
public static void Blit(RenderTexture source, RenderTexture dest)
{
Graphics.Blit(source, dest);
}
[Obsolete("Use Graphics.Blit(source, destination, material) instead")]
public static void BlitWithMaterial(Material material, RenderTexture source, RenderTexture dest)
{
Graphics.Blit(source, dest, material);
}
}
}

View File

@@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: 89a037199d11087f1100e2b844295342
MonoImporter:
serializedVersion: 2
defaultReferences:
- blitCopyShader: {fileID: 4800000, guid: 3338b5ea2f3cb594698fae65cf060346, type: 3}
- blitMultiplyShader: {fileID: 4800000, guid: 7034c801b78acab448cdcf845f7c352d,
type: 3}
- blitMultiply2XShader: {fileID: 4800000, guid: cde82987e0a884c4788c65f7b54390e8,
type: 3}
- blitAddShader: {fileID: 4800000, guid: c7515f214a63bdb42b6ae6335a00a8a4, type: 3}
- blitAddSmoothShader: {fileID: 4800000, guid: 7741a77a7c455d0418bc429bd508dc87,
type: 3}
- blitBlendShader: {fileID: 4800000, guid: f1cf7e9c98754c4429ff0f7cc1d9dd7b, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,261 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
public class PostEffectsBase : MonoBehaviour
{
protected bool supportHDRTextures = true;
protected bool supportDX11 = false;
protected bool isSupported = true;
private List<Material> createdMaterials = new List<Material> ();
protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create)
{
if (!s)
{
Debug.Log("Missing shader in " + ToString ());
enabled = false;
return null;
}
if (s.isSupported && m2Create && m2Create.shader == s)
return m2Create;
if (!s.isSupported)
{
NotSupported ();
Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!");
return null;
}
m2Create = new Material (s);
createdMaterials.Add (m2Create);
m2Create.hideFlags = HideFlags.DontSave;
return m2Create;
}
protected Material CreateMaterial (Shader s, Material m2Create)
{
if (!s)
{
Debug.Log ("Missing shader in " + ToString ());
return null;
}
if (m2Create && (m2Create.shader == s) && (s.isSupported))
return m2Create;
if (!s.isSupported)
{
return null;
}
m2Create = new Material (s);
createdMaterials.Add (m2Create);
m2Create.hideFlags = HideFlags.DontSave;
return m2Create;
}
void OnEnable ()
{
isSupported = true;
}
void OnDestroy ()
{
RemoveCreatedMaterials ();
}
private void RemoveCreatedMaterials ()
{
while (createdMaterials.Count > 0)
{
Material mat = createdMaterials[0];
createdMaterials.RemoveAt (0);
#if UNITY_EDITOR
DestroyImmediate (mat);
#else
Destroy(mat);
#endif
}
}
protected bool CheckSupport ()
{
return CheckSupport (false);
}
public virtual bool CheckResources ()
{
Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten.");
return isSupported;
}
protected void Start ()
{
CheckResources ();
}
protected bool CheckSupport (bool needDepth)
{
isSupported = true;
supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
if (!SystemInfo.supportsImageEffects)
{
NotSupported ();
return false;
}
if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth))
{
NotSupported ();
return false;
}
if (needDepth)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
return true;
}
protected bool CheckSupport (bool needDepth, bool needHdr)
{
if (!CheckSupport(needDepth))
return false;
if (needHdr && !supportHDRTextures)
{
NotSupported ();
return false;
}
return true;
}
public bool Dx11Support ()
{
return supportDX11;
}
protected void ReportAutoDisable ()
{
Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
}
// deprecated but needed for old effects to survive upgrading
bool CheckShader (Shader s)
{
Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package.");
if (!s.isSupported)
{
NotSupported ();
return false;
}
else
{
return false;
}
}
protected void NotSupported ()
{
enabled = false;
isSupported = false;
return;
}
protected void DrawBorder (RenderTexture dest, Material material)
{
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b6f4318ec6c2bf643a0f9edfeeaba0ec
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,188 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
class PostEffectsHelper : MonoBehaviour
{
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
Debug.Log("OnRenderImage in Helper called ...");
}
static void DrawLowLevelPlaneAlignedWithCamera (
float dist ,
RenderTexture source, RenderTexture dest ,
Material material ,
Camera cameraForProjectionMatrix )
{
// Make the destination texture the target for all rendering
RenderTexture.active = dest;
// Assign the source texture to a property from a shader
material.SetTexture("_MainTex", source);
bool invertY = true; // source.texelSize.y < 0.0f;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadIdentity();
GL.LoadProjectionMatrix(cameraForProjectionMatrix.projectionMatrix);
float fovYHalfRad = cameraForProjectionMatrix.fieldOfView * 0.5f * Mathf.Deg2Rad;
float cotangent = Mathf.Cos(fovYHalfRad) / Mathf.Sin(fovYHalfRad);
float asp = cameraForProjectionMatrix.aspect;
float x1 = asp/-cotangent;
float x2 = asp/cotangent;
float y1 = 1.0f/-cotangent;
float y2 = 1.0f/cotangent;
float sc = 1.0f; // magic constant (for now)
x1 *= dist * sc;
x2 *= dist * sc;
y1 *= dist * sc;
y2 *= dist * sc;
float z1 = -dist;
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
GL.Begin(GL.QUADS);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, z1);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, z1);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, z1);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, z1);
GL.End();
}
GL.PopMatrix();
}
static void DrawBorder (
RenderTexture dest ,
Material material )
{
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
static void DrawLowLevelQuad ( float x1, float x2, float y1, float y2, RenderTexture source, RenderTexture dest, Material material )
{
// Make the destination texture the target for all rendering
RenderTexture.active = dest;
// Assign the source texture to a property from a shader
material.SetTexture("_MainTex", source);
bool invertY = true; // source.texelSize.y < 0.0f;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
GL.Begin(GL.QUADS);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 50b03df8f04b5c441aaac5b7fccb4734
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,125 @@
using System;
using UnityEngine;
using Object = UnityEngine.Object;
// same as Triangles but creates quads instead which generally
// saves fillrate at the expense for more triangles to issue
namespace UnityStandardAssets.ImageEffects
{
class Quads
{
static Mesh[] meshes;
static int currentQuads = 0;
static bool HasMeshes ()
{
if (meshes == null)
return false;
foreach (Mesh m in meshes)
if (null == m)
return false;
return true;
}
public static void Cleanup ()
{
if (meshes == null)
return;
for (int i = 0; i < meshes.Length; i++)
{
if (null != meshes[i])
{
Object.DestroyImmediate (meshes[i]);
meshes[i] = null;
}
}
meshes = null;
}
public static Mesh[] GetMeshes ( int totalWidth, int totalHeight)
{
if (HasMeshes () && (currentQuads == (totalWidth * totalHeight))) {
return meshes;
}
int maxQuads = 65000 / 6;
int totalQuads = totalWidth * totalHeight;
currentQuads = totalQuads;
int meshCount = Mathf.CeilToInt ((1.0f * totalQuads) / (1.0f * maxQuads));
meshes = new Mesh [meshCount];
int i = 0;
int index = 0;
for (i = 0; i < totalQuads; i += maxQuads)
{
int quads = Mathf.FloorToInt (Mathf.Clamp ((totalQuads-i), 0, maxQuads));
meshes[index] = GetMesh (quads, i, totalWidth, totalHeight);
index++;
}
return meshes;
}
static Mesh GetMesh (int triCount, int triOffset, int totalWidth, int totalHeight)
{
var mesh = new Mesh ();
mesh.hideFlags = HideFlags.DontSave;
var verts = new Vector3[triCount * 4];
var uvs = new Vector2[triCount * 4];
var uvs2 = new Vector2[triCount * 4];
var tris = new int[triCount * 6];
for (int i = 0; i < triCount; i++)
{
int i4 = i * 4;
int i6 = i * 6;
int vertexWithOffset = triOffset + i;
float x = Mathf.Floor (vertexWithOffset % totalWidth) / totalWidth;
float y = Mathf.Floor (vertexWithOffset / totalWidth) / totalHeight;
Vector3 position = new Vector3 (x * 2 - 1, y * 2 - 1, 1.0f);
verts[i4 + 0] = position;
verts[i4 + 1] = position;
verts[i4 + 2] = position;
verts[i4 + 3] = position;
uvs[i4 + 0] = new Vector2 (0.0f, 0.0f);
uvs[i4 + 1] = new Vector2 (1.0f, 0.0f);
uvs[i4 + 2] = new Vector2 (0.0f, 1.0f);
uvs[i4 + 3] = new Vector2 (1.0f, 1.0f);
uvs2[i4 + 0] = new Vector2 (x, y);
uvs2[i4 + 1] = new Vector2 (x, y);
uvs2[i4 + 2] = new Vector2 (x, y);
uvs2[i4 + 3] = new Vector2 (x, y);
tris[i6 + 0] = i4 + 0;
tris[i6 + 1] = i4 + 1;
tris[i6 + 2] = i4 + 2;
tris[i6 + 3] = i4 + 1;
tris[i6 + 4] = i4 + 2;
tris[i6 + 5] = i4 + 3;
}
mesh.vertices = verts;
mesh.triangles = tris;
mesh.uv = uvs;
mesh.uv2 = uvs2;
return mesh;
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: a20852ce049f64e4695a48b6a354be83
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,69 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Other/Screen Overlay")]
public class ScreenOverlay : PostEffectsBase
{
public enum OverlayBlendMode
{
Additive = 0,
ScreenBlend = 1,
Multiply = 2,
Overlay = 3,
AlphaBlend = 4,
}
public OverlayBlendMode blendMode = OverlayBlendMode.Overlay;
public float intensity = 1.0f;
public Texture2D texture = null;
public Shader overlayShader = null;
private Material overlayMaterial = null;
public override bool CheckResources ()
{
CheckSupport (false);
overlayMaterial = CheckShaderAndCreateMaterial (overlayShader, overlayMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit (source, destination);
return;
}
Vector4 UV_Transform = new Vector4(1, 0, 0, 1);
#if UNITY_WP8
// WP8 has no OS support for rotating screen with device orientation,
// so we do those transformations ourselves.
if (Screen.orientation == ScreenOrientation.LandscapeLeft) {
UV_Transform = new Vector4(0, -1, 1, 0);
}
if (Screen.orientation == ScreenOrientation.LandscapeRight) {
UV_Transform = new Vector4(0, 1, -1, 0);
}
if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) {
UV_Transform = new Vector4(-1, 0, 0, -1);
}
#endif
overlayMaterial.SetVector("_UV_Transform", UV_Transform);
overlayMaterial.SetFloat ("_Intensity", intensity);
overlayMaterial.SetTexture ("_Overlay", texture);
Graphics.Blit (source, destination, overlayMaterial, (int) blendMode);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6f19108706fdce9469603d07980eb8ad
MonoImporter:
serializedVersion: 2
defaultReferences:
- texture: {instanceID: 0}
- overlayShader: {fileID: 4800000, guid: 8c81db0e527d24acc9bcec04e87781bd, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,151 @@
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Rendering/Sun Shafts")]
public class SunShafts : PostEffectsBase
{
public enum SunShaftsResolution
{
Low = 0,
Normal = 1,
High = 2,
}
public enum ShaftsScreenBlendMode
{
Screen = 0,
Add = 1,
}
public SunShaftsResolution resolution = SunShaftsResolution.Normal;
public ShaftsScreenBlendMode screenBlendMode = ShaftsScreenBlendMode.Screen;
public Transform sunTransform;
public int radialBlurIterations = 2;
public Color sunColor = Color.white;
public Color sunThreshold = new Color(0.87f,0.74f,0.65f);
public float sunShaftBlurRadius = 2.5f;
public float sunShaftIntensity = 1.15f;
public float maxRadius = 0.75f;
public bool useDepthTexture = true;
public Shader sunShaftsShader;
private Material sunShaftsMaterial;
public Shader simpleClearShader;
private Material simpleClearMaterial;
public override bool CheckResources () {
CheckSupport (useDepthTexture);
sunShaftsMaterial = CheckShaderAndCreateMaterial (sunShaftsShader, sunShaftsMaterial);
simpleClearMaterial = CheckShaderAndCreateMaterial (simpleClearShader, simpleClearMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnRenderImage (RenderTexture source, RenderTexture destination) {
if (CheckResources()==false) {
Graphics.Blit (source, destination);
return;
}
// we actually need to check this every frame
if (useDepthTexture)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
int divider = 4;
if (resolution == SunShaftsResolution.Normal)
divider = 2;
else if (resolution == SunShaftsResolution.High)
divider = 1;
Vector3 v = Vector3.one * 0.5f;
if (sunTransform)
v = GetComponent<Camera>().WorldToViewportPoint (sunTransform.position);
else
v = new Vector3(0.5f, 0.5f, 0.0f);
int rtW = source.width / divider;
int rtH = source.height / divider;
RenderTexture lrColorB;
RenderTexture lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);
// mask out everything except the skybox
// we have 2 methods, one of which requires depth buffer support, the other one is just comparing images
sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius );
sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));
sunShaftsMaterial.SetVector ("_SunThreshold", sunThreshold);
if (!useDepthTexture) {
#if UNITY_5_6_OR_NEWER
var format = GetComponent<Camera>().allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
#else
var format = GetComponent<Camera>().hdr ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
#endif
RenderTexture tmpBuffer = RenderTexture.GetTemporary (source.width, source.height, 0, format);
RenderTexture.active = tmpBuffer;
GL.ClearWithSkybox (false, GetComponent<Camera>());
sunShaftsMaterial.SetTexture ("_Skybox", tmpBuffer);
Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 3);
RenderTexture.ReleaseTemporary (tmpBuffer);
}
else {
Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 2);
}
// paint a small black small border to get rid of clamping problems
DrawBorder (lrDepthBuffer, simpleClearMaterial);
// radial blur:
radialBlurIterations = Mathf.Clamp (radialBlurIterations, 1, 4);
float ofs = sunShaftBlurRadius * (1.0f / 768.0f);
sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f));
sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));
for (int it2 = 0; it2 < radialBlurIterations; it2++ ) {
// each iteration takes 2 * 6 samples
// we update _BlurRadius each time to cheaply get a very smooth look
lrColorB = RenderTexture.GetTemporary (rtW, rtH, 0);
Graphics.Blit (lrDepthBuffer, lrColorB, sunShaftsMaterial, 1);
RenderTexture.ReleaseTemporary (lrDepthBuffer);
ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f;
sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );
lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);
Graphics.Blit (lrColorB, lrDepthBuffer, sunShaftsMaterial, 1);
RenderTexture.ReleaseTemporary (lrColorB);
ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f;
sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );
}
// put together:
if (v.z >= 0.0f)
sunShaftsMaterial.SetVector ("_SunColor", new Vector4 (sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity);
else
sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection !
sunShaftsMaterial.SetTexture ("_ColorBuffer", lrDepthBuffer);
Graphics.Blit (source, destination, sunShaftsMaterial, (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4);
RenderTexture.ReleaseTemporary (lrDepthBuffer);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 60e318a6043c1cb4a8ce1c8805bab930
MonoImporter:
serializedVersion: 2
defaultReferences:
- sunTransform: {instanceID: 0}
- sunShaftsShader: {fileID: 4800000, guid: d3b1c8c1036784176946f5cfbfb7fe4c, type: 3}
- simpleClearShader: {fileID: 4800000, guid: f688f89ed5eb847c5b19c934a0f1e772, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,112 @@
using System;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityStandardAssets.ImageEffects
{
class Triangles
{
private static Mesh[] meshes;
private static int currentTris = 0;
static bool HasMeshes()
{
if (meshes == null)
return false;
for (int i = 0; i < meshes.Length; i++)
if (null == meshes[i])
return false;
return true;
}
static void Cleanup()
{
if (meshes == null)
return;
for (int i = 0; i < meshes.Length; i++)
{
if (null != meshes[i])
{
Object.DestroyImmediate(meshes[i]);
meshes[i] = null;
}
}
meshes = null;
}
static Mesh[] GetMeshes(int totalWidth, int totalHeight)
{
if (HasMeshes() && (currentTris == (totalWidth * totalHeight)))
{
return meshes;
}
int maxTris = 65000 / 3;
int totalTris = totalWidth * totalHeight;
currentTris = totalTris;
int meshCount = Mathf.CeilToInt((1.0f * totalTris) / (1.0f * maxTris));
meshes = new Mesh[meshCount];
int i = 0;
int index = 0;
for (i = 0; i < totalTris; i += maxTris)
{
int tris = Mathf.FloorToInt(Mathf.Clamp((totalTris - i), 0, maxTris));
meshes[index] = GetMesh(tris, i, totalWidth, totalHeight);
index++;
}
return meshes;
}
static Mesh GetMesh(int triCount, int triOffset, int totalWidth, int totalHeight)
{
var mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
var verts = new Vector3[triCount * 3];
var uvs = new Vector2[triCount * 3];
var uvs2 = new Vector2[triCount * 3];
var tris = new int[triCount * 3];
for (int i = 0; i < triCount; i++)
{
int i3 = i * 3;
int vertexWithOffset = triOffset + i;
float x = Mathf.Floor(vertexWithOffset % totalWidth) / totalWidth;
float y = Mathf.Floor(vertexWithOffset / totalWidth) / totalHeight;
Vector3 position = new Vector3(x * 2 - 1, y * 2 - 1, 1.0f);
verts[i3 + 0] = position;
verts[i3 + 1] = position;
verts[i3 + 2] = position;
uvs[i3 + 0] = new Vector2(0.0f, 0.0f);
uvs[i3 + 1] = new Vector2(1.0f, 0.0f);
uvs[i3 + 2] = new Vector2(0.0f, 1.0f);
uvs2[i3 + 0] = new Vector2(x, y);
uvs2[i3 + 1] = new Vector2(x, y);
uvs2[i3 + 2] = new Vector2(x, y);
tris[i3 + 0] = i3 + 0;
tris[i3 + 1] = i3 + 1;
tris[i3 + 2] = i3 + 2;
}
mesh.vertices = verts;
mesh.triangles = tris;
mesh.uv = uvs;
mesh.uv2 = uvs2;
return mesh;
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 18b91636de2ba3445913e4cf38528dc8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:

View File

@@ -0,0 +1,6 @@
fileFormatVersion: 2
guid: b2145489f7c704db8acb14a52bddeee9
folderAsset: yes
DefaultImporter:
userData:
assetBundleName:

View File

@@ -0,0 +1,136 @@
Shader "Hidden/BlendModesOverlay" {
Properties {
_MainTex ("Screen Blended", 2D) = "" {}
_Overlay ("Color", 2D) = "grey" {}
}
CGINCLUDE
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv[2] : TEXCOORD0;
};
sampler2D _Overlay;
half4 _Overlay_ST;
sampler2D _MainTex;
half4 _MainTex_ST;
half _Intensity;
half4 _MainTex_TexelSize;
half4 _UV_Transform = half4(1, 0, 0, 1);
v2f vert( appdata_img v ) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv[0] = UnityStereoScreenSpaceUVAdjust(float2(
dot(v.texcoord.xy, _UV_Transform.xy),
dot(v.texcoord.xy, _UV_Transform.zw)
), _Overlay_ST);
#if UNITY_UV_STARTS_AT_TOP
if(_MainTex_TexelSize.y<0.0)
o.uv[0].y = 1.0-o.uv[0].y;
#endif
o.uv[1] = UnityStereoScreenSpaceUVAdjust(v.texcoord.xy, _MainTex_ST);
return o;
}
half4 fragAddSub (v2f i) : SV_Target {
half4 toAdd = tex2D(_Overlay, i.uv[0]) * _Intensity;
return tex2D(_MainTex, i.uv[1]) + toAdd;
}
half4 fragMultiply (v2f i) : SV_Target {
half4 toBlend = tex2D(_Overlay, i.uv[0]) * _Intensity;
return tex2D(_MainTex, i.uv[1]) * toBlend;
}
half4 fragScreen (v2f i) : SV_Target {
half4 toBlend = (tex2D(_Overlay, i.uv[0]) * _Intensity);
return 1-(1-toBlend)*(1-(tex2D(_MainTex, i.uv[1])));
}
half4 fragOverlay (v2f i) : SV_Target {
half4 m = (tex2D(_Overlay, i.uv[0]));// * 255.0;
half4 color = (tex2D(_MainTex, i.uv[1]));//* 255.0;
// overlay blend mode
//color.rgb = (color.rgb/255.0) * (color.rgb + ((2*m.rgb)/( 255.0 )) * (255.0-color.rgb));
//color.rgb /= 255.0;
/*
if (Target > ½) R = 1 - (1-2x(Target-½)) x (1-Blend)
if (Target <= ½) R = (2xTarget) x Blend
*/
float3 check = step(half3(0.5,0.5,0.5), color.rgb);
float3 result = 0;
result = check * (half3(1,1,1) - ( (half3(1,1,1) - 2*(color.rgb-0.5)) * (1-m.rgb)));
result += (1-check) * (2*color.rgb) * m.rgb;
return half4(lerp(color.rgb, result.rgb, (_Intensity)), color.a);
}
half4 fragAlphaBlend (v2f i) : SV_Target {
half4 toAdd = tex2D(_Overlay, i.uv[0]) ;
return lerp(tex2D(_MainTex, i.uv[1]), toAdd, toAdd.a * _Intensity);
}
ENDCG
Subshader {
ZTest Always Cull Off ZWrite Off
ColorMask RGB
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment fragAddSub
ENDCG
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment fragScreen
ENDCG
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment fragMultiply
ENDCG
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment fragOverlay
ENDCG
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment fragAlphaBlend
ENDCG
}
}
Fallback off
} // shader

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 8c81db0e527d24acc9bcec04e87781bd
ShaderImporter:
userData:

View File

@@ -0,0 +1,52 @@
Shader "Hidden/BlurEffectConeTap" {
Properties { _MainTex ("", any) = "" {} }
CGINCLUDE
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
half2 uv : TEXCOORD0;
half2 taps[4] : TEXCOORD1;
};
sampler2D _MainTex;
half4 _MainTex_TexelSize;
half4 _MainTex_ST;
half4 _BlurOffsets;
v2f vert( appdata_img v ) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord - _BlurOffsets.xy * _MainTex_TexelSize.xy; // hack, see BlurEffect.cs for the reason for this. let's make a new blur effect soon
#ifdef UNITY_SINGLE_PASS_STEREO
// we need to keep texel size correct after the uv adjustment.
o.taps[0] = UnityStereoScreenSpaceUVAdjust(o.uv + _MainTex_TexelSize * _BlurOffsets.xy * (1.0f / _MainTex_ST.xy), _MainTex_ST);
o.taps[1] = UnityStereoScreenSpaceUVAdjust(o.uv - _MainTex_TexelSize * _BlurOffsets.xy * (1.0f / _MainTex_ST.xy), _MainTex_ST);
o.taps[2] = UnityStereoScreenSpaceUVAdjust(o.uv + _MainTex_TexelSize * _BlurOffsets.xy * half2(1, -1) * (1.0f / _MainTex_ST.xy), _MainTex_ST);
o.taps[3] = UnityStereoScreenSpaceUVAdjust(o.uv - _MainTex_TexelSize * _BlurOffsets.xy * half2(1, -1) * (1.0f / _MainTex_ST.xy), _MainTex_ST);
#else
o.taps[0] = o.uv + _MainTex_TexelSize * _BlurOffsets.xy;
o.taps[1] = o.uv - _MainTex_TexelSize * _BlurOffsets.xy;
o.taps[2] = o.uv + _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);
o.taps[3] = o.uv - _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);
#endif
return o;
}
half4 frag(v2f i) : SV_Target {
half4 color = tex2D(_MainTex, i.taps[0]);
color += tex2D(_MainTex, i.taps[1]);
color += tex2D(_MainTex, i.taps[2]);
color += tex2D(_MainTex, i.taps[3]);
return color * 0.25;
}
ENDCG
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 57e6deea7c2924e22a5138e2b70bb4dc
ShaderImporter:
userData:

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a40c1b84cf7fe418bae97a29041b85a4

View File

@@ -0,0 +1,70 @@
// Calculates adaptation to minimum/maximum luminance values,
// based on "currently adapted" and "new values to adapt to"
// textures (both 1x1).
Shader "Hidden/Contrast Stretch Adaptation" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
_CurTex ("Base (RGB)", 2D) = "white" {}
}
Category {
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex; // currently adapted to
uniform sampler2D _CurTex; // new value to adapt to
uniform float4 _AdaptParams; // x=adaptLerp, y=limitMinimum, z=limitMaximum
half4 _MainTex_ST;
half4 _CurTex_ST;
float4 frag (v2f_img i) : SV_Target {
// value is: max, min
float2 valAdapted = tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST)).xy;
float2 valCur = tex2D(_CurTex, UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST)).xy;
// Calculate new adapted values: interpolate
// from valAdapted to valCur by script-supplied amount.
//
// Because we store adaptation levels in a simple 8 bit/channel
// texture, we might not have enough precision - the interpolation
// amount might be too small to change anything, and we'll never
// arrive at the needed values.
//
// So we make sure the change we do is at least 1/255th of the
// color range - this way we'll always change the value.
const float kMinChange = 1.0/255.0;
float2 delta = (valCur-valAdapted) * _AdaptParams.x;
delta.x = sign(delta.x) * max( kMinChange, abs(delta.x) );
delta.y = sign(delta.y) * max( kMinChange, abs(delta.y) );
float4 valNew;
valNew.xy = valAdapted + delta;
// Impose user limits on maximum/minimum values
valNew.x = max( valNew.x, _AdaptParams.z );
valNew.y = min( valNew.y, _AdaptParams.y );
// Optimization so that our final apply pass is faster:
// z = max-min (plus a small amount to prevent division by zero)
valNew.z = valNew.x - valNew.y + 0.01;
// w = min/(max-min)
valNew.w = valNew.y / valNew.z;
return valNew;
}
ENDCG
}
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 257bc83cbeb544540bd0e558aa9b1383
ShaderImporter:
userData:

View File

@@ -0,0 +1,56 @@
// Final pass in the contrast stretch effect: apply
// color stretch to the original image, based on currently
// adapted to minimum/maximum luminances.
Shader "Hidden/Contrast Stretch Apply" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
_AdaptTex ("Base (RGB)", 2D) = "white" {}
}
Category {
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv[2] : TEXCOORD0;
};
uniform sampler2D _MainTex;
uniform sampler2D _AdaptTex;
half4 _MainTex_ST;
v2f vert (appdata_img v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv[0] = MultiplyUV (UNITY_MATRIX_TEXTURE0, UnityStereoScreenSpaceUVAdjust(v.texcoord, _MainTex_ST));
o.uv[1] = float2(0.5,0.5);
return o;
}
float4 frag (v2f i) : SV_Target
{
float4 col = tex2D(_MainTex, i.uv[0]);
float4 adapted = tex2D(_AdaptTex, i.uv[1]);
float vmul = 1.0 / adapted.z;
float vadd = -adapted.w;
col.rgb = col.rgb * vmul + vadd;
return col;
}
ENDCG
}
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: f4901f25d4e1542589348bbb89563d8e
ShaderImporter:
userData:

View File

@@ -0,0 +1,36 @@
// Outputs luminance (grayscale) of the input image _MainTex
Shader "Hidden/Contrast Stretch Luminance" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
Category {
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
half4 _MainTex_ST;
float4 frag (v2f_img i) : SV_Target
{
float4 col = tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST));
col.rgb = Luminance(col.rgb) * (1+col.a*2);
return col;
}
ENDCG
}
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: befbb4b9c320b4b18a08ef7afb93b6c9
ShaderImporter:
userData:

View File

@@ -0,0 +1,66 @@
// Reduces input image (_MainTex) by 2x2.
// Outputs maximum value in R, minimum in G.
Shader "Hidden/Contrast Stretch Reduction" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
Category {
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 position : SV_POSITION;
float2 uv[4] : TEXCOORD0;
};
uniform sampler2D _MainTex;
half4 _MainTex_ST;
v2f vert (appdata_img v) {
v2f o;
o.position = UnityObjectToClipPos(v.vertex);
float2 uv = MultiplyUV (UNITY_MATRIX_TEXTURE0, v.texcoord);
// Compute UVs to sample 2x2 pixel block.
o.uv[0] = UnityStereoScreenSpaceUVAdjust(uv + float2(0,0), _MainTex_ST);
o.uv[1] = UnityStereoScreenSpaceUVAdjust(uv + float2(0,1), _MainTex_ST);
o.uv[2] = UnityStereoScreenSpaceUVAdjust(uv + float2(1,0), _MainTex_ST);
o.uv[3] = UnityStereoScreenSpaceUVAdjust(uv + float2(1,1), _MainTex_ST);
return o;
}
float4 frag (v2f i) : SV_Target
{
// Sample pixel block
float4 v00 = tex2D(_MainTex, i.uv[0]);
float2 v01 = tex2D(_MainTex, i.uv[1]).xy;
float2 v10 = tex2D(_MainTex, i.uv[2]).xy;
float2 v11 = tex2D(_MainTex, i.uv[3]).xy;
float4 res;
// output x: maximum of the four values
res.x = max( max(v00.x,v01.x), max(v10.x,v11.x) );
// output y: minimum of the four values
res.y = min( min(v00.y,v01.y), min(v10.y,v11.y) );
// output zw unchanged from the first pixel
res.zw = v00.zw;
return res;
}
ENDCG
}
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 57b33a14b6d5347c5a85c36f6cb3b280
ShaderImporter:
userData:

View File

@@ -0,0 +1,70 @@
Shader "Hidden/ContrastComposite" {
Properties {
_MainTex ("Base (RGB)", 2D) = "" {}
_MainTexBlurred ("Base Blurred (RGB)", 2D) = "" {}
}
// Shader code pasted into all further CGPROGRAM blocks
CGINCLUDE
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv[2] : TEXCOORD0;
};
sampler2D _MainTex;
sampler2D _MainTexBlurred;
float4 _MainTex_TexelSize;
half4 _MainTex_ST;
half4 _MainTexBlurred_ST;
float intensity;
float threshold;
v2f vert( appdata_img v ) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv[0] = UnityStereoScreenSpaceUVAdjust(v.texcoord.xy, _MainTexBlurred_ST);
o.uv[1] = UnityStereoScreenSpaceUVAdjust(v.texcoord.xy, _MainTex_ST);
#if UNITY_UV_STARTS_AT_TOP
if (_MainTex_TexelSize.y < 0)
o.uv[0].y = 1-o.uv[0].y;
#endif
return o;
}
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D (_MainTex, i.uv[1]);
half4 blurred = tex2D (_MainTexBlurred, (i.uv[0]));
half4 difference = color - blurred;
half4 signs = sign (difference);
half4 enhancement = saturate (abs(difference) - threshold) * signs * 1.0/(1.0-threshold);
color += enhancement * intensity;
return color;
}
ENDCG
Subshader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
}
Fallback off
} // shader

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 273404942eede4ea1883ca1fb2942507
ShaderImporter:
userData:

View File

@@ -0,0 +1,56 @@
Shader "Hidden/ConvertDepth" {
Properties {
_MainTex ("Base (RGB)", 2D) = "" {}
}
// Shader code pasted into all further CGPROGRAM blocks
CGINCLUDE
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
sampler2D_float _CameraDepthTexture;
half4 _CameraDepthTexture_ST;
v2f vert( appdata_img v )
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = UnityStereoScreenSpaceUVAdjust(v.texcoord.xy, _CameraDepthTexture_ST);
return o;
}
half4 frag(v2f i) : SV_Target
{
float d = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv.xy);
d = Linear01Depth(d);
if(d>0.99999)
return half4(1,1,1,1);
else
return EncodeFloatRGBA(d);
}
ENDCG
Subshader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
}
Fallback off
} // shader

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 14768d3865b1342e3a861fbe19ba2db2
ShaderImporter:
userData:

View File

@@ -0,0 +1,97 @@
Shader "Hidden/PrepareSunShaftsBlur" {
Properties {
_MainTex ("Base", 2D) = "" {}
_Skybox ("Skybox", 2D) = "" {}
}
CGINCLUDE
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
sampler2D _Skybox;
sampler2D_float _CameraDepthTexture;
uniform half _NoSkyBoxMask;
uniform half4 _SunPosition;
v2f vert (appdata_img v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord.xy;
return o;
}
half TransformColor (half4 skyboxValue) {
return max (skyboxValue.a, _NoSkyBoxMask * dot (skyboxValue.rgb, float3 (0.59,0.3,0.11)));
}
half4 frag (v2f i) : SV_Target {
float depthSample = SAMPLE_DEPTH_TEXTURE( _CameraDepthTexture, i.uv.xy);
half4 tex = tex2D (_MainTex, i.uv.xy);
depthSample = Linear01Depth (depthSample);
// consider maximum radius
half2 vec = _SunPosition.xy - i.uv.xy;
half dist = saturate (_SunPosition.w - length (vec.xy));
half4 outColor = 0;
// consider shafts blockers
if (depthSample > 0.99)
outColor = TransformColor (tex) * dist;
return outColor;
}
half4 fragNoDepthNeeded (v2f i) : SV_Target {
float4 sky = (tex2D (_Skybox, i.uv.xy));
float4 tex = (tex2D (_MainTex, i.uv.xy));
// consider maximum radius
half2 vec = _SunPosition.xy - i.uv.xy;
half dist = saturate (_SunPosition.w - length (vec));
half4 outColor = 0;
if (Luminance ( abs(sky.rgb - tex.rgb)) < 0.2)
outColor = TransformColor (sky) * dist;
return outColor;
}
ENDCG
Subshader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment fragNoDepthNeeded
ENDCG
}
}
Fallback off
} // shader

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: 9ad381ed8492840ab9f165df743e4826
ShaderImporter:
userData:

View File

@@ -0,0 +1,261 @@
/**
\author Michael Mara and Morgan McGuire, Casual Effects. 2015.
*/
#ifndef SCREEN_SPACE_RAYTRACE_INCLUDED
#define SCREEN_SPACE_RAYTRACE_INCLUDED
sampler2D_float _CameraDepthTexture;
float distanceSquared(float2 A, float2 B) {
A -= B;
return dot(A, A);
}
float distanceSquared(float3 A, float3 B) {
A -= B;
return dot(A, A);
}
void swap(inout float v0, inout float v1) {
float temp = v0;
v0 = v1;
v1 = temp;
}
bool isIntersecting(float rayZMin, float rayZMax, float sceneZ, float layerThickness) {
return (rayZMax >= sceneZ - layerThickness) && (rayZMin <= sceneZ);
}
void rayIterations(inout float2 P, inout float stepDirection, inout float end, inout int stepCount, inout int maxSteps, inout bool intersecting,
inout float sceneZ, inout float2 dP, inout float3 Q, inout float3 dQ, inout float k, inout float dk,
inout float rayZMin, inout float rayZMax, inout float prevZMaxEstimate, inout bool permute, inout float2 hitPixel,
inout float2 invSize, inout float layerThickness) {
UNITY_LOOP
for (;
( (P.x * stepDirection) <= end) &&
(stepCount < maxSteps) &&
(!intersecting);
P += dP, Q.z += dQ.z, k += dk, stepCount += 1) {
// The depth range that the ray covers within this loop iteration.
// Assume that the ray is moving in increasing z and swap if backwards.
rayZMin = prevZMaxEstimate;
//rayZMin = (dQ.z * -0.5 + Q.z) / (dk * -0.5 + k);
// Compute the value at 1/2 pixel into the future
rayZMax = (dQ.z * 0.5 + Q.z) / (dk * 0.5 + k);
prevZMaxEstimate = rayZMax;
if (rayZMin > rayZMax) { swap(rayZMin, rayZMax); }
// Undo the homogeneous operation to obtain the camera-space
// Q at each point
hitPixel = permute ? P.yx : P;
sceneZ = tex2Dlod(_CameraDepthTexture, float4(hitPixel * invSize,0,0)).r;
sceneZ = -LinearEyeDepth(sceneZ);
intersecting = isIntersecting(rayZMin, rayZMax, sceneZ, layerThickness);
} // pixel on ray
P -= dP, Q.z -= dQ.z, k -= dk;
}
/**
\param csOrigin must have z < -0.01, and project within the valid screen rectangle
\param stepRate Set to 1.0 by default, higher to step faster
*/
bool castDenseScreenSpaceRay
(float3 csOrigin,
float3 csDirection,
float4x4 projectToPixelMatrix,
float2 csZBufferSize,
float3 clipInfo,
float jitterFraction,
int maxSteps,
float layerThickness,
float maxRayTraceDistance,
out float2 hitPixel,
int stepRate,
bool refine,
out float3 csHitPoint,
out float stepCount) {
float2 invSize = float2(1.0 / csZBufferSize.x, 1.0 / csZBufferSize.y);
// Initialize to off screen
hitPixel = float2(-1, -1);
float nearPlaneZ = -0.01;
// Clip ray to a near plane in 3D (doesn't have to be *the* near plane, although that would be a good idea)
float rayLength = ((csOrigin.z + csDirection.z * maxRayTraceDistance) > nearPlaneZ) ?
((nearPlaneZ - csOrigin.z) / csDirection.z) :
maxRayTraceDistance;
float3 csEndPoint = csDirection * rayLength + csOrigin;
// Project into screen space
// This matrix has a lot of zeroes in it. We could expand
// out these multiplies to avoid multiplying by zero
// ...but 16 MADDs are not a big deal compared to what's ahead
float4 H0 = mul(projectToPixelMatrix, float4(csOrigin, 1.0));
float4 H1 = mul(projectToPixelMatrix, float4(csEndPoint, 1.0));
// There are a lot of divisions by w that can be turned into multiplications
// at some minor precision loss...and we need to interpolate these 1/w values
// anyway.
//
// Because the caller was required to clip to the near plane,
// this homogeneous division (projecting from 4D to 2D) is guaranteed
// to succeed.
float k0 = 1.0 / H0.w;
float k1 = 1.0 / H1.w;
// Screen-space endpoints
float2 P0 = H0.xy * k0;
float2 P1 = H1.xy * k1;
// Switch the original points to values that interpolate linearly in 2D:
float3 Q0 = csOrigin * k0;
float3 Q1 = csEndPoint * k1;
#if 1 // Clipping to the screen coordinates. We could simply modify maxSteps instead
float yMax = csZBufferSize.y - 0.5;
float yMin = 0.5;
float xMax = csZBufferSize.x - 0.5;
float xMin = 0.5;
// 2D interpolation parameter
float alpha = 0.0;
// P0 must be in bounds
if (P1.y > yMax || P1.y < yMin) {
float yClip = (P1.y > yMax) ? yMax : yMin;
float yAlpha = (P1.y - yClip) / (P1.y - P0.y); // Denominator is not zero, since P0 != P1 (or P0 would have been clipped!)
alpha = yAlpha;
}
// P0 must be in bounds
if (P1.x > xMax || P1.x < xMin) {
float xClip = (P1.x > xMax) ? xMax : xMin;
float xAlpha = (P1.x - xClip) / (P1.x - P0.x); // Denominator is not zero, since P0 != P1 (or P0 would have been clipped!)
alpha = max(alpha, xAlpha);
}
// These are all in homogeneous space, so they interpolate linearly
P1 = lerp(P1, P0, alpha);
k1 = lerp(k1, k0, alpha);
Q1 = lerp(Q1, Q0, alpha);
#endif
// We're doing this to avoid divide by zero (rays exactly parallel to an eye ray)
P1 = (distanceSquared(P0, P1) < 0.0001) ? P0 + float2(0.01, 0.01) : P1;
float2 delta = P1 - P0;
// Assume horizontal
bool permute = false;
if (abs(delta.x) < abs(delta.y)) {
// More-vertical line. Create a permutation that swaps x and y in the output
permute = true;
// Directly swizzle the inputs
delta = delta.yx;
P1 = P1.yx;
P0 = P0.yx;
}
// From now on, "x" is the primary iteration direction and "y" is the secondary one
float stepDirection = sign(delta.x);
float invdx = stepDirection / delta.x;
float2 dP = float2(stepDirection, invdx * delta.y);
// Track the derivatives of Q and k
float3 dQ = (Q1 - Q0) * invdx;
float dk = (k1 - k0) * invdx;
dP *= stepRate;
dQ *= stepRate;
dk *= stepRate;
P0 += dP * jitterFraction;
Q0 += dQ * jitterFraction;
k0 += dk * jitterFraction;
// Slide P from P0 to P1, (now-homogeneous) Q from Q0 to Q1, and k from k0 to k1
float3 Q = Q0;
float k = k0;
// We track the ray depth at +/- 1/2 pixel to treat pixels as clip-space solid
// voxels. Because the depth at -1/2 for a given pixel will be the same as at
// +1/2 for the previous iteration, we actually only have to compute one value
// per iteration.
float prevZMaxEstimate = csOrigin.z;
stepCount = 0.0;
float rayZMax = prevZMaxEstimate, rayZMin = prevZMaxEstimate;
float sceneZ = 100000;
// P1.x is never modified after this point, so pre-scale it by
// the step direction for a signed comparison
float end = P1.x * stepDirection;
bool intersecting = isIntersecting(rayZMin, rayZMax, sceneZ, layerThickness);
// We only advance the z field of Q in the inner loop, since
// Q.xy is never used until after the loop terminates
//int rayIterations = min(maxSteps, stepsToGetOffscreen);
float2 P = P0;
int originalStepCount = 0;
rayIterations(P, stepDirection, end, originalStepCount, maxSteps, intersecting,
sceneZ, dP, Q, dQ, k, dk,
rayZMin, rayZMax, prevZMaxEstimate, permute, hitPixel,
invSize, layerThickness);
stepCount = originalStepCount;
if (refine && intersecting && stepRate > 1) {
// We're going back a step.
P -= dP, Q.z -= dQ.z, k -= dk;
prevZMaxEstimate = Q.z / k;
rayZMin = prevZMaxEstimate;
rayZMax = prevZMaxEstimate;
intersecting = false;
int refinementStepCount = 0;
int refinementMaxSteps = stepRate;
float refinementConstant = 1.0 / stepRate;
dQ.z *= refinementConstant;
dP *= refinementConstant;
dk *= refinementConstant;
// Refinement
rayIterations(P, stepDirection, end, refinementStepCount, refinementMaxSteps, intersecting,
sceneZ, dP, Q, dQ, k, dk,
rayZMin, rayZMax, prevZMaxEstimate, permute, hitPixel,
invSize, layerThickness);
stepCount += refinementStepCount * refinementConstant - 1.0;
//stepCount = refinementStepCount;
intersecting = true;
}
// Loop only advanced the Z component. Now that we know where we are going
// update xy
Q.xy += dQ.xy * stepCount;
// Q is a vector, so we are trying to get by with 1 division instead of 3.
csHitPoint = Q * (1.0 / k);
return intersecting;
}
#endif // SCREEN_SPACE_RAYTRACE_INCLUDED

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 26c67b7245085cf438e3d42d50d94f55
timeCreated: 1425661779
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
Shader "Hidden/ShowAlphaChannel" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
_EdgeTex ("_EdgeTex", 2D) = "white" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform sampler2D _EdgeTex;
uniform float4 _MainTex_TexelSize;
float filterRadius;
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert( appdata_img v )
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord.xy;
return o;
}
half4 frag (v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.uv.xy);
half edges = color.a;
return edges;
}
ENDCG
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: da310021e2a4142429d95c537846dc38
ShaderImporter:
userData:

View File

@@ -0,0 +1,41 @@
Shader "Hidden/SimpleClear" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform float4 _MainTex_TexelSize;
struct v2f {
float4 pos : SV_POSITION;
};
v2f vert( appdata_img v )
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
half4 frag (v2f i) : SV_Target
{
return half4(0,0,0,0);
}
ENDCG
}
}
Fallback off
}

View File

@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: f688f89ed5eb847c5b19c934a0f1e772
ShaderImporter:
userData:

Some files were not shown because too many files have changed in this diff Show More