Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AssetEditor/Language_Cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "开始或结束时间不是有限数值",
Expand Down
1 change: 1 addition & 0 deletions AssetEditor/Language_En.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions AssetEditor/Language_Fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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<DbField, object>(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<InvalidDataException>(() => 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<InvalidDataException>(() => 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<InvalidDataException>(() => 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);
}
}
}
164 changes: 164 additions & 0 deletions Editors/AnimationMeta/Test.AnimationMeta/SoundTriggerGameTests.cs
Original file line number Diff line number Diff line change
@@ -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<uint, uint> NoChoices = new Dictionary<uint, uint>();

[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<IPackFileContainerLoader>();
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<OpenEditorCommand>().Execute(EditorEnums.SuperView_Editor);
_resolver = superView.LoadSounds(CancellationToken.None).GetAwaiter().GetResult();
_loadTime = clock.Elapsed;
_tags = AudioMetadataTags.Read(_runner.PackFileService);
}

static IReadOnlyList<uint> 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<OpenEditorCommand>().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<uint>());
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<SceneObjectEditor>(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<MetaDataFileParser>(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);
}
}
}
}
Loading
Loading