AudioValidation.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using UnityEditor;
  7. using DiamondArrow.Platform;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. namespace DiamondArrow.Editor
  11. {
  12. // Real controller/UI events with an isolated save; verifies the audio device output too.
  13. public static class AudioValidation
  14. {
  15. public static string Status = "Not started";
  16. static DiamondArrowGame game;
  17. static GameAudio audio;
  18. static PlayerSave original;
  19. static SaveStore originalStore, temporaryStore;
  20. static Queue<Action> steps;
  21. static List<string> report;
  22. static readonly BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
  23. static readonly float[] samples = new float[1024];
  24. static float peak, previousTime;
  25. static int previousCount;
  26. static double next;
  27. [MenuItem("Diamond Arrow/Validate audio in Play Mode")]
  28. public static void Begin()
  29. {
  30. if (!EditorApplication.isPlaying || Status == "Running") throw new InvalidOperationException("Enter Play Mode; no other audio validation may be running.");
  31. game = UnityEngine.Object.FindFirstObjectByType<DiamondArrowGame>();
  32. audio = game.GetComponent<GameAudio>();
  33. original = game.Save;
  34. originalStore = (SaveStore)typeof(DiamondArrowGame).GetField("store", Private).GetValue(game);
  35. temporaryStore = new SaveStore(Path.Combine(Application.temporaryCachePath, "DiamondArrowAudioValidation", Guid.NewGuid().ToString("N")));
  36. var testSave = new PlayerSave { tutorial = true, seen = true, gems = 500, music = true, sfx = true };
  37. for (int i = 0; i < 7; i++) testSave.stars[i] = 3;
  38. typeof(DiamondArrowGame).GetProperty("Save").SetValue(game, testSave);
  39. typeof(DiamondArrowGame).GetField("store", Private).SetValue(game, temporaryStore);
  40. var services = game.GetComponentInChildren<PlatformServices>();
  41. services.EditorShowReward = id => services.ReceiveAdResult(id + ":1");
  42. audio.ApplyPreferences(true, true);
  43. audio.SetSuspended(false);
  44. report = new List<string>(); steps = new Queue<Action>(); peak = 0; Status = "Running";
  45. Add(() => {
  46. Check(audio.MusicSource.clip == game.theme.backgroundMusic && audio.MusicSource.clip.name == "NeonDaydream", "BGM reference resolves");
  47. Check(game.GetComponentsInChildren<AudioSource>().Length == GameAudio.VoiceCount + 1, "Bounded voice pool");
  48. Check(audio.MusicSource.loop && audio.MusicSource.spatialBlend == 0, "Looping 2D music");
  49. Check(UnityEngine.Object.FindObjectsByType<AudioListener>(FindObjectsSortMode.None).Count(x => x.enabled) == 1, "One active listener");
  50. foreach (SoundCue cue in Enum.GetValues(typeof(SoundCue))) {
  51. var clip = game.theme.soundEffects[(int)cue]; var data = new float[clip.samples * clip.channels];
  52. Check(clip.GetData(data, 0) && data.Any(x => Mathf.Abs(x) > .01f) && data.All(x => !float.IsNaN(x) && Mathf.Abs(x) < 1), cue + " PCM signal has headroom");
  53. }
  54. game.ShowLobby(); previousTime = audio.MusicSource.time;
  55. });
  56. Add(() => { Check(audio.MusicSource.isPlaying && audio.MusicSource.time > previousTime, "Music clock advances in lobby"); Check(peak > .0001f, "Music GetOutputData contains audible signal (peak " + peak.ToString("F5") + ")"); game.ShowSettings(); Click("Toggle Music"); });
  57. Add(() => { Check(!game.Save.music && !audio.MusicSource.isPlaying && audio.MusicSource.volume == 0, "Music OFF fades and pauses"); Check(!temporaryStore.Load().music, "Music OFF persisted"); previousTime = audio.MusicSource.time; Click("Toggle Music"); });
  58. Add(() => { Check(game.Save.music && audio.MusicSource.isPlaying && audio.MusicSource.time >= previousTime, "Music ON resumes without restarting"); Check(temporaryStore.Load().music, "Music ON persisted"); Click("Toggle Sound effects"); previousCount = audio.PlayedCount; });
  59. Add(() => { Check(!audio.Play(SoundCue.Reward) && audio.PlayedCount == previousCount, "SFX OFF rejects playback"); Check(audio.MusicSource.isPlaying, "SFX switch leaves music running"); Click("Toggle Sound effects"); game.ShowLobby(); game.StartLevel(8); });
  60. Add(() => { game.TapArrow(game.Run.FreeArrows()[0]); Cue(SoundCue.Slide, "Free arrow uses slide sound"); });
  61. Add(() => { game.TapArrow(Enumerable.Range(0, game.Run.Alive.Length).First(i => game.Run.Alive[i] && game.Run.Blocker(i) >= 0)); Cue(SoundCue.Blocked, "Blocked arrow uses impact sound"); });
  62. Add(() => { Click("Spotlight"); Cue(SoundCue.Hint, "Spotlight uses hint sound"); });
  63. Add(() => { Click("+1 Heart"); Cue(SoundCue.Heart, "Refill uses heart sound"); });
  64. Add(() => { Click("Hammer"); game.TapArrow(game.Run.FreeArrows()[0]); Cue(SoundCue.Hammer, "Hammer removal uses shatter sound"); });
  65. Add(() => { while (game.Run.Status == RunStatus.Playing) game.TapArrow(game.Run.FreeArrows()[0]); });
  66. Add(() => { Check(game.CurrentModal == "Result", "Clear modal reached"); Cue(SoundCue.Clear, "Clear uses dedicated fanfare"); Check(audio.MusicSource.volume < game.theme.musicVolume * .8f, "Fanfare ducks music"); });
  67. Add(() => { game.StartLevel(8); game.SendMessage("OnApplicationFocus", true); game.Run.Tick(game.Run.TimeLeft - 4.8f); });
  68. Add(() => { Cue(SoundCue.Countdown, "Final seconds have a countdown cue"); game.Run.Tick(999); game.ShowFail(); Cue(SoundCue.Fail, "Failure uses descending cue"); });
  69. Add(() => { Click("Revive"); Cue(SoundCue.Heart, "Revival uses heart cue"); game.ShowLobby(); game.ShowCheckin(); Click("Claim"); Cue(SoundCue.Reward, "Check-in reward cue"); });
  70. Add(() => { game.ShowChest(); Click("Open chest"); Cue(SoundCue.ChestOpen, "Chest opening cue"); });
  71. Add(() => { Cue(SoundCue.Reward, "Chest reveal reward cue"); game.ShowLobby(); audio.SetSuspended(true); previousTime = audio.MusicSource.time; });
  72. Add(() => { Check(!audio.MusicSource.isPlaying && Mathf.Abs(audio.MusicSource.time - previousTime) < .05f, "Background pauses music"); Check(!audio.Play(SoundCue.Tap), "Background suppresses effects"); audio.SetSuspended(false); });
  73. Add(() => { Check(audio.MusicSource.isPlaying, "Foreground resumes music"); audio.MusicSource.time = audio.MusicSource.clip.length - .2f; });
  74. Add(() => { Check(audio.MusicSource.isPlaying && audio.MusicSource.time < 3, "BGM loops past clip end"); previousCount = audio.PlayedCount; for (int i=0;i<100;i++) audio.Play(SoundCue.Slide); Check(audio.PlayedCount == previousCount + 1, "Rapid taps are rate limited"); });
  75. Add(() => {
  76. game.ShowSettings();
  77. AppRuntimesEvents.RaisePlatformOpen();
  78. Check(!audio.MusicSource.isPlaying && !temporaryStore.Load().music, "Platform open stops and persists music");
  79. var toggle = game.GetComponentsInChildren<Button>().Single(x => x.name == "Toggle Music");
  80. Check(toggle.GetComponentInChildren<Text>().text == "OFF", "Open settings reflects platform event");
  81. audio.SetSuspended(true); audio.SetSuspended(false);
  82. Check(!audio.MusicSource.isPlaying && game.Save.sfx, "Resume respects music and keeps SFX enabled");
  83. Click("Toggle Music");
  84. Check(game.Save.music && audio.MusicSource.isPlaying, "User can resume music after platform open");
  85. });
  86. AssemblyReloadEvents.beforeAssemblyReload += Interrupted;
  87. EditorApplication.update += Tick;
  88. next = EditorApplication.timeSinceStartup + 1;
  89. }
  90. static void Add(Action action) { steps.Enqueue(action); }
  91. static void Cue(SoundCue cue, string label) { Check(audio.LastCue == cue, label); }
  92. static void Check(bool ok, string label) { if (!ok) throw new InvalidOperationException(label); report.Add("PASS " + label); }
  93. static void Click(string name) { game.GetComponentsInChildren<Button>().First(x => x.name == name && x.isActiveAndEnabled && x.interactable).onClick.Invoke(); }
  94. static void Tick()
  95. {
  96. try {
  97. if (!EditorApplication.isPlaying || !game) throw new InvalidOperationException("Play Mode ended");
  98. audio.MusicSource.GetOutputData(samples, 0);
  99. foreach (var sample in samples) peak = Mathf.Max(peak, Mathf.Abs(sample));
  100. if (EditorApplication.timeSinceStartup < next) return;
  101. next = EditorApplication.timeSinceStartup + 1.5;
  102. if (steps.Count > 0) { steps.Dequeue()(); return; }
  103. Status = "Passed"; Finish();
  104. } catch (Exception e) { Status = "Failed: " + e.Message; report.Add(e.ToString()); Finish(); }
  105. }
  106. static void Interrupted() { Status = "Interrupted by reload"; Finish(); }
  107. static void Finish()
  108. {
  109. EditorApplication.update -= Tick;
  110. AssemblyReloadEvents.beforeAssemblyReload -= Interrupted;
  111. if (game) {
  112. typeof(DiamondArrowGame).GetProperty("Save").SetValue(game, original);
  113. typeof(DiamondArrowGame).GetField("store", Private).SetValue(game, originalStore);
  114. game.GetComponentInChildren<PlatformServices>().EditorShowReward = null;
  115. audio.SetSuspended(false); audio.ApplyPreferences(original.music, original.sfx); game.ShowLobby();
  116. }
  117. string folder = "Library/DiamondArrowValidation/Audio";
  118. Directory.CreateDirectory(folder);
  119. File.WriteAllLines(folder + "/runtime-report.txt", new[]{Status}.Concat(report));
  120. Debug.Log("Diamond Arrow audio validation: " + Status);
  121. }
  122. }
  123. }