using System.IO;
using UnityEngine;
using UnityEngine.Video;
namespace GrassCutter
{
///
/// A character's talking loops (Assets/StreamingAssets/Talk/<who>_<mood>.webm, made by Tools/director/talk_videos.py):
/// one player per mood, each looping into its own texture; the picture shows the one for the mood of the moment, the others
/// wait where they left off, so a change of mood is a cut, not a stall.
///
/// Unity's player drops the webm's alpha and shows the figure on the black it was filmed on. Every frame the shader
/// (Resources/Talk/TalkHolo) cuts the black away again, puts the figure over the room behind the character, and draws the
/// hologram: fades the call in with a sweep of light, scanlines
/// and glitches, and out the same way; while on, only faint scanlines are left.
///
public class TalkVideo
{
const float InTime = 0.8f, OutTime = 0.5f;
readonly VideoPlayer[] _players;
readonly RenderTexture[] _raw;
readonly RenderTexture _out;
readonly Material _mat;
int _on = -1;
float _appear, _target;
bool _clear = true;
/// The finished picture, the size of the window it fills.
public RenderTexture Rt => _out;
/// 0 gone .. 1 fully there.
public float Appear => _appear;
/// Called once the picture has faded right out after (false).
public System.Action Gone;
/// Called every frame the picture is drawn, with : for what fades along with it.
public System.Action Drawn;
/// The loops' width and height (the picture half).
/// The window's shape, in pixels to render.
/// Where the figure stands in the window, 0..1 from the bottom left; it fills it like ScaleAndCrop.
/// Resources/Talk/<bg>: the room behind, filling the window.
public TalkVideo(string who, string[] moods, int figW, int figH, int outW, int outH, Rect figRect, string bg)
{
var go = new GameObject("Talk " + who);
Object.DontDestroyOnLoad(go);
go.AddComponent().Owner = this;
_players = new VideoPlayer[moods.Length];
_raw = new RenderTexture[moods.Length];
for (int i = 0; i < moods.Length; i++)
{
var rt = new RenderTexture(figW, figH, 0, RenderTextureFormat.ARGB32) { name = $"Talk {who} {moods[i]}" };
rt.Create();
Clear(rt, Color.black);
var vp = go.AddComponent();
vp.playOnAwake = false;
vp.source = VideoSource.Url;
vp.url = Path.Combine(Application.streamingAssetsPath, "Talk", who + "_" + moods[i] + ".webm");
vp.isLooping = true;
vp.skipOnDrop = true;
vp.audioOutputMode = VideoAudioOutputMode.None;
vp.renderMode = VideoRenderMode.RenderTexture;
vp.targetTexture = rt;
vp.Prepare();
_players[i] = vp;
_raw[i] = rt;
}
_out = new RenderTexture(outW, outH, 0, RenderTextureFormat.ARGB32) { name = $"Talk {who}" };
_out.Create();
Clear(_out, Color.clear);
var shader = Resources.Load("Talk/TalkHolo");
_mat = new Material(shader) { hideFlags = HideFlags.DontSave };
var bgTex = Resources.Load("Talk/" + bg);
_mat.SetTexture("_BgTex", bgTex);
_mat.SetFloat("_HasBg", bgTex ? 1f : 0f);
_mat.SetVector("_FigST", Cover(figRect, outW, outH, figW, figH));
_mat.SetVector("_BgST", Cover(new Rect(0f, 0f, 1f, 1f), outW, outH, bgTex ? bgTex.width : outW, bgTex ? bgTex.height : outH));
_mat.SetVector("_Px", new Vector4(outW, outH, 0f, 0f));
}
/// uv in the window -> uv in a picture of srcW x srcH that fills (cropped, not squeezed).
static Vector4 Cover(Rect r, int outW, int outH, float srcW, float srcH)
{
float rw = r.width * outW, rh = r.height * outH;
float s = Mathf.Max(rw / srcW, rh / srcH);
float fx = rw / (srcW * s), fy = rh / (srcH * s);
float sx = fx / r.width, sy = fy / r.height;
return new Vector4(sx, sy, 0.5f - fx * 0.5f - r.x * sx, 0.5f - fy * 0.5f - r.y * sy);
}
static void Clear(RenderTexture rt, Color c)
{
var was = RenderTexture.active;
RenderTexture.active = rt;
GL.Clear(true, true, c);
RenderTexture.active = was;
}
/// Plays the loop for this mood (and only it).
public void Play(int mood)
{
mood = Mathf.Clamp(mood, 0, _players.Length - 1);
if (mood != _on)
{
if (_on >= 0) _players[_on].Pause();
_on = mood;
}
if (!_players[mood].isPlaying) _players[mood].Play();
}
/// Fades the call in (with the hologram's sweep) or out; out, the loop stops once it's gone.
public void Show(bool on)
{
_target = on ? 1f : 0f;
if (on && _on < 0) Play(0);
}
/// Gone at once, no fade (a film cuts in).
public void Cut()
{
_target = _appear = 0f;
Tick();
}
internal void Tick()
{
float dt = Time.unscaledDeltaTime;
_appear = Mathf.MoveTowards(_appear, _target, dt / (_target > _appear ? InTime : OutTime));
if (_appear <= 0f && _target <= 0f)
{
if (_clear) return;
_clear = true;
if (_on >= 0) _players[_on].Pause();
Clear(_out, Color.clear);
Drawn?.Invoke(0f);
Gone?.Invoke();
return;
}
_clear = false;
if (_on < 0) return;
_mat.SetFloat("_Appear", _appear);
_mat.SetFloat("_T", Time.unscaledTime);
Graphics.Blit(_raw[_on], _out, _mat);
Drawn?.Invoke(_appear);
}
/// The Director: calm (and pleased), stern (and worried), furious.
public static int BossMood(Mood m) => m == Mood.Angry ? 2 : m == Mood.Stern || m == Mood.Scared || m == Mood.Sad ? 1 : 0;
/// The assistant: cheerful, matter-of-fact, fed up.
public static int AssistantMood(Mood m) => m == Mood.Stern ? 1 : m == Mood.Angry || m == Mood.Scared || m == Mood.Sad ? 2 : 0;
/// The strongest of the eased moods.
public static Mood Strongest(float[] mood)
{
int best = 0;
for (int i = 1; i < mood.Length; i++) if (mood[i] > mood[best]) best = i;
return (Mood)best;
}
}
/// Draws a 's picture once a frame, after the players have had theirs.
public class TalkVideoTicker : MonoBehaviour
{
public TalkVideo Owner;
void LateUpdate() => Owner?.Tick();
}
}