using System.Linq;
using UnityEngine;
namespace Crosstales.RTVoice
{
/// Global cache for wrappers.
[ExecuteInEditMode]
[DisallowMultipleComponent]
[HelpURL("https://crosstales.com/media/data/assets/rtvoice/api/class_crosstales_1_1_r_t_voice_1_1_global_cache.html")]
public class GlobalCache : Crosstales.Common.Util.Singleton
{
#region Variables
[UnityEngine.Serialization.FormerlySerializedAsAttribute("ClipCacheSize")] [Header("Cache Settings"), Tooltip("Size of the clip cache in MB (default: 256)"), Range(16, 1024), SerializeField]
private int clipCacheSize = Util.Constants.DEFAULT_CACHE_SIZE_CLIPS;
///Dictionary with all cached clips.
public readonly System.Collections.Generic.Dictionary Clips = new System.Collections.Generic.Dictionary();
private readonly System.Collections.Generic.List clipKeys = new System.Collections.Generic.List();
private Transform tf;
#endregion
#region Properties
///Size of the clip cache in Bytes.
public int ClipCacheSize
{
get => clipCacheSize * Util.Constants.FACTOR_MB;
set => clipCacheSize = Mathf.Clamp(value / Util.Constants.FACTOR_MB, 1, Util.Constants.DEFAULT_MAX_CACHE_SIZE_CLIPS);
}
/// Current size of the clip cache in Bytes.
public int CurrentClipCacheSize => Clips.Sum(pair => pair.Value.samples * 2 * 4);
#endregion
#region MonoBehaviour methods
private void OnValidate()
{
if (clipCacheSize <= 16)
{
clipCacheSize = 16;
}
else if (clipCacheSize > Util.Constants.DEFAULT_MAX_CACHE_SIZE_CLIPS)
{
clipCacheSize = Util.Constants.DEFAULT_MAX_CACHE_SIZE_CLIPS;
}
}
protected override void OnApplicationQuit()
{
ClearCache();
base.OnApplicationQuit();
}
#endregion
#region Public methods
/// Resets this object.
//[RuntimeInitializeOnLoadMethod]
public static void ResetObject()
{
DeleteInstance();
}
/// Returns the AudioClip for a given key.
/// Key for the AudioClip.
/// AudioClip for the given key.
public AudioClip GetClip(Model.Wrapper key)
{
if (key != null)
{
Clips.TryGetValue(key, out AudioClip data);
return data;
}
return null;
}
/// Removes an AudioClip for a given key.
/// Key for the AudioClip.
public void RemoveClip(Model.Wrapper key)
{
if (key != null && Clips.ContainsKey(key))
{
Destroy(Clips[key]);
Clips.Remove(key);
clipKeys.Remove(key);
}
}
/// Adds an AudioClip for a given key.
/// Key for the AudioClip.
/// AudioClip for the key.
public void AddClip(Model.Wrapper key, AudioClip data)
{
if (key != null && data != null && !Clips.ContainsKey(key))
{
while (CurrentClipCacheSize >= ClipCacheSize)
{
RemoveClip(clipKeys[0]);
}
Clips.Add(key, data);
clipKeys.Add(key);
}
}
/// Clears the clips cache.
public void ClearClipCache()
{
Util.Context.NumberOfCachedSpeeches = 0;
Util.Context.NumberOfNonCachedSpeeches = 0;
foreach (System.Collections.Generic.KeyValuePair kvp in Clips)
{
Destroy(kvp.Value);
}
Clips.Clear();
clipKeys.Clear();
}
/// Clears the complete cache.
public void ClearCache()
{
ClearClipCache();
}
#endregion
}
}
// © 2020 crosstales LLC (https://www.crosstales.com)