This commit is contained in:
Caiyanpeng committed 2021-12-28 11:25:09 +08:00
1 parent a2b44262f7
commit 2b390717c2
130 files changed
+21774 -2581

No files matched your search

@@ -12,7 +12,7 @@ using System.Linq;
#endif
#endif
namespace Assets.Scripts.UI.UIEffect.Common
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Base class for effects that modify the generated Mesh.
@@ -27,10 +27,10 @@ namespace Assets.Scripts.UI.UIEffect.Common
#if TMP_PRESENT
static readonly List<Vector2> s_Uv0 = new List<Vector2> (4096);
static readonly List<Vector2> s_Uv1 = new List<Vector2> (4096);
#if UNITY_2017_1_OR_NEWER
#if UNITY_2017_1_OR_NEWER
static readonly List<Vector2> s_Uv2 = new List<Vector2> (4096);
static readonly List<Vector2> s_Uv3 = new List<Vector2> (4096);
#endif
#endif
static readonly List<Vector3> s_Vertices = new List<Vector3> (4096);
static readonly List<int> s_Indices = new List<int> (4096);
static readonly List<Vector3> s_Normals = new List<Vector3> (4096);
@@ -42,7 +42,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
static readonly List<UIVertex> s_UIVertices = new List<UIVertex> (4096);
static readonly List<BaseMeshEffect> s_TmpEffects = new List<BaseMeshEffect>(4);
#endif
static readonly Material[] s_EmptyMaterials = new Material[0];
static readonly Material [] s_EmptyMaterials = new Material [0];
//################################
@@ -51,12 +51,12 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// The Graphic attached to this GameObject.
/// </summary>
public Graphic graphic { get { Initialize(); return _graphic; } }
public Graphic graphic { get { Initialize (); return _graphic; } }
/// <summary>
/// The CanvasRenderer attached to this GameObject.
/// </summary>
public CanvasRenderer canvasRenderer { get { Initialize(); return _canvasRenderer; } }
public CanvasRenderer canvasRenderer { get { Initialize (); return _canvasRenderer; } }
#if TMP_PRESENT
/// <summary>
@@ -68,7 +68,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// The RectTransform attached to this GameObject.
/// </summary>
public RectTransform rectTransform { get { Initialize(); return _rectTransform; } }
public RectTransform rectTransform { get { Initialize (); return _rectTransform; } }
#if UNITY_5_6_OR_NEWER
/// <summary>
@@ -146,7 +146,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
#endif
if (graphic)
{
_materials[0] = graphic.material;
_materials [0] = graphic.material;
return _materials;
}
else
@@ -160,7 +160,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// Call used to modify mesh. (legacy)
/// </summary>
/// <param name="mesh">Mesh.</param>
public virtual void ModifyMesh(Mesh mesh)
public virtual void ModifyMesh (Mesh mesh)
{
}
@@ -168,14 +168,14 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// Call used to modify mesh.
/// </summary>
/// <param name="vh">VertexHelper.</param>
public virtual void ModifyMesh(VertexHelper vh)
public virtual void ModifyMesh (VertexHelper vh)
{
}
/// <summary>
/// Mark the vertices as dirty.
/// </summary>
public virtual void SetVerticesDirty()
public virtual void SetVerticesDirty ()
{
#if TMP_PRESENT
if (textMeshPro)
@@ -213,11 +213,11 @@ namespace Assets.Scripts.UI.UIEffect.Common
#endif
if (graphic)
{
graphic.SetVerticesDirty();
graphic.SetVerticesDirty ();
}
}
public void ShowTMProWarning(Shader shader, Shader mobileShader, Shader spriteShader, System.Action<Material> onCreatedMaterial)
public void ShowTMProWarning (Shader shader, Shader mobileShader, Shader spriteShader, System.Action<Material> onCreatedMaterial)
{
#if UNITY_EDITOR && TMP_PRESENT
if(!textMeshPro || !textMeshPro.fontSharedMaterial)
@@ -324,14 +324,14 @@ namespace Assets.Scripts.UI.UIEffect.Common
protected virtual bool isLegacyMeshModifier { get { return false; } }
protected virtual void Initialize()
protected virtual void Initialize ()
{
if (!_initialized)
{
_initialized = true;
_graphic = _graphic ?? GetComponent<Graphic>();
_canvasRenderer = _canvasRenderer ?? GetComponent<CanvasRenderer>();
_rectTransform = _rectTransform ?? GetComponent<RectTransform>();
_graphic = _graphic ?? GetComponent<Graphic> ();
_canvasRenderer = _canvasRenderer ?? GetComponent<CanvasRenderer> ();
_rectTransform = _rectTransform ?? GetComponent<RectTransform> ();
#if TMP_PRESENT
_textMeshPro = _textMeshPro ?? GetComponent<TMP_Text> ();
#endif
@@ -341,10 +341,10 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
protected override void OnEnable()
protected override void OnEnable ()
{
_initialized = false;
SetVerticesDirty();
SetVerticesDirty ();
#if TMP_PRESENT
if (textMeshPro)
{
@@ -366,7 +366,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
var canvas = graphic.canvas;
if (canvas && (canvas.additionalShaderChannels & channels) != channels)
{
Debug.LogWarningFormat(this, "Enable {1} of Canvas.additionalShaderChannels to use {0}.", GetType().Name, channels);
Debug.LogWarningFormat (this, "Enable {1} of Canvas.additionalShaderChannels to use {0}.", GetType ().Name, channels);
}
}
#endif
@@ -375,12 +375,12 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// This function is called when the behaviour becomes disabled () or inactive.
/// </summary>
protected override void OnDisable()
protected override void OnDisable ()
{
#if TMP_PRESENT
TMPro_EventManager.TEXT_CHANGED_EVENT.Remove (OnTextChanged);
#endif
SetVerticesDirty();
SetVerticesDirty ();
#if UNITY_EDITOR && TMP_PRESENT
if (graphic && textMeshPro)
@@ -394,7 +394,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// LateUpdate is called every frame, if the Behaviour is enabled.
/// </summary>
protected virtual void LateUpdate()
protected virtual void LateUpdate ()
{
#if TMP_PRESENT
if (textMeshPro)
@@ -411,18 +411,18 @@ namespace Assets.Scripts.UI.UIEffect.Common
/// <summary>
/// Callback for when properties have been changed by animation.
/// </summary>
protected override void OnDidApplyAnimationProperties()
protected override void OnDidApplyAnimationProperties ()
{
SetVerticesDirty();
SetVerticesDirty ();
}
#if UNITY_EDITOR
/// <summary>
/// This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
/// </summary>
protected override void OnValidate()
protected override void OnValidate ()
{
SetVerticesDirty();
SetVerticesDirty ();
}
#endif
@@ -434,7 +434,7 @@ namespace Assets.Scripts.UI.UIEffect.Common
CanvasRenderer _canvasRenderer;
RectTransform _rectTransform;
Graphic _graphic;
Material[] _materials = new Material[1];
Material [] _materials = new Material [1];
#if TMP_PRESENT
bool _isTextMeshProActive;
@@ -532,12 +532,12 @@ namespace Assets.Scripts.UI.UIEffect.Common
mesh.GetTangents (s_Tangents);
mesh.GetIndices (s_Indices, 0);
#if UNITY_2017_1_OR_NEWER
#if UNITY_2017_1_OR_NEWER
mesh.GetUVs (2, s_Uv2);
mesh.GetUVs (3, s_Uv3);
bool useUv2 = 0 < s_Uv2.Count;
bool useUv3 = 0 < s_Uv3.Count;
#endif
#endif
s_UIVertices.Clear();
UIVertex v = default(UIVertex);
@@ -547,12 +547,12 @@ namespace Assets.Scripts.UI.UIEffect.Common
v.color = s_Colors[i];
v.uv0 = s_Uv0[i];
v.uv1 = s_Uv1[i];
#if UNITY_2017_1_OR_NEWER
#if UNITY_2017_1_OR_NEWER
if (useUv2 && i < s_Uv2.Count)
v.uv2 = s_Uv2[i];
if (useUv3 && i < s_Uv3.Count)
v.uv3 = s_Uv3[i];
#endif
#endif
v.normal = s_Normals[i];
v.tangent = s_Tangents[i];
@@ -562,4 +562,4 @@ namespace Assets.Scripts.UI.UIEffect.Common
}
#endif
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: c52a957894a7bbf418d6b190bd7816a3
guid: 229ee7044e2514b0e9bd9fd40a2baa3a
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -0,0 +1,13 @@
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Blur effect mode.
/// </summary>
public enum BlurMode
{
None = 0,
FastBlur = 1,
MediumBlur = 2,
DetailBlur = 3,
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5645838b01af8764d8f381f04b62b9a2
timeCreated: 1528296875
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Color effect mode.
/// </summary>
public enum ColorMode
{
Multiply = 0,
Fill = 1,
Add = 2,
Subtract = 3,
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e6ba1e487e0a19644afde2bd5531bd04
timeCreated: 1528296875
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,112 @@
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Area for effect.
/// </summary>
public enum EffectArea
{
RectTransform,
Fit,
Character,
}
public static class EffectAreaExtensions
{
static readonly Rect rectForCharacter = new Rect(0, 0, 1, 1);
static readonly Vector2 [] splitedCharacterPosition = { Vector2.up, Vector2.one, Vector2.right, Vector2.zero };
/// <summary>
/// Gets effect for area.
/// </summary>
public static Rect GetEffectArea (this EffectArea area, VertexHelper vh, Rect rectangle, float aspectRatio = -1)
{
Rect rect = default(Rect);
switch (area)
{
case EffectArea.RectTransform:
rect = rectangle;
break;
case EffectArea.Character:
rect = rectForCharacter;
break;
case EffectArea.Fit:
// Fit to contents.
UIVertex vertex = default (UIVertex);
float xMin = float.MaxValue;
float yMin = float.MaxValue;
float xMax = float.MinValue;
float yMax = float.MinValue;
for (int i = 0; i < vh.currentVertCount; i++)
{
vh.PopulateUIVertex(ref vertex, i);
float x = vertex.position.x;
float y = vertex.position.y;
xMin = Mathf.Min(xMin, x);
yMin = Mathf.Min(yMin, y);
xMax = Mathf.Max(xMax, x);
yMax = Mathf.Max(yMax, y);
}
rect.Set (xMin, yMin, xMax - xMin, yMax - yMin);
break;
default:
rect = rectangle;
break;
}
if(0 < aspectRatio)
{
if (rect.width < rect.height)
{
rect.width = rect.height * aspectRatio;
}
else
{
rect.height = rect.width / aspectRatio;
}
}
return rect;
}
/// <summary>
/// Gets position factor for area.
/// </summary>
public static void GetPositionFactor (this EffectArea area, int index, Rect rect, Vector2 position, bool isText, bool isTMPro, out float x, out float y)
{
if (isText && area == EffectArea.Character)
{
index = isTMPro ? (index + 3) % 4 : index % 4;
x = splitedCharacterPosition [index].x;
y = splitedCharacterPosition [index].y;
}
else if (area == EffectArea.Fit)
{
x = Mathf.Clamp01 ((position.x - rect.xMin) / rect.width);
y = Mathf.Clamp01 ((position.y - rect.yMin) / rect.height);
}
else
{
x = Mathf.Clamp01 (position.x / rect.width + 0.5f);
y = Mathf.Clamp01 (position.y / rect.height + 0.5f);
}
}
/// <summary>
/// Normalize vertex position by local matrix.
/// </summary>
public static void GetNormalizedFactor (this EffectArea area, int index, Matrix2x3 matrix, Vector2 position, bool isText, out Vector2 nomalizedPos)
{
if (isText && area == EffectArea.Character)
{
nomalizedPos = matrix * splitedCharacterPosition [(index + 3) % 4];
}
else
{
nomalizedPos = matrix * position;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a78f43d1382a048a99411472ca714e1b
timeCreated: 1528636556
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,156 @@
using UnityEngine;
using System;
using System.Collections.Generic;
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Effect player.
/// </summary>
[Serializable]
public class EffectPlayer
{
//################################
// Public Members.
//################################
/// <summary>
/// Gets or sets a value indicating whether is playing.
/// </summary>
[Header("Effect Player")]
[Tooltip("Playing.")]
public bool play = false;
/// <summary>
/// Gets or sets the delay before looping.
/// </summary>
[Tooltip("Initial play delay.")]
[Range(0f, 10f)]
public float initialPlayDelay = 0;
/// <summary>
/// Gets or sets the duration.
/// </summary>
[Tooltip("Duration.")]
[Range(0.01f,10f)]
public float duration = 1;
/// <summary>
/// Gets or sets a value indicating whether can loop.
/// </summary>
[Tooltip("Loop.")]
public bool loop = false;
/// <summary>
/// Gets or sets the delay before looping.
/// </summary>
[Tooltip("Delay before looping.")]
[Range(0f,10f)]
public float loopDelay = 0;
/// <summary>
/// Gets or sets the update mode.
/// </summary>
[Tooltip("Update mode")]
public AnimatorUpdateMode updateMode = AnimatorUpdateMode.Normal;
static List<Action> s_UpdateActions;
/// <summary>
/// Register player.
/// </summary>
public void OnEnable(Action<float> callback = null)
{
if (s_UpdateActions == null)
{
s_UpdateActions = new List<Action>();
Canvas.willRenderCanvases += () =>
{
var count = s_UpdateActions.Count;
for (int i = 0; i < count; i++)
{
s_UpdateActions[i].Invoke();
}
};
}
s_UpdateActions.Add(OnWillRenderCanvases);
if (play)
{
_time = -initialPlayDelay;
}
else
{
_time = 0;
}
_callback = callback;
}
/// <summary>
/// Unregister player.
/// </summary>
public void OnDisable()
{
_callback = null;
s_UpdateActions.Remove(OnWillRenderCanvases);
}
/// <summary>
/// Start playing.
/// </summary>
public void Play(bool reset, Action<float> callback = null)
{
if (reset)
{
_time = 0;
}
play = true;
if (callback != null)
{
_callback = callback;
}
}
/// <summary>
/// Stop playing.
/// </summary>
public void Stop(bool reset)
{
if (reset)
{
_time = 0;
if (_callback != null)
{
_callback(_time);
}
}
play = false;
}
//################################
// Private Members.
//################################
float _time = 0;
Action<float> _callback;
void OnWillRenderCanvases()
{
if (!play || !Application.isPlaying || _callback == null)
{
return;
}
_time += updateMode == AnimatorUpdateMode.UnscaledTime
? Time.unscaledDeltaTime
: Time.deltaTime;
var current = _time / duration;
if (duration <= _time)
{
play = loop;
_time = loop ? -loopDelay : 0;
}
_callback(current);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 1656fb67110cd44298010d95c324e87a
timeCreated: 1528296875
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,95 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Assets.Scripts.UI.UIEffect
{
public class MaterialCache
{
public ulong hash { get; private set; }
public int referenceCount { get; private set; }
public Texture texture { get; private set; }
public Material material { get; private set; }
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
static void ClearCache()
{
foreach (var cache in materialCaches)
{
cache.material = null;
}
materialCaches.Clear();
}
#endif
public static List<MaterialCache> materialCaches = new List<MaterialCache>();
public static MaterialCache Register(ulong hash, Texture texture, System.Func<Material> onCreateMaterial)
{
var cache = materialCaches.FirstOrDefault(x => x.hash == hash);
if (cache != null && cache.material)
{
if (cache.material)
{
cache.referenceCount++;
}
else
{
materialCaches.Remove(cache);
cache = null;
}
}
if (cache == null)
{
cache = new MaterialCache()
{
hash = hash,
material = onCreateMaterial(),
referenceCount = 1,
};
materialCaches.Add(cache);
}
return cache;
}
public static MaterialCache Register(ulong hash, System.Func<Material> onCreateMaterial)
{
var cache = materialCaches.FirstOrDefault(x => x.hash == hash);
if (cache != null)
{
cache.referenceCount++;
}
if (cache == null)
{
cache = new MaterialCache()
{
hash = hash,
material = onCreateMaterial(),
referenceCount = 1,
};
materialCaches.Add(cache);
}
return cache;
}
public static void Unregister(MaterialCache cache)
{
if (cache == null)
{
return;
}
cache.referenceCount--;
if (cache.referenceCount <= 0)
{
MaterialCache.materialCaches.Remove(cache);
cache.material = null;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2160d2c55a6100642b6c7ba09df935da
timeCreated: 1528509206
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,126 @@
#if UNITY_EDITOR
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace Assets.Scripts.UI.UIEffect
{
public class MaterialResolver
{
static readonly StringBuilder s_StringBuilder = new StringBuilder();
static readonly Dictionary<string, Material> s_MaterialMap = new Dictionary<string, Material>();
public static Material GetOrGenerateMaterialVariant(Shader shader, params object[] append)
{
if (!shader)
{
return null;
}
Material mat = null;
string variantName = GetVariantName(shader, append);
if (s_MaterialMap.TryGetValue(variantName, out mat) && mat)
{
return mat;
}
string[] keywords = append.Where(x => 0 < (int)x)
.Select(x => x.ToString().ToUpper())
.ToArray();
mat = GetMaterial(shader, append);
if (mat)
{
if (!mat.shaderKeywords.OrderBy(x => x).SequenceEqual(keywords.OrderBy(x => x)))
{
mat.shaderKeywords = keywords;
EditorUtility.SetDirty(mat);
if (!Application.isPlaying)
{
EditorApplication.delayCall += AssetDatabase.SaveAssets;
}
}
return mat;
}
if (s_MaterialMap.TryGetValue(variantName, out mat) && mat)
{
return mat;
}
Debug.Log("Generate material : " + variantName);
mat = new Material(shader);
mat.shaderKeywords = keywords;
mat.name = variantName;
mat.hideFlags |= HideFlags.NotEditable;
s_MaterialMap[variantName] = mat;
bool isMainAsset = append.Cast<int>().All(x => x == 0);
EditorApplication.delayCall += () => SaveMaterial(mat, shader, isMainAsset);
return mat;
}
static void SaveMaterial(Material mat, Shader shader, bool isMainAsset)
{
string materialPath = GetDefaultMaterialPath(shader);
#if UIEFFECT_SEPARATE
string dir = Path.GetDirectoryName(materialPath);
materialPath = Path.Combine(Path.Combine(dir, "Separated"), mat.name + ".mat");
isMainAsset = true;
#endif
if (isMainAsset)
{
Directory.CreateDirectory(Path.GetDirectoryName(materialPath));
AssetDatabase.CreateAsset(mat, materialPath);
}
else
{
GetOrGenerateMaterialVariant(shader);
mat.hideFlags |= HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(mat, materialPath);
}
AssetDatabase.SaveAssets();
}
public static Material GetMaterial(Shader shader, params object[] append)
{
string variantName = GetVariantName(shader, append);
return AssetDatabase.FindAssets("t:Material " + Path.GetFileName(shader.name))
.Select(x => AssetDatabase.GUIDToAssetPath(x))
.SelectMany(x => AssetDatabase.LoadAllAssetsAtPath(x))
.OfType<Material>()
.FirstOrDefault(x => x.name == variantName);
}
public static string GetDefaultMaterialPath(Shader shader)
{
var name = Path.GetFileName(shader.name);
return AssetDatabase.FindAssets("t:Material " + name)
.Select(x => AssetDatabase.GUIDToAssetPath(x))
.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x) == name)
?? ("Assets/" + name + ".mat");
}
public static string GetVariantName(Shader shader, params object[] append)
{
s_StringBuilder.Length = 0;
#if UIEFFECT_SEPARATE
s_StringBuilder.Append("[Separated] ");
#endif
s_StringBuilder.Append(Path.GetFileName(shader.name));
foreach (object mode in append.Where(x=>0<(int)x))
{
s_StringBuilder.Append("-");
s_StringBuilder.Append(mode.ToString());
}
return s_StringBuilder.ToString();
}
}
}
#endif
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 70261fa2760d4c040ac28aebb1f155fb
timeCreated: 1528297353
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
using UnityEngine;
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Matrix2x3.
/// </summary>
public struct Matrix2x3
{
public float m00, m01, m02, m10, m11, m12;
public Matrix2x3(Rect rect, float cos, float sin)
{
const float center = 0.5f;
float dx = -rect.xMin / rect.width - center;
float dy = -rect.yMin / rect.height - center;
m00 = cos / rect.width;
m01 = -sin / rect.height;
m02 = dx * cos - dy * sin + center;
m10 = sin / rect.width;
m11 = cos / rect.height;
m12 = dx * sin + dy * cos + center;
}
public static Vector2 operator*(Matrix2x3 m, Vector2 v)
{
return new Vector2(
(m.m00 * v.x) + (m.m01 * v.y) + m.m02,
(m.m10 * v.x) + (m.m11 * v.y) + m.m12
);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5a9b962044ca64867b713425f7e5daab
timeCreated: 1527590245
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,60 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Packer
{
/// <summary>
/// Pack 4 low-precision [0-1] floats values to a float.
/// Each value [0-1] has 64 steps(6 bits).
/// </summary>
public static float ToFloat(float x, float y, float z, float w)
{
x = x < 0 ? 0 : 1 < x ? 1 : x;
y = y < 0 ? 0 : 1 < y ? 1 : y;
z = z < 0 ? 0 : 1 < z ? 1 : z;
w = w < 0 ? 0 : 1 < w ? 1 : w;
const int PRECISION = (1 << 6) - 1;
return (Mathf.FloorToInt(w * PRECISION) << 18)
+ (Mathf.FloorToInt(z * PRECISION) << 12)
+ (Mathf.FloorToInt(y * PRECISION) << 6)
+ Mathf.FloorToInt(x * PRECISION);
}
/// <summary>
/// Pack 4 low-precision [0-1] floats values to a float.
/// Each value [0-1] has 64 steps(6 bits).
/// </summary>
public static float ToFloat(Vector4 factor)
{
return ToFloat(Mathf.Clamp01(factor.x), Mathf.Clamp01(factor.y), Mathf.Clamp01(factor.z), Mathf.Clamp01(factor.w));
}
/// <summary>
/// Pack 1 middle-precision & 2 low-precision [0-1] floats values to a float.
/// z value [0-1] has 4096 steps(12 bits) and xy value [0-1] has 64 steps(6 bits).
/// </summary>
public static float ToFloat(float x, float y, float z)
{
x = x < 0 ? 0 : 1 < x ? 1 : x;
y = y < 0 ? 0 : 1 < y ? 1 : y;
z = z < 0 ? 0 : 1 < z ? 1 : z;
const int PRECISION = (1 << 8) - 1;
return (Mathf.FloorToInt(z * PRECISION) << 16)
+ (Mathf.FloorToInt(y * PRECISION) << 8)
+ Mathf.FloorToInt(x * PRECISION);
}
/// <summary>
/// Pack 2 low-precision [0-1] floats values to a float.
/// Each value [0-1] has 4096 steps(12 bits).
/// </summary>
public static float ToFloat(float x, float y)
{
x = x < 0 ? 0 : 1 < x ? 1 : x;
y = y < 0 ? 0 : 1 < y ? 1 : y;
const int PRECISION = (1 << 12) - 1;
return (Mathf.FloorToInt(y * PRECISION) << 12)
+ Mathf.FloorToInt(x * PRECISION);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b4970b3a69d3b472b8d66c1d92ec7bad
timeCreated: 1527590285
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,190 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using System;
namespace Assets.Scripts.UI.UIEffect
{
public interface IParameterTexture
{
int parameterIndex { get; set; }
ParameterTexture ptex { get; }
}
/// <summary>
/// Parameter texture.
/// </summary>
[System.Serializable]
public class ParameterTexture
{
//################################
// Public Members.
//################################
/// <summary>
/// Initializes a new instance of the <see cref="Assets.Scripts.UI.UIEffect.ParameterTexture"/> class.
/// </summary>
/// <param name="channels">Channels.</param>
/// <param name="instanceLimit">Instance limit.</param>
/// <param name="propertyName">Property name.</param>
public ParameterTexture(int channels, int instanceLimit, string propertyName)
{
_propertyName = propertyName;
_channels = ((channels - 1) / 4 + 1) * 4;
_instanceLimit = ((instanceLimit - 1) / 2 + 1) * 2;
_data = new byte[_channels * _instanceLimit];
_stack = new Stack<int>(_instanceLimit);
for (int i = 1; i < _instanceLimit + 1; i++)
{
_stack.Push(i);
}
}
/// <summary>
/// Register the specified target.
/// </summary>
/// <param name="target">Target.</param>
public void Register(IParameterTexture target)
{
Initialize();
if (target.parameterIndex <= 0 && 0 < _stack.Count)
{
target.parameterIndex = _stack.Pop();
// Debug.LogFormat("<color=green>@@@ Register {0} : {1}</color>", target, target.parameterIndex);
}
}
/// <summary>
/// Unregister the specified target.
/// </summary>
/// <param name="target">Target.</param>
public void Unregister(IParameterTexture target)
{
if (0 < target.parameterIndex)
{
// Debug.LogFormat("<color=red>@@@ Unregister {0} : {1}</color>", target, target.parameterIndex);
_stack.Push(target.parameterIndex);
target.parameterIndex = 0;
}
}
/// <summary>
/// Sets the data.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="channelId">Channel identifier.</param>
/// <param name="value">Value.</param>
public void SetData(IParameterTexture target, int channelId, byte value)
{
int index = (target.parameterIndex - 1) * _channels + channelId;
if (0 < target.parameterIndex && _data[index] != value)
{
_data[index] = value;
_needUpload = true;
}
}
/// <summary>
/// Sets the data.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="channelId">Channel identifier.</param>
/// <param name="value">Value.</param>
public void SetData(IParameterTexture target, int channelId, float value)
{
SetData(target, channelId, (byte)(Mathf.Clamp01(value) * 255));
}
/// <summary>
/// Registers the material.
/// </summary>
/// <param name="mat">Mat.</param>
public void RegisterMaterial(Material mat)
{
if (_propertyId == 0)
{
_propertyId = Shader.PropertyToID(_propertyName);
}
if (mat)
{
mat.SetTexture(_propertyId, _texture);
}
}
/// <summary>
/// Gets the index of the normalized.
/// </summary>
/// <returns>The normalized index.</returns>
/// <param name="target">Target.</param>
public float GetNormalizedIndex(IParameterTexture target)
{
return ((float)target.parameterIndex - 0.5f) / _instanceLimit;
}
//################################
// Private Members.
//################################
Texture2D _texture;
bool _needUpload;
int _propertyId;
readonly string _propertyName;
readonly int _channels;
readonly int _instanceLimit;
readonly byte[] _data;
readonly Stack<int> _stack;
static List<Action> updates;
/// <summary>
/// Initialize this instance.
/// </summary>
void Initialize()
{
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying && UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
#endif
if (updates == null)
{
updates = new List<Action>();
Canvas.willRenderCanvases += () =>
{
var count = updates.Count;
for (int i = 0; i < count; i++)
{
updates[i].Invoke();
}
};
}
if (!_texture)
{
bool isLinear = QualitySettings.activeColorSpace == ColorSpace.Linear;
_texture = new Texture2D(_channels / 4, _instanceLimit, TextureFormat.RGBA32, false, isLinear);
_texture.filterMode = FilterMode.Point;
_texture.wrapMode = TextureWrapMode.Clamp;
updates.Add(UpdateParameterTexture);
_needUpload = true;
}
}
void UpdateParameterTexture()
{
if (_needUpload && _texture)
{
_needUpload = false;
_texture.LoadRawTextureData(_data);
_texture.Apply(false, false);
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 65eafa89b3a3a494a99e185423ba6cad
timeCreated: 1533006319
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Shadow effect style.
/// </summary>
public enum ShadowStyle
{
None = 0,
Shadow,
Outline,
Outline8,
Shadow3,
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b0eda5bf10146491c9cfe6a31c66f9a7
timeCreated: 1528296875
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Effect mode.
/// </summary>
public enum EffectMode
{
None = 0,
Grayscale = 1,
Sepia = 2,
Nega = 3,
Pixel = 4,
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 092769547c242d74cbad96631a00963f
timeCreated: 1528296875
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,165 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scripts.UI.UIEffect
{
/// <summary>
/// Abstract effect base for UI.
/// </summary>
[DisallowMultipleComponent]
public abstract class UIEffectBase : BaseMeshEffect, IParameterTexture
#if UNITY_EDITOR
, ISerializationCallbackReceiver
#endif
{
protected static readonly Vector2[] splitedCharacterPosition = { Vector2.up, Vector2.one, Vector2.right, Vector2.zero };
protected static readonly List<UIVertex> tempVerts = new List<UIVertex>();
[HideInInspector]
[SerializeField] int m_Version;
[SerializeField] protected Material m_EffectMaterial;
/// <summary>
/// Gets or sets the parameter index.
/// </summary>
public int parameterIndex { get; set; }
/// <summary>
/// Gets the parameter texture.
/// </summary>
public virtual ParameterTexture ptex { get { return null; } }
/// <summary>
/// Gets target graphic for effect.
/// </summary>
public Graphic targetGraphic { get { return graphic; } }
/// <summary>
/// Gets material for effect.
/// </summary>
public Material effectMaterial { get { return m_EffectMaterial; } }
#if UNITY_EDITOR
protected override void Reset()
{
m_Version = 300;
OnValidate();
}
/// <summary>
/// Raises the validate event.
/// </summary>
protected override void OnValidate()
{
base.OnValidate ();
var mat = GetMaterial();
if (m_EffectMaterial != mat)
{
m_EffectMaterial = mat;
UnityEditor.EditorUtility.SetDirty(this);
}
ModifyMaterial();
SetVerticesDirty ();
SetDirty ();
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
UnityEditor.EditorApplication.delayCall += UpgradeIfNeeded;
}
protected bool IsShouldUpgrade(int expectedVersion)
{
if (m_Version < expectedVersion)
{
Debug.LogFormat(gameObject, "<b>{0}({1})</b> has been upgraded: <i>version {2} -> {3}</i>", name, GetType().Name, m_Version, expectedVersion);
m_Version = expectedVersion;
//UnityEditor.EditorApplication.delayCall += () =>
{
UnityEditor.EditorUtility.SetDirty(this);
if (!Application.isPlaying && gameObject && gameObject.scene.IsValid())
{
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(gameObject.scene);
}
}
;
return true;
}
return false;
}
protected virtual void UpgradeIfNeeded()
{
}
/// <summary>
/// Gets the material.
/// </summary>
/// <returns>The material.</returns>
protected virtual Material GetMaterial()
{
return null;
}
#endif
/// <summary>
/// Modifies the material.
/// </summary>
public virtual void ModifyMaterial()
{
targetGraphic.material = isActiveAndEnabled ? m_EffectMaterial : null;
}
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
protected override void OnEnable()
{
base.OnEnable ();
if (ptex != null)
{
ptex.Register(this);
}
ModifyMaterial();
SetVerticesDirty();
SetDirty();
}
/// <summary>
/// This function is called when the behaviour becomes disabled () or inactive.
/// </summary>
protected override void OnDisable()
{
base.OnDisable ();
ModifyMaterial ();
SetVerticesDirty();
if (ptex != null)
{
ptex.Unregister(this);
}
}
/// <summary>
/// Mark the UIEffect as dirty.
/// </summary>
protected virtual void SetDirty()
{
SetVerticesDirty();
}
protected override void OnDidApplyAnimationProperties()
{
SetDirty();
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e8b7ed62cf1444b4ebfc5e5338bc6682
timeCreated: 1485321967
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: