diff --git a/.gitignore b/.gitignore index dfcfd56..a57fdbb 100644 --- a/.gitignore +++ b/.gitignore @@ -137,6 +137,9 @@ _TeamCity* .axoCover/* !.axoCover/settings.json +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + # Visual Studio code coverage results *.coverage *.coveragexml @@ -347,4 +350,4 @@ healthchecksdb MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder -.ionide/ +.ionide/ \ No newline at end of file diff --git a/ChartPlugin/Core/ChartCreator.cs b/ChartPlugin/Core/ChartCreator.cs new file mode 100644 index 0000000..c593c9f --- /dev/null +++ b/ChartPlugin/Core/ChartCreator.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BS_Utils.Gameplay; +using DigitalRuby.Tween; +using SongChartVisualizer.Utilities; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace SongChartVisualizer.Core +{ + public class ChartCreator : MonoBehaviour + { + public class NpsInfo + { + public float nps; + public float fromTime; + public float toTime; + + public NpsInfo(float nps, float fromTime, float toTime) + { + this.nps = nps; + this.fromTime = fromTime; + this.toTime = toTime; + } + } + + private LevelData _mainGameSceneSetupData; + private BeatmapData _beatmapData; + private AudioTimeSyncController _audioTimeSyncController; + private List _npsSections; + private WindowGraph _windowGraph; + + private AssetBundle _assetBundle; + private bool _isInitialized; + private bool _isFinished; + private NpsInfo _currentSection; + private int _currentSectionIdx; + private GameObject _selfCursor; + private int _hardestSectionIdx; + private Canvas _canvas; + private TextMeshProUGUI _text; + + private void Start() + { + _audioTimeSyncController = Resources.FindObjectsOfTypeAll().FirstOrDefault(); + _mainGameSceneSetupData = BS_Utils.Plugin.LevelData; + _beatmapData = _mainGameSceneSetupData?.GameplayCoreSceneSetupData?.difficultyBeatmap?.beatmapData; + + if (_beatmapData != null) + { + //Logger.log.Debug("There are " + _beatmapData.notesCount + " notes"); + //Logger.log.Debug("There are " + _beatmapData.beatmapLinesData.Length + " lines"); + var songDuration = _mainGameSceneSetupData?.GameplayCoreSceneSetupData?.difficultyBeatmap?.level?.beatmapLevelData?.audioClip?.length ?? -1f; + if (songDuration >= 0) + { + _npsSections = GetNpsSections(); + for (var i = 0; i < _npsSections.Count; i++) + { + var npsInfos = _npsSections[i]; + Logger.log.Debug($"Nps at section {i + 1}: {npsInfos.nps} (from [{npsInfos.fromTime}] to [{npsInfos.toTime}])"); + } + Logger.log.Debug("Loading assetbundle.."); + var assembly = Assembly.GetExecutingAssembly(); + using (var stream = assembly.GetManifestResourceStream("SongChartVisualizer.UI.linegraph")) + _assetBundle = AssetBundle.LoadFromStream(stream); + if (!_assetBundle) + Logger.log.Warn("Failed to load AssetBundle! The chart may not work properly.."); + else + { + var prefab = _assetBundle.LoadAsset("LineGraph"); + var sprite = _assetBundle.LoadAsset("Circle"); + var go = Instantiate(prefab, transform); + //go.transform.Find("Background").GetComponent().material = BeatSaberMarkupLanguage.Utilities.ImageResources.NoGlowMat; + //go.transform.Find("Background").GetComponent().enabled = true; + go.transform.Translate(0.04f, 0, 0); + _windowGraph = go.AddComponent(); + _windowGraph.circleSprite = sprite; + _windowGraph.transform.localScale /= 10; + var npsValues = _npsSections.Select(info => info.nps).ToList(); + _windowGraph.ShowGraph(npsValues, false); + _currentSectionIdx = 0; + _currentSection = _npsSections[_currentSectionIdx]; + var highestValue = _npsSections.Max(info => info.nps); + _hardestSectionIdx = _npsSections.FindIndex(info => Math.Abs(info.nps - highestValue) < 0.001f); + PrepareWarningText(); + CreateSelfCursor(Color.green); + _canvas.enabled = Plugin.config.Value.PeakWarning && _currentSectionIdx + 1 == _hardestSectionIdx; + if (_canvas.enabled) + FadeInText(_text, _currentSection.toTime * 0.2f); + _isInitialized = true; + } + } + } + } + + private void OnDestroy() + { + _assetBundle.Unload(true); + } + + private void PrepareWarningText() + { + _canvas = new GameObject("DiffWarningCanvas").AddComponent(); + _canvas.renderMode = RenderMode.WorldSpace; + _canvas.transform.position = new Vector3(0, 2.25f, 3.5f); + _canvas.transform.localScale /= 100; + var rectTransform = _canvas.transform as RectTransform; + if (rectTransform != null) + rectTransform.sizeDelta = new Vector2(140, 50); + _text = Utils.CreateText((RectTransform)_canvas.transform, + "", + new Vector2()); + _text.alignment = TextAlignmentOptions.Center; + _text.fontSize = 16f; + _text.alpha = 0f; + _canvas.enabled = false; + } + + private static void FadeInText(TMP_Text text, float t) + { + text.gameObject.Tween("FadeInText" + text.gameObject.GetInstanceID(), 0, 1, t, + TweenScaleFunctions.Linear, tween => { text.alpha = tween.CurrentValue; }); + } + + private void CreateSelfCursor(Color cursorColor) + { + _selfCursor = new GameObject("SelfCursor"); + _selfCursor.transform.SetParent(_windowGraph.GraphContainer, false); + var image = _selfCursor.AddComponent(); + image.sprite = _windowGraph.circleSprite; + image.useSpriteMesh = true; + image.color = cursorColor; + var rectTransform = _selfCursor.GetComponent(); + rectTransform.sizeDelta = new Vector2(11, 11); + var dotPos = _windowGraph.DotObjects[_currentSectionIdx].GetComponent().position; + dotPos.z -= 0.001f; + _selfCursor.transform.position = dotPos; + } + + private void Update() + { + if (_audioTimeSyncController && _isInitialized && !_isFinished) + { + if (_currentSection.toTime < _audioTimeSyncController.songTime) + { + _currentSectionIdx += 1; + var oldState = _canvas.enabled; + _canvas.enabled = Plugin.config.Value.PeakWarning && _currentSectionIdx + 1 == _hardestSectionIdx; + if (_currentSectionIdx + 1 >= _npsSections.Count) + { + _isFinished = true; + return; + } + _currentSection = _npsSections[_currentSectionIdx]; + if (Plugin.config.Value.PeakWarning && !oldState && _canvas && _canvas.enabled) + FadeInText(_text, (_currentSection.toTime - _audioTimeSyncController.songTime) * 0.2f); + } + var dotPos = Vector3.Lerp(_windowGraph.DotObjects[_currentSectionIdx].GetComponent().position, + _windowGraph.DotObjects[_currentSectionIdx + 1].GetComponent().position, + (_audioTimeSyncController.songTime - _currentSection.fromTime) / (_currentSection.toTime - _currentSection.fromTime)); + dotPos.z -= 0.001f; + _selfCursor.transform.position = dotPos; + if (Plugin.config.Value.PeakWarning && _canvas && _canvas.enabled) + _text.text = $"You're about to reach the peak difficulty in {_currentSection.toTime - _audioTimeSyncController.songTime:F1} seconds!"; + } + } + + private List GetNpsSections() + { + var npsSections = new List(); + var songDuration = _mainGameSceneSetupData?.GameplayCoreSceneSetupData?.difficultyBeatmap?.level?.beatmapLevelData?.audioClip?.length ?? -1f; + if (!(songDuration >= 0)) return npsSections; + var notes = new List(); + + notes = _beatmapData.beatmapLinesData.Aggregate(notes, (current, beatmapLineData) => current.Concat(beatmapLineData.beatmapObjectsData) + .Where(data => data.beatmapObjectType == BeatmapObjectType.Note).ToList()); + notes.Sort((s1, s2) => s1.time.CompareTo(s2.time)); + if (notes.Count > 0) + { + var tempNoteCount = 0; + var startingTime = notes[0].time; + npsSections.Add(new NpsInfo(0, 0, startingTime)); + for (var i = 0; i < notes.Count; ++i) + { + tempNoteCount += 1; + if (i > 0 && (i % 25 == 0 || i + 1 == notes.Count)) + { + var nps = tempNoteCount / (notes[i].time - startingTime); + if (!float.IsInfinity(nps)) + npsSections.Add(new NpsInfo(nps, startingTime, notes[i].time)); + tempNoteCount = 0; + startingTime = notes[i].time; + } + } + npsSections.Add(new NpsInfo(0, startingTime, songDuration)); + } + + return npsSections; + } + } +} \ No newline at end of file diff --git a/ChartPlugin/Core/WindowGraph.cs b/ChartPlugin/Core/WindowGraph.cs new file mode 100644 index 0000000..5dceeec --- /dev/null +++ b/ChartPlugin/Core/WindowGraph.cs @@ -0,0 +1,210 @@ +/* + ------------------- Code Monkey ------------------- + + Thank you for downloading this package + I hope you find it useful in your projects + If you have any questions let me know + Cheers! + + unitycodemonkey.com + -------------------------------------------------- + */ + +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +public class WindowGraph : MonoBehaviour +{ + public Sprite circleSprite; + private RectTransform _labelTemplateX; + private RectTransform _labelTemplateY; + private RectTransform _dashTemplateX; + private RectTransform _dashTemplateY; + + public RectTransform GraphContainer { get; private set; } + public List DotObjects { get; private set; } + public List LinkObjects { get; private set; } + public List LabelXObjects { get; private set; } + public List LabelYObjects { get; private set; } + public List DashXObjects { get; private set; } + public List DashYObjects { get; private set; } + + private void Awake() + { + GraphContainer = transform.Find("GraphContainer").GetComponent(); + _labelTemplateX = GraphContainer.Find("LabelTemplateX").GetComponent(); + _labelTemplateY = GraphContainer.Find("LabelTemplateY").GetComponent(); + _dashTemplateX = GraphContainer.Find("DashTemplateX").GetComponent(); + _dashTemplateY = GraphContainer.Find("DashTemplateY").GetComponent(); + + DotObjects = new List(); + LinkObjects = new List(); + LabelXObjects = new List(); + LabelYObjects = new List(); + DashXObjects = new List(); + DashYObjects = new List(); + } + + public void ShowGraph(List valueList, bool makeDotsVisible = true, bool makeLinksVisible = true, + bool makeOriginZero = false, int maxVisibleValueAmount = -1, + Func getAxisLabelX = null, Func getAxisLabelY = null) + { + if (getAxisLabelX == null) + getAxisLabelX = delegate(float _i) { return _i.ToString(); }; + if (getAxisLabelY == null) + getAxisLabelY = delegate(float _f) { return Mathf.RoundToInt(_f).ToString(); }; + + if (maxVisibleValueAmount <= 0) + maxVisibleValueAmount = valueList.Count; + + if (DotObjects != null) + { + foreach (var go in DotObjects) + Destroy(go); + DotObjects.Clear(); + } + if (LinkObjects != null) + { + foreach (var go in LinkObjects) + Destroy(go); + LinkObjects.Clear(); + } + if (LabelXObjects != null) + { + foreach (var go in LabelXObjects) + Destroy(go); + LabelXObjects.Clear(); + } + if (LabelYObjects != null) + { + foreach (var go in LabelYObjects) + Destroy(go); + LabelYObjects.Clear(); + } + if (DashXObjects != null) + { + foreach (var go in DashXObjects) + Destroy(go); + DashXObjects.Clear(); + } + if (DashYObjects != null) + { + foreach (var go in DashYObjects) + Destroy(go); + DashYObjects.Clear(); + } + + var graphWidth = GraphContainer.sizeDelta.x; + var graphHeight = GraphContainer.sizeDelta.y; + + var yMaximum = valueList[0]; + var yMinimum = valueList[0]; + + for (var i = Mathf.Max(valueList.Count - maxVisibleValueAmount, 0); i < valueList.Count; i++) + { + var value = valueList[i]; + if (value > yMaximum) + yMaximum = value; + if (value < yMinimum) + yMinimum = value; + } + + var yDifference = yMaximum - yMinimum; + if (yDifference <= 0) + yDifference = 5f; + yMaximum = yMaximum + (yDifference * 0.2f); + yMinimum = yMinimum - (yDifference * 0.2f); + + if (makeOriginZero) + yMinimum = 0f; // Start the graph at zero + + var xSize = graphWidth / (maxVisibleValueAmount + 1); + var xIndex = 0; + + GameObject lastCircleGameObject = null; + for (var i = Mathf.Max(valueList.Count - maxVisibleValueAmount, 0); i < valueList.Count; i++) + { + var xPosition = xSize + xIndex * xSize; + var yPosition = (valueList[i] - yMinimum) / (yMaximum - yMinimum) * graphHeight; + var circleGameObject = CreateCircle(new Vector2(xPosition, yPosition), makeDotsVisible); + DotObjects.Add(circleGameObject); + if (lastCircleGameObject != null) + { + var dotConnectionGameObject = CreateDotConnection(lastCircleGameObject.GetComponent().anchoredPosition, + circleGameObject.GetComponent().anchoredPosition, + makeLinksVisible); + LinkObjects.Add(dotConnectionGameObject); + } + lastCircleGameObject = circleGameObject; + + var labelX = Instantiate(_labelTemplateX); + labelX.SetParent(GraphContainer, false); + labelX.gameObject.SetActive(true); + labelX.anchoredPosition = new Vector2(xPosition, -7f); + labelX.GetComponent().text = getAxisLabelX(i); + LabelXObjects.Add(labelX.gameObject); + + var dashX = Instantiate(_dashTemplateX); + dashX.SetParent(GraphContainer, false); + dashX.gameObject.SetActive(true); + dashX.anchoredPosition = new Vector2(yPosition, -3); + DashXObjects.Add(dashX.gameObject); + + xIndex++; + } + + var separatorCount = 10; + for (var i = 0; i <= separatorCount; i++) + { + var labelY = Instantiate(_labelTemplateY); + labelY.SetParent(GraphContainer, false); + labelY.gameObject.SetActive(true); + var normalizedValue = i * 1f / separatorCount; + labelY.anchoredPosition = new Vector2(-7f, normalizedValue * graphHeight); + labelY.GetComponent().text = getAxisLabelY(yMinimum + (normalizedValue * (yMaximum - yMinimum))); + LabelYObjects.Add(labelY.gameObject); + + var dashY = Instantiate(_dashTemplateY); + dashY.SetParent(GraphContainer, false); + dashY.gameObject.SetActive(true); + dashY.anchoredPosition = new Vector2(-4f, normalizedValue * graphHeight); + DashYObjects.Add(dashY.gameObject); + } + } + + private GameObject CreateCircle(Vector2 anchoredPosition, bool makeDotsVisible) + { + var gameObject = new GameObject("Circle", typeof(Image)); + gameObject.transform.SetParent(GraphContainer, false); + var image = gameObject.GetComponent(); + image.sprite = circleSprite; + image.useSpriteMesh = true; + image.enabled = makeDotsVisible; + var rectTransform = gameObject.GetComponent(); + rectTransform.anchoredPosition = anchoredPosition; + rectTransform.sizeDelta = new Vector2(8, 8); + rectTransform.anchorMin = new Vector2(0, 0); + rectTransform.anchorMax = new Vector2(0, 0); + return gameObject; + } + + private GameObject CreateDotConnection(Vector2 dotPositionA, Vector2 dotPositionB, bool makeLinkVisible) + { + var gameObject = new GameObject("DotConnection", typeof(Image)); + gameObject.transform.SetParent(GraphContainer, false); + var image = gameObject.GetComponent(); + image.color = new Color(1, 1, 1, .5f); + image.enabled = makeLinkVisible; + var rectTransform = gameObject.GetComponent(); + var dir = (dotPositionB - dotPositionA).normalized; + var distance = Vector2.Distance(dotPositionA, dotPositionB); + rectTransform.anchorMin = new Vector2(0, 0); + rectTransform.anchorMax = new Vector2(0, 0); + rectTransform.sizeDelta = new Vector2(distance, 2f); + rectTransform.anchoredPosition = dotPositionA + dir * distance * .5f; + rectTransform.localEulerAngles = new Vector3(0, 0, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg); + return gameObject; + } +} \ No newline at end of file diff --git a/ChartPlugin/Logger.cs b/ChartPlugin/Logger.cs new file mode 100644 index 0000000..df0f77f --- /dev/null +++ b/ChartPlugin/Logger.cs @@ -0,0 +1,9 @@ +using IPALogger = IPA.Logging.Logger; + +namespace SongChartVisualizer +{ + internal static class Logger + { + public static IPALogger log { get; set; } + } +} diff --git a/ChartPlugin/Models/Float3.cs b/ChartPlugin/Models/Float3.cs new file mode 100644 index 0000000..1e2bebc --- /dev/null +++ b/ChartPlugin/Models/Float3.cs @@ -0,0 +1,32 @@ +using UnityEngine; + +namespace SongChartVisualizer.Models +{ + public class Float3 + { + public float x; + public float y; + public float z; + + public Float3() { } + + public Float3(Float3 float3) : this(float3.x, float3.y, float3.z) { } + + public Float3(float x, float y, float z) + { + this.x = x; + this.y = y; + this.z = z; + } + + /// + /// Converts the PluginConfig.StoreableFloatVector3 to a UnityEngine.Vector3 format + /// + public static Vector3 ToVector3(Float3 float3) => new Vector3() + { + x = float3.x, + y = float3.y, + z = float3.z + }; + } +} diff --git a/ChartPlugin/Plugin.cs b/ChartPlugin/Plugin.cs new file mode 100644 index 0000000..f1cde55 --- /dev/null +++ b/ChartPlugin/Plugin.cs @@ -0,0 +1,79 @@ +using System.Collections; +using BeatSaberMarkupLanguage; +using BeatSaberMarkupLanguage.FloatingScreen; +using BeatSaberMarkupLanguage.Settings; +using BS_Utils.Utilities; +using IPA; +using IPA.Config; +using IPA.Utilities; +using SongChartVisualizer.Core; +using SongChartVisualizer.Models; +using SongChartVisualizer.UI.ViewControllers; +using SongChartVisualizer.Utilities; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.UI; +using Config = IPA.Config.Config; +using IPALogger = IPA.Logging.Logger; + +namespace SongChartVisualizer +{ + public class Plugin : IBeatSaberPlugin + { + internal static Ref config; + internal static IConfigProvider configProvider; + + public void Init(IPALogger logger, [Config.Prefer("json")] IConfigProvider cfgProvider) + { + Logger.log = logger; + BSEvents.menuSceneLoadedFresh += OnMenuSceneLoadedFresh; + BSEvents.gameSceneLoaded += OnGameSceneActive; + configProvider = cfgProvider; + + config = cfgProvider.MakeLink((p, v) => { + if (v.Value == null || v.Value.RegenerateConfig) + p.Store(v.Value = new PluginConfig() { RegenerateConfig = false }); + config = v; + }); + } + + private static void OnMenuSceneLoadedFresh() + { + BSMLSettings.instance.AddSettingsMenu("Song Chart Visualizer", "SongChartVisualizer.UI.Views.settings.bsml", SettingsController.instance); + } + + private static IEnumerator ShowFloating() + { + yield return new WaitForEndOfFrame(); + var is360Level = BS_Utils.Plugin.LevelData?.GameplayCoreSceneSetupData?.difficultyBeatmap?.beatmapData?.spawnRotationEventsCount > 0; + var pos = is360Level ? Float3.ToVector3(config.Value.Chart360LevelPosition) : Float3.ToVector3(config.Value.ChartStandardLevelPosition); + var rot = is360Level + ? Quaternion.Euler(Float3.ToVector3(config.Value.Chart360LevelRotation)) + : Quaternion.Euler(Float3.ToVector3(config.Value.ChartStandardLevelRotation)); + var floatingScreen = FloatingScreen.CreateFloatingScreen(new Vector2(105, 65), false, pos, rot); + floatingScreen.SetRootViewController(BeatSaberUI.CreateViewController(), true); + floatingScreen.GetComponent().enabled = false; + floatingScreen.gameObject.AddComponent(); + } + + private static void OnGameSceneActive() + { + if (config.Value.EnablePlugin) + new UnityTask(ShowFloating()); + } + + public void OnApplicationStart() { } + + public void OnApplicationQuit() { } + + public void OnFixedUpdate() { } + + public void OnUpdate() { } + + public void OnActiveSceneChanged(Scene prevScene, Scene nextScene) { } + + public void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode) { } + + public void OnSceneUnloaded(Scene scene) { } + } +} \ No newline at end of file diff --git a/ChartPlugin/PluginConfig.cs b/ChartPlugin/PluginConfig.cs new file mode 100644 index 0000000..286f89c --- /dev/null +++ b/ChartPlugin/PluginConfig.cs @@ -0,0 +1,15 @@ +using SongChartVisualizer.Models; + +namespace SongChartVisualizer +{ + internal class PluginConfig + { + public bool RegenerateConfig = true; + public bool EnablePlugin = true; + public bool PeakWarning = true; + public Float3 ChartStandardLevelPosition = new Float3(0, -0.4f, 2.25f); + public Float3 ChartStandardLevelRotation = new Float3(35, 0, 0); + public Float3 Chart360LevelPosition = new Float3(0, 3.5f, 3); + public Float3 Chart360LevelRotation = new Float3(-30, 0, 0); + } +} diff --git a/ChartPlugin/Properties/AssemblyInfo.cs b/ChartPlugin/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9f6571a --- /dev/null +++ b/ChartPlugin/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SongChartVisualizer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("HP Inc.")] +[assembly: AssemblyProduct("SongChartVisualizer")] +[assembly: AssemblyCopyright("Copyright © HP Inc. 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("64a2a30b-9dc5-44ce-90e4-a790ca13a124")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.3")] +[assembly: AssemblyFileVersion("1.0.3")] diff --git a/ChartPlugin/SongChartVisualizer.csproj b/ChartPlugin/SongChartVisualizer.csproj new file mode 100644 index 0000000..9beabdc --- /dev/null +++ b/ChartPlugin/SongChartVisualizer.csproj @@ -0,0 +1,127 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {64A2A30B-9DC5-44CE-90E4-A790CA13A124} + Library + Properties + SongChartVisualizer + SongChartVisualizer + v4.7.2 + 512 + $(SolutionDir)=C:\ + portable + + + true + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Libs\0Harmony.1.2.0.1.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Plugins\BSML.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Plugins\BS_Utils.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\HMLib.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\HMUI.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\IPA.Loader.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\MainAssembly.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Libs\Newtonsoft.Json.12.0.0.0.dll + + + + + + + + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\Unity.TextMeshPro.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.dll + + + False + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.AssetBundleModule.dll + + + False + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.AudioModule.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.CoreModule.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.UI.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.UIElementsModule.dll + + + ..\..\..\..\..\Program Files\Steam\steamapps\common\Beat Saber\Beat Saber_Data\Managed\UnityEngine.UIModule.dll + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + + + + Designer + + + + + copy "SongChartVisualizer.dll" "D:\Program Files\Steam\steamapps\common\Beat Saber\Plugins" + + \ No newline at end of file diff --git a/ChartPlugin/UI/ViewControllers/ChartViewController.cs b/ChartPlugin/UI/ViewControllers/ChartViewController.cs new file mode 100644 index 0000000..9c802d2 --- /dev/null +++ b/ChartPlugin/UI/ViewControllers/ChartViewController.cs @@ -0,0 +1,9 @@ +using BeatSaberMarkupLanguage.ViewControllers; + +namespace SongChartVisualizer.UI.ViewControllers +{ + public class ChartViewController : BSMLResourceViewController + { + public override string ResourceName => "SongChartVisualizer.UI.Views.ChartView.bsml"; + } +} diff --git a/ChartPlugin/UI/ViewControllers/SettingsController.cs b/ChartPlugin/UI/ViewControllers/SettingsController.cs new file mode 100644 index 0000000..adebefe --- /dev/null +++ b/ChartPlugin/UI/ViewControllers/SettingsController.cs @@ -0,0 +1,161 @@ +using System.Collections.Generic; +using BeatSaberMarkupLanguage.Attributes; +using BeatSaberMarkupLanguage.Parser; +using SongChartVisualizer.Models; +using UnityEngine; + +namespace SongChartVisualizer.UI.ViewControllers +{ + public class SettingsController : PersistentSingleton + { + [UIParams] + private BSMLParserParams parserParams; + + private Float3 _stdPos = new Float3(); + private Float3 _stdRot = new Float3(); + private Float3 _noStdPos = new Float3(); + private Float3 _noStdRot = new Float3(); + + [UIValue("enabled-bool")] + public bool enabledValue + { + get => Plugin.config.Value.EnablePlugin; + set => Plugin.config.Value.EnablePlugin = value; + } + + [UIValue("peak-warning-bool")] + public bool peakWarningValue + { + get => Plugin.config.Value.PeakWarning; + set => Plugin.config.Value.PeakWarning = value; + } + + [UIValue("std-panel-x-pos-float")] + public float stdPanelXPosValue + { + get => Plugin.config.Value.ChartStandardLevelPosition.x; + set => _stdPos = new Float3(value, _stdPos.y, _stdPos.z); + } + + [UIValue("std-panel-y-pos-float")] + public float stdPanelYPosValue + { + get => Plugin.config.Value.ChartStandardLevelPosition.y; + set => _stdPos = new Float3(_stdPos.x, value, _stdPos.z); + } + + [UIValue("std-panel-z-pos-float")] + public float stdPanelZPosValue + { + get => Plugin.config.Value.ChartStandardLevelPosition.z; + set => _stdPos = new Float3(_stdPos.x, _stdPos.y, value); + } + + [UIValue("std-panel-x-rot-float")] + public float stdPanelXRotValue + { + get => Plugin.config.Value.ChartStandardLevelRotation.x; + set => _stdRot = new Float3(value, _stdRot.y, _stdRot.z); + } + + [UIValue("std-panel-y-rot-float")] + public float stdPanelYRotValue + { + get => Plugin.config.Value.ChartStandardLevelRotation.y; + set => _stdRot = new Float3(_stdRot.x, value, _stdRot.z); + } + + [UIValue("std-panel-z-rot-float")] + public float stdPanelZRotValue + { + get => Plugin.config.Value.ChartStandardLevelRotation.z; + set => _stdRot = new Float3(_stdRot.x, _stdRot.y, value); + } + + [UIValue("no-std-panel-x-pos-float")] + public float noStdPanelXPosValue + { + get => Plugin.config.Value.Chart360LevelPosition.x; + set => _noStdPos = new Float3(value, _noStdPos.y, _noStdPos.z); + } + + [UIValue("no-std-panel-y-pos-float")] + public float noStdPanelYPosValue + { + get => Plugin.config.Value.Chart360LevelPosition.y; + set => _noStdPos = new Float3(_noStdPos.x, value, _noStdPos.z); + } + + [UIValue("no-std-panel-z-pos-float")] + public float noStdPanelZPosValue + { + get => Plugin.config.Value.Chart360LevelPosition.z; + set => _noStdPos = new Float3(_noStdPos.x, _noStdPos.y, value); + } + + [UIValue("no-std-panel-x-rot-float")] + public float noStdPanelXRotValue + { + get => Plugin.config.Value.Chart360LevelRotation.x; + set => _noStdRot = new Float3(value, _noStdRot.y, _noStdRot.z); + } + + [UIValue("no-std-panel-y-rot-float")] + public float noStdPanelYRotValue + { + get => Plugin.config.Value.Chart360LevelRotation.y; + set => _noStdRot = new Float3(_noStdRot.x, value, _noStdRot.z); + } + + [UIValue("no-std-panel-z-rot-float")] + public float noStdPanelZRotValue + { + get => Plugin.config.Value.Chart360LevelRotation.z; + set => _noStdRot = new Float3(_noStdRot.x, _noStdRot.y, value); + } + + [UIObject("std-pos-x-field")] public GameObject stdPosXField; + [UIObject("std-pos-y-field")] public GameObject stdPosYField; + [UIObject("std-pos-z-field")] public GameObject stdPosZField; + [UIObject("std-rot-x-field")] public GameObject stdRotXField; + [UIObject("std-rot-y-field")] public GameObject stdRotYField; + [UIObject("std-rot-z-field")] public GameObject stdRotZField; + [UIObject("no-std-pos-x-field")] public GameObject noStdPosXField; + [UIObject("no-std-pos-y-field")] public GameObject noStdPosYField; + [UIObject("no-std-pos-z-field")] public GameObject noStdPosZField; + [UIObject("no-std-rot-x-field")] public GameObject noStdRotXField; + [UIObject("no-std-rot-y-field")] public GameObject noStdRotYField; + [UIObject("no-std-rot-z-field")] public GameObject noStdRotZField; + + private static void ResizeValuePicker(GameObject go) + { + if (go == null) return; + var rectPicker = go.transform.Find("ValuePicker")?.GetComponent(); + if (rectPicker) + rectPicker.sizeDelta = new Vector2(25, rectPicker.sizeDelta.y); + } + + [UIAction("#post-parse")] + internal void Setup() + { + var list = new List { + stdPosXField, stdPosYField, stdPosZField, stdRotXField, stdRotYField, stdRotZField, + noStdPosXField, noStdPosYField, noStdPosZField, noStdRotXField, noStdRotYField, noStdRotZField + }; + foreach (var go in list) + ResizeValuePicker(go); + } + + [UIAction("#apply")] + public void OnApply() + { + Plugin.config.Value.EnablePlugin = enabledValue; + Plugin.config.Value.PeakWarning = peakWarningValue; + Plugin.config.Value.ChartStandardLevelPosition = _stdPos; + Plugin.config.Value.ChartStandardLevelRotation = _stdRot; + Plugin.config.Value.Chart360LevelPosition = _noStdPos; + Plugin.config.Value.Chart360LevelRotation = _noStdRot; + Plugin.configProvider.Store(Plugin.config.Value); + } + } +} diff --git a/ChartPlugin/UI/Views/ChartView.bsml b/ChartPlugin/UI/Views/ChartView.bsml new file mode 100644 index 0000000..913dd3f --- /dev/null +++ b/ChartPlugin/UI/Views/ChartView.bsml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/ChartPlugin/UI/Views/settings.bsml b/ChartPlugin/UI/Views/settings.bsml new file mode 100644 index 0000000..c1144ff --- /dev/null +++ b/ChartPlugin/UI/Views/settings.bsml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ChartPlugin/UI/linegraph b/ChartPlugin/UI/linegraph new file mode 100644 index 0000000..96d60d1 Binary files /dev/null and b/ChartPlugin/UI/linegraph differ diff --git a/ChartPlugin/Utilities/TaskManager.cs b/ChartPlugin/Utilities/TaskManager.cs new file mode 100644 index 0000000..55797d2 --- /dev/null +++ b/ChartPlugin/Utilities/TaskManager.cs @@ -0,0 +1,266 @@ +/// TaskManager.cs +/// Copyright (c) 2011, Ken Rockot . All rights reserved. +/// Everyone is granted non-exclusive license to do anything at all with this code. +/// +/// This is a new coroutine interface for Unity. +/// +/// The motivation for this is twofold: +/// +/// 1. The existing coroutine API provides no means of stopping specific +/// coroutines; StopCoroutine only takes a string argument, and it stops +/// all coroutines started with that same string; there is no way to stop +/// coroutines which were started directly from an enumerator. This is +/// not robust enough and is also probably pretty inefficient. +/// +/// 2. StartCoroutine and friends are MonoBehaviour methods. This means +/// that in order to start a coroutine, a user typically must have some +/// component reference handy. There are legitimate cases where such a +/// constraint is inconvenient. This implementation hides that +/// constraint from the user. +/// +/// Example usage: +/// +/// ---------------------------------------------------------------------------- +/// IEnumerator MyAwesomeTask(UnityTask self) +/// { +/// while(true) { +/// Debug.Log("Logcat iz in ur consolez, spammin u wif messagez."); +/// yield return null; +//// } +/// } +/// +/// IEnumerator TaskKiller(UnityTask self, float delay, Task t) +/// { +/// yield return new WaitForSeconds(delay); +/// t.Stop(); +/// } +/// +/// void SomeCodeThatCouldBeAnywhereInTheUniverse() +/// { +/// UnityTask spam = UnityTask.CreateUnityTask(MyAwesomeTask); +/// UnityTask.CreateUnityTask(TaskKiller, 5, spam); +/// } +/// ---------------------------------------------------------------------------- +/// +/// When SomeCodeThatCouldBeAnywhereInTheUniverse is called, the debug console +/// will be spammed with annoying messages for 5 seconds. +/// +/// Simple, really. There is no need to initialize or even refer to TaskManager. +/// When the first Task is created in an application, a "TaskManager" GameObject +/// will automatically be added to the scene root with the TaskManager component +/// attached. This component will be responsible for dispatching all coroutines +/// behind the scenes. +/// +/// Task also provides an event that is triggered when the coroutine exits. + +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +/// A Task object represents a coroutine. Tasks can be started, paused, and stopped. +/// It is an error to attempt to start a task that has been stopped or which has +/// naturally terminated. +namespace SongChartVisualizer.Utilities +{ + public class UnityTask + { + /// Delegate for termination subscribers. manual is true if and only if + /// the coroutine was stopped with an explicit call to Stop(). + public delegate void PausedHandler(UnityTask self); + public delegate void ResumedHandler(UnityTask self); + public delegate void FinishedHandler(bool manual, UnityTask self); + + private UnityTaskManager.UnityTaskState task; + + /// Creates a new Task object for the given coroutine. + /// + /// If autoStart is true (default) the task is automatically started + /// upon construction. + public UnityTask(IEnumerator c, bool autoStart = true) + { + returnedValues = new Dictionary(); + InitUnityTask(c, autoStart); + } + + public UnityTask() + { + returnedValues = new Dictionary(); + } + + public void CreateUnityTask(IEnumerator c, bool autoStart = true) + { + InitUnityTask(c, autoStart); + } + + public static UnityTask CreateUnityTask(Func coroutine, T1 arg1, bool autoStart = true) + { + var unityTask = new UnityTask(); + unityTask.InitUnityTask(coroutine(unityTask, arg1), autoStart); + return unityTask; + } + + public static UnityTask CreateUnityTask(Func coroutine, T1 arg1, T2 arg2, bool autoStart = true) + { + var unityTask = new UnityTask(); + unityTask.InitUnityTask(coroutine(unityTask, arg1, arg2), autoStart); + return unityTask; + } + + public static UnityTask CreateUnityTask(Func coroutine, T1 arg1, T2 arg2, T3 arg3, bool autoStart = true) + { + var unityTask = new UnityTask(); + unityTask.InitUnityTask(coroutine(unityTask, arg1, arg2, arg3), autoStart); + return unityTask; + } + + private void InitUnityTask(IEnumerator c, bool autoStart) + { + task = UnityTaskManager.CreateTask(c); + task.Paused += TaskPaused; + task.Resumed += TaskResumed; + task.Finished += TaskFinished; + if (autoStart) + Start(); + } + + /// Returns true if and only if the coroutine is running. Paused tasks + /// are considered to be running. + public bool Running + { + get { return task.Running; } + } + + /// Returns true if and only if the coroutine is currently paused. + public bool IsPaused + { + get { return task.IsPaused; } + } + + /// Termination event. Triggered when the coroutine completes execution. + public event PausedHandler Paused; + public event ResumedHandler Resumed; + public event FinishedHandler Finished; + + public Dictionary returnedValues; + + /// Begins execution of the coroutine + public void Start() + { + task.Start(); + } + + /// Discontinues execution of the coroutine at its next yield. + public void Stop() + { + task.Stop(); + } + + public void Pause() + { + task.Pause(); + } + + public void Unpause() + { + task.Unpause(); + } + + private void TaskFinished(bool manual) + { + Finished?.Invoke(manual, this); + } + + private void TaskPaused() + { + Paused?.Invoke(this); + } + + private void TaskResumed() + { + Resumed?.Invoke(this); + } + } + + internal class UnityTaskManager : MonoBehaviour + { + private static UnityTaskManager singleton; + + public static UnityTaskState CreateTask(IEnumerator coroutine) + { + if (singleton == null) + { + var go = new GameObject("TaskManager"); + DontDestroyOnLoad(go); + singleton = go.AddComponent(); + } + return new UnityTaskState(coroutine); + } + + public class UnityTaskState + { + public delegate void PausedHandler(); + public delegate void ResumedHandler(); + public delegate void FinishedHandler(bool manual); + + private readonly IEnumerator coroutine; + private bool stopped; + + public UnityTaskState(IEnumerator c) + { + coroutine = c; + } + + public bool Running { get; private set; } + + public bool IsPaused { get; private set; } + + public event PausedHandler Paused; + public event ResumedHandler Resumed; + public event FinishedHandler Finished; + + public void Pause() + { + Paused?.Invoke(); + IsPaused = true; + } + + public void Unpause() + { + Resumed?.Invoke(); + IsPaused = false; + } + + public void Start() + { + Running = true; + singleton.StartCoroutine(CallWrapper()); + } + + public void Stop() + { + stopped = true; + Running = false; + } + + private IEnumerator CallWrapper() + { + //yield return null; + var e = coroutine; + while (Running) + { + if (IsPaused) + yield return null; + else + { + if (e != null && e.MoveNext()) + yield return e.Current; + else + Running = false; + } + } + Finished?.Invoke(stopped); + } + } + } +} \ No newline at end of file diff --git a/ChartPlugin/Utilities/Tween.cs b/ChartPlugin/Utilities/Tween.cs new file mode 100644 index 0000000..f1aff1d --- /dev/null +++ b/ChartPlugin/Utilities/Tween.cs @@ -0,0 +1,1101 @@ +/* +The MIT License (MIT) +Copyright (c) 2016 Digital Ruby, LLC +http://www.digitalruby.com +Created by Jeff Johnson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace DigitalRuby.Tween +{ + /// + /// State of an ITween object + /// + public enum TweenState + { + /// + /// The tween is running. + /// + Running, + + /// + /// The tween is paused. + /// + Paused, + + /// + /// The tween is stopped. + /// + Stopped + } + + /// + /// The behavior to use when manually stopping a tween. + /// + public enum TweenStopBehavior + { + /// + /// Does not change the current value. + /// + DoNotModify, + + /// + /// Causes the tween to progress to the end value immediately. + /// + Complete + } + + /// + /// Tween manager - do not add directly as a script, instead call the static methods in your other scripts. + /// + public class TweenFactory : MonoBehaviour + { + private static GameObject root; + private static readonly List tweens = new List(); + private static GameObject toDestroy; + + private static void EnsureCreated() + { + if (root == null && Application.isPlaying) + { + root = GameObject.Find("DigitalRubyTween"); + if (root == null || root.GetComponent() == null) + { + if (root != null) + { + toDestroy = root; + } + root = new GameObject { name = "DigitalRubyTween", hideFlags = HideFlags.HideAndDontSave }; + root.AddComponent().hideFlags = HideFlags.HideAndDontSave; + } + if (Application.isPlaying) + { + GameObject.DontDestroyOnLoad(root); + } + } + } + + private void Start() + { + UnityEngine.SceneManagement.SceneManager.sceneLoaded += SceneManagerSceneLoaded; + if (toDestroy != null) + { + GameObject.Destroy(toDestroy); + toDestroy = null; + } + } + + private void SceneManagerSceneLoaded(UnityEngine.SceneManagement.Scene s, UnityEngine.SceneManagement.LoadSceneMode m) + { + if (ClearTweensOnLevelLoad) + { + tweens.Clear(); + } + } + + private void Update() + { + ITween t; + + for (int i = tweens.Count - 1; i >= 0; i--) + { + t = tweens[i]; + if (t.Update(Time.deltaTime) && i < tweens.Count && tweens[i] == t) + { + tweens.RemoveAt(i); + } + } + } + + /// + /// Start and add a float tween + /// + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// FloatTween + public static FloatTween Tween(object key, float start, float end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + FloatTween t = new FloatTween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Start and add a Vector2 tween + /// + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector2Tween + public static Vector2Tween Tween(object key, Vector2 start, Vector2 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector2Tween t = new Vector2Tween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Start and add a Vector3 tween + /// + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector3Tween + public static Vector3Tween Tween(object key, Vector3 start, Vector3 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector3Tween t = new Vector3Tween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Start and add a Vector4 tween + /// + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector4Tween + public static Vector4Tween Tween(object key, Vector4 start, Vector4 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector4Tween t = new Vector4Tween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Start and add a Color tween + /// + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// ColorTween + public static ColorTween Tween(object key, Color start, Color end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + ColorTween t = new ColorTween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Start and add a Quaternion tween + /// + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// QuaternionTween + public static QuaternionTween Tween(object key, Quaternion start, Quaternion end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + QuaternionTween t = new QuaternionTween(); + t.Key = key; + t.Setup(start, end, duration, scaleFunc, progress, completion); + t.Start(); + AddTween(t); + + return t; + } + + /// + /// Add a tween + /// + /// Tween to add + public static void AddTween(ITween tween) + { + EnsureCreated(); + if (tween.Key != null) + { + RemoveTweenKey(tween.Key, AddKeyStopBehavior); + } + tweens.Add(tween); + } + + /// + /// Remove a tween + /// + /// Tween to remove + /// Stop behavior + /// True if removed, false if not + public static bool RemoveTween(ITween tween, TweenStopBehavior stopBehavior) + { + tween.Stop(stopBehavior); + return tweens.Remove(tween); + } + + /// + /// Remove a tween by key + /// + /// Key to remove + /// Stop behavior + /// True if removed, false if not + public static bool RemoveTweenKey(object key, TweenStopBehavior stopBehavior) + { + if (key == null) + { + return false; + } + + bool foundOne = false; + for (int i = tweens.Count - 1; i >= 0; i--) + { + ITween t = tweens[i]; + if (key.Equals(t.Key)) + { + t.Stop(stopBehavior); + tweens.RemoveAt(i); + foundOne = true; + } + } + return foundOne; + } + + /// + /// Clear all tweens + /// + public static void Clear() + { + tweens.Clear(); + } + + /// + /// Stop behavior if you add a tween with a key and tweens already exist with the key + /// + public static TweenStopBehavior AddKeyStopBehavior = TweenStopBehavior.DoNotModify; + + /// + /// Whether to clear tweens on level load, default is false + /// + public static bool ClearTweensOnLevelLoad; + } + + /// + /// Extensions for tween for game objects - unity only + /// + public static class GameObjectTweenExtensions + { + /// + /// Start and add a float tween + /// + /// Game object + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// FloatTween + public static FloatTween Tween(this GameObject obj, object key, float start, float end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + FloatTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + + /// + /// Start and add a Vector2 tween + /// + /// Game object + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector2Tween + public static Vector2Tween Tween(this GameObject obj, object key, Vector2 start, Vector2 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector2Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + + /// + /// Start and add a Vector3 tween + /// + /// Game object + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector3Tween + public static Vector3Tween Tween(this GameObject obj, object key, Vector3 start, Vector3 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector3Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + + /// + /// Start and add a Vector4 tween + /// + /// Game object + /// Key + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// Vector4Tween + public static Vector4Tween Tween(this GameObject obj, object key, Vector4 start, Vector4 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + Vector4Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + + /// + /// Start and add a Color tween + /// + /// Game object + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// ColorTween + public static ColorTween Tween(this GameObject obj, object key, Color start, Color end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + ColorTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + + /// + /// Start and add a Quaternion tween + /// + /// Game object + /// Start value + /// End value + /// Duration in seconds + /// Scale function + /// Progress handler + /// Completion handler + /// QuaternionTween + public static QuaternionTween Tween(this GameObject obj, object key, Quaternion start, Quaternion end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + QuaternionTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); + t.GameObject = obj; + t.Renderer = obj.GetComponent(); + return t; + } + } + + /// + /// Interface for a tween object. + /// + public interface ITween + { + /// + /// The key that identifies this tween - can be null + /// + object Key { get; } + + /// + /// Gets the current state of the tween. + /// + TweenState State { get; } + + /// + /// Start the tween. + /// + void Start(); + + /// + /// Pauses the tween. + /// + void Pause(); + + /// + /// Resumes the paused tween. + /// + void Resume(); + + /// + /// Stops the tween. + /// + /// The behavior to use to handle the stop. + void Stop(TweenStopBehavior stopBehavior); + + /// + /// Updates the tween. + /// + /// The elapsed time to add to the tween. + /// True if done, false if not + bool Update(float elapsedTime); + } + + /// + /// Interface for a tween object that handles a specific type. + /// + /// The type to tween. + public interface ITween< T > : ITween where T : struct + { + /// + /// Gets the current value of the tween. + /// + T CurrentValue { get; } + + /// + /// Gets the current progress of the tween. + /// + float CurrentProgress { get; } + + /// + /// Initialize a tween. + /// + /// The start value. + /// The end value. + /// The duration of the tween. + /// A function used to scale progress over time. + /// Progress callback + /// Called when the tween completes + Tween Setup(T start, T end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null); + } + + /// + /// An implementation of a tween object. + /// + /// The type to tween. + public class Tween< T > : ITween where T : struct + { + private readonly Func, T, T, float, T> lerpFunc; + + private float currentTime; + private float duration; + private Func scaleFunc; + private System.Action> progressCallback; + private System.Action> completionCallback; + private TweenState state; + + private T start; + private T end; + private T value; + + private ITween continueWith; + + /// + /// The key that identifies this tween - can be null + /// + public object Key { get; set; } + + /// + /// Gets the current time of the tween. + /// + public float CurrentTime { + get { return currentTime; } + } + + /// + /// Gets the duration of the tween. + /// + public float Duration { + get { return duration; } + } + + /// + /// Delay before starting the tween + /// + public float Delay { get; set; } + + /// + /// Gets the current state of the tween. + /// + public TweenState State { + get { return state; } + } + + /// + /// Gets the starting value of the tween. + /// + public T StartValue { + get { return start; } + } + + /// + /// Gets the ending value of the tween. + /// + public T EndValue { + get { return end; } + } + + /// + /// Gets the current value of the tween. + /// + public T CurrentValue { + get { return value; } + } + + /// + /// The game object - null if none + /// + public GameObject GameObject { get; set; } + + /// + /// The renderer - null if none + /// + public Renderer Renderer { get; set; } + + /// + /// Whether to force update even if renderer is null or not visible or deactivated, default is false + /// + public bool ForceUpdate { get; set; } + + /// + /// Gets the current progress of the tween (0 - 1). + /// + public float CurrentProgress { get; private set; } + + /// + /// Initializes a new Tween with a given lerp function. + /// + /// + /// C# generics are good but not good enough. We need a delegate to know how to + /// interpolate between the start and end values for the given type. + /// + /// The interpolation function for the tween type. + public Tween(Func, T, T, float, T> lerpFunc) + { + this.lerpFunc = lerpFunc; + state = TweenState.Stopped; + } + + /// + /// Initialize a tween. + /// + /// The start value. + /// The end value. + /// The duration of the tween. + /// A function used to scale progress over time. + /// Progress callback + /// Called when the tween completes + public Tween Setup(T start, T end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) + { + scaleFunc = (scaleFunc ?? TweenScaleFunctions.Linear); + currentTime = 0; + this.duration = duration; + this.scaleFunc = scaleFunc; + this.progressCallback = progress; + this.completionCallback = completion; + this.start = start; + this.end = end; + + return this; + } + + /// + /// Starts a tween. Setup must be called first. + /// + public void Start() + { + if (state != TweenState.Running) + { + if (duration <= 0.0f && Delay <= 0.0f) + { + // complete immediately + value = end; + if (progressCallback != null) + { + progressCallback(this); + } + if (completionCallback != null) + { + completionCallback(this); + } + return; + } + + state = TweenState.Running; + UpdateValue(); + } + } + + /// + /// Pauses the tween. + /// + public void Pause() + { + if (state == TweenState.Running) + { + state = TweenState.Paused; + } + } + + /// + /// Resumes the paused tween. + /// + public void Resume() + { + if (state == TweenState.Paused) + { + state = TweenState.Running; + } + } + + /// + /// Stops the tween. + /// + /// The behavior to use to handle the stop. + public void Stop(TweenStopBehavior stopBehavior) + { + if (state != TweenState.Stopped) + { + state = TweenState.Stopped; + if (stopBehavior == TweenStopBehavior.Complete) + { + currentTime = duration; + UpdateValue(); + if (completionCallback != null) + { + completionCallback.Invoke(this); + completionCallback = null; + } + if (continueWith != null) + { + continueWith.Start(); + TweenFactory.AddTween(continueWith); + continueWith = null; + } + } + } + } + + /// + /// Updates the tween. + /// + /// The elapsed time to add to the tween. + /// True if done, false if not + public bool Update(float elapsedTime) + { + if (state == TweenState.Running) + { + if (Delay > 0.0f) + { + currentTime += elapsedTime; + if (currentTime <= Delay) + { + // delay is not over yet + return false; + } + else + { + // set to left-over time beyond delay + currentTime = (currentTime - Delay); + Delay = 0.0f; + } + } + else + { + currentTime += elapsedTime; + } + + if (currentTime >= duration) + { + Stop(TweenStopBehavior.Complete); + return true; + } + else + { + UpdateValue(); + return false; + } + } + return (state == TweenState.Stopped); + } + + /// + /// Set another tween to execute when this tween finishes. Inherits the Key and if using Unity, GameObject, Renderer and ForceUpdate properties. + /// + /// Type of new tween + /// New tween + /// New tween + public Tween ContinueWith< TNewTween >(Tween tween) where TNewTween : struct + { + tween.Key = Key; + + tween.GameObject = GameObject; + tween.Renderer = Renderer; + tween.ForceUpdate = ForceUpdate; + + continueWith = tween; + return tween; + } + + /// + /// Helper that uses the current time, duration, and delegates to update the current value. + /// + private void UpdateValue() + { + if (Renderer == null || Renderer.isVisible || ForceUpdate) + { + CurrentProgress = scaleFunc(currentTime / duration); + value = lerpFunc(this, start, end, CurrentProgress); + if (progressCallback != null) + { + progressCallback.Invoke(this); + } + } + } + } + + /// + /// Object used to tween float values. + /// + public class FloatTween : Tween + { + private static float LerpFloat(ITween t, float start, float end, float progress) + { + return start + (end - start) * progress; + } + + private static readonly Func, float, float, float, float> LerpFunc = LerpFloat; + + /// + /// Initializes a new FloatTween instance. + /// + public FloatTween() : base(LerpFunc) { } + } + + /// + /// Object used to tween Vector2 values. + /// + public class Vector2Tween : Tween + { + private static Vector2 LerpVector2(ITween t, Vector2 start, Vector2 end, float progress) + { + return Vector2.Lerp(start, end, progress); + } + + private static readonly Func, Vector2, Vector2, float, Vector2> LerpFunc = LerpVector2; + + /// + /// Initializes a new Vector2Tween instance. + /// + public Vector2Tween() : base(LerpFunc) { } + } + + /// + /// Object used to tween Vector3 values. + /// + public class Vector3Tween : Tween + { + private static Vector3 LerpVector3(ITween t, Vector3 start, Vector3 end, float progress) + { + return Vector3.Lerp(start, end, progress); + } + + private static readonly Func, Vector3, Vector3, float, Vector3> LerpFunc = LerpVector3; + + /// + /// Initializes a new Vector3Tween instance. + /// + public Vector3Tween() : base(LerpFunc) { } + } + + /// + /// Object used to tween Vector4 values. + /// + public class Vector4Tween : Tween + { + private static Vector4 LerpVector4(ITween t, Vector4 start, Vector4 end, float progress) + { + return Vector4.Lerp(start, end, progress); + } + + private static readonly Func, Vector4, Vector4, float, Vector4> LerpFunc = LerpVector4; + + /// + /// Initializes a new Vector4Tween instance. + /// + public Vector4Tween() : base(LerpFunc) { } + } + + /// + /// Object used to tween Color values. + /// + public class ColorTween : Tween + { + private static Color LerpColor(ITween t, Color start, Color end, float progress) + { + return Color.Lerp(start, end, progress); + } + + private static readonly Func, Color, Color, float, Color> LerpFunc = LerpColor; + + /// + /// Initializes a new ColorTween instance. + /// + public ColorTween() : base(LerpFunc) { } + } + + /// + /// Object used to tween Quaternion values. + /// + public class QuaternionTween : Tween + { + private static Quaternion LerpQuaternion(ITween t, Quaternion start, Quaternion end, float progress) + { + return Quaternion.Lerp(start, end, progress); + } + + private static readonly Func, Quaternion, Quaternion, float, Quaternion> LerpFunc = LerpQuaternion; + + /// + /// Initializes a new QuaternionTween instance. + /// + public QuaternionTween() : base(LerpFunc) { } + } + + /// + /// Tween scale functions + /// Implementations based on http://theinstructionlimit.com/flash-style-tweeneasing-functions-in-c, which are based on http://www.robertpenner.com/easing/ + /// + public static class TweenScaleFunctions + { + private const float halfPi = Mathf.PI * 0.5f; + + /// + /// A linear progress scale function. + /// + public static readonly Func Linear = linear; + + private static float linear(float progress) + { + return progress; + } + + /// + /// A quadratic (x^2) progress scale function that eases in. + /// + public static readonly Func QuadraticEaseIn = quadraticEaseIn; + + private static float quadraticEaseIn(float progress) + { + return EaseInPower(progress, 2); + } + + /// + /// A quadratic (x^2) progress scale function that eases out. + /// + public static readonly Func QuadraticEaseOut = quadraticEaseOut; + + private static float quadraticEaseOut(float progress) + { + return EaseOutPower(progress, 2); + } + + /// + /// A quadratic (x^2) progress scale function that eases in and out. + /// + public static readonly Func QuadraticEaseInOut = quadraticEaseInOut; + + private static float quadraticEaseInOut(float progress) + { + return EaseInOutPower(progress, 2); + } + + /// + /// A cubic (x^3) progress scale function that eases in. + /// + public static readonly Func CubicEaseIn = cubicEaseIn; + + private static float cubicEaseIn(float progress) + { + return EaseInPower(progress, 3); + } + + /// + /// A cubic (x^3) progress scale function that eases out. + /// + public static readonly Func CubicEaseOut = cubicEaseOut; + + private static float cubicEaseOut(float progress) + { + return EaseOutPower(progress, 3); + } + + /// + /// A cubic (x^3) progress scale function that eases in and out. + /// + public static readonly Func CubicEaseInOut = cubicEaseInOut; + + private static float cubicEaseInOut(float progress) + { + return EaseInOutPower(progress, 3); + } + + /// + /// A quartic (x^4) progress scale function that eases in. + /// + public static readonly Func QuarticEaseIn = quarticEaseIn; + + private static float quarticEaseIn(float progress) + { + return EaseInPower(progress, 4); + } + + /// + /// A quartic (x^4) progress scale function that eases out. + /// + public static readonly Func QuarticEaseOut = quarticEaseOut; + + private static float quarticEaseOut(float progress) + { + return EaseOutPower(progress, 4); + } + + /// + /// A quartic (x^4) progress scale function that eases in and out. + /// + public static readonly Func QuarticEaseInOut = quarticEaseInOut; + + private static float quarticEaseInOut(float progress) + { + return EaseInOutPower(progress, 4); + } + + /// + /// A quintic (x^5) progress scale function that eases in. + /// + public static readonly Func QuinticEaseIn = quinticEaseIn; + + private static float quinticEaseIn(float progress) + { + return EaseInPower(progress, 5); + } + + /// + /// A quintic (x^5) progress scale function that eases out. + /// + public static readonly Func QuinticEaseOut = quinticEaseOut; + + private static float quinticEaseOut(float progress) + { + return EaseOutPower(progress, 5); + } + + /// + /// A quintic (x^5) progress scale function that eases in and out. + /// + public static readonly Func QuinticEaseInOut = quinticEaseInOut; + + private static float quinticEaseInOut(float progress) + { + return EaseInOutPower(progress, 5); + } + + /// + /// A sine progress scale function that eases in. + /// + public static readonly Func SineEaseIn = sineEaseIn; + + private static float sineEaseIn(float progress) + { + return Mathf.Sin(progress * halfPi - halfPi) + 1; + } + + /// + /// A sine progress scale function that eases out. + /// + public static readonly Func SineEaseOut = sineEaseOut; + + private static float sineEaseOut(float progress) + { + return Mathf.Sin(progress * halfPi); + } + + /// + /// A sine progress scale function that eases in and out. + /// + public static readonly Func SineEaseInOut = sineEaseInOut; + + private static float sineEaseInOut(float progress) + { + return (Mathf.Sin(progress * Mathf.PI - halfPi) + 1) / 2; + } + + private static float EaseInPower(float progress, int power) + { + return Mathf.Pow(progress, power); + } + + private static float EaseOutPower(float progress, int power) + { + int sign = power % 2 == 0 ? -1 : 1; + return (sign * (Mathf.Pow(progress - 1, power) + sign)); + } + + private static float EaseInOutPower(float progress, int power) + { + progress *= 2.0f; + if (progress < 1) + { + return Mathf.Pow(progress, power) / 2.0f; + } + else + { + int sign = power % 2 == 0 ? -1 : 1; + return (sign / 2.0f * (Mathf.Pow(progress - 2, power) + sign * 2)); + } + } + } +} \ No newline at end of file diff --git a/ChartPlugin/Utilities/Utils.cs b/ChartPlugin/Utilities/Utils.cs new file mode 100644 index 0000000..a9b0ec9 --- /dev/null +++ b/ChartPlugin/Utilities/Utils.cs @@ -0,0 +1,35 @@ +using System.Linq; +using TMPro; +using UnityEngine; + +namespace SongChartVisualizer.Utilities +{ + public static class Utils + { + public static TextMeshProUGUI CreateText(RectTransform parent, string text, Vector2 anchoredPosition) + { + return CreateText(parent, text, anchoredPosition, new Vector2(60f, 10f)); + } + + public static TextMeshProUGUI CreateText(RectTransform parent, string text, Vector2 anchoredPosition, Vector2 sizeDelta) + { + GameObject gameObj = new GameObject("CustomUIText"); + gameObj.SetActive(false); + + TextMeshProUGUI textMesh = gameObj.AddComponent(); + textMesh.font = Object.Instantiate(Resources.FindObjectsOfTypeAll().First(t => t.name == "Teko-Medium SDF No Glow")); + textMesh.rectTransform.SetParent(parent, false); + textMesh.text = text; + textMesh.fontSize = 4; + textMesh.color = Color.white; + + textMesh.rectTransform.anchorMin = new Vector2(0.5f, 0.5f); + textMesh.rectTransform.anchorMax = new Vector2(0.5f, 0.5f); + textMesh.rectTransform.sizeDelta = sizeDelta; + textMesh.rectTransform.anchoredPosition = anchoredPosition; + + gameObj.SetActive(true); + return textMesh; + } + } +} diff --git a/ChartPlugin/manifest.json b/ChartPlugin/manifest.json new file mode 100644 index 0000000..0c15b08 --- /dev/null +++ b/ChartPlugin/manifest.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://raw.githubusercontent.com/nike4613/ModSaber-MetadataFileSchema/master/Schema.json", + "author": "Shoko84", + "description": "Displays an in-game chart with song difficulty information!", + "gameVersion": "1.7.0", + "id": "SongChartVisualizer", + "name": "SongChartVisualizer", + "version": "1.0.3", + "dependsOn": { + "BS Utils": "^1.4.1", + "BeatSaberMarkupLanguage": "^1.1.4" + } +} \ No newline at end of file diff --git a/SongChartVisualizer.sln b/SongChartVisualizer.sln new file mode 100644 index 0000000..d7e166d --- /dev/null +++ b/SongChartVisualizer.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2047 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SongChartVisualizer", "ChartPlugin\SongChartVisualizer.csproj", "{64A2A30B-9DC5-44CE-90E4-A790CA13A124}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {64A2A30B-9DC5-44CE-90E4-A790CA13A124}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64A2A30B-9DC5-44CE-90E4-A790CA13A124}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64A2A30B-9DC5-44CE-90E4-A790CA13A124}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64A2A30B-9DC5-44CE-90E4-A790CA13A124}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5E772049-C240-463B-851B-2BA5EAD4D68B} + EndGlobalSection +EndGlobal