From d156a9f3927f2ce85c458139b508f47a4417de5e Mon Sep 17 00:00:00 2001 From: Yohann Gayao <68230605+DerpyNewb@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:31:06 +0800 Subject: [PATCH] Play SOUND_TRIGGER tags in SuperView A Sound box in SuperView plays the SOUND_TRIGGER tags of the clip meta, the persistent meta, the slot's .snd.meta and the persistent row's .snd.meta as the playhead crosses them. Each tag goes through audio_metadata_tags_tables to its battle event, then through the event's Play actions and containers to the WEMs, as the game resolves it: random and sequence containers follow their playlist rules, and each switch group the triggers reach gets a picker. Status lines say what the triggers resolve to and why one plays nothing. The sounds play through a small mixer of their own, as triggers overlap and SoundEngine plays one stream. Adds a DB table reader (Shared/GameFiles/DB) with the tags table's layouts from RPFM's schema, and makes AudioRepository's lookups and loads safe from two threads, as SuperView resolves off the UI thread. --- AssetEditor/Language_Cn.json | 1 + AssetEditor/Language_En.json | 1 + AssetEditor/Language_Fr.json | 1 + .../AudioMetadataTagsTableTests.cs | 131 ++ .../SoundTriggerGameTests.cs | 164 ++ .../Test.AnimationMeta/SuperViewSoundTests.cs | 874 +++++++++ Editors/Audio/AudioCacheTests.cs | 89 + Editors/Audio/Editors.Audio.csproj | 2 + .../Audio/Shared/Storage/AudioRepository.cs | 348 ++-- Editors/Audio/SoundTriggerTests.cs | 1578 +++++++++++++++++ .../Audio/SoundTriggers/AudioMetadataTags.cs | 30 + .../SoundTriggers/SoundTriggerCrossing.cs | 35 + .../Audio/SoundTriggers/SoundTriggerMixer.cs | 200 +++ .../SoundTriggers/SoundTriggerResolver.cs | 233 +++ .../SoundTriggers/SoundTriggerSession.cs | 101 ++ Editors/Audio/Test.Audio.csproj | 1 + .../Editors.AnimationMeta.csproj | 1 + .../AnimationMeta/SuperView/EditorView.xaml | 21 + .../SuperView/SuperViewViewModel.Sound.cs | 413 +++++ .../SuperView/SuperViewViewModel.cs | 11 +- .../AnimationPlayerViewModel.cs | 4 + .../ReferenceModel/BinAnimationViewModel.cs | 15 +- .../Editors.Shared.Core/Common/SceneObject.cs | 2 + .../Common/SceneObjectEditor.cs | 1 + .../Resources/Db/schema_wh3_extract.txt | 525 ++++++ .../Shared.EmbeddedResources.csproj | 4 + Shared/GameFiles/DB/DbSchema.cs | 40 + Shared/GameFiles/DB/DbTableReader.cs | 82 + Shared/GameFiles/DB/DbTables.cs | 49 + 29 files changed, 4806 insertions(+), 151 deletions(-) create mode 100644 Editors/AnimationMeta/Test.AnimationMeta/AudioMetadataTagsTableTests.cs create mode 100644 Editors/AnimationMeta/Test.AnimationMeta/SoundTriggerGameTests.cs create mode 100644 Editors/AnimationMeta/Test.AnimationMeta/SuperViewSoundTests.cs create mode 100644 Editors/Audio/SoundTriggerTests.cs create mode 100644 Editors/Audio/SoundTriggers/AudioMetadataTags.cs create mode 100644 Editors/Audio/SoundTriggers/SoundTriggerCrossing.cs create mode 100644 Editors/Audio/SoundTriggers/SoundTriggerMixer.cs create mode 100644 Editors/Audio/SoundTriggers/SoundTriggerResolver.cs create mode 100644 Editors/Audio/SoundTriggers/SoundTriggerSession.cs create mode 100644 Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.Sound.cs create mode 100644 Shared/EmbeddedResources/Resources/Db/schema_wh3_extract.txt create mode 100644 Shared/GameFiles/DB/DbSchema.cs create mode 100644 Shared/GameFiles/DB/DbTableReader.cs create mode 100644 Shared/GameFiles/DB/DbTables.cs diff --git a/AssetEditor/Language_Cn.json b/AssetEditor/Language_Cn.json index 456099282..6efc96e2c 100644 --- a/AssetEditor/Language_Cn.json +++ b/AssetEditor/Language_Cn.json @@ -556,6 +556,7 @@ "SuperView.Edit3D.Focus": "聚焦", "SuperView.Edit3D.FocusTooltip": "将相机对准所选标签。双击其标记效果相同", "SuperView.Problems.Header": "问题({0})", + "SuperView.Sound": "声音", "SuperView.Problems.Tooltip": "两个 META 文件中的问题。单击可打开对应标签。红色问题会阻止保存", "SuperView.Problems.InvalidField": "字段“{0}”的值无效,无法保存文件", "SuperView.Problems.NonFiniteTime": "开始或结束时间不是有限数值", diff --git a/AssetEditor/Language_En.json b/AssetEditor/Language_En.json index 648a9a5f7..5f6f6b7cb 100644 --- a/AssetEditor/Language_En.json +++ b/AssetEditor/Language_En.json @@ -556,6 +556,7 @@ "SuperView.Edit3D.Focus": "Focus", "SuperView.Edit3D.FocusTooltip": "Centre the camera on the selected tag. Double-clicking its marker does the same", "SuperView.Problems.Header": "Problems ({0})", + "SuperView.Sound": "Sound", "SuperView.Problems.Tooltip": "What is wrong in the two META files. Click one to open its tag. Red ones stop the file from saving", "SuperView.Problems.InvalidField": "{0} does not hold a valid value, so the file cannot be saved", "SuperView.Problems.NonFiniteTime": "Its start or end time is not a number", diff --git a/AssetEditor/Language_Fr.json b/AssetEditor/Language_Fr.json index 6e6140774..9d14226b2 100644 --- a/AssetEditor/Language_Fr.json +++ b/AssetEditor/Language_Fr.json @@ -532,6 +532,7 @@ "SuperView.Edit3D.Focus": "Focus", "SuperView.Edit3D.FocusTooltip": "Centre the camera on the selected tag. Double-clicking its marker does the same", "SuperView.Problems.Header": "Problems ({0})", + "SuperView.Sound": "Son", "SuperView.Problems.Tooltip": "What is wrong in the two META files. Click one to open its tag. Red ones stop the file from saving", "SuperView.Problems.InvalidField": "{0} does not hold a valid value, so the file cannot be saved", "SuperView.Problems.NonFiniteTime": "Its start or end time is not a number", diff --git a/Editors/AnimationMeta/Test.AnimationMeta/AudioMetadataTagsTableTests.cs b/Editors/AnimationMeta/Test.AnimationMeta/AudioMetadataTagsTableTests.cs new file mode 100644 index 000000000..57da2978b --- /dev/null +++ b/Editors/AnimationMeta/Test.AnimationMeta/AudioMetadataTagsTableTests.cs @@ -0,0 +1,131 @@ +using System.IO; +using System.Text; +using Editors.Audio.SoundTriggers; +using Shared.Core.PackFiles; +using Shared.Core.PackFiles.Models; +using Shared.GameFormats.DB; +using Test.TestingUtility.Shared; + +namespace Test.AnimationMeta +{ + public class AudioMetadataTagsTableTests + { + const string Tags = "audio_metadata_tags_tables"; + const int Version = 22; + + static object[] Row(string key, string battleEvent = "Derpy_Event", double duration = 0) => + [ + .. DbSchema.Versions(Tags)[Version].Select(x => x.Name switch + { + "key" => key, + "sound_event_battle_start" => battleEvent, + "persistent_one_shot_duration_override" => duration, + "vocalisation_bank_split" => "derpy_bank", + _ => x.Type switch { "Boolean" => false, "I32" => 0, "F32" => 0f, "F64" => 0d, _ => "" }, + }) + ]; + + [Test] + public void ReadsAnF64Column() + { + var (version, rows) = DbTableReader.Read(File(Row("derpy_tag", duration: 1.25)), Tags, "test/derpy_f64"); + + Assert.That(version, Is.EqualTo(Version)); + Assert.That(rows.Single()["persistent_one_shot_duration_override"], Is.EqualTo(1.25d)); + Assert.That(rows.Single()["vocalisation_bank_split"], Is.EqualTo("derpy_bank")); + } + + [Test] + public void ATruncatedFile_IsRefused_NamingTableVersionAndFile() + { + var e = Assert.Throws(() => DbTableReader.Read(File(Row("derpy_a"))[..^3], Tags, "test/derpy_cut")); + Assert.That(e!.Message, Does.Contain(Tags).And.Contain($"v{Version}").And.Contain("test/derpy_cut")); + } + + [Test] + public void TrailingBytes_AreRefused() + { + var e = Assert.Throws(() => DbTableReader.Read([.. File(Row("derpy_a")), 0], Tags, "test/derpy_long")); + Assert.That(e!.Message, Does.Contain("test/derpy_long")); + } + + [Test] + public void AVersionNotInTheExtract_IsRefused() + { + var data = File(Row("derpy_a")); + data[4] = 99; + var e = Assert.Throws(() => DbTableReader.Read(data, Tags, "test/derpy_v99")); + Assert.That(e!.Message, Does.Contain("v99").And.Contain("test/derpy_v99")); + } + + [Test] + public void TheCopyTheGameKeeps_ComesFirst() + { + var runner = new AssetEditorTestRunner(); + Pack(runner, "zzz_dbtest_z", ("aaa_dbtest_cross", [Row("u2", "z_aaa")]), ("dbtest_samepath", [Row("u4", "z_samepath"), Row("u5", "z_samepath")])); + Pack(runner, "!!dbtest_a", ("aaa_dbtest_samepack", [Row("u1", "a_aaa")]), ("zzz_dbtest_samepack", [Row("u1", "a_zzz")]), + ("zzz_dbtest_cross", [Row("u2", "a_zzz")]), ("dbtest_samepath", [Row("u4", "a_samepath")])); + + var rows = DbTables.Read(runner.PackFileService, Tags); + string[] Copies(string key) => [.. rows.Where(x => x.Text("key") == key).Select(x => x.Text("sound_event_battle_start"))]; + + Assert.Multiple(() => + { + Assert.That(Copies("u1"), Is.EqualTo(new[] { "a_aaa", "a_zzz" }), "in one pack, the file whose name sorts first"); + Assert.That(Copies("u2"), Is.EqualTo(new[] { "z_aaa", "a_zzz" }), "the file's name decides, not its pack's"); + Assert.That(Copies("u4"), Is.EqualTo(new[] { "a_samepath" }), "one path in two packs: the first pack keeps its whole file"); + Assert.That(Copies("u5"), Is.Empty, "and the other pack's rows at that path are gone"); + }); + Assert.That(AudioMetadataTags.Read(runner.PackFileService).Find("u1")?.BattleStart, Is.EqualTo("a_aaa"), "the lookup keeps the first copy"); + } + + static void Pack(AssetEditorTestRunner runner, string name, params (string File, object[][] Rows)[] files) + { + var pack = runner.CreateEmptyPackFile(name, false); + runner.PackFileService.AddFilesToPack(pack, + [.. files.Select(x => new NewPackFileEntry(@"db\" + Tags, PackFile.CreateFromBytes(x.File, File(x.Rows))))]); + } + + static byte[] File(params object[][] rows) + { + var fields = DbSchema.Versions(Tags)[Version]; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(new byte[] { 0xFC, 0xFD, 0xFE, 0xFF }); + writer.Write(Version); + writer.Write((byte)1); + writer.Write(rows.Length); + foreach (var row in rows) + for (var i = 0; i < fields.Count; i++) + Cell(writer, fields[i].Type, row[i]); + writer.Flush(); + return stream.ToArray(); + } + + static void Cell(BinaryWriter writer, string type, object value) + { + switch (type) + { + case "OptionalStringU8": + var text = (string)value; + writer.Write((byte)(text.Length == 0 ? 0 : 1)); + if (text.Length != 0) + Text(writer, text); + break; + case "StringU8": Text(writer, (string)value); break; + case "Boolean": writer.Write((bool)value); break; + case "I32": writer.Write((int)value); break; + case "F32": writer.Write((float)value); break; + case "F64": writer.Write((double)value); break; + default: throw new NotSupportedException(type); + } + } + + static void Text(BinaryWriter writer, string text) + { + var bytes = Encoding.UTF8.GetBytes(text); + writer.Write((ushort)bytes.Length); + writer.Write(bytes); + } + } +} diff --git a/Editors/AnimationMeta/Test.AnimationMeta/SoundTriggerGameTests.cs b/Editors/AnimationMeta/Test.AnimationMeta/SoundTriggerGameTests.cs new file mode 100644 index 000000000..a570fb807 --- /dev/null +++ b/Editors/AnimationMeta/Test.AnimationMeta/SoundTriggerGameTests.cs @@ -0,0 +1,164 @@ +using System.Diagnostics; +using System.IO; +using Editors.AnimationMeta.SuperView; +using Editors.Audio.SoundTriggers; +using Editors.Shared.Core.Common; +using Microsoft.Extensions.DependencyInjection; +using Shared.Core.Commands; +using Shared.Core.PackFiles.Models; +using Shared.Core.PackFiles.Utility; +using Shared.Core.Services; +using Shared.Core.ToolCreation; +using Shared.GameFormats.AnimationMeta.Definitions; +using Shared.GameFormats.AnimationMeta.Parsing; +using Test.TestingUtility.Shared; + +namespace Test.AnimationMeta +{ + public class SoundTriggerGameTests + { + static readonly string[] Packs = ["db.pack", "audio_base_bnk.pack", "audio_base.pack", "audio_en_bnk.pack", "audio_en.pack", "anim2.pack"]; + + const string AttackSndMeta = "hu1_sws_attack_01."; + const string AttackFolder = "humanoid01/sword_and_shield/attacks/"; + + AssetEditorTestRunner _runner = null!; + SoundTriggerResolver _resolver = null!; + AudioMetadataTags _tags = null!; + TimeSpan _loadTime; + static readonly IReadOnlyDictionary NoChoices = new Dictionary(); + + [OneTimeSetUp] + public void LoadTheGamesAudio() + { + var data = Environment.GetEnvironmentVariable("WH3_DATA"); + Assume.That(data != null && Directory.Exists(data), "set WH3_DATA to the game's data folder"); + + _runner = new AssetEditorTestRunner(); + var loader = _runner.ServiceProvider.GetRequiredService(); + foreach (var pack in Packs) + { + var container = loader.CreateFromPackFile(PackFileContainerType.Normal, Path.Combine(data!, pack), true); + container.IsCaPackFile = true; + _runner.PackFileService.AddContainer(container); + } + + var clock = Stopwatch.StartNew(); + var superView = (SuperViewViewModel)_runner.CommandFactory.Create().Execute(EditorEnums.SuperView_Editor); + _resolver = superView.LoadSounds(CancellationToken.None).GetAwaiter().GetResult(); + _loadTime = clock.Elapsed; + _tags = AudioMetadataTags.Read(_runner.PackFileService); + } + + static IReadOnlyList Leaves(SoundTriggerResult result) => [.. SoundNodes.Leaves(result.Sound!)]; + + [Test] + public void VanillaPainCry_Resolves() + { + Assert.That(_tags.Find("Vocalisation_Humanoid_Male_Pain")?.BattleStart, Is.EqualTo("Battle_Individual_Vocalisation_Humanoid_Male_Pain")); + + var result = _resolver.Resolve("Vocalisation_Humanoid_Male_Pain", false, NoChoices); + + Assert.That(result.Silent, Is.Null); + Assert.That(Leaves(result).Any(x => FindWem(x) != null), Is.True); + } + + [Test] + public void DropWeaponRest_UsesTheTable() + { + Assert.That(_tags.Find("Drop_Weapon_Rest")?.BattleStart, Is.EqualTo("Battle_Individual_Melee_Weapon_Drop_Weapon_Rest")); + + var result = _resolver.Resolve("Drop_Weapon_Rest", false, NoChoices); + + Assert.That(result.Silent, Is.Null); + Assert.That(Leaves(result).Any(x => FindWem(x) != null), Is.True); + } + + [Test] + public void MadeUpTag_IsSilent() + { + Assert.That(_resolver.Resolve("Derpy_Made_Up_Tag", false, NoChoices).Silent, Is.EqualTo("no audio_metadata_tags_tables row")); + } + + [Test] + public void MeleeWeaponHitPrimary_IsNotSupported_AndSaysWhatItReaches() + { + var result = _resolver.Resolve("Melee_Weapon_Hit_Primary", false, NoChoices); + TestContext.Out.WriteLine(result.Silent); + + Assert.That(result.Silent, Does.StartWith("not supported: 0x2303 action -> ").And.EndWith("Dialogue_Event")); + } + + PackFile? FindWem(uint sourceId) => _runner.PackFileService.FindFile($"audio\\wwise\\{sourceId}.wem") + ?? _runner.PackFileService.FindFile($"audio\\wwise\\english(uk)\\{sourceId}.wem"); + + [Test] + public void RealClip_ResolvesAndDecodes_OffTheUiThread() + { + var file = _runner.PackFileService.GetAllPackfileContainers().SelectMany(x => x.SearchFiles(AttackSndMeta, [".snd.meta"])) + .Where(x => x.Path.Replace('\\', '/').Contains(AttackFolder)).OrderBy(x => x.Path).FirstOrDefault(); + Assert.That(file.File, Is.Not.Null, $"the game has a .snd.meta named {AttackSndMeta}* under {AttackFolder}"); + var (ui, before) = (new UiThread(), SynchronizationContext.Current); + SynchronizationContext.SetSynchronizationContext(ui); + try + { + var superView = (SuperViewViewModel)_runner.CommandFactory.Create().Execute(EditorEnums.SuperView_Editor); + var mixer = new SoundTriggerMixer(openDevice: false); + superView.OpenMixer = () => mixer; + superView.LoadSounds = _ => Task.FromResult(_resolver); + var (prepare, queued) = (superView.PrepareSound, new List()); + superView.PrepareSound = id => + { + queued.Add(id); + return prepare(id); + }; + superView.SoundOn = true; + ui.Settle(superView); + var memory = GC.GetTotalMemory(true); + + var onThisThread = Stopwatch.StartNew(); + var main = superView.SceneObjects[0].Data; + main.SoundMetaData = file.File; + _runner.ScopeRepository.GetRequiredService(superView).SetMetaFile(main, main.MetaData, main.PersistMetaData); + onThisThread.Stop(); + var firstResolves = Stopwatch.StartNew(); + Assert.That(superView.SoundDecoding.Wait(TimeSpan.FromMinutes(2)), Is.True, "resolved within two minutes"); + firstResolves.Stop(); + Pump(); + var whileDecoding = superView.SoundStatus.LastOrDefault(); + var decoding = Stopwatch.StartNew(); + do + Assert.That(superView.SoundDecoding.Wait(TimeSpan.FromMinutes(2)), Is.True, "decoded within two minutes"); + while (Pump()); + decoding.Stop(); + + var sources = queued.Distinct().ToList(); + var decoded = sources.Count(id => mixer.Prepare(id, () => null)); + var triggers = _runner.ScopeRepository.GetRequiredService(superView).ParseFile(file.File.DataSource.ReadData()).Attributes.Count(x => x is SoundTrigger_v10 or SoundTrigger_v4); + TestContext.Out.WriteLine($"The fixture's LoadSounds took {_loadTime.TotalSeconds:0.0} s. {file.Path}: {triggers} triggers, {sources.Count} sources. " + + $"On the UI thread: {onThisThread.Elapsed.TotalMilliseconds:0} ms. Off it: the first resolves {firstResolves.Elapsed.TotalMilliseconds:0} ms, " + + $"{decoded} decoded in {decoding.Elapsed.TotalMilliseconds:0} ms, {(GC.GetTotalMemory(true) - memory) / 1_048_576.0:0} MB. " + + string.Join(" | ", superView.SoundStatus)); + Assert.That(triggers, Is.GreaterThan(0)); + Assert.That(decoded, Is.GreaterThan(0), "real WEMs decode"); + Assert.That(onThisThread.Elapsed.TotalMilliseconds, Is.LessThan(1000), "the first resolves and the decoding are not on the UI thread"); + Assert.That((firstResolves.Elapsed + onThisThread.Elapsed).TotalMilliseconds, Is.GreaterThan(1000), "the clip was cold, or this measures nothing"); + Assert.That(whileDecoding, Is.EqualTo("Decoding sounds..."), "the status says so while the decoding runs"); + Assert.That(superView.SoundStatus, Has.None.EqualTo("Decoding sounds..."), "and not after"); + GC.KeepAlive(mixer); + + bool Pump() + { + onThisThread.Start(); + var ran = ui.RunPosted(); + onThisThread.Stop(); + return ran; + } + } + finally + { + SynchronizationContext.SetSynchronizationContext(before); + } + } + } +} diff --git a/Editors/AnimationMeta/Test.AnimationMeta/SuperViewSoundTests.cs b/Editors/AnimationMeta/Test.AnimationMeta/SuperViewSoundTests.cs new file mode 100644 index 000000000..0b0edf1f0 --- /dev/null +++ b/Editors/AnimationMeta/Test.AnimationMeta/SuperViewSoundTests.cs @@ -0,0 +1,874 @@ +using System.Collections.Concurrent; +using System.IO; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Media; +using Editors.AnimationMeta.Presentation; +using Editors.AnimationMeta.SuperView; +using Editors.Audio.SoundTriggers; +using Editors.Shared.Core.Common; +using Editors.Shared.Core.Common.BaseControl; +using Editors.Shared.Core.Common.ReferenceModel; +using Microsoft.Xna.Framework; +using Moq; +using NAudio.Wave; +using Shared.Core.Commands; +using Shared.Core.PackFiles; +using Shared.Core.PackFiles.Models; +using Shared.Core.PackFiles.Utility; +using Shared.Core.ToolCreation; +using Shared.GameFormats.AnimationMeta.Definitions; +using Shared.GameFormats.AnimationMeta.Parsing; +using Shared.GameFormats.AnimationPack; +using Shared.GameFormats.Wwise; +using Shared.GameFormats.Wwise.Enums; +using Shared.GameFormats.Wwise.Hirc; +using Shared.GameFormats.Wwise.Hirc.V136; +using Shared.GameFormats.Wwise.Hirc.V136.Shared; +using Test.TestingUtility.Shared; +using Test.TestingUtility.TestUtility; + +namespace Test.AnimationMeta +{ + sealed class UiThread : SynchronizationContext + { + readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _posted = new(); + + public override void Post(SendOrPostCallback d, object? state) => _posted.Enqueue((d, state)); + + public bool RunPosted() + { + var ran = false; + while (_posted.TryDequeue(out var item)) + { + item.Callback(item.State); + ran = true; + } + return ran; + } + + public void Settle(SuperViewViewModel superView) + { + do + Assert.That(superView.SoundDecoding.Wait(TimeSpan.FromMinutes(2)), Is.True, "the background work ended"); + while (RunPosted()); + } + } + + public class SuperViewSoundTests + { + const string Decoding = "Decoding sounds..."; + const string ThrotVmd = @"variantmeshes\variantmeshdefinitions\skv_throt.variantmeshdefinition"; + const string ThrotTable = @"animations/database/battle/bin/hu17_dlc16_throt.bin"; + const string SndMeta = "animations/derpy/throt_attack_5.snd.meta"; + + const uint PersistLeaf = 11, ClipLeaf = 12, SlotLeaf = 13, PersistSndLeaf = 14, Dirt = 21, Stone = 22; + + AssetEditorTestRunner _runner = null!; + SuperViewViewModel _superView = null!; + Bank _bank = null!; + readonly List> _loads = []; + readonly List _played = [], _prepared = []; + int _stops; + UiThread _ui = null!; + SynchronizationContext? _before; + + [SetUp] + public void Setup() + { + _before = SynchronizationContext.Current; + _ui = new UiThread(); + SynchronizationContext.SetSynchronizationContext(_ui); + _loads.Clear(); + _played.Clear(); + _prepared.Clear(); + _stops = 0; + _bank = new Bank(); + _bank.Tag("Derpy_Persist", PersistLeaf); + _bank.Tag("Derpy_Clip", ClipLeaf); + _bank.Tag("Derpy_Slot", SlotLeaf); + _bank.Tag("Derpy_PersistSnd", PersistSndLeaf); + + _runner = new AssetEditorTestRunner(); + _runner.CreateCaContainer(); + _runner.LoadPackFile(PathHelper.GetDataFile("Throt.pack"), true); + _superView = Open(); + _superView.Load(new AnimationToolInput() + { + Mesh = _runner.PackFileService.FindFile(ThrotVmd)!, + FragmentName = ThrotTable, + AnimationSlot = DefaultAnimationSlotTypeHelper.GetfromValue("ATTACK_5") + }); + Assert.That(Selection.FragmentSlotList.SelectedItem?.SlotName, Is.EqualTo("ATTACK_5"), "Throt ATTACK_5 did not load"); + Assert.That(_superView.PersistentMetaEditor.ParsedFile, Is.Not.Null, "Throt's persistent meta"); + Assert.That(_superView.MetaEditor.ParsedFile, Is.Not.Null, "ATTACK_5's meta"); + _stops = 0; + } + + [TearDown] + public void RestoreTheContext() => SynchronizationContext.SetSynchronizationContext(_before); + + void Settle() => _ui.Settle(_superView); + + SuperViewViewModel Open() + { + var superView = (SuperViewViewModel)_runner.CommandFactory.Create().Execute(EditorEnums.SuperView_Editor); + superView.LoadSounds = _ => + { + var load = new TaskCompletionSource(); + _loads.Add(load); + return load.Task; + }; + superView.PrepareSound = id => + { + _prepared.Add(id); + return true; + }; + superView.PlaySound = _played.Add; + superView.StopSounds = () => _stops++; + superView.SoundName = id => _bank.Names.GetValueOrDefault(id, id.ToString()); + superView.OpenMixer = () => new SoundTriggerMixer(openDevice: false); + return superView; + } + + void Finish(int? load = null) + { + _loads[load ?? _loads.Count - 1].SetResult(_bank.Resolver()); + Settle(); + } + + SceneObject Main => _superView.SceneObjects[0].Data; + BinAnimationViewModel Selection => _superView.SceneObjects[0].FragAndSlotSelection; + MetaDataFileParser Parser => _runner.GetRequiredServiceInCurrentEditorScope(); + SceneObjectEditor SceneEditor => _runner.GetRequiredServiceInCurrentEditorScope(); + + void PointSlotSoundAt(string path, bool replayClip = false) + { + Selection.SoundMetaName = path; + Main.SoundMetaData = _runner.PackFileService.FindFile(path); + if (replayClip) + SceneEditor.SetAnimation(Main, Selection.FragmentSlotList.SelectedItem!.AnimationFile); + SceneEditor.SetMetaFile(Main, Main.MetaData, Main.PersistMetaData); + } + + void PointPersistentSoundAt(string path) + { + Selection.SoundMetaPersistName = path; + Main.PersistSoundMetaData = _runner.PackFileService.FindFile(path); + SceneEditor.SetMetaFile(Main, Main.MetaData, Main.PersistMetaData); + } + + SoundTrigger_v11 Trigger(string soundEvent, float at) + { + var tag = (SoundTrigger_v11)Parser.CreateDefault("SOUND_TRIGGER_11"); + (tag.StartTime, tag.EndTime, tag.SoundEvent) = (at, at, soundEvent); + return tag; + } + + void AddTag(MetaDataEditorViewModel editor, string soundEvent, float at) + { + editor.ParsedFile!.Attributes.Add(Trigger(soundEvent, at)); + editor.UpdateView(); + _ui.RunPosted(); + } + + string WriteSndMeta(string path, string soundEvent, float at) + { + var file = new ParsedMetadataFile { Version = 2, Attributes = [Trigger(soundEvent, at)] }; + var pfs = _runner.PackFileService; + pfs.AddFilesToPack(pfs.GetEditablePack()!, [new NewPackFileEntry(Path.GetDirectoryName(path)!, PackFile.CreateFromBytes(Path.GetFileName(path), Parser.GenerateBytes(2, file)))]); + return path; + } + + void AddATriggerToEachFile() + { + AddTag(_superView.PersistentMetaEditor, "Derpy_Persist", 0.1f); + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + PointSlotSoundAt(WriteSndMeta(SndMeta, "Derpy_Slot", 0.3f)); + } + + int TriggersInTheThreeFiles() => new[] { _superView.PersistentMetaEditor.ParsedFile, _superView.MetaEditor.ParsedFile, Main.SoundMetaData is { } sound ? Parser.ParseFile(sound.DataSource.ReadData()) : null } + .Sum(x => x?.Attributes.Count(a => a is SoundTrigger_v10 or SoundTrigger_v4) ?? 0); + + void PlayTo(float seconds) + { + var player = Main.Player; + Assert.That(player.GetAnimationLengthUs(), Is.GreaterThan(seconds * 1_000_000), "the clip is long enough not to loop"); + player.Pause(); + player.CurrentFrame = 0; + player.Play(); + while (player.GetTimeUs() < seconds * 1_000_000) + player.Update(new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(20))); + } + + string[] Status(params string[] then) => [.. _superView.SoundFileProblems, .. then]; + + [Test] + public void SoundOff_ByDefault_AndNothingLoads() + { + Assert.That(_superView.SoundOn, Is.False); + Assert.That(_loads, Is.Empty); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status())); + } + + [Test] + public void SoundOn_ShowsLoading_ThenTheStatus() + { + AddATriggerToEachFile(); + var triggers = TriggersInTheThreeFiles(); + + _superView.SoundOn = true; + + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("Loading sounds..."))); + Finish(); + var summary = _superView.SoundStatus[_superView.SoundFileProblems.Count]; + Assert.That(summary, Does.StartWith($"{triggers} triggers:")); + Assert.That(summary, Does.Contain(" 3 play,"), "the three added tags play"); + } + + [Test] + public void Playing_FiresTagsFromAllThreeFiles() + { + AddATriggerToEachFile(); + _superView.SoundOn = true; + Finish(); + + PlayTo(0.35f); + + Assert.That(_played, Is.EqualTo(new[] { PersistLeaf, ClipLeaf, SlotLeaf })); + Assert.That(_prepared, Is.SupersetOf(new[] { PersistLeaf, ClipLeaf, SlotLeaf }), "decoded ahead of the firing"); + } + + [Test] + public void Playing_StartsEachSoundTheLeadEarly() + { + Assert.That(1.0 - SuperViewViewModel.SoundLeadSeconds, Is.InRange(0.96, 0.98), "the lead puts the tag's due time in the frame landing at 0.98 s"); + Assert.That(Main.Player.GetAnimationLengthUs(), Is.GreaterThan(1_000_000), "the clip is long enough not to loop"); + AddTag(_superView.MetaEditor, "Derpy_Clip", 1.0f); + _superView.SoundOn = true; + Finish(); + + PlayTo(0.96f); + var before = _played.ToList(); + Main.Player.Update(new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(20))); + var atTheLead = _played.ToList(); + Main.Player.Update(new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(20))); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty); + Assert.That(atTheLead, Is.EqualTo(new[] { ClipLeaf }), "fired by the frame crossing 0.974 s"); + Assert.That(_played, Is.EqualTo(new[] { ClipLeaf }), "not again at 1.0 s"); + }); + } + + void Frames(int count) + { + for (var i = 0; i < count; i++) + Main.Player.Update(new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(20))); + } + + [Test] + public void Looping_FiresTheTagsAtBothEnds_OncePerPass() + { + var player = Main.Player; + var length = player.GetAnimationLengthUs() / 1_000_000d; + var frame = length / player.FrameCount(); + var end = (float)length; + if (end > length) + end = MathF.BitDecrement(end); + AddTag(_superView.MetaEditor, "Derpy_Persist", 0f); + AddTag(_superView.MetaEditor, "Derpy_Clip", (float)(length - frame / 2)); + AddTag(_superView.MetaEditor, "Derpy_Slot", end); + _superView.SoundOn = true; + Finish(); + var loops = 0; + _superView.Player.Looping += () => loops++; + Assert.That(_superView.Player.LoopAnimation.Value, Is.True, "Loop is on"); + + _superView.Player.SetAnimationNextFrame(); + _superView.Player.SetAnimationFirstFrame(); + _superView.Player.ToggleAnimationPausePlay(); + for (var i = 0; loops < 3 && i < 10_000; i++) + Frames(1); + + Assert.That(loops, Is.EqualTo(3)); + Assert.That(_played.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()), + Is.EqualTo(new Dictionary { [PersistLeaf] = 4, [ClipLeaf] = 3, [SlotLeaf] = 3 })); + } + + [Test] + public void FirstFrameThenPlay_AndPlayAtTheEnd_FireATagAtZeroOnce() + { + AddTag(_superView.MetaEditor, "Derpy_Persist", 0f); + _superView.SoundOn = true; + Finish(); + PlayTo(1.0f); + _played.Clear(); + + _superView.Player.SetAnimationFirstFrame(); + _superView.Player.ToggleAnimationPausePlay(); + Frames(10); + var firstFrame = _played.ToList(); + + _superView.Player.LoopAnimation.Value = false; + for (var i = 0; Main.Player.IsPlaying && i < 10_000; i++) + Frames(1); + _played.Clear(); + _superView.Player.ToggleAnimationPausePlay(); + Frames(10); + + Assert.Multiple(() => + { + Assert.That(firstFrame, Is.EqualTo(new[] { PersistLeaf }), "First Frame, then Play"); + Assert.That(_played, Is.EqualTo(new[] { PersistLeaf }), "Play at the end"); + }); + } + + [Test] + public void LoopOff_ATagAtZeroSoundsOnceAtEachPlay_AndNotAtTheEnd() + { + AddTag(_superView.MetaEditor, "Derpy_Persist", 0f); + _superView.SoundOn = true; + Finish(); + _superView.Player.LoopAnimation.Value = false; + + _superView.Player.SetAnimationNextFrame(); + _superView.Player.SetAnimationFirstFrame(); + _superView.Player.ToggleAnimationPausePlay(); + for (var i = 0; Main.Player.IsPlaying && i < 10_000; i++) + Frames(1); + var thePass = _played.ToList(); + _superView.Player.ToggleAnimationPausePlay(); + Frames(10); + + Assert.Multiple(() => + { + Assert.That(Main.Player.GetTimeUs(), Is.LessThan(Main.Player.GetAnimationLengthUs()), "Play at the end started the clip again"); + Assert.That(thePass, Is.EqualTo(new[] { PersistLeaf }), "once, at the start of the pass"); + Assert.That(_played, Is.EqualTo(new[] { PersistLeaf, PersistLeaf }), "and once more at the next Play"); + }); + } + + [Test] + public void LoopOff_ATagDueInTheStepThatReachesTheEnd_Sounds() + { + var lengthUs = Main.Player.GetAnimationLengthUs(); + var leadUs = (long)(SuperViewViewModel.SoundLeadSeconds * 1_000_000); + var frameMs = Enumerable.Range(30, 20).First(ms => lengthUs - (lengthUs - 1) / (ms * 1000L) * ms * 1000L > leadUs + 2000); + var end = (float)(lengthUs / 1_000_000d); + if (end > lengthUs / 1_000_000d) + end = MathF.BitDecrement(end); + AddTag(_superView.MetaEditor, "Derpy_Slot", end); + _superView.SoundOn = true; + Finish(); + _superView.Player.LoopAnimation.Value = false; + + _superView.Player.SetAnimationNextFrame(); + _superView.Player.SetAnimationFirstFrame(); + _superView.Player.ToggleAnimationPausePlay(); + for (var i = 0; Main.Player.IsPlaying && i < 10_000; i++) + Main.Player.Update(new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(frameMs))); + + Assert.That(Main.Player.GetTimeUs(), Is.EqualTo(lengthUs), "the clip ran out"); + Assert.That(_played, Is.EqualTo(new[] { SlotLeaf })); + } + + [Test] + public void ASlotReplay_FiresNothingOfTheLastClip_OnTheFrameItPutsBack() + { + var player = Main.Player; + var frameUs = player.GetAnimationLengthUs() / player.FrameCount(); + var at = 0.30f; + if ((long)(at * 1_000_000) % frameUs == 0) + at = 0.32f; + var restored = (long)(at * 1_000_000) / frameUs * frameUs / 1_000_000d; + AddTag(_superView.MetaEditor, "Derpy_Clip", (float)(restored + SuperViewViewModel.SoundLeadSeconds - 5e-7)); + _superView.SoundOn = true; + Finish(); + PlayTo(at); + Assert.That(_played, Is.EqualTo(new[] { ClipLeaf }), "the tag fires on its own pass"); + _played.Clear(); + + PointSlotSoundAt(WriteSndMeta(SndMeta, "Derpy_Slot", 3.0f), replayClip: true); + + Assert.That(player.GetTimeUs() / 1_000_000d, Is.EqualTo(restored).Within(1e-6), "the replay put the clip back on its frame"); + Assert.That(_played, Is.Empty); + } + + [Test] + public void Playing_FiresThePersistentRowsSndMeta() + { + _superView.SoundOn = true; + Finish(); + PointPersistentSoundAt(WriteSndMeta("animations/derpy/throt_persistent.snd.meta", "Derpy_PersistSnd", 0.1f)); + Settle(); + + PlayTo(0.15f); + + Assert.That(_played, Is.EqualTo(new[] { PersistSndLeaf })); + Assert.That(_superView.SoundStatus, Has.None.Contains("persistent .snd.meta"), "it resolves, so no line names it"); + } + + [Test] + public void AnEditWhileOn_PlaysOnTheNextPass() + { + _superView.SoundOn = true; + Finish(); + + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + Settle(); + PlayTo(0.25f); + + Assert.That(_played, Is.EqualTo(new[] { ClipLeaf })); + } + + [Test] + public void DeletingTheOnlyTag_StopsItPlaying() + { + var file = _superView.MetaEditor.ParsedFile!; + file.Attributes.Clear(); + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _superView.SoundOn = true; + Finish(); + + file.Attributes.Clear(); + _superView.MetaEditor.UpdateView(); + Settle(); + PlayTo(0.25f); + + Assert.That(_played, Is.Empty); + } + + [Test] + public void AFieldEditWhileOn_PlaysTheNewEvent() + { + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _superView.SoundOn = true; + Finish(); + + _superView.MetaEditor.Tags.SelectMany(x => x.Variables).Single(x => x.ValueAsString == "Derpy_Clip").ValueAsString = "Derpy_Slot"; + Settle(); + PlayTo(0.25f); + + Assert.That(_played, Is.EqualTo(new[] { SlotLeaf })); + } + + [Test] + public void APickedAnimation_DropsTheSlotsSndMeta() + { + var clip = _runner.PackFileService.FindFile(Selection.FragmentSlotList.SelectedItem!.AnimationFile)!; + PointSlotSoundAt(WriteSndMeta(SndMeta, "Derpy_Slot", 0.3f)); + _superView.SoundOn = true; + Finish(); + + Selection.SetAnimationFile(clip); + Settle(); + PlayTo(0.35f); + + Assert.That(_played, Has.No.Member(SlotLeaf)); + Assert.That(Selection.SoundMetaName, Is.Null); + } + + [Test] + public void ANewMesh_DropsTheSndMetas() + { + PointSlotSoundAt(WriteSndMeta(SndMeta, "Derpy_Slot", 0.3f)); + _superView.SoundOn = true; + Finish(); + Assert.That(_superView.SoundStatus[_superView.SoundFileProblems.Count], Does.StartWith("1 trigger:")); + + SceneEditor.SetMesh(Main, _runner.PackFileService.FindFile(ThrotVmd)!); + Settle(); + + Assert.That(_superView.SoundStatus[_superView.SoundFileProblems.Count], Does.StartWith("0 triggers")); + } + + [Test] + public void Decoding_ShowsUntilTheBackgroundWorkEnds() + { + _superView.SoundOn = true; + Finish(); + Assert.That(_superView.SoundStatus, Has.None.EqualTo(Decoding)); + + using var hold = new ManualResetEventSlim(); + _bank.Hold = hold; + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _ui.RunPosted(); + Assert.That((_superView.SoundDecoding.IsCompleted, _superView.SoundStatus[^1]), Is.EqualTo((false, Decoding))); + + hold.Set(); + Settle(); + Assert.That(_superView.SoundStatus, Has.None.EqualTo(Decoding)); + Assert.That(_superView.SoundStatus[_superView.SoundFileProblems.Count], Does.Contain(" 1 plays,"), "the added tag is in the status"); + } + + [Test] + public void ANewSlot_PlaysNoneOfTheLastClipsTriggers_UntilItsRebuildLands() + { + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _superView.SoundOn = true; + Finish(); + PlayTo(0.25f); + Assert.That(_played, Is.EqualTo(new[] { ClipLeaf }), "the tag fires on its own clip"); + _played.Clear(); + + var slots = _superView.SceneObjects[0].FragAndSlotSelection.FragmentSlotList; + slots.SelectedItem = slots.PossibleValues.First(x => x.SlotName.StartsWith("ATTACK_") && x.SlotName != "ATTACK_5" && _runner.PackFileService.FindFile(x.AnimationFile) != null); + PlayTo(0.25f); + + Assert.That(_played, Is.Empty, "the last clip's trigger did not fire on this one"); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status(Decoding)), "the last clip's summary is gone"); + Settle(); + PlayTo(0.25f); + Assert.That(_played, Is.Empty, "and the new clip's own triggers do not have it"); + } + + [Test] + public void AStaleWarmUp_StopsAtItsNextTag() + { + AddATriggerToEachFile(); + _superView.SoundOn = true; + Finish(); + using var hold = new ManualResetEventSlim(); + _bank.Hold = hold; + _bank.OffThread.Clear(); + + _superView.SoundOn = false; + _superView.SoundOn = true; + _superView.SoundOn = false; + _superView.SoundOn = true; + hold.Set(); + Settle(); + + var lastTag = WwiseHash.Compute("Derpy_Slot_Event"); + Assert.That(_bank.OffThread.Count(x => x == lastTag), Is.EqualTo(1), "only the latest warm-up reached the last tag"); + } + + [Test] + public void AJobThatThrows_EndsCleanly_AndSaysWhy() + { + _superView.SoundOn = true; + Finish(); + _bank.Throw = new InvalidOperationException("the bank is gone"); + + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + Settle(); + + Assert.That(_superView.SoundDecoding.IsFaulted, Is.False); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("Sounds could not be prepared: the bank is gone"))); + _bank.Throw = null; + _superView.SoundOn = false; + _superView.SoundOn = true; + Settle(); + Assert.That(_superView.SoundStatus, Has.None.StartsWith("Sounds could not be prepared")); + } + + [Test] + public void TheFirstWarmUpsFailure_ReplacesLoadingSounds() + { + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _bank.Throw = new InvalidOperationException("the bank is gone"); + + _superView.SoundOn = true; + Finish(); + + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("Sounds could not be prepared: the bank is gone"))); + } + + [Test] + public void AStaleJobsFailure_IsDropped() + { + AddTag(_superView.MetaEditor, "Derpy_Clip", 0.2f); + _superView.SoundOn = true; + Finish(); + using var hold = new ManualResetEventSlim(); + _bank.Hold = hold; + _bank.Throw = new InvalidOperationException("the bank is gone"); + + AddTag(_superView.MetaEditor, "Derpy_Slot", 0.3f); + Assert.That(SpinWait.SpinUntil(() => _bank.Held > 0, TimeSpan.FromSeconds(30)), Is.True, "the first job is inside a lookup"); + _bank.Hold = null; + AddTag(_superView.MetaEditor, "Derpy_Persist", 0.1f); + hold.Set(); + Settle(); + + Assert.That(_superView.SoundStatus, Has.None.StartsWith("Sounds could not be prepared")); + Assert.That(_superView.SoundStatus[_superView.SoundFileProblems.Count], Does.Contain(" 3 play,"), "the later rebuild landed"); + } + + [Test] + public void ANewSlot_HidesTheLastClipsPickers_UntilItsRebuildLands() + { + _bank.Rows["Derpy_Step"] = new AudioTagEvents(_bank.Event("Derpy_Step_Event", _bank.Switch("Surface", "Dirt", ("Dirt", _bank.Sound(Dirt)), ("Stone", _bank.Sound(Stone)))), ""); + AddTag(_superView.MetaEditor, "Derpy_Step", 0.1f); + _superView.SoundOn = true; + Finish(); + Assert.That(_superView.SoundSwitchPickers, Has.Count.EqualTo(1)); + + var slots = _superView.SceneObjects[0].FragAndSlotSelection.FragmentSlotList; + slots.SelectedItem = slots.PossibleValues.First(x => x.SlotName.StartsWith("ATTACK_") && x.SlotName != "ATTACK_5" && _runner.PackFileService.FindFile(x.AnimationFile) != null); + + Assert.That(_superView.SoundSwitchPickers, Is.Empty, "while the rebuild is on its way"); + Settle(); + Assert.That(_superView.SoundSwitchPickers, Is.Empty, "the new clip's triggers reach no switch"); + } + + [Test] + public void SoundOffDuringLoad_PlaysNothing() + { + AddATriggerToEachFile(); + _superView.SoundOn = true; + _superView.SoundOn = false; + Finish(0); + _superView.SoundOn = true; + + PlayTo(0.35f); + + Assert.That(_played, Is.Empty); + Assert.That((_loads.Count, _superView.SoundStatus), Is.EqualTo((2, Status("Loading sounds..."))), "the stale load built no session"); + + _superView.Close(); + Assert.DoesNotThrow(() => Finish(1)); + PlayTo(0.35f); + Assert.That(_played, Is.Empty); + } + + [Test] + public void SlotChange_StopsSounds() + { + _superView.SoundOn = true; + Finish(); + var slots = _superView.SceneObjects[0].FragAndSlotSelection.FragmentSlotList; + + slots.SelectedItem = slots.PossibleValues.First(x => x.SlotName != "ATTACK_5" && _runner.PackFileService.FindFile(x.AnimationFile) != null); + Assert.That(_stops, Is.EqualTo(1)); + + _superView.SoundOn = false; + Assert.That(_stops, Is.EqualTo(2)); + } + + [Test] + public void Picker_ChangesWhatPlays() + { + _bank.Rows["Derpy_Step"] = new AudioTagEvents(_bank.Event("Derpy_Step_Event", _bank.Switch("Surface", "Dirt", ("Dirt", _bank.Sound(Dirt)), ("Stone", _bank.Sound(Stone)))), ""); + AddTag(_superView.MetaEditor, "Derpy_Step", 0.1f); + _superView.SoundOn = true; + Finish(); + + var picker = _superView.SoundSwitchPickers.Single(); + Assert.That((picker.GroupName, picker.Options.Select(x => x.ToString()), picker.Selected.Name), + Is.EqualTo(("Surface", new[] { "Dirt (default)", "Stone" }, "Dirt"))); + PlayTo(0.15f); + Assert.That(_played, Is.EqualTo(new[] { Dirt })); + + picker.Selected = picker.Options.Single(x => x.Name == "Stone"); + Settle(); + PlayTo(0.15f); + + Assert.That(_played, Is.EqualTo(new[] { Dirt, Stone })); + Assert.That(_superView.SoundSwitchPickers.Single().Selected.Name, Is.EqualTo("Stone"), "the picker keeps the choice"); + } + + [Test] + public void PickingASlot_PlaysTheSndMetaItNames() + { + var attack = Selection.FragmentSlotList.SelectedItem!; + var persist = Selection.FragmentSlotList.PossibleValues.First(x => x.SlotName == "PERSISTENT_METADATA_ALIVE"); + Assert.That((Selection.SoundMetaName, Selection.SoundMetaPersistName), Is.EqualTo((attack.SoundFile, persist.SoundFile))); + Assert.That(_superView.SoundFileProblems, Does.Contain($"Slot .snd.meta {attack.SoundFile} is in no loaded pack.")); + WriteSndMeta(attack.SoundFile, "Derpy_Slot", 0.3f); + WriteSndMeta(persist.SoundFile, "Derpy_PersistSnd", 0.1f); + + Selection.FragmentSlotList.SelectedItem = Selection.FragmentSlotList.PossibleValues.First(x => x != attack && x != persist); + Selection.FragmentSlotList.SelectedItem = attack; + _superView.SoundOn = true; + Finish(); + PlayTo(0.35f); + + Assert.That(_played, Is.EqualTo(new[] { PersistSndLeaf, SlotLeaf })); + Assert.That(_superView.SoundFileProblems, Is.Empty); + } + + [Test] + public void NoAudioDevice_SaysSo_AndSoundStaysOff() + { + _superView.OpenMixer = () => throw new InvalidOperationException("no device here"); + + _superView.SoundOn = true; + + Assert.That((_superView.SoundOn, _loads.Count), Is.EqualTo((false, 0))); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("No audio device could be opened: no device here"))); + } + + [Test] + public void ADeviceThatStops_SaysSo_AndSoundGoesOff() + { + var devices = new List>(); + _superView.OpenMixer = () => new SoundTriggerMixer([() => + { + devices.Add(new Mock()); + return devices[^1].Object; + }]); + _superView.SoundOn = true; + Finish(); + + devices[0].Raise(x => x.PlaybackStopped += null, new StoppedEventArgs(new InvalidOperationException("the endpoint went away"))); + Settle(); + + Assert.That(_superView.SoundOn, Is.False); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("The sound device stopped: the endpoint went away"))); + devices[0].Verify(x => x.Dispose(), Times.Once); + + _superView.SoundOn = true; + Assert.That((devices.Count, _superView.SoundOn), Is.EqualTo((2, true)), "a new device"); + + devices[0].Raise(x => x.PlaybackStopped += null, new StoppedEventArgs(new InvalidOperationException("late"))); + Settle(); + Assert.That(_superView.SoundOn, Is.True, "the device let go of is no longer heard from"); + } + + [Test] + public void Status_ShowsFileProblems_AlwaysAndTheTriggers_OnlyWithSoundOn() + { + const string Missing = "animations/derpy/nowhere.snd.meta"; + PointSlotSoundAt(Missing); + Assert.That(_superView.SoundFileProblems, Does.Contain($"Slot .snd.meta {Missing} is in no loaded pack.")); + Assert.That(_superView.SoundStatus, Is.EqualTo(Status())); + + _superView.SoundOn = true; + Assert.That(_superView.SoundStatus, Is.EqualTo(Status("Loading sounds..."))); + Finish(); + var problems = _superView.SoundFileProblems.Count; + Assert.That(_superView.SoundStatus.Take(problems), Is.EqualTo(Status())); + Assert.That(_superView.SoundStatus[problems], Does.Match("^[0-9]+ triggers?")); + + _superView.SoundOn = false; + Assert.That(_superView.SoundStatus, Is.EqualTo(Status())); + } + + [Test, Apartment(ApartmentState.STA)] + public void TheSoundStrip_IsBound() + { + _bank.Rows["Derpy_Step"] = new AudioTagEvents(_bank.Event("Derpy_Step_Event", _bank.Switch("Surface", "Dirt", ("Dirt", _bank.Sound(Dirt)), ("Stone", _bank.Sound(Stone)))), ""); + AddTag(_superView.MetaEditor, "Derpy_Step", 0.1f); + var panel = new EditorView { DataContext = _superView }; + Lay(panel); + + Descendants(panel).OfType().Single(x => AutomationProperties.GetAutomationId(x) == "SoundOn").IsChecked = true; + Assert.That(_superView.SoundOn, Is.True); + Finish(); + Lay(panel); + Assert.That(Descendants(panel).OfType().Select(x => x.Text), Is.SupersetOf(_superView.SoundStatus)); + var combo = Descendants(panel).OfType().Single(x => AutomationProperties.GetAutomationId(x) == "SoundSwitch"); + combo.SelectedIndex = 1; + Assert.That(_superView.SoundSwitchPickers.Single().Selected.Name, Is.EqualTo("Stone")); + var picker = _superView.SoundSwitchPickers.Single(); + _superView.SoundOn = false; + Lay(panel); + Assert.That((_superView.SoundSwitchPickers.Count, picker.Selected?.Name), Is.EqualTo((0, "Stone"))); + } + + static void Lay(FrameworkElement element) + { + element.Measure(new Size(1400, 900)); + element.Arrange(new Rect(0, 0, 1400, 900)); + element.UpdateLayout(); + } + + static IEnumerable Descendants(DependencyObject root) + { + for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++) + { + var child = VisualTreeHelper.GetChild(root, i); + yield return child; + foreach (var below in Descendants(child)) + yield return below; + } + } + + sealed class Bank + { + uint _next = 1_000_000; + + public Dictionary Items { get; } = []; + public Dictionary Rows { get; } = new(StringComparer.Ordinal); + public Dictionary Names { get; } = []; + + readonly int _thread = Environment.CurrentManagedThreadId; + + public ManualResetEventSlim? Hold { get; set; } + + public int Held => Volatile.Read(ref _held); + int _held; + + public Exception? Throw { get => _throw; set => _throw = value; } + Exception? _throw; + + public ConcurrentQueue OffThread { get; } = new(); + + public SoundTriggerResolver Resolver() => new(tag => Rows.GetValueOrDefault(tag), id => + { + if (Environment.CurrentManagedThreadId != _thread) + { + if (Hold is { } hold) + { + Interlocked.Increment(ref _held); + hold.Wait(TimeSpan.FromSeconds(30)); + } + if (Interlocked.Exchange(ref _throw, null) is { } thrown) + throw thrown; + OffThread.Enqueue(id); + } + return Items.TryGetValue(id, out var item) ? [item] : []; + }, _ => true); + + uint Hash(string name) + { + var id = WwiseHash.Compute(name); + Names[id] = name; + return id; + } + + public void Tag(string tag, uint leaf) => Rows[tag] = new AudioTagEvents(Event(tag + "_Event", Sound(leaf)), ""); + + public string Event(string name, uint target) + { + var action = _next++; + Items[action] = new CAkAction_V136 { Id = action, HircType = AkBkHircType.Action, ActionType = AkActionType.Play, IdExt = target }; + var id = Hash(name); + Items[id] = new CAkEvent_V136 { Id = id, HircType = AkBkHircType.Event, Actions = [new CAkEvent_V136.Action_V136 { ActionId = action }] }; + return name; + } + + public uint Sound(uint sourceId) + { + var id = _next++; + Items[id] = new CAkSound_V136 + { + Id = id, + HircType = AkBkHircType.Sound, + AkBankSourceData = new AkBankSourceData_V136 { AkMediaInformation = new AkBankSourceData_V136.AkMediaInformation_V136 { SourceId = sourceId } }, + }; + return id; + } + + public uint Switch(string group, string defaultCase, params (string Case, uint Child)[] cases) + { + var id = _next++; + Items[id] = new CAkSwitchCntr_V136 + { + Id = id, + HircType = AkBkHircType.SwitchContainer, + GroupId = Hash(group), + DefaultSwitch = Hash(defaultCase), + SwitchList = cases + .Select(x => (ICAkSwitchCntr.ICAkSwitchPackage)new CAkSwitchCntr_V136.CAkSwitchPackage_V136 { SwitchId = Hash(x.Case), NodeIdList = [x.Child] }) + .ToList(), + }; + return id; + } + } + } +} diff --git a/Editors/Audio/AudioCacheTests.cs b/Editors/Audio/AudioCacheTests.cs index 841672fe6..a0ea83184 100644 --- a/Editors/Audio/AudioCacheTests.cs +++ b/Editors/Audio/AudioCacheTests.cs @@ -645,5 +645,94 @@ private static void WriteChunk(Stream output, string tag, byte[] payload) writer.Write((uint)payload.Length); output.Write(payload); } + + private sealed class HeldCacheHelper(AudioCache cache) : IAudioCacheHelper + { + public ManualResetEventSlim? Hold { get; set; } + public ManualResetEventSlim Entered { get; } = new(); + + public string ComputeFingerprint(List containers, string cacheKind) => cacheKind; + public string GetCacheFilePath(string label, string fingerprint) => fingerprint; + public AudioCache TryLoadFromCache(string cacheFilePath, string fingerprint) => throw new NotSupportedException(); + public AudioCache SaveAndLoadCache(AudioCacheSource source) => throw new NotSupportedException(); + + public AudioCache LoadOrBuildCache(AudioCacheSource source) + { + Entered.Set(); + Hold?.Wait(TimeSpan.FromSeconds(30)); + return cache; + } + } + + const string HeldBnkPath = @"audio\wwise\held.bnk"; + const uint HeldEventId = 555; + + private (AudioRepository Repository, HeldCacheHelper Helper, AudioCache Cache) HeldRepository(Func holdReads, ManualResetEventSlim readEntered) + { + var bnk = PackFile.CreateFromBytes("held.bnk", CreateBnk(HeldEventId, 1, 0)); + var container = CreateContainer(true, [(HeldBnkPath, bnk)]); + var dbOptions = CreateTestDbOptions(); + SaveCache("game files", [container.Object], dbOptions); + var cache = AudioCache.CreateFromFingerPrint(dbOptions, "game files"); + + var packFileService = new Mock(); + packFileService.Setup(x => x.GetAllPackfileContainers()).Returns([container.Object]); + packFileService.Setup(x => x.FindFile(HeldBnkPath, It.IsAny())).Returns(() => + { + if (holdReads() is { } hold) + { + readEntered.Set(); + hold.Wait(TimeSpan.FromSeconds(30)); + } + return bnk; + }); + var settings = new ApplicationSettingsService(GameTypeEnum.Warhammer3); + var helper = new HeldCacheHelper(cache); + var repository = new AudioRepository(settings, packFileService.Object, helper, new BnkLoader(packFileService.Object), new Mock().Object); + return (repository, helper, cache); + } + + [Test] + public void Repository_ALookupWaitsForOneInProgress() + { + ManualResetEventSlim? holdReads = null; + using var readEntered = new ManualResetEventSlim(); + using var hold = new ManualResetEventSlim(); + var (repository, _, _) = HeldRepository(() => holdReads, readEntered); + using (repository) + { + repository.Load([]); + holdReads = hold; + + var first = Task.Run(() => repository.GetHircs(HeldEventId)); + Assert.That(readEntered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the first lookup is reading the bank"); + holdReads = null; + var second = Task.Run(() => repository.GetHircs(HeldEventId + 1)); + var secondWaited = !second.Wait(TimeSpan.FromMilliseconds(300)); + hold.Set(); + + Assert.That(secondWaited, Is.True, "the second lookup waited"); + Assert.That(first.Wait(TimeSpan.FromSeconds(10)) && second.Wait(TimeSpan.FromSeconds(10)), Is.True); + Assert.That(first.Result, Has.Count.EqualTo(1)); + } + } + + [Test] + public void Repository_DisposedDuringALoad_LetsGoOfWhatTheLoadOpens() + { + using var readEntered = new ManualResetEventSlim(); + using var hold = new ManualResetEventSlim(); + var (repository, helper, cache) = HeldRepository(() => null, readEntered); + helper.Hold = hold; + + var load = Task.Run(() => repository.Load([])); + Assert.That(helper.Entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the load is reading the cache"); + Assert.That(Task.Run(repository.Dispose).Wait(TimeSpan.FromSeconds(5)), Is.True, "Dispose does not wait for the load"); + hold.Set(); + Assert.That(load.Wait(TimeSpan.FromSeconds(10)), Is.True, "the load ended"); + + Assert.Throws(() => cache.GetBnks(), "the cache the load opened was disposed"); + Assert.That(repository.GetHircs(HeldEventId), Is.Empty); + } } } diff --git a/Editors/Audio/Editors.Audio.csproj b/Editors/Audio/Editors.Audio.csproj index 7b077925d..040e53e32 100644 --- a/Editors/Audio/Editors.Audio.csproj +++ b/Editors/Audio/Editors.Audio.csproj @@ -8,12 +8,14 @@ + + diff --git a/Editors/Audio/Shared/Storage/AudioRepository.cs b/Editors/Audio/Shared/Storage/AudioRepository.cs index bfab84bb9..f7b7ba569 100644 --- a/Editors/Audio/Shared/Storage/AudioRepository.cs +++ b/Editors/Audio/Shared/Storage/AudioRepository.cs @@ -58,6 +58,11 @@ internal class AudioRepository : IAudioRepository, IDisposable private readonly IEventHub _eventHub; private readonly ILogger _logger = Logging.Create(); + // Lookups and a load's final swap only, so a lookup never waits for a whole load. + private readonly object _gate = new(); + private readonly object _loadGate = new(); + private bool _disposed; + private readonly List _loadedBnkDataLanguages = []; private readonly List _loadedLayers = []; private string _loadedFingerprint = ""; @@ -116,33 +121,43 @@ public void EnsureGameFilesCache() public void Load(List languages) { - var requestedLanguages = _loadedBnkDataLanguages - .Union(languages, StringComparer.OrdinalIgnoreCase) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); + lock (_loadGate) + { + List requestedLanguages; + lock (_gate) + { + requestedLanguages = _loadedBnkDataLanguages + .Union(languages, StringComparer.OrdinalIgnoreCase) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + } - var gameInformation = GameInformationDatabase.GetGameById(_applicationSettingsService.CurrentSettings.CurrentGame); - if (gameInformation.BankGeneratorVersion == GameBnkVersion.Unsupported) - return; + var gameInformation = GameInformationDatabase.GetGameById(_applicationSettingsService.CurrentSettings.CurrentGame); + if (gameInformation.BankGeneratorVersion == GameBnkVersion.Unsupported) + return; - var cacheSources = CreateCacheSources(); - if (cacheSources.Count == 0) - return; + var cacheSources = CreateCacheSources(); + if (cacheSources.Count == 0) + return; - LoadCacheSources(cacheSources, requestedLanguages); + LoadCacheSources(cacheSources, requestedLanguages); + } } internal void LoadCacheSources(List cacheSources, List requestedLanguages) { var fingerprint = CreateCombinedFingerprint(cacheSources); - if (_loadedLayers.Count != 0 - && fingerprint == _loadedFingerprint - && requestedLanguages.All( - language => _loadedBnkDataLanguages.Contains( - language, - StringComparer.OrdinalIgnoreCase))) + lock (_gate) { - return; + if (_loadedLayers.Count != 0 + && fingerprint == _loadedFingerprint + && requestedLanguages.All( + language => _loadedBnkDataLanguages.Contains( + language, + StringComparer.OrdinalIgnoreCase))) + { + return; + } } var layers = LoadLayers(cacheSources); @@ -153,12 +168,20 @@ internal void LoadCacheSources(List cacheSources, List bnk.Layer.ResolvedBnkPaths.Add(bnk.Bnk.Path); var datData = MergeDatData(layers.Select(layer => layer.AudioCache.LoadDatData())); - ApplyLoadedLayers( - layers, - resolvedBnks.Keys.ToList(), - datData, - requestedLanguages, - fingerprint); + lock (_gate) + { + if (_disposed) + { + DisposeLayers(layers); + return; + } + ApplyLoadedLayers( + layers, + resolvedBnks.Keys.ToList(), + datData, + requestedLanguages, + fingerprint); + } } catch { @@ -197,155 +220,167 @@ internal List CreateCacheSources() public void Clear() { - DisposeLayers(_loadedLayers); - _loadedLayers.Clear(); - _loadedBnkDataLanguages.Clear(); - _loadedFingerprint = ""; - _allCachedHircsLoaded = false; - _allCachedDidxLoaded = false; - _hircsById = []; - _hircByBnkPathById = []; - _resolvedHircByReferringBnkPathById = []; - _hircsByType = []; - _didxAudioListById = []; - PackFileByBnkName = []; - NameById = []; - StateGroupsByDialogueEvent = []; - QualifiedStateGroupByStateGroupByDialogueEvent = []; - StatesByStateGroup = []; - + lock (_gate) + { + DisposeLayers(_loadedLayers); + _loadedLayers.Clear(); + _loadedBnkDataLanguages.Clear(); + _loadedFingerprint = ""; + _allCachedHircsLoaded = false; + _allCachedDidxLoaded = false; + _hircsById = []; + _hircByBnkPathById = []; + _resolvedHircByReferringBnkPathById = []; + _hircsByType = []; + _didxAudioListById = []; + PackFileByBnkName = []; + NameById = []; + StateGroupsByDialogueEvent = []; + QualifiedStateGroupByStateGroupByDialogueEvent = []; + StatesByStateGroup = []; + } } public List GetHircs(AkBkHircType hircType) { - if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) + lock (_gate) { - if (_hircsByType.TryGetValue(hircType, out var cachedHircs)) - return cachedHircs; - - var references = new List(); - foreach (var layer in _loadedLayers) + if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) { - references.AddRange( - layer.AudioCache.FindHircs( - hircType, - layer.ResolvedBnkPaths)); + if (_hircsByType.TryGetValue(hircType, out var cachedHircs)) + return cachedHircs; + + var references = new List(); + foreach (var layer in _loadedLayers) + { + references.AddRange( + layer.AudioCache.FindHircs( + hircType, + layer.ResolvedBnkPaths)); + } + + var hircs = _bnkLoader.LoadHircs(references); + _hircsByType[hircType] = hircs; + return hircs; } - var hircs = _bnkLoader.LoadHircs(references); - _hircsByType[hircType] = hircs; - return hircs; + return _hircsById + .SelectMany(entry => entry.Value) + .Where(hirc => hirc.HircType == hircType) + .ToList(); } - - return _hircsById - .SelectMany(entry => entry.Value) - .Where(hirc => hirc.HircType == hircType) - .ToList(); } public List GetHircs(uint id) { - if (_hircsById.TryGetValue(id, out var hircs)) - return hircs; - - if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) + lock (_gate) { - var references = new List(); - foreach (var layer in _loadedLayers) + if (_hircsById.TryGetValue(id, out var hircs)) + return hircs; + + if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) { - references.AddRange( - layer.AudioCache.FindHircs( - id, - layer.ResolvedBnkPaths)); + var references = new List(); + foreach (var layer in _loadedLayers) + { + references.AddRange( + layer.AudioCache.FindHircs( + id, + layer.ResolvedBnkPaths)); + } + + hircs = _bnkLoader.LoadHircs(references); + _hircsById[id] = hircs; + return hircs; } - hircs = _bnkLoader.LoadHircs(references); - _hircsById[id] = hircs; - return hircs; + return []; } - - return []; } public List GetHircs(uint id, string owningFileName) => GetHircs(id).Where(x => x.BnkFilePath == owningFileName).ToList(); public Dictionary ResolveHircReferences(IReadOnlyCollection requests) { - var result = new Dictionary(); - var unresolvedRequests = new List(); - - foreach (var request in (requests ?? []).Where(request => request != null && request.HircId != 0).Distinct()) + lock (_gate) { - if (TryGetResolvedHirc(request.HircId, request.ReferringBnkFilePath, out var resolvedHirc)) - { - result[request] = resolvedHirc; - continue; - } + var result = new Dictionary(); + var unresolvedRequests = new List(); - if (TryGetCachedHirc(request.HircId, request.ReferringBnkFilePath, out var sameBankHirc)) + foreach (var request in (requests ?? []).Where(request => request != null && request.HircId != 0).Distinct()) { - CacheResolvedHirc(request.HircId, request.ReferringBnkFilePath, sameBankHirc); - result[request] = sameBankHirc; - continue; - } + if (TryGetResolvedHirc(request.HircId, request.ReferringBnkFilePath, out var resolvedHirc)) + { + result[request] = resolvedHirc; + continue; + } - if (_hircsById.TryGetValue(request.HircId, out var cachedCandidates) && cachedCandidates.Count != 0) - { - var selectedHirc = SelectCachedFallback(request, cachedCandidates); - CacheResolvedHirc(request.HircId, request.ReferringBnkFilePath, selectedHirc); - result[request] = selectedHirc; - continue; - } + if (TryGetCachedHirc(request.HircId, request.ReferringBnkFilePath, out var sameBankHirc)) + { + CacheResolvedHirc(request.HircId, request.ReferringBnkFilePath, sameBankHirc); + result[request] = sameBankHirc; + continue; + } - unresolvedRequests.Add(request); - } + if (_hircsById.TryGetValue(request.HircId, out var cachedCandidates) && cachedCandidates.Count != 0) + { + var selectedHirc = SelectCachedFallback(request, cachedCandidates); + CacheResolvedHirc(request.HircId, request.ReferringBnkFilePath, selectedHirc); + result[request] = selectedHirc; + continue; + } + + unresolvedRequests.Add(request); + } - if (unresolvedRequests.Count != 0 && _loadedLayers.Count != 0 && !_allCachedHircsLoaded) - ResolveUncachedHircReferences(unresolvedRequests, result); + if (unresolvedRequests.Count != 0 && _loadedLayers.Count != 0 && !_allCachedHircsLoaded) + ResolveUncachedHircReferences(unresolvedRequests, result); - return result; + return result; + } } public Dictionary> GetHircs(IReadOnlyCollection ids) { - var resolvedHircsById = new Dictionary>(); - var uncachedIds = new HashSet(); - - foreach (var id in ids) + lock (_gate) { - if (_hircsById.TryGetValue(id, out var cachedHircs)) - resolvedHircsById[id] = cachedHircs; - else - uncachedIds.Add(id); - } + var resolvedHircsById = new Dictionary>(); + var uncachedIds = new HashSet(); - if (uncachedIds.Count != 0 && _loadedLayers.Count != 0 && !_allCachedHircsLoaded) - { - var references = new List(); - foreach (var layer in _loadedLayers) - references.AddRange(layer.AudioCache.FindHircs(uncachedIds, layer.ResolvedBnkPaths)); + foreach (var id in ids) + { + if (_hircsById.TryGetValue(id, out var cachedHircs)) + resolvedHircsById[id] = cachedHircs; + else + uncachedIds.Add(id); + } - var loadedHircs = _bnkLoader.LoadHircs(references); - foreach (var hircsForId in loadedHircs.GroupBy(hirc => hirc.Id)) + if (uncachedIds.Count != 0 && _loadedLayers.Count != 0 && !_allCachedHircsLoaded) { - var groupedHircs = hircsForId.ToList(); - CacheHircsByBnkPath(groupedHircs); - _hircsById[hircsForId.Key] = groupedHircs; - resolvedHircsById[hircsForId.Key] = groupedHircs; + var references = new List(); + foreach (var layer in _loadedLayers) + references.AddRange(layer.AudioCache.FindHircs(uncachedIds, layer.ResolvedBnkPaths)); + + var loadedHircs = _bnkLoader.LoadHircs(references); + foreach (var hircsForId in loadedHircs.GroupBy(hirc => hirc.Id)) + { + var groupedHircs = hircsForId.ToList(); + CacheHircsByBnkPath(groupedHircs); + _hircsById[hircsForId.Key] = groupedHircs; + resolvedHircsById[hircsForId.Key] = groupedHircs; + } } - } - return resolvedHircsById; + return resolvedHircsById; + } } public string GetNameFromId(uint value) => GetNameFromId(value, out var _); public string GetNameFromId(uint value, out bool found) { - found = NameById.ContainsKey(value); - if (found) - return NameById[value]; - return value.ToString(); + found = NameById.TryGetValue(value, out var name); + return found ? name! : value.ToString(); } public string GetNameFromId(uint? key) @@ -358,26 +393,29 @@ public string GetNameFromId(uint? key) public HashSet GetUsedVanillaHircIdsByLanguageId(uint languageId) { - if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) + lock (_gate) { - var result = new HashSet(); - foreach (var layer in _loadedLayers) + if (_loadedLayers.Count != 0 && !_allCachedHircsLoaded) { - result.UnionWith( - layer.AudioCache.FindHircIds( - languageId, - true, - layer.ResolvedBnkPaths)); + var result = new HashSet(); + foreach (var layer in _loadedLayers) + { + result.UnionWith( + layer.AudioCache.FindHircIds( + languageId, + true, + layer.ResolvedBnkPaths)); + } + return result; } - return result; - } - return HircsById - .SelectMany( - entry => entry.Value - .Where(hirc => hirc.LanguageId == languageId && hirc.IsCA == true) - .Select(_ => entry.Key)) - .ToHashSet(); + return HircsById + .SelectMany( + entry => entry.Value + .Where(hirc => hirc.LanguageId == languageId && hirc.IsCA == true) + .Select(_ => entry.Key)) + .ToHashSet(); + } } public HashSet GetUsedVanillaSourceIdsByLanguageId(uint languageId) @@ -573,15 +611,17 @@ private static void AppendLists(Dictionary> target, Diction } } + // Filled before it is published: FindDataWem reads it without the lock. private void SetCurrentBnkFiles(List bnkPaths) { - PackFileByBnkName = []; + var packFileByBnkName = new Dictionary(); foreach (var bnkPath in bnkPaths) { var bnk = _packFileService.FindFile(bnkPath); if (bnk != null) - PackFileByBnkName.TryAdd(bnk.Name, bnk); + packFileByBnkName.TryAdd(bnk.Name, bnk); } + PackFileByBnkName = packFileByBnkName; } private static Dictionary CreateEffectiveBnks(List layers, List languages) @@ -617,8 +657,11 @@ private void EnsureAllCachedHircsLoaded() private Dictionary> GetAllCachedHircs() { - EnsureAllCachedHircsLoaded(); - return _hircsById; + lock (_gate) + { + EnsureAllCachedHircsLoaded(); + return _hircsById; + } } private void EnsureAllCachedDidxLoaded() @@ -652,8 +695,11 @@ private void EnsureAllCachedDidxLoaded() private Dictionary> GetAllCachedDidx() { - EnsureAllCachedDidxLoaded(); - return _didxAudioListById; + lock (_gate) + { + EnsureAllCachedDidxLoaded(); + return _didxAudioListById; + } } private static string CreateCombinedFingerprint(List sources) @@ -850,7 +896,11 @@ private void WarnIfAmbiguousHircReference(uint id, string referringBnkFilePath, public void Dispose() { _eventHub.UnRegister(this); - Clear(); + lock (_gate) + { + _disposed = true; + Clear(); + } } private sealed class LoadedLayer(AudioCache audioCache) diff --git a/Editors/Audio/SoundTriggerTests.cs b/Editors/Audio/SoundTriggerTests.cs new file mode 100644 index 000000000..4b581bc32 --- /dev/null +++ b/Editors/Audio/SoundTriggerTests.cs @@ -0,0 +1,1578 @@ +using Editors.Audio.SoundTriggers; +using Moq; +using NAudio.Wave; +using Shared.GameFormats.DB; +using Shared.GameFormats.Wwise; +using Shared.GameFormats.Wwise.Enums; +using Shared.GameFormats.Wwise.Hirc; +using Shared.GameFormats.Wwise.Hirc.V136; +using Shared.GameFormats.Wwise.Hirc.V136.Shared; +using Shared.GameFormats.Wwise.Wem.V132; +using Shared.GameFormats.Wwise.Wem.V132.Encoding; + +namespace Test.Audio +{ + [TestFixture] + internal class SoundTriggerTests + { + static DbRow Tag(string key, string battleStart, string campaignStart = "") => new( + new Dictionary + { + ["key"] = key, + ["sound_event_battle_start"] = battleStart, + ["sound_event_campaign_start"] = campaignStart, + }, 22, "test_pack", "db/audio_metadata_tags_tables/test"); + + [Test] + public void TagTable_FirstRowWins_ExactCase() + { + var tags = AudioMetadataTags.From([Tag("Drop_Weapon_Rest", "A", "CA"), Tag("Drop_Weapon_Rest", "B", "CB"), Tag("drop_weapon_rest", "C", "CC")]); + + Assert.Multiple(() => + { + Assert.That(tags.Find("Drop_Weapon_Rest")!.BattleStart, Is.EqualTo("A")); + Assert.That(tags.Find("Drop_Weapon_Rest")!.CampaignStart, Is.EqualTo("CA")); + Assert.That(tags.Find("drop_weapon_rest"), Is.EqualTo(new AudioTagEvents("C", "CC"))); + Assert.That(tags.Find("DROP_WEAPON_REST"), Is.Null); + Assert.That(tags.Count, Is.EqualTo(2)); + }); + } + + sealed class Bank + { + const uint SoundIdOffset = 10000; + uint _next = 1000000; + + public Dictionary Items { get; } = []; + public HashSet Wems { get; } = []; + public Dictionary Rows { get; } = new(StringComparer.Ordinal); + + public List SameIds { get; } = []; + + public SoundTriggerResolver Resolver() => new( + tag => Rows.GetValueOrDefault(tag), + id => [.. Items.TryGetValue(id, out var item) ? [item] : Array.Empty(), .. SameIds.Where(x => x.Id == id)], + Wems.Contains); + + public Bank Row(string tag, string battleEvent, string campaignEvent = "") + { + Rows[tag] = new AudioTagEvents(battleEvent, campaignEvent); + return this; + } + + public uint Sound(uint sourceId, bool wemExists = true) + { + var id = sourceId + SoundIdOffset; + Items[id] = new CAkSound_V136 + { + Id = id, + HircType = AkBkHircType.Sound, + AkBankSourceData = new AkBankSourceData_V136 { AkMediaInformation = new AkBankSourceData_V136.AkMediaInformation_V136 { SourceId = sourceId } }, + }; + if (wemExists) + Wems.Add(sourceId); + return id; + } + + public uint Event(string name, params uint[] actionIds) + { + var id = WwiseHash.Compute(name); + Items[id] = new CAkEvent_V136 + { + Id = id, + HircType = AkBkHircType.Event, + Actions = actionIds.Select(x => new CAkEvent_V136.Action_V136 { ActionId = x }).ToList(), + }; + return id; + } + + public uint Action(AkActionType type, uint targetId) + { + var id = _next++; + Items[id] = new CAkAction_V136 { Id = id, HircType = AkBkHircType.Action, ActionType = type, IdExt = targetId }; + return id; + } + + public uint Play(uint targetId) => Action(AkActionType.Play, targetId); + + public uint Random(params uint[] children) + { + var id = _next++; + Items[id] = new CAkRanSeqCntr_V136 + { + Id = id, + HircType = AkBkHircType.RandomSequenceContainer, + CAkPlayList = new CAkRanSeqCntr_V136.CAkPlayList_V136 + { + Playlist = children.Select(x => new CAkRanSeqCntr_V136.CAkPlayList_V136.AkPlaylistItem_V136 { PlayId = x, Weight = 50000 }).ToList(), + }, + }; + return id; + } + + public uint Container(byte mode, byte randomMode, ushort avoidRepeat, params (uint Child, int Weight)[] playlist) + { + var id = _next++; + Items[id] = new CAkRanSeqCntr_V136 + { + Id = id, + HircType = AkBkHircType.RandomSequenceContainer, + Mode = mode, + RandomMode = randomMode, + AvoidRepeatCount = avoidRepeat, + BitVector = 0x12, + CAkPlayList = new CAkRanSeqCntr_V136.CAkPlayList_V136 + { + Playlist = playlist.Select(x => new CAkRanSeqCntr_V136.CAkPlayList_V136.AkPlaylistItem_V136 { PlayId = x.Child, Weight = x.Weight }).ToList(), + }, + }; + return id; + } + + public uint Blend(params uint[] children) + { + var id = _next++; + Items[id] = new CAkLayerCntr_V136 { Id = id, HircType = AkBkHircType.LayerContainer, Children = new Children_V136 { ChildIds = [.. children] } }; + return id; + } + + public uint Mixer(params uint[] children) + { + var id = _next++; + Items[id] = new CAkActorMixer_V136 { Id = id, HircType = AkBkHircType.ActorMixer, Children = new Children_V136 { ChildIds = [.. children] } }; + return id; + } + + public uint Switch(string group, string defaultCase, params (string Case, uint Child)[] cases) + { + var id = _next++; + Items[id] = new CAkSwitchCntr_V136 + { + Id = id, + HircType = AkBkHircType.SwitchContainer, + GroupId = WwiseHash.Compute(group), + DefaultSwitch = WwiseHash.Compute(defaultCase), + SwitchList = cases + .Select(x => (ICAkSwitchCntr.ICAkSwitchPackage)new CAkSwitchCntr_V136.CAkSwitchPackage_V136 { SwitchId = WwiseHash.Compute(x.Case), NodeIdList = [x.Child] }) + .ToList(), + }; + return id; + } + } + + static readonly IReadOnlyDictionary NoChoices = new Dictionary(); + static uint Hash(string name) => WwiseHash.Compute(name); + + static SoundTriggerResult Resolve(Bank bank, string tag = "Tag", bool campaign = false, IReadOnlyDictionary? choices = null) => + bank.Resolver().Resolve(tag, campaign, choices ?? NoChoices); + + static uint[] Leaves(SoundTriggerResult result) => SoundNodes.Leaves(result.Sound!).ToArray(); + + [Test] + public void Resolve_UsesTheTableRow_NotTheTagName() + { + var bank = new Bank().Row("Drop_Weapon_Rest", "Battle_Individual_Melee_Weapon_Drop_Weapon_Rest"); + bank.Event("Battle_Individual_Melee_Weapon_Drop_Weapon_Rest", bank.Play(bank.Sound(101))); + bank.Event("Battle_Individual_Drop_Weapon_Rest", bank.Play(bank.Sound(999))); + + var result = Resolve(bank, "Drop_Weapon_Rest"); + + Assert.Multiple(() => + { + Assert.That(result.Tag, Is.EqualTo("Drop_Weapon_Rest")); + Assert.That(result.Silent, Is.Null); + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 101 })); + }); + } + + [Test] + public void Resolve_NoRow_IsSilent() + { + var result = Resolve(new Bank(), "Nothing"); + + Assert.Multiple(() => + { + Assert.That(result.Silent, Is.EqualTo("no audio_metadata_tags_tables row")); + Assert.That(result.Sound, Is.Null); + Assert.That(result.Switches, Is.Empty); + }); + } + + [Test] + public void Resolve_EmptyEvent_AndMissingEvent_AreSilent() + { + var bank = new Bank() + .Row("EmptyBattle", "", "Campaign_Event") + .Row("EmptyCampaign", "Battle_Event", " ") + .Row("Missing", "Battle_Event_Nobody_Loaded"); + bank.Event("Campaign_Event", bank.Play(bank.Sound(1))); + + Assert.Multiple(() => + { + Assert.That(Resolve(bank, "EmptyBattle").Silent, Is.EqualTo("the row names no battle event")); + Assert.That(Resolve(bank, "EmptyCampaign", campaign: true).Silent, Is.EqualTo("the row names no campaign event")); + Assert.That(Resolve(bank, "Missing").Silent, Is.EqualTo("event Battle_Event_Nobody_Loaded is in no loaded bank")); + Assert.That(Resolve(bank, "EmptyBattle").Sound, Is.Null); + }); + } + + [Test] + public void Resolve_AnEventWithNoActions_HasNoPlayAction() + { + var bank = new Bank().Row("Tag", "Empty_Event"); + bank.Event("Empty_Event"); + + Assert.That(Resolve(bank).Silent, Is.EqualTo("event Empty_Event has no Play action")); + } + + [TestCase(AkActionType.PlayAndContinue, "PlayAndContinue")] + [TestCase(AkActionType.PlayEvent, "PlayEvent")] + [TestCase(AkActionType.Trigger, "Trigger")] + [TestCase(AkActionType.Trigger_O, "Trigger_O")] + [TestCase(AkActionType.Trigger_E, "Trigger_E")] + [TestCase(AkActionType.Trigger_E_O, "Trigger_E_O")] + [TestCase((AkActionType)0x2303, "0x2303")] + [TestCase(AkActionType.Stop_E_O, null)] + [TestCase(AkActionType.StopEvent, null)] + [TestCase(AkActionType.Pause_E_O, null)] + [TestCase(AkActionType.Resume_E_O, null)] + [TestCase(AkActionType.Seek_E_O, null)] + [TestCase(AkActionType.Release, null)] + [TestCase(AkActionType.Break_E_O, null)] + [TestCase(AkActionType.SetVolume_O, null)] + [TestCase(AkActionType.ResetPitch_O, null)] + [TestCase(AkActionType.Mute_O, null)] + public void Resolve_OnlyActionsThatCanStartASound_AreNotSupported(AkActionType type, string? named) + { + var bank = new Bank().Row("Tag", "Event_A"); + bank.Event("Event_A", bank.Action(type, bank.Sound(7))); + + Assert.That(Resolve(bank).Silent, Is.EqualTo(named == null ? "event Event_A has no Play action" : $"not supported: {named} action -> Sound")); + } + + [Test] + public void Resolve_AStopBesideAPlay_LeavesThePlaysProblemAsTheReason() + { + var bank = new Bank().Row("Tag", "Event_A"); + bank.Event("Event_A", bank.Action(AkActionType.Stop_E_O, bank.Sound(7)), bank.Play(bank.Sound(8, wemExists: false))); + + Assert.That(Resolve(bank).Silent, Is.EqualTo("WEM not found: 8.wem")); + } + + [Test] + public void Resolve_MusicObjectAndMissingWem_TheFirstMetIsTheReason() + { + var bank = new Bank().Row("WemFirst", "Event_A").Row("MusicFirst", "Event_B"); + var segment = new CAkMusicSegment_V136 { Id = 5, HircType = AkBkHircType.Music_Segment }; + bank.Items[segment.Id] = segment; + var missing = bank.Sound(8, wemExists: false); + bank.Event("Event_A", bank.Play(bank.Random(missing, segment.Id))); + bank.Event("Event_B", bank.Play(bank.Random(segment.Id, missing))); + + Assert.Multiple(() => + { + Assert.That(Resolve(bank, "WemFirst").Silent, Is.EqualTo("WEM not found: 8.wem")); + Assert.That(Resolve(bank, "MusicFirst").Silent, Is.EqualTo("not supported: Music_Segment")); + }); + } + + [Test] + public void Resolve_UnknownActionToAnEvent_IsNotSupported_AndNamesTheDialogueEvent() + { + const AkActionType Unknown = (AkActionType)0x2303; + Assert.That(Enum.IsDefined(Unknown), Is.False, "0x2303 has no name in the enum"); + var bank = new Bank().Row("Hit", "Hit_Event"); + const uint Shared = 77; + bank.Items[Shared] = new CAkEvent_V136 { Id = Shared, HircType = AkBkHircType.Event, Actions = [new CAkEvent_V136.Action_V136 { ActionId = bank.Action(Unknown, Shared) }] }; + bank.SameIds.Add(new CAkDialogueEvent_V136 { Id = Shared, HircType = AkBkHircType.Dialogue_Event }); + bank.Event("Hit_Event", bank.Action(Unknown, Shared)); + + var result = Resolve(bank, "Hit"); + + Assert.Multiple(() => + { + Assert.That(result.Sound, Is.Null); + Assert.That(result.Silent, Is.EqualTo("not supported: 0x2303 action -> Event -> 0x2303 action -> Dialogue_Event")); + }); + } + + [Test] + public void Resolve_ActionInNoLoadedBank_SaysSo() + { + var bank = new Bank().Row("Tag", "Event_A"); + bank.Event("Event_A", 404); + + Assert.That(Resolve(bank).Silent, Is.EqualTo("action 404 of event Event_A is in no loaded bank")); + } + + [Test] + public void Resolve_PlayActionWhoseTargetIsNotLoaded_IsDropped() + { + var bank = new Bank().Row("Tag", "Event_A").Row("OnlyBad", "Event_B"); + bank.Event("Event_A", bank.Play(404), bank.Play(bank.Sound(11))); + bank.Event("Event_B", bank.Play(404)); + + Assert.Multiple(() => + { + Assert.That(Leaves(Resolve(bank, "Tag")), Is.EqualTo(new uint[] { 11 })); + Assert.That(Resolve(bank, "OnlyBad").Silent, Is.EqualTo("event Event_B plays nothing found in the loaded banks")); + }); + } + + [Test] + public void Resolve_PlayActionsThatReachNothing_AreNotTheSameAsNoPlayAction() + { + var bank = new Bank().Row("EmptyContainer", "Event_C").Row("StopAndUnloaded", "Event_D").Row("WemWins", "Event_E"); + bank.Event("Event_C", bank.Play(bank.Random())); + bank.Event("Event_D", bank.Action(AkActionType.Stop_E_O, bank.Sound(7)), bank.Play(404)); + bank.Event("Event_E", bank.Play(404), bank.Play(bank.Sound(8, wemExists: false))); + + Assert.Multiple(() => + { + Assert.That(Resolve(bank, "EmptyContainer").Silent, Is.EqualTo("event Event_C plays nothing found in the loaded banks")); + Assert.That(Resolve(bank, "StopAndUnloaded").Silent, Is.EqualTo("event Event_D plays nothing found in the loaded banks"), "a Stop cannot start a sound"); + Assert.That(Resolve(bank, "WemWins").Silent, Is.EqualTo("WEM not found: 8.wem")); + }); + } + + [Test] + public void Resolve_SeveralPlayActions_PlayTogether() + { + var bank = new Bank().Row("Tag", "Event_A"); + bank.Event("Event_A", bank.Play(bank.Sound(21)), bank.Action(AkActionType.Stop_E_O, bank.Sound(99)), bank.Play(bank.Sound(22))); + + var result = Resolve(bank); + + Assert.Multiple(() => + { + Assert.That(result.Sound, Is.InstanceOf()); + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 21, 22 })); + Assert.That(SoundNodes.Pick(result.Sound!, new Random(1)), Is.EqualTo(new uint[] { 21, 22 })); + }); + } + + [Test] + public void Resolve_EventIdThatIsNotAnEvent_AndMusicObject_AreNotSupported() + { + var bank = new Bank().Row("NotAnEvent", "Mixer_Name").Row("Music", "Music_Event"); + var mixerId = Hash("Mixer_Name"); + bank.Items[mixerId] = new CAkActorMixer_V136 { Id = mixerId, HircType = AkBkHircType.ActorMixer }; + var segment = new CAkMusicSegment_V136 { Id = 5, HircType = AkBkHircType.Music_Segment }; + bank.Items[segment.Id] = segment; + bank.Event("Music_Event", bank.Play(segment.Id)); + + Assert.Multiple(() => + { + Assert.That(Resolve(bank, "NotAnEvent").Silent, Is.EqualTo("not supported: ActorMixer")); + Assert.That(Resolve(bank, "Music").Silent, Is.EqualTo("not supported: Music_Segment")); + }); + } + + [Test] + public void Resolve_Switch_PlaysDefault_ThenTheChoice() + { + var bank = new Bank().Row("Tag", "Step"); + var grass = bank.Sound(201); + var stone = bank.Sound(202); + bank.Event("Step", bank.Play(bank.Switch("Surface", "Grass", ("Grass", grass), ("Stone", stone)))); + + var byDefault = Resolve(bank); + var chosen = Resolve(bank, choices: new Dictionary { [Hash("Surface")] = Hash("Stone") }); + + Assert.Multiple(() => + { + Assert.That(Leaves(byDefault), Is.EqualTo(new uint[] { 201 })); + Assert.That(byDefault.Switches, Has.Count.EqualTo(1)); + Assert.That(byDefault.Switches[0].GroupId, Is.EqualTo(Hash("Surface"))); + Assert.That(byDefault.Switches[0].DefaultSwitch, Is.EqualTo(Hash("Grass"))); + Assert.That(byDefault.Switches[0].Values, Is.EqualTo(new[] { Hash("Grass"), Hash("Stone") })); + Assert.That(Leaves(chosen), Is.EqualTo(new uint[] { 202 })); + }); + } + + [Test] + public void Resolve_Switch_ChoiceNoCaseHas_FallsBackToTheDefault() + { + var bank = new Bank().Row("Tag", "Step"); + bank.Event("Step", bank.Play(bank.Switch("Surface", "Stone", ("Grass", bank.Sound(201)), ("Stone", bank.Sound(202))))); + + var result = Resolve(bank, choices: new Dictionary { [Hash("Surface")] = Hash("Snow") }); + + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 202 })); + } + + [Test] + public void Resolve_SwitchWithNoDefault_PlaysTheFirstCase() + { + var bank = new Bank().Row("Tag", "Step"); + bank.Event("Step", bank.Play(bank.Switch("Surface", "None", ("Grass", bank.Sound(201)), ("Stone", bank.Sound(202))))); + + var result = Resolve(bank); + + Assert.Multiple(() => + { + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 201 })); + Assert.That(result.Switches.Single().DefaultSwitch, Is.EqualTo(Hash("None"))); + }); + } + + [Test] + public void Resolve_SameSwitchGroupInTwoContainers_ListsItOnce() + { + var bank = new Bank().Row("Tag", "Step"); + var inner = bank.Switch("Surface", "Mud", ("Mud", bank.Sound(301)), ("Ice", bank.Sound(302))); + var outer = bank.Switch("Surface", "Grass", ("Grass", inner), ("Stone", bank.Sound(303))); + bank.Event("Step", bank.Play(outer)); + + var result = Resolve(bank); + + Assert.Multiple(() => + { + Assert.That(result.Switches, Has.Count.EqualTo(1)); + Assert.That(result.Switches[0].DefaultSwitch, Is.EqualTo(Hash("Grass"))); + Assert.That(result.Switches[0].Values, Is.EqualTo(new[] { Hash("Grass"), Hash("Stone") })); + }); + } + + [Test] + public void Resolve_Random_IsOneOf_Blend_IsAll() + { + var bank = new Bank().Row("Rand", "Rand_Event").Row("Layer", "Layer_Event").Row("Mix", "Mix_Event"); + bank.Event("Rand_Event", bank.Play(bank.Random(bank.Sound(301), bank.Sound(302)))); + bank.Event("Layer_Event", bank.Play(bank.Blend(bank.Sound(401), bank.Sound(402)))); + bank.Event("Mix_Event", bank.Play(bank.Mixer(bank.Sound(411), bank.Sound(412)))); + + var random = Resolve(bank, "Rand"); + var blend = Resolve(bank, "Layer"); + var mixer = Resolve(bank, "Mix"); + var seeded = new Random(7); + var picks = Enumerable.Range(0, 40).Select(_ => SoundNodes.Pick(random.Sound!, seeded)).ToList(); + + Assert.Multiple(() => + { + Assert.That(random.Sound, Is.InstanceOf()); + Assert.That(Leaves(random), Is.EqualTo(new uint[] { 301, 302 })); + Assert.That(picks.All(x => x.Count == 1), Is.True); + Assert.That(picks.Select(x => x.Single()).Distinct().Order(), Is.EqualTo(new uint[] { 301, 302 })); + Assert.That(blend.Sound, Is.InstanceOf()); + Assert.That(SoundNodes.Pick(blend.Sound!, new Random(7)), Is.EqualTo(new uint[] { 401, 402 })); + Assert.That(mixer.Sound, Is.InstanceOf()); + Assert.That(SoundNodes.Pick(mixer.Sound!, new Random(7)), Is.EqualTo(new uint[] { 411, 412 })); + }); + } + + static List Picks(Bank bank, int firings, string tag = "Tag") + { + var sound = Resolve(bank, tag).Sound!; + var picker = new SoundPicker(new Random(1)); + return Enumerable.Range(0, firings).Select(_ => picker.Pick(sound).Single()).ToList(); + } + + static (uint, int)[] Equal(params uint[] children) => children.Select(x => (x, 50000)).ToArray(); + + [Test] + public void Sequence_PlaysThePlaylistInOrder_AndStartsOver() + { + var bank = new Bank().Row("Tag", "Seq"); + bank.Event("Seq", bank.Play(bank.Container(1, 0, 0, Equal(bank.Sound(1), bank.Sound(2), bank.Sound(3))))); + Assert.That(Picks(bank, 7), Is.EqualTo(new uint[] { 1, 2, 3, 1, 2, 3, 1 })); + } + + [Test] + public void Random_WeighsItsChildren_AndADroppedChildTakesItsWeight() + { + var bank = new Bank().Row("Tag", "Weighted").Row("Gap", "Gapped"); + bank.Event("Weighted", bank.Play(bank.Container(0, 0, 0, (bank.Sound(1), 90000), (bank.Sound(2), 10000)))); + bank.Event("Gapped", bank.Play(bank.Container(0, 0, 0, (bank.Sound(3), 10000), (bank.Sound(4, wemExists: false), 90000), (bank.Sound(5), 10000)))); + var weighted = Picks(bank, 2000); + var gapped = Picks(bank, 2000, "Gap"); + Assert.Multiple(() => + { + Assert.That(weighted.Count(x => x == 1) / 2000.0, Is.EqualTo(0.9).Within(0.03)); + Assert.That(gapped.Count(x => x == 3) / 2000.0, Is.EqualTo(0.5).Within(0.05)); + }); + } + + [TestCase((ushort)1, 2)] + [TestCase((ushort)2, 3)] + [TestCase((ushort)5, 3)] + public void Random_AvoidsRepeatingItsLastPicks(ushort avoid, int window) + { + var bank = new Bank().Row("Tag", "Avoid"); + bank.Event("Avoid", bank.Play(bank.Container(0, 0, avoid, Equal(bank.Sound(1), bank.Sound(2), bank.Sound(3))))); + var picks = Picks(bank, 300); + Assert.That(Enumerable.Range(0, picks.Count - window + 1).All(i => picks.Skip(i).Take(window).Distinct().Count() == window), Is.True); + } + + [Test] + public void Shuffle_PlaysEachChildOnceARound() + { + var bank = new Bank().Row("Tag", "Shuffle"); + bank.Event("Shuffle", bank.Play(bank.Container(0, 1, 1, Equal(bank.Sound(1), bank.Sound(2), bank.Sound(3), bank.Sound(4))))); + var picks = Picks(bank, 400); + var rounds = picks.Chunk(4).ToList(); + Assert.Multiple(() => + { + Assert.That(rounds.All(x => x.Order().SequenceEqual(new uint[] { 1, 2, 3, 4 })), Is.True); + Assert.That(rounds.Select(x => string.Join(",", x)).Distinct().Count(), Is.GreaterThan(5), "the order changes"); + Assert.That(Enumerable.Range(1, picks.Count - 1).All(i => picks[i] != picks[i - 1]), Is.True, "no repeat at a round's turn"); + }); + } + + [Test] + public void Session_SequenceGoesOn_AcrossFiringsAndRebuilds() + { + var bank = new Bank().Row("Tag", "Seq"); + bank.Event("Seq", bank.Play(bank.Container(1, 0, 0, Equal(bank.Sound(1), bank.Sound(2), bank.Sound(3))))); + var run = new SessionRun(bank).Rebuild(Trigger("Tag", 0.5f)).Frames(0, 200); + run.Rebuild(Trigger("Tag", 0.5f)).Frames(200, 100); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 2, 3 })); + } + + [Test] + public void Resolve_NestedContainers_PickOneThenPlayAll() + { + var bank = new Bank().Row("Tag", "Nested"); + var oneOf = bank.Random(bank.Sound(1), bank.Sound(2)); + bank.Event("Nested", bank.Play(bank.Blend(bank.Sound(3), oneOf))); + + var result = Resolve(bank); + var seeded = new Random(3); + var picks = Enumerable.Range(0, 40).Select(_ => SoundNodes.Pick(result.Sound!, seeded)).ToList(); + + Assert.Multiple(() => + { + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 3, 1, 2 })); + Assert.That(picks.All(x => x.Count == 2 && x[0] == 3), Is.True); + Assert.That(picks.Select(x => x[1]).Distinct().Order(), Is.EqualTo(new uint[] { 1, 2 })); + }); + } + + [Test] + public void Resolve_MissingWems_AreDropped_AllMissing_IsSilent() + { + var some = new Bank().Row("Tag", "Event_A"); + some.Event("Event_A", some.Play(some.Random(some.Sound(501), some.Sound(502, wemExists: false)))); + var none = new Bank().Row("Tag", "Event_A"); + none.Event("Event_A", none.Play(none.Random(none.Sound(501, wemExists: false), none.Sound(502, wemExists: false)))); + + var partial = Resolve(some); + var allMissing = Resolve(none); + + Assert.Multiple(() => + { + Assert.That(partial.Silent, Is.Null); + Assert.That(partial.Sound, Is.EqualTo(new SoundLeaf(501))); + Assert.That(Leaves(partial), Is.EqualTo(new uint[] { 501 })); + Assert.That(allMissing.Sound, Is.Null); + Assert.That(allMissing.Silent, Is.EqualTo("WEM not found: 501.wem")); + }); + } + + [Test] + public void Resolve_ContainerThatContainsItself_DoesNotLoopForever() + { + var bank = new Bank().Row("Tag", "Loop"); + var mixerId = 777u; + bank.Items[mixerId] = new CAkActorMixer_V136 { Id = mixerId, HircType = AkBkHircType.ActorMixer, Children = new Children_V136 { ChildIds = [mixerId, bank.Sound(1)] } }; + bank.Event("Loop", bank.Play(mixerId)); + + var result = Resolve(bank); + + Assert.That(Leaves(result), Is.EqualTo(new uint[] { 1 })); + } + + [Test] + public void Resolve_CampaignFlag_UsesTheCampaignEvent() + { + var bank = new Bank().Row("Tag", "Battle_Event", "Campaign_Event"); + bank.Event("Battle_Event", bank.Play(bank.Sound(1))); + bank.Event("Campaign_Event", bank.Play(bank.Sound(2))); + + Assert.Multiple(() => + { + Assert.That(Leaves(Resolve(bank, campaign: false)), Is.EqualTo(new uint[] { 1 })); + Assert.That(Leaves(Resolve(bank, campaign: true)), Is.EqualTo(new uint[] { 2 })); + }); + } + + const double ClipLength = 2.0; + + static (double From, double To, bool Wrapped) StepOf(double previous, double now, double elapsed, double speed = 1) => + SoundTriggerCrossing.Step(previous, now, ClipLength, elapsed, speed); + + static bool Crosses(double start, (double From, double To, bool Wrapped) step) => SoundTriggerCrossing.Crossed(start, step, ClipLength); + + [Test] + public void Step_Playback_FiresTagsInTheSpanCovered() + { + var step = StepOf(0.50, 0.52, 0.02); + + Assert.Multiple(() => + { + Assert.That(step.Wrapped, Is.False); + Assert.That(Crosses(0.51, step), Is.True); + Assert.That(Crosses(0.50, step), Is.False); + Assert.That(Crosses(0.53, step), Is.False); + }); + } + + [Test] + public void Step_LoopWrap_FiresBothSides() + { + var step = StepOf(1.99, 0.01, 0.02); + + Assert.Multiple(() => + { + Assert.That(step.Wrapped, Is.True); + Assert.That(Crosses(1.995, step), Is.True); + Assert.That(Crosses(0.0, step), Is.True); + Assert.That(Crosses(0.005, step), Is.True); + Assert.That(Crosses(1.98, step), Is.False); + Assert.That(Crosses(0.02, step), Is.False); + }); + } + + [Test] + public void Step_Jump_FiresOnlyTheLastFrame() + { + var forward = StepOf(0.2, 1.5, 0.02); + var back = StepOf(1.5, 0.2, 0.02); + + Assert.Multiple(() => + { + Assert.That(forward.Wrapped, Is.False); + Assert.That(Crosses(1.0, forward), Is.False); + Assert.That(Crosses(1.49, forward), Is.True); + Assert.That(back.Wrapped, Is.False); + Assert.That(Crosses(1.8, back), Is.False); + Assert.That(Crosses(0.1, back), Is.False); + Assert.That(Crosses(0.19, back), Is.True); + }); + } + + [Test] + public void Step_ElapsedIsCapped_AndScaledBySpeed() + { + var resume = StepOf(1.0, 0.016, 30); + var normal = StepOf(0.5, 0.56, 0.02); + var slow = StepOf(0.5, 0.56, 0.02, speed: 0.25); + + Assert.Multiple(() => + { + Assert.That(resume.Wrapped, Is.False); + Assert.That(Crosses(1.5, resume), Is.False); + Assert.That(Crosses(1.99, resume), Is.False); + Assert.That(Crosses(0.0, resume), Is.True); + Assert.That(normal, Is.EqualTo((0.5, 0.56, false))); + Assert.That(slow.Wrapped, Is.False); + Assert.That(slow.From, Is.EqualTo(0.555).Within(0.001)); + Assert.That(Crosses(0.51, slow), Is.False); + }); + } + + [Test] + public void Step_FromNoFrame_IsAJump() + { + var mid = StepOf(double.NaN, 0.5, 0.02); + var start = StepOf(double.NaN, 0.01, 0.02); + + Assert.Multiple(() => + { + Assert.That(mid.Wrapped, Is.False); + Assert.That(mid.From, Is.EqualTo(0.48).Within(1e-5)); + Assert.That(Crosses(0.49, mid), Is.True); + Assert.That(Crosses(0.47, mid), Is.False); + Assert.That(Crosses(0.0, start), Is.True); + }); + } + + [Test] + public void Step_WrapAndJump_AtAnotherSpeed() + { + var fastWrap = StepOf(1.95, 0.08, 0.05, speed: 2); + var slowJump = StepOf(1.95, 0.08, 0.05, speed: 1); + var fastJump = StepOf(0.5, 0.9, 0.05, speed: 2); + + Assert.Multiple(() => + { + Assert.That(fastWrap, Is.EqualTo((1.95, 0.08, true))); + Assert.That(slowJump.Wrapped, Is.False); + Assert.That(Crosses(1.99, slowJump), Is.False); + Assert.That(fastJump.From, Is.EqualTo(0.8).Within(1e-5), "a jump reaches back one frame of clip time at double speed"); + Assert.That(Crosses(0.82, fastJump), Is.True); + Assert.That(Crosses(0.78, fastJump), Is.False); + }); + } + + [Test] + public void Crossed_TagOutsideTheClip_NeverFires() + { + var steps = new[] { StepOf(0.5, 0.52, 0.02), StepOf(1.99, 0.01, 0.02), StepOf(1.0, 0.016, 30), StepOf(0.2, 1.99, 0.02) }; + + Assert.Multiple(() => + { + foreach (var step in steps) + { + Assert.That(Crosses(-0.1, step), Is.False); + Assert.That(Crosses(-0.05, step), Is.False); + Assert.That(Crosses(2.1, step), Is.False); + } + }); + } + + static Bank Sounding(params (string Tag, uint Source)[] tags) + { + var bank = new Bank(); + foreach (var (tag, source) in tags) + { + bank.Row(tag, tag + "_Event"); + bank.Event(tag + "_Event", bank.Play(bank.Sound(source))); + } + return bank; + } + + static SoundTriggerTag Trigger(string tag, float start) => new(tag, start, "slot .snd.meta"); + + sealed class SessionRun + { + public List Played { get; } = []; + public List Prepared { get; } = []; + public SoundTriggerSession Session { get; } + + public SessionRun(Bank bank, bool prepareResult = true) => + Session = new SoundTriggerSession(bank.Resolver(), id => { Prepared.Add(id); return prepareResult; }, Played.Add, new Random(1)); + + public SessionRun Rebuild(params SoundTriggerTag[] tags) + { + Session.Rebuild(tags, campaign: false); + return this; + } + + public SessionRun Advance(double now, double elapsed = 0.02, bool playing = true, double speed = 1, bool loop = true) + { + Session.Advance(now, playing, elapsed, speed, ClipLength, loop); + return this; + } + + public SessionRun Frames(int first, int count, bool loop = true) + { + foreach (var i in Enumerable.Range(first, count)) + Advance(i % 100 / 50.0, loop: loop); + return this; + } + } + + [Test] + public void Session_PlayStartAtZero_FiresTagAtZero() + { + var run = new SessionRun(Sounding(("Start", 1), ("Late", 2))).Rebuild(Trigger("Start", 0f), Trigger("Late", 1.5f)); + run.Advance(1.3, playing: false).Advance(0.016, elapsed: 5); + + var resumed = new SessionRun(Sounding(("Tag", 3))).Rebuild(Trigger("Tag", 0.9f)); + resumed.Advance(1.0, elapsed: 0.016).Advance(1.016, elapsed: 30); + + Assert.Multiple(() => + { + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + Assert.That(resumed.Played, Is.Empty); + }); + } + + [Test] + public void Session_NotPlaying_FiresNothing_ButRemembersTheTime() + { + var run = new SessionRun(Sounding(("Before", 1), ("AtThePause", 2))).Rebuild(Trigger("Before", 0.95f), Trigger("AtThePause", 1.0f)); + + run.Advance(1.0, playing: false); + var whilePaused = run.Played.ToList(); + run.Advance(1.02, elapsed: 0.1); + + Assert.Multiple(() => + { + Assert.That(whilePaused, Is.Empty); + Assert.That(run.Played, Is.EqualTo(new uint[] { 2 })); + }); + } + + [TestCase(0.0)] + [TestCase(0.03)] + public void Session_FirstFrameThenPlay_FiresATagAtZero_Once(double offset) + { + var run = new SessionRun(Sounding(("Start", 1))).Rebuild(Trigger("Start", 0f)); + run.Session.OffsetSeconds = offset; + + run.Frames(30, 10); + run.Advance(0, playing: false); + run.Frames(1, 10); + + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + } + + [TestCase(0.0, true)] + [TestCase(0.0, false)] + [TestCase(0.03, true)] + [TestCase(0.03, false)] + public void Session_Loop_FiresTheTagsAtBothEnds_OncePerPass(double offset, bool afterTheLoop) + { + var run = new SessionRun(Sounding(("Start", 1), ("LastFrame", 2), ("End", 3))).Rebuild(Trigger("Start", 0f), Trigger("LastFrame", 1.97f), Trigger("End", 2.0f)); + run.Session.OffsetSeconds = offset; + + run.Advance(0, playing: false); + foreach (var _ in Enumerable.Range(0, 3)) + { + run.Frames(1, 97); + if (!afterTheLoop) + run.Advance(1.96); + run.Session.Loop(1, ClipLength); + run.Advance(0, playing: false); + if (afterTheLoop) + run.Advance(0, elapsed: 0); + } + run.Advance(0.02); + + Assert.That(run.Played.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()), Is.EqualTo(new Dictionary { [1] = 4, [2] = 3, [3] = 3 })); + } + + [Test] + public void Session_Status_CountsWhatIsNotSupported_ApartFromWhatIsSilentInGame() + { + var bank = Sounding(("A", 1)).Row("Continue", "Continue_Event"); + bank.Event("Continue_Event", bank.Action(AkActionType.PlayAndContinue, bank.Sound(7))); + var run = new SessionRun(bank).Rebuild(Trigger("A", 0.1f), Trigger("Continue", 0.2f), Trigger("X", 0.3f)); + + Assert.That(run.Session.StatusLines, Is.EqualTo(new[] + { + "3 triggers: 1 plays, 1 silent in game, 1 not supported", + "Continue (slot .snd.meta): not supported: PlayAndContinue action -> Sound", + "X (slot .snd.meta): no audio_metadata_tags_tables row", + })); + } + + [Test] + public void Session_FiresEachTagOncePerPass() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 1.0f)); + + run.Frames(48, 4); + var firstPass = run.Played.ToList(); + run.Frames(52, 100); + + Assert.Multiple(() => + { + Assert.That(firstPass, Is.EqualTo(new uint[] { 1 })); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 1 })); + }); + } + + [Test] + public void Session_UnsavedEdit_FiresAtTheNewTime() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0.5f)).Rebuild(Trigger("Tag", 1.0f)); + + run.Frames(23, 5); + var throughOldTime = run.Played.ToList(); + run.Frames(28, 25); + + Assert.Multiple(() => + { + Assert.That(throughOldTime, Is.Empty); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + }); + } + + [Test] + public void Session_Rebuild_KeepsThePlayheadTime() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(); + run.Advance(0.50); + run.Rebuild(Trigger("Tag", 0.51f)); + run.Advance(0.52, elapsed: 0.001); + + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + } + + [Test] + public void Session_AdvanceBeforeRebuild_DoesNothing() + { + var run = new SessionRun(Sounding(("Tag", 1))); + + Assert.DoesNotThrow(() => run.Advance(0.48).Advance(0.52)); + run.Rebuild(Trigger("Tag", 0.5f)).Advance(0.52); + + Assert.That(run.Played, Is.Empty); + } + + [TestCase(0.0)] + [TestCase(0.03)] + public void Session_LoopOff_ATagAtZeroFiresOnceAtEachPlay_AndNotAtTheEnd(double offset) + { + var run = new SessionRun(Sounding(("Start", 1))).Rebuild(Trigger("Start", 0f)); + run.Session.OffsetSeconds = offset; + + run.Advance(0, playing: false, loop: false); + run.Frames(1, 10, loop: false); + var atPlay = run.Played.ToList(); + run.Frames(11, 89, loop: false); + run.Advance(2.0, playing: false, loop: false); + var throughThePass = run.Played.ToList(); + run.Advance(0, playing: false, loop: false); + run.Frames(1, 10, loop: false); + + Assert.Multiple(() => + { + Assert.That(atPlay, Is.EqualTo(new uint[] { 1 })); + Assert.That(throughThePass, Is.EqualTo(new uint[] { 1 }), "nothing more by the end"); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 1 }), "once more at the next Play"); + }); + } + + [Test] + public void Session_LoopOff_TheStepThatReachesTheEnd_FiresWhatIsDueInIt() + { + var run = new SessionRun(Sounding(("LastStep", 1), ("End", 2), ("Paused", 3))).Rebuild(Trigger("LastStep", 1.99f), Trigger("End", 2.0f), Trigger("Paused", 0.99f)); + + run.Frames(40, 9, loop: false); + run.Advance(1.0, playing: false, loop: false); + var pausedMidClip = run.Played.ToList(); + run.Frames(51, 48, loop: false); + run.Advance(2.0, playing: false, loop: false); + var atTheEnd = run.Played.ToList(); + run.Advance(2.0, playing: false, loop: false); + + Assert.Multiple(() => + { + Assert.That(pausedMidClip, Is.Empty, "a frame step onto 1.0 fires nothing"); + Assert.That(atTheEnd, Is.EqualTo(new uint[] { 1, 2 })); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 2 }), "a second paused frame there fires nothing more"); + }); + } + + [Test] + public void Session_LoopOff_LateOffset_FiresATagAtTheEnd_OnTheLastStep() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 1.99f)); + run.Session.OffsetSeconds = -0.03; + + run.Frames(95, 4, loop: false); + var before = run.Played.ToList(); + run.Advance(2.0, playing: false, loop: false); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + }); + } + + [Test] + public void Session_LoopOn_AHitchThatStopsAtTheEnd_LeavesATagAtZeroForTheNextPlay() + { + var run = new SessionRun(Sounding(("Start", 1), ("LastStep", 2))).Rebuild(Trigger("Start", 0f), Trigger("LastStep", 1.995f)); + run.Session.OffsetSeconds = 0.03; + + run.Advance(0, playing: false); + run.Frames(1, 98); + var atPlay = run.Played.ToList(); + run.Advance(2.0, playing: false); + var atTheEnd = run.Played.ToList(); + run.Advance(0, playing: false); + run.Frames(1, 10); + + Assert.Multiple(() => + { + Assert.That(atPlay, Is.EqualTo(new uint[] { 1 })); + Assert.That(atTheEnd, Is.EqualTo(new uint[] { 1, 2 }), "only the tag due in the last step"); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 2, 1 }), "the tag at 0.0 once more, at the next Play"); + }); + } + + [Test] + public void Session_OffsetLongerThanTheClip_StillFiresOncePerPass() + { + const double Length = 0.04; + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0.03f)); + run.Session.OffsetSeconds = 0.1; + + foreach (var i in Enumerable.Range(1, 32)) + run.Session.Advance(i % 4 * 0.01, true, 0.01, 1, Length, true); + + Assert.That(run.Played, Has.Count.EqualTo(8)); + } + + [TestCase(0.5, 0.01, 1.98, 1.99)] + [TestCase(2.0, 0.02, 1.92, 1.94)] + public void Session_EarlyOffset_WrapsByTheClipTimeAtTheFramesSpeed(double speed, double step, double lastWithout, double firing) + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0f)); + run.Session.OffsetSeconds = 0.03; + var frame = step / speed; + + for (var at = 1.80; at < lastWithout + 1e-9; at += step) + run.Advance(Math.Round(at, 2), elapsed: frame, speed: speed); + var before = run.Played.ToList(); + run.Advance(firing, elapsed: frame, speed: speed); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty, $"nothing up to {lastWithout}"); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 }), $"fired by the frame landing at {firing}"); + }); + } + + [Test] + public void Session_Status_SummaryThenOneLinePerSilentTag() + { + var run = new SessionRun(Sounding(("A", 1), ("B", 2))); + run.Rebuild(Trigger("A", 0.1f), Trigger("Derpy_Swing_01", 0.2f), Trigger("B", 0.3f)); + + Assert.That(run.Session.StatusLines, Is.EqualTo(new[] + { + "3 triggers: 2 play, 1 silent in game", + "Derpy_Swing_01 (slot .snd.meta): no audio_metadata_tags_tables row", + })); + } + + [Test] + public void Session_Status_NoTags_OneTag_AndAllSilent() + { + var run = new SessionRun(Sounding(("A", 1))); + + Assert.Multiple(() => + { + Assert.That(run.Rebuild().Session.StatusLines, Is.EqualTo(new[] { "0 triggers" })); + Assert.That(run.Rebuild(Trigger("A", 0.1f)).Session.StatusLines, Is.EqualTo(new[] { "1 trigger: 1 plays, 0 silent in game" })); + Assert.That(run.Rebuild(Trigger("X", 0.1f)).Session.StatusLines[0], Is.EqualTo("1 trigger: 0 play, 1 silent in game")); + Assert.That(run.Rebuild(Trigger("X", 0.1f), Trigger("Y", 0.2f)).Session.StatusLines, Has.Count.EqualTo(3)); + Assert.That(run.Session.StatusLines[0], Is.EqualTo("2 triggers: 0 play, 2 silent in game")); + }); + } + + [Test] + public void Session_Status_AgreesInNumber_OnBothCounts() + { + var run = new SessionRun(Sounding(("A", 1), ("B", 2))); + + Assert.Multiple(() => + { + Assert.That(run.Rebuild(Trigger("A", 0.1f), Trigger("X", 0.2f), Trigger("Y", 0.3f)).Session.StatusLines[0], Is.EqualTo("3 triggers: 1 plays, 2 silent in game")); + Assert.That(run.Rebuild(Trigger("A", 0.1f), Trigger("B", 0.2f), Trigger("X", 0.3f)).Session.StatusLines[0], Is.EqualTo("3 triggers: 2 play, 1 silent in game")); + Assert.That(run.Rebuild(Trigger("A", 0.1f), Trigger("B", 0.2f)).Session.StatusLines[0], Is.EqualTo("2 triggers: 2 play, 0 silent in game")); + }); + } + + [Test] + public void Session_FailedPrepare_StillCountsAsPlayable() + { + var run = new SessionRun(Sounding(("A", 1)), prepareResult: false).Rebuild(Trigger("A", 0.1f)); + + Assert.Multiple(() => + { + Assert.That(run.Session.StatusLines, Is.EqualTo(new[] { "1 trigger: 1 plays, 0 silent in game" })); + Assert.That(run.Prepared, Is.EqualTo(new uint[] { 1 })); + }); + } + + [Test] + public void Session_LeavesAndSwitches_AreDistinctAcrossTags() + { + var bank = new Bank().Row("A", "Ea").Row("B", "Eb"); + var grass = bank.Sound(201); + var stone = bank.Sound(202); + var shared = bank.Sound(300); + bank.Event("Ea", bank.Play(bank.Switch("Surface", "Grass", ("Grass", grass), ("Stone", stone))), bank.Play(shared)); + bank.Event("Eb", bank.Play(bank.Switch("Surface", "Stone", ("Stone", stone), ("Grass", grass))), bank.Play(shared)); + var run = new SessionRun(bank).Rebuild(Trigger("A", 0.1f), Trigger("B", 0.2f)); + + Assert.Multiple(() => + { + Assert.That(run.Session.Leaves, Is.EqualTo(new uint[] { 201, 300, 202 })); + Assert.That(run.Prepared, Is.EqualTo(new uint[] { 201, 300, 202 })); + Assert.That(run.Session.Switches, Has.Count.EqualTo(1)); + Assert.That(run.Session.Switches[0].DefaultSwitch, Is.EqualTo(Hash("Grass"))); + }); + } + + [Test] + public void Session_SwitchChoice_SurvivesRebuild() + { + var bank = new Bank().Row("Tag", "Step"); + bank.Event("Step", bank.Play(bank.Switch("Surface", "Grass", ("Grass", bank.Sound(201)), ("Stone", bank.Sound(202))))); + var run = new SessionRun(bank); + run.Session.SwitchChoices[Hash("Surface")] = Hash("Stone"); + + run.Rebuild(Trigger("Tag", 0.5f)).Rebuild(Trigger("Tag", 0.5f)).Advance(0.5); + + Assert.Multiple(() => + { + Assert.That(run.Session.Leaves, Is.EqualTo(new uint[] { 202 })); + Assert.That(run.Played, Is.EqualTo(new uint[] { 202 })); + }); + } + + [Test] + public void Session_Offset_FiresEarly() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0.50f)); + run.Session.OffsetSeconds = 0.03; + + run.Advance(0.46); + var before = run.Played.ToList(); + run.Advance(0.48); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + }); + } + + [Test] + public void Session_Offset_IsRealTime_SoAtHalfSpeedItIsHalfAsMuchOfTheClip() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0.50f)); + run.Session.OffsetSeconds = 0.05; + + foreach (var i in Enumerable.Range(40, 8)) + run.Advance(i / 100.0, speed: 0.5); + var before = run.Played.ToList(); + run.Advance(0.48, speed: 0.5); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty, "nothing up to the frame at 0.47"); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 }), "fired by the frame crossing 0.475"); + }); + } + + [Test] + public void Session_EarlyOffset_FiresATagAtZeroBeforeTheLoop_Once() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0f)); + run.Session.OffsetSeconds = 0.03; + + run.Advance(1.96); + var before = run.Played.ToList(); + run.Advance(1.98); + var early = run.Played.ToList(); + run.Advance(1.99).Advance(0.01); + var acrossTheWrap = run.Played.ToList(); + run.Frames(1, 99); + + Assert.Multiple(() => + { + Assert.That(before, Is.Empty); + Assert.That(early, Is.EqualTo(new uint[] { 1 })); + Assert.That(acrossTheWrap, Is.EqualTo(new uint[] { 1 })); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1, 1 })); + }); + } + + [Test] + public void Session_EarlyOffset_TagAtZeroStillFiresOnThePlayStartJump() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 0f)); + run.Session.OffsetSeconds = 0.03; + + run.Advance(1.3, playing: false).Advance(0.016, elapsed: 5); + + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + } + + [Test] + public void Session_LateOffset_FiresATagAtTheEndAfterTheWrap_NotBefore() + { + var run = new SessionRun(Sounding(("Tag", 1))).Rebuild(Trigger("Tag", 1.99f)); + run.Session.OffsetSeconds = -0.03; + + run.Advance(1.98).Advance(2.0); + var atTheEnd = run.Played.ToList(); + run.Advance(0.01); + var wrapped = run.Played.ToList(); + run.Advance(0.03); + + Assert.Multiple(() => + { + Assert.That(atTheEnd, Is.Empty); + Assert.That(wrapped, Is.Empty); + Assert.That(run.Played, Is.EqualTo(new uint[] { 1 })); + }); + } + + [TestCase(0.03)] + [TestCase(-0.03)] + public void Session_TagOutsideTheClip_NeverFires_WhateverTheOffset(double offset) + { + var run = new SessionRun(Sounding(("Before", 1), ("After", 2))).Rebuild(Trigger("Before", -0.1f), Trigger("After", 2.1f)); + run.Session.OffsetSeconds = offset; + + run.Frames(0, 200); + + Assert.That(run.Played, Is.Empty); + } + + static byte[] SineWem(params double[] amplitudes) + { + if (amplitudes.Length == 0) + amplitudes = [0.5]; + + const int rate = 44100; + var channels = amplitudes.Length; + var frames = rate / 5; + var samples = new short[frames * channels]; + for (var i = 0; i < frames; i++) + { + for (var c = 0; c < channels; c++) + samples[i * channels + c] = (short)(amplitudes[c] * short.MaxValue * Math.Sin(2 * Math.PI * 1000 * i / rate)); + } + + using var wav = new MemoryStream(); + using (var writer = new NAudio.Wave.WaveFileWriter(wav, new NAudio.Wave.WaveFormat(rate, 16, channels))) + writer.WriteSamples(samples, 0, samples.Length); + return WemFile.CreateFromWavBytes(wav.ToArray(), new WemEncodingSettings()).WriteData(); + } + + const int FiftyMs = 4800; + + static float[] Read(SoundTriggerMixer mixer, int count) + { + var buffer = new float[count]; + Assert.That(mixer.Output.Read(buffer, 0, count), Is.EqualTo(count), "the output always fills the request"); + return buffer; + } + + static double Rms(float[] samples) => Math.Sqrt(samples.Sum(x => (double)x * x) / samples.Length); + + static float[] Channel(float[] interleaved, int channel) => interleaved.Where((_, i) => i % 2 == channel).ToArray(); + + static SoundTriggerMixer MixerWith(uint id, byte[]? wem = null) + { + var mixer = new SoundTriggerMixer(openDevice: false); + Assert.That(mixer.Prepare(id, () => wem ?? SineWem()), Is.True); + return mixer; + } + + [Test] + public void Mixer_PlaysAPreparedSound() + { + using var mixer = MixerWith(7); + + mixer.Play(7); + + Assert.That(Rms(Read(mixer, FiftyMs)), Is.GreaterThan(0.05)); + } + + [Test] + public void Mixer_MonoSource_PlaysOnBothChannels_At1000Hz() + { + using var mixer = MixerWith(7); + + mixer.Play(7); + var read = Read(mixer, FiftyMs); + var left = Channel(read, 0); + var right = Channel(read, 1); + var crossings = left.Zip(left.Skip(1)).Count(pair => pair.First < 0 != pair.Second < 0); + + Assert.Multiple(() => + { + Assert.That(right, Is.EqualTo(left), "a mono source plays the same on both channels"); + Assert.That(crossings, Is.InRange(97, 103)); + }); + } + + [Test] + public void Mixer_StereoSource_KeepsItsChannels() + { + using var mixer = MixerWith(7, SineWem(0.5, 0)); + + mixer.Play(7); + var read = Read(mixer, FiftyMs); + + Assert.Multiple(() => + { + Assert.That(Rms(Channel(read, 0)), Is.GreaterThan(0.05)); + Assert.That(Rms(Channel(read, 1)), Is.LessThan(0.02)); + }); + } + + [TestCase(3)] + [TestCase(4)] + [TestCase(6)] + public void Mixer_MoreThanTwoChannels_KeepsTheFirstTwo(int channels) + { + var wem = SineWem(Enumerable.Range(0, channels).Select(c => 0.1 + 0.15 * c).ToArray()); + var decoded = DecodedChannelRms(wem, frames: 4410); + using var mixer = MixerWith(7, wem); + + mixer.Play(7); + var read = Read(mixer, 2 * FiftyMs); + + Assert.Multiple(() => + { + Assert.That(Math.Abs(decoded[0] - decoded[2]), Is.GreaterThan(0.04), "the third channel is told apart from the first"); + Assert.That(Math.Abs(decoded[1] - decoded[2]), Is.GreaterThan(0.04), "and from the second"); + Assert.That(Rms(Channel(read, 0)), Is.EqualTo(decoded[0]).Within(0.02)); + Assert.That(Rms(Channel(read, 1)), Is.EqualTo(decoded[1]).Within(0.02)); + }); + } + + static double[] DecodedChannelRms(byte[] wem, int frames) + { + using var reader = new NAudio.Vorbis.VorbisWaveReader(new MemoryStream(Shared.GameFormats.Audio.Containers.Ogg.OggFile.CreateFromWemBytes(wem).WriteData(), writable: false)); + var channels = reader.WaveFormat.Channels; + var buffer = new float[frames * channels]; + Assert.That(reader.Read(buffer, 0, buffer.Length), Is.EqualTo(buffer.Length)); + return Enumerable.Range(0, channels).Select(c => Rms(buffer.Where((_, i) => i % channels == c).ToArray())).ToArray(); + } + + [Test] + public void Mixer_AVoice_PlaysItsSoundOnceAndEnds() + { + using var mixer = MixerWith(7); + + mixer.Play(7); + var chunks = Enumerable.Range(0, 6).Select(_ => Rms(Read(mixer, FiftyMs))).ToList(); + + Assert.Multiple(() => + { + Assert.That(chunks.Take(4), Is.All.GreaterThan(0.05), "the sound plays through its 0.2 s"); + Assert.That(chunks[5], Is.EqualTo(0), "and is silent from 0.25 s on"); + }); + } + + [Test] + public void Mixer_SameSoundTwice_IsTwoVoices() + { + using var mixer = MixerWith(7); + + mixer.Play(7); + var alone = Rms(Read(mixer, FiftyMs)); + mixer.Play(7); + var overlap = Rms(Read(mixer, FiftyMs)); + Read(mixer, 2 * FiftyMs); + var pastTheFirst = Rms(Read(mixer, FiftyMs)); + + Assert.Multiple(() => + { + Assert.That(alone, Is.GreaterThan(0.05)); + Assert.That(overlap, Is.GreaterThan(alone * 1.5)); + Assert.That(pastTheFirst, Is.GreaterThan(0.05), "the second voice is still sounding after the first has ended"); + }); + } + + [Test] + public void Mixer_StopAll_Silences() + { + using var mixer = MixerWith(7); + mixer.Play(7); + Assert.That(Rms(Read(mixer, FiftyMs)), Is.GreaterThan(0.05), "the sound was playing"); + + mixer.StopAll(); + + Assert.That(Read(mixer, FiftyMs), Is.All.EqualTo(0f)); + } + + [Test] + public void Mixer_UnpreparedOrBadBytes() + { + using var mixer = new SoundTriggerMixer(openDevice: false); + + var results = new bool[2]; + Assert.DoesNotThrow(() => results[0] = mixer.Prepare(8, () => null)); + Assert.DoesNotThrow(() => results[1] = mixer.Prepare(9, () => [1, 2, 3])); + mixer.Play(8); + mixer.Play(9); + mixer.Play(10); + + Assert.Multiple(() => + { + Assert.That(results, Is.All.False); + Assert.That(Read(mixer, FiftyMs), Is.All.EqualTo(0f)); + }); + } + + [Test] + public void Mixer_Keep_DropsOthers() + { + using var mixer = MixerWith(7); + Assert.That(mixer.Prepare(10, () => SineWem()), Is.True); + + mixer.Keep([7]); + mixer.Play(10); + var dropped = Read(mixer, FiftyMs); + mixer.Play(7); + var kept = Read(mixer, FiftyMs); + + Assert.Multiple(() => + { + Assert.That(dropped, Is.All.EqualTo(0f)); + Assert.That(Rms(kept), Is.GreaterThan(0.05)); + }); + } + + [Test] + public void Mixer_Keep_LetsAPlayingVoiceFinish() + { + using var mixer = MixerWith(7); + mixer.Play(7); + + mixer.Keep([]); + + Assert.That(Rms(Read(mixer, FiftyMs)), Is.GreaterThan(0.05)); + } + + [Test] + public void Mixer_PreparedAgain_DoesNotDecodeAgain() + { + using var mixer = MixerWith(7); + + var asked = false; + var again = mixer.Prepare(7, () => { asked = true; return SineWem(); }); + + Assert.Multiple(() => + { + Assert.That(again, Is.True); + Assert.That(asked, Is.False); + }); + } + + [Test] + public void Mixer_AfterDispose_PlaysNothing() + { + var mixer = MixerWith(7); + mixer.Dispose(); + + mixer.Play(7); + var (preparedAfter, asked) = (true, false); + Assert.DoesNotThrow(() => preparedAfter = mixer.Prepare(8, () => { asked = true; return SineWem(); })); + mixer.Play(8); + + Assert.Multiple(() => + { + Assert.That(preparedAfter, Is.False); + Assert.That(asked, Is.False, "the bytes were not asked for"); + Assert.That(Read(mixer, FiftyMs), Is.All.EqualTo(0f)); + }); + } + + [Test] + public void Mixer_MoreVoicesThanTheMixerTakes_PlaysTheFirst1024() + { + using var mixer = MixerWith(7); + mixer.Play(7); + var one = Rms(Read(mixer, FiftyMs)); + mixer.StopAll(); + + Assert.DoesNotThrow(() => { for (var i = 0; i < 1100; i++) mixer.Play(7); }); + var many = Rms(Read(mixer, FiftyMs)); + + Assert.That(many / one, Is.EqualTo(1024).Within(1).Percent); + } + + static Mock Device(string? failAt = null) + { + var device = new Mock(); + var fail = new InvalidOperationException("the device refused: " + failAt); + if (failAt == "Play") + device.Setup(x => x.Play()).Throws(fail); + if (failAt == "Init") + device.Setup(x => x.Init(It.IsAny())).Throws(fail); + if (failAt == "Stop") + device.Setup(x => x.Stop()).Throws(fail); + if (failAt == "Dispose") + device.Setup(x => x.Dispose()).Throws(fail); + return device; + } + + [TestCase("Init")] + [TestCase("Play")] + public void Mixer_ADeviceThatCannotStart_IsDisposed_AndTheNextOneIsUsed(string failAt) + { + var (first, second) = (Device(failAt), Device()); + + using (new SoundTriggerMixer([() => first.Object, () => second.Object])) + { + first.Verify(x => x.Dispose(), Times.Once); + second.Verify(x => x.Play(), Times.Once); + second.Verify(x => x.Dispose(), Times.Never); + } + second.Verify(x => x.Dispose(), Times.Once); + } + + [Test] + public void Mixer_ADeviceThatStopsWithAFailure_SaysSo() + { + var device = Device(); + using var mixer = new SoundTriggerMixer([() => device.Object]); + var stopped = new List(); + mixer.DeviceStopped += stopped.Add; + var failure = new InvalidOperationException("the endpoint went away"); + + device.Raise(x => x.PlaybackStopped += null, new StoppedEventArgs()); + device.Raise(x => x.PlaybackStopped += null, new StoppedEventArgs(failure)); + + Assert.That(stopped, Is.EqualTo(new[] { failure })); + } + + [Test] + public void Mixer_WhenNoDeviceStarts_EachIsDisposed_AndTheLastFailureIsThrown() + { + var (first, second) = (Device("Play"), Device("Init")); + + var thrown = Assert.Throws(() => new SoundTriggerMixer([() => first.Object, () => second.Object])); + + Assert.That(thrown!.Message, Does.EndWith("Init")); + first.Verify(x => x.Dispose(), Times.Once); + second.Verify(x => x.Dispose(), Times.Once); + } + + [Test] + public void Mixer_Dispose_StopsAndDisposesTheDeviceOnce_AndNeverThrows() + { + var (quiet, failingStop, failingDispose) = (Device(), Device("Stop"), Device("Dispose")); + var mixer = new SoundTriggerMixer([() => quiet.Object]); + + mixer.Dispose(); + Assert.DoesNotThrow(mixer.Dispose); + Assert.DoesNotThrow(new SoundTriggerMixer([() => failingStop.Object]).Dispose); + Assert.DoesNotThrow(new SoundTriggerMixer([() => failingDispose.Object]).Dispose); + + quiet.Verify(x => x.Stop(), Times.Once); + quiet.Verify(x => x.Dispose(), Times.Once); + failingStop.Verify(x => x.Dispose(), Times.Once); + failingDispose.Verify(x => x.Stop(), Times.Once); + } + + [Test] + public void Mixer_UsedFromSeveralThreads_KeepsWorking() + { + using var mixer = new SoundTriggerMixer(openDevice: false); + var wem = SineWem(); + using var stop = new CancellationTokenSource(); + var reader = Task.Run(() => + { + var buffer = new float[FiftyMs]; + while (!stop.IsCancellationRequested) + Assert.That(mixer.Output.Read(buffer, 0, buffer.Length), Is.EqualTo(buffer.Length)); + }); + var users = Enumerable.Range(0, 2).Select(t => Task.Run(() => + { + for (var i = 0; i < 100; i++) + { + var id = (uint)(t * 1000 + i % 5); + mixer.Prepare(id, () => wem); + mixer.Play(id); + mixer.Keep([id, (uint)((1 - t) * 1000 + i % 5)]); + } + })).ToArray(); + + Assert.That(Task.WaitAll(users, TimeSpan.FromSeconds(15)), Is.True, "the two threads finished"); + stop.Cancel(); + Assert.That(reader.Wait(TimeSpan.FromSeconds(5)), Is.True); + Assert.That(mixer.Prepare(7, () => wem), Is.True); + mixer.StopAll(); + mixer.Play(7); + Assert.That(Rms(Read(mixer, FiftyMs)), Is.GreaterThan(0.05)); + } + } +} diff --git a/Editors/Audio/SoundTriggers/AudioMetadataTags.cs b/Editors/Audio/SoundTriggers/AudioMetadataTags.cs new file mode 100644 index 000000000..4fa705037 --- /dev/null +++ b/Editors/Audio/SoundTriggers/AudioMetadataTags.cs @@ -0,0 +1,30 @@ +#nullable enable +using Shared.Core.PackFiles; +using Shared.GameFormats.DB; + +namespace Editors.Audio.SoundTriggers +{ + public sealed record AudioTagEvents(string BattleStart, string CampaignStart); + + public sealed class AudioMetadataTags + { + readonly Dictionary _tags; + + AudioMetadataTags(Dictionary tags) => _tags = tags; + + public static AudioMetadataTags From(IEnumerable rows) + { + var tags = new Dictionary(StringComparer.Ordinal); + foreach (var row in rows) + tags.TryAdd(row.Text("key"), new AudioTagEvents(row.Text("sound_event_battle_start"), row.Text("sound_event_campaign_start"))); + return new AudioMetadataTags(tags); + } + + public static AudioMetadataTags Read(IPackFileService pfs, List? problems = null) => + From(DbTables.Read(pfs, "audio_metadata_tags_tables", problems)); + + public AudioTagEvents? Find(string tag) => _tags.GetValueOrDefault(tag); + + public int Count => _tags.Count; + } +} diff --git a/Editors/Audio/SoundTriggers/SoundTriggerCrossing.cs b/Editors/Audio/SoundTriggers/SoundTriggerCrossing.cs new file mode 100644 index 000000000..9f301ddfb --- /dev/null +++ b/Editors/Audio/SoundTriggers/SoundTriggerCrossing.cs @@ -0,0 +1,35 @@ +#nullable enable +namespace Editors.Audio.SoundTriggers +{ + public static class SoundTriggerCrossing + { + public const double SlackSeconds = 0.05; + + public const double MaxFrameSeconds = 0.1; + + public static (double From, double To, bool Wrapped) Step(double previous, double now, double length, double elapsedSeconds, double speed) + { + var frame = Math.Min(elapsedSeconds, MaxFrameSeconds) * speed; + var allowed = frame + SlackSeconds; + + var ahead = now - previous; + if (ahead >= 0 && ahead <= allowed) + return (previous, now, false); + if (now < previous && length - previous + now <= allowed) + return (previous, now, true); + + // The nudge keeps a tag exactly at the last frame's start inside the span. + return (now - frame - 1e-6, now, false); + } + + public static bool Crossed(double start, (double From, double To, bool Wrapped) step, double length) + { + if (start < 0 || start > length) + return false; + + return step.Wrapped + ? start > step.From || start <= step.To + : start > step.From && start <= step.To; + } + } +} diff --git a/Editors/Audio/SoundTriggers/SoundTriggerMixer.cs b/Editors/Audio/SoundTriggers/SoundTriggerMixer.cs new file mode 100644 index 000000000..690e7f2b5 --- /dev/null +++ b/Editors/Audio/SoundTriggers/SoundTriggerMixer.cs @@ -0,0 +1,200 @@ +#nullable enable +using System.IO; +using NAudio.CoreAudioApi; +using NAudio.Vorbis; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using Shared.GameFormats.Audio.Containers.Ogg; + +namespace Editors.Audio.SoundTriggers +{ + public sealed class SoundTriggerMixer : IDisposable + { + public static readonly WaveFormat Format = WaveFormat.CreateIeeeFloatWaveFormat(48000, 2); + static readonly ILogger s_logger = Logging.Create(); + + readonly object _gate = new(); + readonly Dictionary _cache = []; + readonly MixingSampleProvider _mixer = new(Format) { ReadFully = true }; + IWavePlayer? _device; + bool _disposed; + + public SoundTriggerMixer(bool openDevice = true, int latencyMs = 30) + : this(openDevice + ? [() => new WasapiOut(AudioClientShareMode.Shared, true, latencyMs), () => new WaveOutEvent { DesiredLatency = Math.Max(latencyMs, 60), NumberOfBuffers = 3 }] + : []) + { + } + + internal SoundTriggerMixer(IReadOnlyList> devices) + { + for (var i = 0; i < devices.Count; i++) + { + IWavePlayer? device = null; + try + { + device = devices[i](); + device.Init(_mixer); + // Before Play, so a device that fails to start on its own thread is heard. + device.PlaybackStopped += (_, e) => + { + if (e.Exception != null) + DeviceStopped?.Invoke(e.Exception); + }; + device.Play(); + _device = device; + return; + } + catch when (i < devices.Count - 1) + { + device?.Dispose(); + } + catch + { + device?.Dispose(); + throw; + } + } + } + + public event Action? DeviceStopped; + + public ISampleProvider Output => _mixer; + + public bool Prepare(uint sourceId, Func wemBytes) + { + lock (_gate) + { + if (_disposed) + return false; + if (_cache.ContainsKey(sourceId)) + return true; + } + + var pcm = Decode(wemBytes()); + if (pcm == null) + return false; + + lock (_gate) + { + if (_disposed) + return false; + _cache[sourceId] = pcm; + } + return true; + } + + public void Play(uint sourceId) + { + lock (_gate) + { + if (!_cache.TryGetValue(sourceId, out var pcm)) + return; + + try + { + _mixer.AddMixerInput(new Voice(pcm)); + } + catch (InvalidOperationException) + { + // NAudio's mixer takes 1,024 inputs at most; the extra voice is dropped. + } + } + } + + public void StopAll() + { + lock (_gate) + _mixer.RemoveAllMixerInputs(); + } + + public void Keep(IEnumerable sourceIds) + { + var keep = sourceIds.ToHashSet(); + lock (_gate) + { + foreach (var id in _cache.Keys.Where(id => !keep.Contains(id)).ToList()) + _cache.Remove(id); + } + } + + public void Dispose() + { + IWavePlayer? device; + lock (_gate) + { + _disposed = true; + _mixer.RemoveAllMixerInputs(); + _cache.Clear(); + device = _device; + _device = null; + } + + // Outside the lock: WasapiOut's Stop joins its thread. + if (device == null) + return; + foreach (var step in new Action[] { device.Stop, device.Dispose }) + { + try + { + step(); + } + catch (Exception e) + { + s_logger.Here().Warning($"SuperView sound: the output device failed to close: {e.Message}"); + } + } + } + + static float[]? Decode(byte[]? wem) + { + if (wem == null) + return null; + + try + { + var ogg = OggFile.CreateFromWemBytes(wem).WriteData(); + using var reader = new VorbisWaveReader(new MemoryStream(ogg, writable: false)); + + ISampleProvider source = reader; + if (source.WaveFormat.Channels == 1) + source = new MonoToStereoSampleProvider(source); + else if (source.WaveFormat.Channels > 2) + { + var firstTwo = new MultiplexingSampleProvider([source], 2); + firstTwo.ConnectInputToOutput(0, 0); + firstTwo.ConnectInputToOutput(1, 1); + source = firstTwo; + } + if (source.WaveFormat.SampleRate != Format.SampleRate) + source = new WdlResamplingSampleProvider(source, Format.SampleRate); + + var samples = new List(); + var buffer = new float[Format.SampleRate * Format.Channels]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + samples.AddRange(new ArraySegment(buffer, 0, read)); + return samples.ToArray(); + } + catch (Exception) + { + return null; + } + } + + sealed class Voice(float[] pcm) : ISampleProvider + { + int _position; + + public WaveFormat WaveFormat => Format; + + public int Read(float[] buffer, int offset, int count) + { + var n = Math.Min(count, pcm.Length - _position); + Array.Copy(pcm, _position, buffer, offset, n); + _position += n; + return n; + } + } + } +} diff --git a/Editors/Audio/SoundTriggers/SoundTriggerResolver.cs b/Editors/Audio/SoundTriggers/SoundTriggerResolver.cs new file mode 100644 index 000000000..5f3842332 --- /dev/null +++ b/Editors/Audio/SoundTriggers/SoundTriggerResolver.cs @@ -0,0 +1,233 @@ +#nullable enable +using Shared.GameFormats.Wwise; +using Shared.GameFormats.Wwise.Enums; +using Shared.GameFormats.Wwise.Hirc; +using Shared.GameFormats.Wwise.Hirc.V136; + +namespace Editors.Audio.SoundTriggers +{ + public abstract record SoundNode; + + public sealed record SoundLeaf(uint SourceId) : SoundNode; + + public sealed record SoundAll(IReadOnlyList Children) : SoundNode; + + public sealed record SoundOneOf(IReadOnlyList Children, uint Id = 0, IReadOnlyList? Weights = null, int AvoidRepeat = 0, + bool Shuffle = false, bool Sequence = false) : SoundNode; + + public static class SoundNodes + { + public static IEnumerable Leaves(SoundNode node) => node switch + { + SoundLeaf leaf => [leaf.SourceId], + SoundAll all => all.Children.SelectMany(Leaves), + SoundOneOf oneOf => oneOf.Children.SelectMany(Leaves), + _ => [], + }; + + public static IReadOnlyList Pick(SoundNode node, Random random) => new SoundPicker(random).Pick(node); + } + + public sealed class SoundPicker(Random random) + { + readonly Dictionary> _played = []; + readonly Dictionary _next = []; + + public IReadOnlyList Pick(SoundNode node) => node switch + { + SoundLeaf leaf => [leaf.SourceId], + SoundAll all => all.Children.SelectMany(Pick).ToList(), + SoundOneOf { Children.Count: > 0 } oneOf => Pick(oneOf.Children[Choose(oneOf)]), + _ => [], + }; + + int Choose(SoundOneOf container) + { + var count = container.Children.Count; + if (container.Sequence) + { + var index = _next.GetValueOrDefault(container.Id) % count; + _next[container.Id] = index + 1; + return index; + } + + if (!_played.TryGetValue(container.Id, out var played)) + _played[container.Id] = played = []; + var avoided = played.TakeLast(Math.Min(container.AvoidRepeat, count - 1)).ToHashSet(); + if (container.Shuffle) + avoided.UnionWith(played.TakeLast(played.Count % count)); + var allowed = Enumerable.Range(0, count).Where(x => !avoided.Contains(x)).ToList(); + var chosen = Weighted(allowed, container.Weights); + played.Add(chosen); + return chosen; + } + + int Weighted(List allowed, IReadOnlyList? weights) + { + var total = weights == null ? 0 : allowed.Sum(x => (double)Math.Max(0, weights[x])); + if (total <= 0) + return allowed[random.Next(allowed.Count)]; + var at = random.NextDouble() * total; + foreach (var index in allowed) + { + at -= Math.Max(0, weights![index]); + if (at < 0) + return index; + } + return allowed[^1]; + } + } + + public sealed record SwitchGroupSeen(uint GroupId, uint DefaultSwitch, IReadOnlyList Values); + + public sealed record SoundTriggerResult(string Tag, SoundNode? Sound, string? Silent, IReadOnlyList Switches); + + public sealed class SoundTriggerResolver(Func tagRow, Func> hircs, Func wemExists) + { + public const string NotSupported = "not supported: "; + + HircItem? Hirc(uint id) => hircs(id).FirstOrDefault(); + + public SoundTriggerResult Resolve(string tag, bool campaign, IReadOnlyDictionary switchChoices) + { + var row = tagRow(tag); + if (row == null) + return Silent(tag, "no audio_metadata_tags_tables row"); + + var eventName = campaign ? row.CampaignStart : row.BattleStart; + if (string.IsNullOrWhiteSpace(eventName)) + return Silent(tag, campaign ? "the row names no campaign event" : "the row names no battle event"); + + var item = Hirc(WwiseHash.Compute(eventName)); + if (item == null) + return Silent(tag, $"event {eventName} is in no loaded bank"); + if (item is not ICAkEvent actionEvent) + return Silent(tag, NotSupported + item.HircType); + + var walk = new Walk(Hirc, wemExists, switchChoices); + var plays = new List(); + var playActions = 0; + string? unsupported = null; + uint? missing = null; + foreach (var actionId in actionEvent.GetActionIds()) + { + switch (Hirc(actionId)) + { + case null: + missing ??= actionId; + break; + case ICAkAction action when action.GetActionType() == AkActionType.Play: + playActions++; + if (walk.Visit(action.GetChildId()) is { } node) + plays.Add(node); + break; + case { } other when MayStartASound(other): + unsupported ??= Describe(other, actionEvent); + break; + } + } + + var sound = Combine(plays, oneOf: false); + var silent = sound != null ? null + : unsupported != null ? NotSupported + unsupported + : walk.Problem + ?? (missing != null ? $"action {missing} of event {eventName} is in no loaded bank" + : playActions != 0 ? $"event {eventName} plays nothing found in the loaded banks" + : $"event {eventName} has no Play action"); + return new SoundTriggerResult(tag, sound, silent, walk.Switches); + } + + static SoundTriggerResult Silent(string tag, string reason) => new(tag, null, reason, []); + + static bool MayStartASound(HircItem item) => item is not ICAkAction action || action.GetActionType() is var type && (!Enum.IsDefined(type) + || type is AkActionType.PlayAndContinue or AkActionType.PlayEvent or AkActionType.Trigger or AkActionType.Trigger_O or AkActionType.Trigger_E or AkActionType.Trigger_E_O); + + string Describe(HircItem item, ICAkEvent owner, bool follow = true) + { + if (item is not ICAkAction action) + return item.HircType.ToString(); + + var type = action.GetActionType(); + var text = (Enum.IsDefined(type) ? type.ToString() : $"0x{(ushort)type:X4}") + " action"; + if (hircs(action.GetChildId()).FirstOrDefault(x => !ReferenceEquals(x, owner)) is not { } target) + return text; + text += " -> " + target.HircType; + if (follow && target is ICAkEvent inner && inner.GetActionIds().Select(Hirc).OfType().FirstOrDefault() is { } first) + text += " -> " + Describe(first, inner, follow: false); + return text; + } + + static SoundNode? Combine(List children, bool oneOf) => children.Count switch + { + 0 => null, + 1 => children[0], + _ => oneOf ? new SoundOneOf(children) : new SoundAll(children), + }; + + sealed class Walk(Func hirc, Func wemExists, IReadOnlyDictionary switchChoices) + { + readonly HashSet _path = []; + + public List Switches { get; } = []; + public string? Problem { get; private set; } + + public SoundNode? Visit(uint id) + { + if (hirc(id) is not { } item || !_path.Add(id)) + return null; + + try + { + switch (item) + { + case ICAkSound sound: + var sourceId = sound.GetSourceId(); + if (wemExists(sourceId)) + return new SoundLeaf(sourceId); + Problem ??= $"WEM not found: {sourceId}.wem"; + return null; + case ICAkSwitchCntr container: + return VisitSwitch(container); + case ICAkRanSeqCntr container: + return VisitRanSeq(container); + case ICAkLayerCntr container: + return Combine(VisitAll(container.GetChildren()), oneOf: false); + case ICAkActorMixer container: + return Combine(VisitAll(container.GetChildren()), oneOf: false); + default: + Problem ??= NotSupported + item.HircType; + return null; + } + } + finally + { + _path.Remove(id); + } + } + + List VisitAll(IEnumerable ids) => ids.Select(Visit).OfType().ToList(); + + // Weights always apply: bIsUsingWeight is clear on every CA container, even unequally weighted ones. + SoundNode? VisitRanSeq(ICAkRanSeqCntr container) + { + var kept = container.GetChildren().Select((id, index) => (Node: Visit(id), Index: index)).Where(x => x.Node != null).ToList(); + if (kept.Count < 2 || container is not CAkRanSeqCntr_V136 rules) + return Combine(kept.Select(x => x.Node!).ToList(), oneOf: true); + var sequence = rules.Mode == 1; + return new SoundOneOf(kept.Select(x => x.Node!).ToList(), rules.Id, kept.Select(x => rules.CAkPlayList.Playlist[x.Index].Weight).ToList(), + rules.AvoidRepeatCount, Shuffle: rules.RandomMode == 1, Sequence: sequence); + } + + SoundNode? VisitSwitch(ICAkSwitchCntr container) + { + var cases = container.SwitchList; + if (Switches.All(x => x.GroupId != container.GroupId)) + Switches.Add(new SwitchGroupSeen(container.GroupId, container.DefaultSwitch, cases.Select(x => x.SwitchId).ToList())); + + var chosen = switchChoices.TryGetValue(container.GroupId, out var choice) ? cases.FirstOrDefault(x => x.SwitchId == choice) : null; + chosen ??= cases.FirstOrDefault(x => x.SwitchId == container.DefaultSwitch) ?? cases.FirstOrDefault(); + return chosen == null ? null : Combine(VisitAll(chosen.NodeIdList), oneOf: false); + } + } + } +} diff --git a/Editors/Audio/SoundTriggers/SoundTriggerSession.cs b/Editors/Audio/SoundTriggers/SoundTriggerSession.cs new file mode 100644 index 000000000..5420a0dde --- /dev/null +++ b/Editors/Audio/SoundTriggers/SoundTriggerSession.cs @@ -0,0 +1,101 @@ +#nullable enable +namespace Editors.Audio.SoundTriggers +{ + public sealed record SoundTriggerTag(string SoundEvent, float StartTime, string File); + + public sealed class SoundTriggerSession(SoundTriggerResolver resolver, Func prepare, Action play, Random random) + { + List<(double Start, SoundNode Sound)> _playable = []; + List _leaves = []; + readonly SoundPicker _picker = new(random); + + double _previous = double.NaN; + bool _paused; + bool _looped; + + public double OffsetSeconds { get; set; } + + public Dictionary SwitchChoices { get; } = []; + + public IReadOnlyList Switches { get; private set; } = []; + + public IReadOnlyList StatusLines { get; private set; } = []; + + public IEnumerable Leaves => _leaves; + + public void Rebuild(IReadOnlyList tags, bool campaign) + { + var resolved = tags.Select(tag => (Tag: tag, Result: resolver.Resolve(tag.SoundEvent, campaign, SwitchChoices))).ToList(); + + _playable = resolved + .Where(x => x.Result.Sound != null) + .Select(x => (Start: (double)x.Tag.StartTime, Sound: x.Result.Sound!)) + .ToList(); + _leaves = _playable.SelectMany(x => SoundNodes.Leaves(x.Sound)).Distinct().ToList(); + foreach (var id in _leaves) + prepare(id); + + Switches = resolved.SelectMany(x => x.Result.Switches).DistinctBy(x => x.GroupId).ToList(); + + var silent = resolved.Where(x => x.Result.Silent != null).ToList(); + var unsupported = silent.Count(x => x.Result.Silent!.StartsWith(SoundTriggerResolver.NotSupported, StringComparison.Ordinal)); + var summary = resolved.Count == 0 + ? "0 triggers" + : $"{resolved.Count} {(resolved.Count == 1 ? "trigger" : "triggers")}: {_playable.Count} {(_playable.Count == 1 ? "plays" : "play")}, {silent.Count - unsupported} silent in game" + + (unsupported == 0 ? "" : $", {unsupported} not supported"); + StatusLines = [summary, .. silent.Select(x => $"{x.Tag.SoundEvent} ({x.Tag.File}): {x.Result.Silent}")]; + } + + public void Advance(double now, bool playing, double elapsedSeconds, double speed, double length, bool loop) + { + var (previous, paused, looped) = (_previous, _paused, _looped); + _previous = now; + _paused = !playing; + // The player reports the step that reaches the clip's end as paused. + var reachedTheEnd = !playing && !paused && !looped && now >= length; + if (!playing && !reachedTheEnd) + return; + _looped = false; + + var step = looped ? (length, now, true) : SoundTriggerCrossing.Step(previous, now, length, elapsedSeconds, speed); + if (paused && !looped && step == (previous, now, false)) + step = (previous - 1e-6, now, false); + Fire(step, OffsetSeconds * speed, length, loop && !reachedTheEnd); + } + + public void Loop(double speed, double length) + { + if (!double.IsNaN(_previous)) + Fire((_paused ? _previous - 1e-6 : _previous, length, false), OffsetSeconds * speed, length, true); + _previous = 0; + _looped = true; + } + + void Fire((double From, double To, bool Wrapped) step, double offset, double length, bool loop) + { + foreach (var (start, sound) in _playable) + { + if (!Fires(start, offset, step, length, loop)) + continue; + + foreach (var id in _picker.Pick(sound)) + play(id); + } + } + + static bool Fires(double tagStart, double offset, (double From, double To, bool Wrapped) step, double length, bool loop) + { + if (tagStart < 0 || tagStart > length) + return false; + + var due = tagStart - offset; + var dueInClip = !loop ? Math.Clamp(due, 0, length) + : due >= 0 && due <= length ? due + : due - length * Math.Floor(due / length); + if (SoundTriggerCrossing.Crossed(dueInClip, step, length)) + return true; + + return due < 0 && !step.Wrapped && step.From < 0 && step.To >= 0; + } + } +} diff --git a/Editors/Audio/Test.Audio.csproj b/Editors/Audio/Test.Audio.csproj index ad18fa942..1c5c3838a 100644 --- a/Editors/Audio/Test.Audio.csproj +++ b/Editors/Audio/Test.Audio.csproj @@ -24,6 +24,7 @@ + diff --git a/Editors/MetaDataEditor/AnimationMeta/Editors.AnimationMeta.csproj b/Editors/MetaDataEditor/AnimationMeta/Editors.AnimationMeta.csproj index 33f796847..73fc9c501 100644 --- a/Editors/MetaDataEditor/AnimationMeta/Editors.AnimationMeta.csproj +++ b/Editors/MetaDataEditor/AnimationMeta/Editors.AnimationMeta.csproj @@ -10,6 +10,7 @@ + diff --git a/Editors/MetaDataEditor/AnimationMeta/SuperView/EditorView.xaml b/Editors/MetaDataEditor/AnimationMeta/SuperView/EditorView.xaml index 2fdae3112..0bc49e676 100644 --- a/Editors/MetaDataEditor/AnimationMeta/SuperView/EditorView.xaml +++ b/Editors/MetaDataEditor/AnimationMeta/SuperView/EditorView.xaml @@ -118,6 +118,27 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.Sound.cs b/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.Sound.cs new file mode 100644 index 000000000..5db4f1ffe --- /dev/null +++ b/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.Sound.cs @@ -0,0 +1,413 @@ +using System.Collections.ObjectModel; +using System.Diagnostics; +using CommunityToolkit.Mvvm.ComponentModel; +using Editors.Audio.Shared.GameInformation.Warhammer3; +using Editors.Audio.Shared.Storage; +using Editors.Audio.SoundTriggers; +using Editors.Shared.Core.Common; +using GameWorld.Core.Animation; +using Shared.Core.PackFiles.Models; +using Shared.GameFormats.AnimationMeta.Definitions; +using Shared.GameFormats.AnimationMeta.Parsing; + +namespace Editors.AnimationMeta.SuperView +{ + public sealed record SoundSwitchOption(uint SwitchId, string Name, bool IsDefault) + { + public override string ToString() => IsDefault ? Name + " (default)" : Name; + } + + public sealed partial class SoundSwitchPicker(string groupName, IReadOnlyList options, SoundSwitchOption selected, Action picked) + : ObservableObject + { + public string GroupName { get; } = groupName; + public IReadOnlyList Options { get; } = options; + [ObservableProperty] SoundSwitchOption _selected = selected; + + partial void OnSelectedChanged(SoundSwitchOption value) => picked(value); + } + + public partial class SuperViewViewModel + { + [ObservableProperty] bool _soundOn; + + [ObservableProperty] IReadOnlyList _soundStatus = []; + + public ObservableCollection SoundSwitchPickers { get; } = []; + + public Func> LoadSounds { get; set; } = null!; + + public Func PrepareSound { get; set; } = null!; + public Action PlaySound { get; set; } = null!; + public Action StopSounds { get; set; } = null!; + + public Func SoundName { get; set; } = null!; + + // Measured through WASAPI loopback at the mixer's 30 ms latency. + public const double SoundLeadSeconds = 0.026; + + public Func OpenMixer { get; set; } = () => new SoundTriggerMixer(); + + public Task SoundDecoding { get; private set; } = Task.CompletedTask; + + public IReadOnlyList SoundFileProblems + { + get + { + var selection = _asset.FragAndSlotSelection; + return [.. Missing("Slot", selection.SoundMetaName), .. Missing("Persistent", selection.SoundMetaPersistName), .. _unreadableSound]; + + IEnumerable Missing(string which, string? path) => string.IsNullOrWhiteSpace(path) || _packFileService.FindFile(path) != null + ? [] : [$"{which} .snd.meta {path} is in no loaded pack."]; + } + } + + const bool Campaign = false; + + SoundTriggerMixer? _mixer; + IAudioRepository _audio = null!; + readonly List _toDecode = []; + SoundTriggerResolver? _resolver; + SoundTriggerSession? _session; + SynchronizationContext? _ui; + volatile int _rebuilds; + int _applied; + int _backgroundJobs; + bool _soundRebuildPosted; + CancellationTokenSource? _soundLoad; + string? _soundRefused; + string? _soundFailed; + ParsedMetadataFile? _slotSoundMeta; + ParsedMetadataFile? _persistSoundMeta; + List _unreadableSound = []; + IReadOnlyList _shownSwitches = []; + readonly Stopwatch _sinceAdvance = Stopwatch.StartNew(); + + void InitSound(IAudioRepository audio) + { + _audio = audio; + _ui = SynchronizationContext.Current; + LoadSounds = token => Task.Run(() => + { + audio.Load([Wh3LanguageInformation.GetLanguageAsString(Wh3Language.EnglishUK)]); + token.ThrowIfCancellationRequested(); + var tags = AudioMetadataTags.Read(_packFileService); + return new SoundTriggerResolver(tags.Find, id => audio.GetHircs(id).ToList(), id => audio.FindWem(id.ToString()) != null); + }, token); + PrepareSound = id => + { + _toDecode.Add(id); + return _mixer != null; + }; + PlaySound = id => _mixer?.Play(id); + StopSounds = () => _mixer?.StopAll(); + SoundName = audio.GetNameFromId; + + _asset.Data.AnimationChanged += OnSoundAnimationChanged; + _asset.Data.Player.OnFrameChanged += AdvanceSounds; + Player.Looping += LoopSounds; + ShowSoundStatus(); + } + + // Before the player puts the new clip on the old frame index, or that frame fires the last clip's triggers. + void OnSoundAnimationChanged(AnimationClip? clip) + { + RebuildSounds(); + StopSounds(); + ShowSwitchPickers([]); + } + + void LoadSoundMetas(SceneObject owner) + { + _unreadableSound = []; + _slotSoundMeta = Parse("Slot", owner.SoundMetaData); + _persistSoundMeta = Parse("Persistent", owner.PersistSoundMetaData); + OnPropertyChanged(nameof(SoundFileProblems)); + + ParsedMetadataFile? Parse(string which, PackFile? file) + { + if (file == null) + return null; + try + { + return _metaDataFileParser.ParseFile(file.DataSource.ReadData()); + } + catch (Exception ex) + { + _unreadableSound.Add($"{which} .snd.meta {_packFileService.GetFullPath(file)} could not be read: {ex.Message}"); + return null; + } + } + } + + partial void OnSoundOnChanged(bool value) + { + if (!value) + { + _soundLoad?.Cancel(); + _soundLoad = null; + _rebuilds++; + StopSounds(); + ShowSwitchPickers([]); + ShowSoundStatus(); + return; + } + + _soundRefused = null; + try + { + if (_mixer == null) + { + var mixer = _mixer = OpenMixer(); + mixer.DeviceStopped += e => OnUi(() => DeviceStopped(mixer, e)); + } + } + catch (Exception e) + { + Refuse($"No audio device could be opened: {e.Message}"); + return; + } + if (_session == null) + LoadSession(); + RebuildSounds(); + } + + void DeviceStopped(SoundTriggerMixer mixer, Exception e) + { + if (mixer != _mixer) + return; + _mixer = null; + mixer.Dispose(); + Refuse($"The sound device stopped: {e.Message}"); + } + + void Refuse(string why) + { + _soundRefused = why; + SoundOn = false; + ShowSoundStatus(); + } + + async void LoadSession() + { + var load = _soundLoad = new CancellationTokenSource(); + SoundTriggerResolver resolver; + try + { + resolver = await LoadSounds(load.Token); + } + catch (Exception e) + { + if (load == _soundLoad && !load.IsCancellationRequested) + { + _soundLoad = null; + Refuse($"The game's sounds could not be loaded: {e.Message}"); + } + return; + } + if (load != _soundLoad || load.IsCancellationRequested) + return; + + _soundLoad = null; + _resolver = resolver; + _session = new SoundTriggerSession(resolver, id => PrepareSound(id), id => PlaySound(id), new Random()) { OffsetSeconds = SoundLeadSeconds }; + RebuildSounds(); + } + + // Only warms the repository's cache off the UI thread; ApplyRebuild resolves the tags again on it. + void RebuildSounds() + { + if (SoundOn && _session != null) + { + var (request, tags, choices, resolver) = (++_rebuilds, SoundTriggers(), new Dictionary(_session.SwitchChoices), _resolver!); + _soundFailed = null; + Background(request, () => + { + foreach (var tag in tags) + { + if (request != _rebuilds) + return; + resolver.Resolve(tag.SoundEvent, Campaign, choices); + } + OnUi(() => ApplyRebuild(request)); + }); + } + ShowSoundStatus(); + } + + // UpdateView re-adds tags one at a time, each raising a change. + void RebuildSoundsSoon() + { + if (_soundRebuildPosted) + return; + _soundRebuildPosted = true; + OnUi(() => + { + _soundRebuildPosted = false; + RebuildSounds(); + }); + } + + void ApplyRebuild(int request) + { + if (request != _rebuilds || !SoundOn || _session == null) + return; + _session.Rebuild(SoundTriggers(), Campaign); + _applied = request; + DecodeQueued(request, _session.Leaves.ToHashSet()); + ShowSwitchPickers(_session.Switches); + ShowSoundStatus(); + } + + void DecodeQueued(int request, HashSet wanted) + { + var (mixer, ids, audio) = (_mixer, _toDecode.ToList(), _audio); + _toDecode.Clear(); + if (mixer == null) + return; + Background(request, () => + { + foreach (var id in ids) + { + if (request != _rebuilds) + return; + mixer.Prepare(id, () => ReadWem(audio, id)); + } + mixer.Keep(wanted); + }); + } + + void Background(int request, Action job) + { + _backgroundJobs++; + SoundDecoding = SoundDecoding.ContinueWith(_ => + { + string? failure = null; + try + { + job(); + } + catch (Exception e) + { + failure = e.Message; + } + OnUi(() => + { + _backgroundJobs--; + if (failure != null && request == _rebuilds) + _soundFailed = $"Sounds could not be prepared: {failure}"; + ShowSoundStatus(); + }); + }, TaskScheduler.Default); + } + + void OnUi(Action action) + { + if (_ui == null) + action(); + else + _ui.Post(_ => action(), null); + } + + static byte[]? ReadWem(IAudioRepository audio, uint id) + { + try + { + return audio.FindWem(id.ToString())?.DataSource.ReadData(); + } + catch (Exception) + { + return null; + } + } + + List SoundTriggers() => + [ + .. Triggers(PersistentMetaEditor.ParsedFile, "persistent meta"), + .. Triggers(MetaEditor.ParsedFile, "clip meta"), + .. Triggers(_slotSoundMeta, "slot .snd.meta"), + .. Triggers(_persistSoundMeta, "persistent .snd.meta"), + ]; + + static IEnumerable Triggers(ParsedMetadataFile? file, string label) => (file?.Attributes ?? []).Select(x => x switch + { + SoundTrigger_v10 tag => new SoundTriggerTag(tag.SoundEvent, tag.StartTime, label), + SoundTrigger_v4 tag => new SoundTriggerTag(tag.SoundEvent, tag.StartTime, label), + _ => null, + }).OfType(); + + // Until the latest rebuild lands, the session still holds the last clip's triggers. + bool SoundsLive => SoundOn && _session != null && _applied == _rebuilds; + + void AdvanceSounds(int frame) + { + if (!SoundsLive) + return; + var player = _asset.Data.Player; + var elapsed = _sinceAdvance.Elapsed.TotalSeconds; + _sinceAdvance.Restart(); + _session!.Advance(player.GetTimeUs() / 1_000_000d, player.IsPlaying, elapsed, 1, player.GetAnimationLengthUs() / 1_000_000d, + Player.LoopAnimation.Value); + } + + void LoopSounds() + { + if (SoundsLive) + _session!.Loop(1, _asset.Data.Player.GetAnimationLengthUs() / 1_000_000d); + } + + void ShowSoundStatus() + { + IReadOnlyList lines = [.. SoundFileProblems, .. SessionLines()]; + if (!lines.SequenceEqual(SoundStatus)) + SoundStatus = lines; + + IEnumerable SessionLines() + { + if (!SoundOn) + return _soundRefused == null ? [] : [_soundRefused]; + if (_session == null || _session.StatusLines.Count == 0) + return [_soundFailed ?? "Loading sounds..."]; + List lines = _applied == _rebuilds ? [.. _session.StatusLines] : []; + if (_backgroundJobs != 0) + lines.Add("Decoding sounds..."); + if (_soundFailed != null) + lines.Add(_soundFailed); + return lines; + } + } + + void ShowSwitchPickers(IReadOnlyList switches) + { + switches = [.. switches.Where(x => x.Values.Count != 0)]; + if (switches.Count == _shownSwitches.Count && switches.Zip(_shownSwitches).All(x => x.First.GroupId == x.Second.GroupId && x.First.Values.SequenceEqual(x.Second.Values))) + return; + + _shownSwitches = switches; + var session = _session!; + SoundSwitchPickers.Clear(); + foreach (var group in switches) + { + var options = group.Values.Select(x => new SoundSwitchOption(x, SoundName(x), x == group.DefaultSwitch)).ToList(); + var picked = session.SwitchChoices.TryGetValue(group.GroupId, out var choice) ? options.FirstOrDefault(x => x.SwitchId == choice) : null; + SoundSwitchPickers.Add(new SoundSwitchPicker(SoundName(group.GroupId), options, picked ?? options.FirstOrDefault(x => x.IsDefault) ?? options[0], x => + { + session.SwitchChoices[group.GroupId] = x.SwitchId; + RebuildSounds(); + })); + } + } + + void CloseSound() + { + _asset.Data.AnimationChanged -= OnSoundAnimationChanged; + _asset.Data.Player.OnFrameChanged -= AdvanceSounds; + Player.Looping -= LoopSounds; + _soundLoad?.Cancel(); + _soundLoad = null; + _rebuilds++; + _mixer?.Dispose(); + _mixer = null; + } + } +} diff --git a/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.cs b/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.cs index e91bf8d49..77b5e2a30 100644 --- a/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.cs +++ b/Editors/MetaDataEditor/AnimationMeta/SuperView/SuperViewViewModel.cs @@ -2,6 +2,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Editors.AnimationMeta.Presentation; +using Editors.Audio.Shared.Storage; using Editors.AnimationMeta.SuperView.Editing; using Editors.AnimationMeta.SuperView.Problems; using Editors.AnimationMeta.SuperView.Timeline; @@ -123,7 +124,8 @@ public SuperViewViewModel( CombatMetaDataGizmoComponent gizmo, MetaDataMarkerPickerComponent markerPicker, IFileSaveService fileSaveService, - IStandardDialogs standardDialogs) + IStandardDialogs standardDialogs, + IAudioRepository audioRepository) : base(editorHostParameters) { DisplayName = "Super view"; @@ -155,6 +157,7 @@ public SuperViewViewModel( eventHub.Register(this, OnSelectedMetaDataAttributeChanged); globalEventHub.Register(this, x => OnPackFilesChanged(x.Container, x.AddedFiles)); globalEventHub.Register(this, x => OnPackFilesChanged(x.Container, x.ChangedFiles)); + InitSound(audioRepository); } // A vfx file, a texture, or a model, material or animation a rigid particle may draw changed in a pack (the VFX editor @@ -186,6 +189,7 @@ void OnMetaDataAttributeChanged(MetaDataAttributeChangedEvent @event) { RecreateMetaDataInformation(); RebuildTimeline(); + RebuildSoundsSoon(); } void OnMetaDataChanged(SceneObject sceneObject) => RecreateMetaDataInformation(); @@ -345,10 +349,13 @@ private void OnSceneObjectUpdated(SceneObjectUpdateEvent e) if (MetaEditor.ParsedFile != animation) _editSession.ResetDocument(MetaEditor); + LoadSoundMetas(e.Owner); + RecreateMetaDataInformation(); RebuildTimeline(); UpdateEditTarget(); NotifyMetaFileState(); + RebuildSounds(); } void OnSlotSelectionChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) @@ -395,6 +402,7 @@ void OnTagsChanged(object? sender, System.Collections.Specialized.NotifyCollecti else if (ReferenceEquals(sender, MetaEditor.Tags)) _editSession.ResetDocument(MetaEditor); RebuildTimeline(); + RebuildSoundsSoon(); } // One marker per timed tag in both META files, on the animation player's scrub bar. @@ -586,6 +594,7 @@ void FocusMarker(ParsedMetadataAttribute source) public override void Close() { + CloseSound(); _markerPicker.Disconnect(); _gizmo.EndDrag(); _editSession.ValueChanged -= OnEditValueChanged; diff --git a/Editors/Shared/Editors.Shared.Core/Common/AnimationPlayer/AnimationPlayerViewModel.cs b/Editors/Shared/Editors.Shared.Core/Common/AnimationPlayer/AnimationPlayerViewModel.cs index 7b9e1073f..b15056559 100644 --- a/Editors/Shared/Editors.Shared.Core/Common/AnimationPlayer/AnimationPlayerViewModel.cs +++ b/Editors/Shared/Editors.Shared.Core/Common/AnimationPlayer/AnimationPlayerViewModel.cs @@ -39,6 +39,9 @@ public double ScrubTime public event Action? TimelineItemClicked; public ICommand TimelineItemClickCommand { get; } + /// Raised before Loop's jump back to frame 0, a paused frame set listeners can't otherwise tell from a scrub. + public event Action? Looping; + public NotifyAttr PlayerControlsVisibility { get; private set; } = new(Visibility.Collapsed); public ObservableCollection PlayerItems { get; private set; } = new ObservableCollection(); @@ -193,6 +196,7 @@ private void OnAnimationFrameChanged(int currentFrame) { if (LoopAnimation.Value) { + Looping?.Invoke(); SetAnimationFirstFrame(); ToggleAnimationPausePlay(); } diff --git a/Editors/Shared/Editors.Shared.Core/Common/ReferenceModel/BinAnimationViewModel.cs b/Editors/Shared/Editors.Shared.Core/Common/ReferenceModel/BinAnimationViewModel.cs index daebedfb5..eeb81dfa6 100644 --- a/Editors/Shared/Editors.Shared.Core/Common/ReferenceModel/BinAnimationViewModel.cs +++ b/Editors/Shared/Editors.Shared.Core/Common/ReferenceModel/BinAnimationViewModel.cs @@ -25,6 +25,8 @@ public partial class BinAnimationViewModel : ObservableObject [ObservableProperty] FilterCollection _fragmentSlotList; [ObservableProperty] string? _metaDataName; [ObservableProperty] string? _metaDataPersistName; + [ObservableProperty] string? _soundMetaName; + [ObservableProperty] string? _soundMetaPersistName; [ObservableProperty] string? _animationFileName; bool _isSettingAnimationFile; @@ -138,6 +140,8 @@ public void SetAnimationFile(PackFile file) var fullPath = _pfs.GetFullPath(file); _sceneObjectEditor.SetAnimation(_sceneObject, file, fullPath); + SoundMetaName = null; + _sceneObject.SoundMetaData = null; _sceneObjectEditor.SetMetaFile(_sceneObject, null, _sceneObject.PersistMetaData); MetaDataName = null; @@ -165,23 +169,32 @@ void OnAnimationSlotSelected(AnimationBinEntryGenericFormat value) if (string.IsNullOrWhiteSpace(value?.MetaFile) == false) meta = _pfs.FindFile(value.MetaFile); + AnimationBinEntryGenericFormat? persistRow = null; var persist = FragmentSlotList.PossibleValues.FirstOrDefault(x => x.SlotName == "PERSISTENT_METADATA_ALIVE"); if (persist != null && string.IsNullOrWhiteSpace(persist.MetaFile) == false) { persistMeta = _pfs.FindFile(persist.MetaFile); persistFullpath = persist.MetaFile; + persistRow = persist; } if (persistMeta == null) { var persistFlying = FragmentSlotList.PossibleValues.FirstOrDefault(x => x.SlotName == "PERSISTENT_METADATA_FLYING"); if (persistFlying != null && string.IsNullOrWhiteSpace(persistFlying.MetaFile) == false) - { + { persistMeta = _pfs.FindFile(persistFlying.MetaFile); persistFullpath = persistFlying.MetaFile; + persistRow = persistFlying; } } + // Before SetMetaFile, whose one scene update carries them. + SoundMetaName = value?.SoundFile; + SoundMetaPersistName = persistRow?.SoundFile; + _sceneObject.SoundMetaData = string.IsNullOrWhiteSpace(SoundMetaName) ? null : _pfs.FindFile(SoundMetaName); + _sceneObject.PersistSoundMetaData = string.IsNullOrWhiteSpace(SoundMetaPersistName) ? null : _pfs.FindFile(SoundMetaPersistName); + _sceneObjectEditor.SetAnimation(_sceneObject, animationReference?.AnimationFile); _sceneObjectEditor.SetMetaFile(_sceneObject, meta, persistMeta); diff --git a/Editors/Shared/Editors.Shared.Core/Common/SceneObject.cs b/Editors/Shared/Editors.Shared.Core/Common/SceneObject.cs index 9f146b2ec..0c8257b55 100644 --- a/Editors/Shared/Editors.Shared.Core/Common/SceneObject.cs +++ b/Editors/Shared/Editors.Shared.Core/Common/SceneObject.cs @@ -39,6 +39,8 @@ public class SceneObject : BaseComponent, ISkeletonProvider public AnimationClip AnimationClip { get; set; } public PackFile? MetaData { get; set; } public PackFile? PersistMetaData { get; set; } + public PackFile? SoundMetaData { get; set; } + public PackFile? PersistSoundMetaData { get; set; } public Matrix Offset { get; set; } = Matrix.Identity; public string Id { get; private set; } diff --git a/Editors/Shared/Editors.Shared.Core/Common/SceneObjectEditor.cs b/Editors/Shared/Editors.Shared.Core/Common/SceneObjectEditor.cs index 23d7e4f7e..8899cfafa 100644 --- a/Editors/Shared/Editors.Shared.Core/Common/SceneObjectEditor.cs +++ b/Editors/Shared/Editors.Shared.Core/Common/SceneObjectEditor.cs @@ -92,6 +92,7 @@ public void SetMesh(SceneObject sceneObject, PackFile file, bool updateSkeleton var skeletonName = SceneNodeHelper.GetSkeletonName(loadedNode); var fullSkeletonName = $"animations\\skeletons\\{skeletonName}.anim"; var skeletonFile = _packFileService.FindFile(fullSkeletonName); + sceneObject.SoundMetaData = sceneObject.PersistSoundMetaData = null; SetMetaFile(sceneObject, null, null); SetSkeleton(sceneObject, skeletonFile, false); } diff --git a/Shared/EmbeddedResources/Resources/Db/schema_wh3_extract.txt b/Shared/EmbeddedResources/Resources/Db/schema_wh3_extract.txt new file mode 100644 index 000000000..4d6efd56e --- /dev/null +++ b/Shared/EmbeddedResources/Resources/Db/schema_wh3_extract.txt @@ -0,0 +1,525 @@ +# From RPFM's schema_wh3.ron (2026-11-04). +@audio_metadata_tags_tables;5 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +@audio_metadata_tags_tables;6 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +@audio_metadata_tags_tables;7 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +@audio_metadata_tags_tables;8 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +@audio_metadata_tags_tables;11 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +@audio_metadata_tags_tables;13 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +require_secondary_melee_switch;Boolean;0 +is_persistent_loop;Boolean;0 +@audio_metadata_tags_tables;14 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +requires_cinematic;Boolean;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +doppler_rtpc_name;OptionalStringU8;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +require_secondary_melee_switch;Boolean;0 +looping_sound_mapping;OptionalStringU8;0 +is_persistent_loop;Boolean;0 +@audio_metadata_tags_tables;18 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +doppler_rtpc_name;OptionalStringU8;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +requires_cinematic;Boolean;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +looping_sound_mapping;OptionalStringU8;0 +is_persistent_loop;Boolean;0 +require_modular_ability_switch;Boolean;0 +require_secondary_melee_switch;Boolean;0 +default_vmd_slot_name;OptionalStringU8;0 +use_character_idle_switch;Boolean;0 +@audio_metadata_tags_tables;19 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +doppler_rtpc_name;OptionalStringU8;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +requires_cinematic;Boolean;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +looping_sound_mapping;OptionalStringU8;0 +is_persistent_loop;Boolean;0 +require_modular_ability_switch;Boolean;0 +require_secondary_melee_switch;Boolean;0 +default_vmd_slot_name;OptionalStringU8;0 +use_character_idle_switch;Boolean;0 +additional_actor_id;OptionalStringU8;0 +@audio_metadata_tags_tables;21 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +doppler_rtpc_name;OptionalStringU8;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +requires_cinematic;Boolean;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +looping_sound_mapping;OptionalStringU8;0 +is_persistent_loop;Boolean;0 +require_modular_ability_switch;Boolean;0 +require_secondary_melee_switch;Boolean;0 +default_vmd_slot_name;OptionalStringU8;0 +use_character_idle_switch;Boolean;0 +additional_actor_id;OptionalStringU8;0 +is_persistent_one_shot;Boolean;0 +persistent_one_shot_duration_override;F64;0 +@audio_metadata_tags_tables;22 +key;StringU8;1 +sound_event_battle_start;OptionalStringU8;0 +sound_event_battle_stop;OptionalStringU8;0 +sound_event_campaign_start;OptionalStringU8;0 +sound_event_campaign_stop;OptionalStringU8;0 +limitation_scale;F32;0 +entity_type_switch;OptionalStringU8;0 +melee_hit_category;OptionalStringU8;0 +melee_hit_type_override;OptionalStringU8;0 +rtpc_1_name;OptionalStringU8;0 +rtpc_1_assignment;OptionalStringU8;0 +rtpc_2_name;OptionalStringU8;0 +rtpc_2_assignment;OptionalStringU8;0 +scaled_sound_upsize;I32;0 +scaled_max_delay;F32;0 +scaled_sound_next;OptionalStringU8;0 +doppler_rtpc_name;OptionalStringU8;0 +max_probability;F32;0 +min_probability;F32;0 +is_vocalisation;Boolean;0 +play_at_bone;Boolean;0 +play_at_position;Boolean;0 +play_at_base;Boolean;0 +require_ground_type_limited;Boolean;0 +require_ground_type;Boolean;0 +require_armour_type;Boolean;0 +require_melee_weapon_type;Boolean;0 +require_shield_type;Boolean;0 +triggers_blood;Boolean;0 +is_tracked;Boolean;0 +require_reverb;Boolean;0 +require_obstruction;Boolean;0 +can_play_under_splice;Boolean;0 +ignore_if_headless;Boolean;0 +play_on_looping_sound;Boolean;0 +cinematic_only;Boolean;0 +requires_cinematic;Boolean;0 +flip_direction;Boolean;0 +blood_enabled_only;Boolean;0 +use_limitation_type_override;Boolean;0 +limitation_type_override;StringU8;0 +culling_distance_override;F32;0 +ignore_alpha_check;Boolean;0 +override_vo;Boolean;0 +looping_sound_mapping;OptionalStringU8;0 +is_persistent_loop;Boolean;0 +require_modular_ability_switch;Boolean;0 +require_secondary_melee_switch;Boolean;0 +default_vmd_slot_name;OptionalStringU8;0 +use_character_idle_switch;Boolean;0 +additional_actor_id;OptionalStringU8;0 +is_persistent_one_shot;Boolean;0 +persistent_one_shot_duration_override;F64;0 +vocalisation_bank_split;OptionalStringU8;0 diff --git a/Shared/EmbeddedResources/Shared.EmbeddedResources.csproj b/Shared/EmbeddedResources/Shared.EmbeddedResources.csproj index 69aba3d94..eea20213b 100644 --- a/Shared/EmbeddedResources/Shared.EmbeddedResources.csproj +++ b/Shared/EmbeddedResources/Shared.EmbeddedResources.csproj @@ -15,6 +15,7 @@ + @@ -122,6 +123,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/Shared/GameFiles/DB/DbSchema.cs b/Shared/GameFiles/DB/DbSchema.cs new file mode 100644 index 000000000..f8f1bf062 --- /dev/null +++ b/Shared/GameFiles/DB/DbSchema.cs @@ -0,0 +1,40 @@ +using Shared.EmbeddedResources; + +namespace Shared.GameFormats.DB +{ + public record DbField(string Name, string Type, bool IsKey); + + public static class DbSchema + { + static Dictionary>>? _tables; + + public static IReadOnlyDictionary> Versions(string table) => + (_tables ??= Parse(ResourceLoader.LoadString("Resources.Db.schema_wh3_extract.txt"))).TryGetValue(table, out var versions) + ? versions + : new Dictionary>(); + + public static Dictionary>> Parse(string text) + { + var tables = new Dictionary>>(); + List? fields = null; + foreach (var raw in text.Split('\n')) + { + var line = raw.TrimEnd('\r'); + if (line.Length == 0 || line.StartsWith('#')) + continue; + var cells = line.TrimStart('@').Split(';'); + if (line.StartsWith('@')) + { + if (!tables.TryGetValue(cells[0], out var versions)) + tables[cells[0]] = versions = []; + versions[int.Parse(cells[1])] = fields = []; + } + else + { + fields!.Add(new DbField(cells[0], cells[1], cells[2] == "1")); + } + } + return tables; + } + } +} diff --git a/Shared/GameFiles/DB/DbTableReader.cs b/Shared/GameFiles/DB/DbTableReader.cs new file mode 100644 index 000000000..3f69da58f --- /dev/null +++ b/Shared/GameFiles/DB/DbTableReader.cs @@ -0,0 +1,82 @@ +using System.IO; +using System.Text; + +namespace Shared.GameFormats.DB +{ + public static class DbTableReader + { + static readonly byte[] GuidMarker = [0xFD, 0xFE, 0xFC, 0xFF]; + static readonly byte[] VersionMarker = [0xFC, 0xFD, 0xFE, 0xFF]; + + public static (int Version, List> Rows) Read(byte[] data, string table, string file) + { + var p = 0; + if (Starts(data, p, GuidMarker)) + p += 6 + BitConverter.ToUInt16(data, p + 4) * 2; + var version = 0; + if (Starts(data, p, VersionMarker)) + { + version = BitConverter.ToInt32(data, p + 4); + p += 8; + } + if (!DbSchema.Versions(table).TryGetValue(version, out var fields)) + throw new InvalidDataException($"{file}: {table} v{version} is not in the schema extract."); + + var rows = new List>(); + try + { + p += 1; + var count = BitConverter.ToInt32(data, p); + p += 4; + for (var i = 0; i < count; i++) + { + var row = new Dictionary(fields.Count); + foreach (var field in fields) + row[field.Name] = Cell(data, ref p, field.Type, table); + rows.Add(row); + } + } + catch (Exception e) when (e is ArgumentException or IndexOutOfRangeException) + { + throw new InvalidDataException($"{file}: {table} v{version} runs past the end of the file."); + } + if (p != data.Length) + throw new InvalidDataException($"{file}: {table} v{version} decoded {p} of {data.Length} bytes."); + return (version, rows); + } + + static bool Starts(byte[] data, int at, byte[] marker) => data.Length >= at + marker.Length && data.AsSpan(at, marker.Length).SequenceEqual(marker); + + static object Cell(byte[] data, ref int p, string type, string table) + { + switch (type) + { + case "OptionalStringU8": + return data[p++] == 0 ? "" : Text(data, ref p); + case "StringU8": + return Text(data, ref p); + case "Boolean": + return data[p++] != 0; + case "I32": + p += 4; + return BitConverter.ToInt32(data, p - 4); + case "F32": + p += 4; + return BitConverter.ToSingle(data, p - 4); + case "F64": + p += 8; + return BitConverter.ToDouble(data, p - 8); + default: + throw new NotSupportedException($"{table}: the field type {type} is not read; DbTableReader reads the six the extract's tables use."); + } + } + + static string Text(byte[] data, ref int p) + { + var length = BitConverter.ToUInt16(data, p); + var text = Encoding.UTF8.GetString(data, p + 2, length); + p += 2 + length; + return text; + } + } +} diff --git a/Shared/GameFiles/DB/DbTables.cs b/Shared/GameFiles/DB/DbTables.cs new file mode 100644 index 000000000..b0fd99dc0 --- /dev/null +++ b/Shared/GameFiles/DB/DbTables.cs @@ -0,0 +1,49 @@ +using System.IO; +using Shared.Core.PackFiles; +using Shared.Core.PackFiles.Models; + +namespace Shared.GameFormats.DB +{ + public record DbRow(IReadOnlyDictionary Cells, int Version, string Pack, string File) + { + public string Text(string column) => Cells.TryGetValue(column, out var value) ? value as string ?? "" : ""; + public bool Flag(string column, bool missing = false) => Cells.TryGetValue(column, out var value) ? value is true : missing; + public int Number(string column, int missing = 0) => Cells.TryGetValue(column, out var value) && value is int number ? number : missing; + } + + public static class DbTables + { + public static List Read(IPackFileService pfs, string table, List? problems = null) + { + var folder = @"db\" + table; + var packs = pfs.GetAllPackfileContainers(); + // The game keeps a mod's row over CA's, and among mods the file whose name sorts first; one mod's file per path. + // Pack names stand in for the mod list's order, which isn't known here. + var mods = packs.Where(x => !x.IsCaPackFile).OrderBy(x => x.Name, StringComparer.Ordinal) + .SelectMany(x => Files(x, folder)) + .DistinctBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .OrderBy(x => x.Name, StringComparer.Ordinal); + var rows = new List(); + foreach (var (container, name) in mods.Concat(packs.Where(x => x.IsCaPackFile).SelectMany(x => Files(x, folder)))) + { + var path = folder + @"\" + name; + if (container.FindFile(path) is not { } file) + continue; + var shown = path.Replace('\\', '/'); + try + { + var (version, read) = DbTableReader.Read(file.DataSource.ReadData(), table, $"{container.Name}: {shown}"); + rows.AddRange(read.Select(x => new DbRow(x, version, container.Name, shown))); + } + catch (InvalidDataException e) when (problems != null) + { + problems.Add(e.Message); + } + } + return rows; + } + + static IEnumerable<(IPackFileContainer Pack, string Name)> Files(IPackFileContainer pack, string folder) => + pack.GetAllFilesByFolder().TryGetValue(folder, out var names) ? names.Select(x => (pack, x)) : []; + } +}