quantum-space-buddies/QSB/PlayerBodySetup/Remote/QSBDitheringAnimator.cs

76 lines
1.7 KiB
C#
Raw Normal View History

2022-08-27 18:44:52 +00:00
using QSB.Utility;
using System.Linq;
2022-02-25 07:13:31 +00:00
using UnityEngine;
2022-02-18 13:33:48 +00:00
using UnityEngine.Rendering;
2022-03-03 03:46:33 +00:00
namespace QSB.PlayerBodySetup.Remote;
2022-08-27 18:44:52 +00:00
[UsedInUnityProject]
2022-03-03 03:46:33 +00:00
public class QSBDitheringAnimator : MonoBehaviour
2022-02-18 13:33:48 +00:00
{
2022-03-03 03:46:33 +00:00
public bool FullyVisible => !enabled && OWMath.ApproxEquals(_visibleFraction, 1);
public bool FullyInvisible => !enabled && OWMath.ApproxEquals(_visibleFraction, 0);
2022-02-18 13:33:48 +00:00
2022-03-03 03:46:33 +00:00
private float _visibleTarget = 1;
private float _visibleFraction = 1;
private float _fadeRate;
private (OWRenderer Renderer, bool UpdateShadows)[] _renderers;
private void Awake()
{
_renderers = GetComponentsInChildren<Renderer>(true)
.Select(x => (x.gameObject.GetAddComponent<OWRenderer>(), x.shadowCastingMode != ShadowCastingMode.Off))
.ToArray();
enabled = false;
}
2022-03-03 03:46:33 +00:00
public void SetVisible(bool visible, float seconds = 0)
{
var visibleTarget = visible ? 1 : 0;
if (OWMath.ApproxEquals(visibleTarget, _visibleTarget))
{
2022-03-03 03:46:33 +00:00
return;
2022-02-25 07:13:31 +00:00
}
2022-02-18 13:33:48 +00:00
2022-03-03 03:46:33 +00:00
_visibleTarget = visibleTarget;
if (seconds != 0)
2022-02-18 13:33:48 +00:00
{
2022-03-03 03:46:33 +00:00
_fadeRate = 1 / seconds;
enabled = true;
}
2022-03-03 03:46:33 +00:00
else
2022-02-18 13:33:48 +00:00
{
2022-03-03 03:46:33 +00:00
_visibleFraction = _visibleTarget;
UpdateRenderers();
}
2022-03-03 03:46:33 +00:00
}
private void Update()
{
_visibleFraction = Mathf.MoveTowards(_visibleFraction, _visibleTarget, _fadeRate * Time.deltaTime);
if (OWMath.ApproxEquals(_visibleFraction, _visibleTarget))
{
_visibleFraction = _visibleTarget;
enabled = false;
}
UpdateRenderers();
}
2022-03-03 03:46:33 +00:00
private void UpdateRenderers()
{
foreach (var (renderer, updateShadows) in _renderers)
{
2022-03-03 03:46:33 +00:00
if (renderer == null)
2022-02-18 13:33:48 +00:00
{
2022-03-03 03:46:33 +00:00
continue;
}
2022-03-03 03:46:33 +00:00
renderer.SetDitherFade(1 - _visibleFraction);
if (updateShadows)
{
renderer._renderer.shadowCastingMode = FullyVisible ? ShadowCastingMode.On : ShadowCastingMode.Off;
2022-02-18 13:33:48 +00:00
}
}
}
2022-03-03 03:46:33 +00:00
}