350 lines
16 KiB
C#
350 lines
16 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Numerics;
|
|
using RustToDust.Client;
|
|
using RustToDust.Core;
|
|
using RustToDust.Core.Audio;
|
|
using RustToDust.Net;
|
|
using RustToDust.Ymir;
|
|
using Xunit;
|
|
|
|
namespace RustToDust.Tests;
|
|
|
|
public sealed class AudioSynthTests
|
|
{
|
|
private static readonly string[] ExpectedHavenWavs =
|
|
{
|
|
"mg_shot_01.wav", "mg_shot_02.wav", "mg_tail.wav",
|
|
"ac_light_01.wav", "ac_light_02.wav", "ac_med_01.wav", "ac_rotary.wav",
|
|
"flak_blast_01.wav", "flak_blast_02.wav", "cannon_heavy_01.wav", "cannon_heavy_02.wav",
|
|
"pd_bark_01.wav", "pd_bark_02.wav", "pd_laser.wav",
|
|
"rocket_salvo_01.wav", "rocket_salvo_02.wav",
|
|
"plasma_ppc_01.wav", "plasma_ppc_02.wav", "lance_beam_01.wav", "laser_heavy_01.wav", "gauss_rail_01.wav",
|
|
"mech_reload_bolt.wav", "mech_quick_bolt.wav", "mech_eject.wav", "mech_turret_servo.wav"
|
|
};
|
|
|
|
private static string LocateAssetsAudioDir()
|
|
{
|
|
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
|
|
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
|
|
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
|
|
return Path.Combine(assetsDir, "audio");
|
|
}
|
|
|
|
[Fact]
|
|
public void CuratedHavenWavs_AreExactly25ValidMono44100PcmUnderBudgetWithZeroThirdPartyFiles()
|
|
{
|
|
string audioDir = LocateAssetsAudioDir();
|
|
string havenDir = Path.Combine(audioDir, "haven");
|
|
Assert.True(Directory.Exists(havenDir), $"Missing curated Haven directory: {havenDir}");
|
|
|
|
string[] allAudioFiles = Directory.GetFiles(audioDir, "*", SearchOption.AllDirectories);
|
|
foreach (string filePath in allAudioFiles)
|
|
{
|
|
string name = Path.GetFileName(filePath);
|
|
Assert.False(name.StartsWith("SW01_", StringComparison.OrdinalIgnoreCase), $"Forbidden SW01 file found: {name}");
|
|
Assert.False(name.StartsWith("MW4", StringComparison.OrdinalIgnoreCase), $"Forbidden MW4 file found: {name}");
|
|
Assert.False(name.StartsWith("Utilities", StringComparison.OrdinalIgnoreCase), $"Forbidden Utilities file found: {name}");
|
|
Assert.False(string.Equals(name, "desktop.ini", StringComparison.OrdinalIgnoreCase), $"Forbidden desktop.ini found: {filePath}");
|
|
}
|
|
|
|
string[] havenFiles = Directory.GetFiles(havenDir);
|
|
Assert.Equal(25, havenFiles.Length);
|
|
|
|
var actualNames = havenFiles.Select(Path.GetFileName).OrderBy(x => x, StringComparer.Ordinal).ToArray();
|
|
var expectedSorted = ExpectedHavenWavs.OrderBy(x => x, StringComparer.Ordinal).ToArray();
|
|
Assert.Equal(expectedSorted, actualNames);
|
|
|
|
long totalBytes = 0;
|
|
foreach (string wavPath in havenFiles)
|
|
{
|
|
totalBytes += new FileInfo(wavPath).Length;
|
|
WavPcmInfo info = WavFileReader.ReadMonoOrStereo16(wavPath);
|
|
|
|
Assert.Equal(44100, info.SampleRate);
|
|
Assert.Equal(1, info.Channels);
|
|
Assert.Equal(16, info.BitsPerSample);
|
|
Assert.True(info.FloatSamples.Length >= 4410, $"{Path.GetFileName(wavPath)} unexpectedly short.");
|
|
|
|
float peak = 0f;
|
|
double sumSq = 0.0;
|
|
for (int i = 0; i < info.FloatSamples.Length; i++)
|
|
{
|
|
float s = info.FloatSamples[i];
|
|
Assert.True(float.IsFinite(s));
|
|
float a = MathF.Abs(s);
|
|
if (a > peak) peak = a;
|
|
sumSq += s * s;
|
|
}
|
|
double rms = Math.Sqrt(sumSq / info.FloatSamples.Length);
|
|
Assert.True(rms > 0.01, $"{Path.GetFileName(wavPath)} is silent (RMS={rms:F5}).");
|
|
Assert.True(peak <= 0.95f, $"{Path.GetFileName(wavPath)} clips/exceeds 0.95 (peak={peak:F4}).");
|
|
}
|
|
|
|
Assert.True(totalBytes < 4L * 1024L * 1024L, $"Curated Haven WAV total size {totalBytes} bytes exceeds 4 MB.");
|
|
}
|
|
|
|
[Fact]
|
|
public void AttributionFile_ExistsAndCreditsHavenKendrick()
|
|
{
|
|
string attributionPath = Path.Combine(LocateAssetsAudioDir(), "ATTRIBUTION.md");
|
|
Assert.True(File.Exists(attributionPath), $"Missing attribution file: {attributionPath}");
|
|
string text = File.ReadAllText(attributionPath);
|
|
Assert.Contains("Haven Kendrick", text, StringComparison.Ordinal);
|
|
Assert.Contains("WetMixMode", text, StringComparison.Ordinal);
|
|
}
|
|
|
|
[Fact]
|
|
public void PcmSynth_AllCuesAreFiniteNonSilentNonClippingInBothWetAndDryModes_AndWetAddsTailEnergy()
|
|
{
|
|
Dictionary<string, PcmClipData> wetClips = PcmSynth.SynthesizeAll(wetMixMode: true);
|
|
Dictionary<string, PcmClipData> dryClips = PcmSynth.SynthesizeAll(wetMixMode: false);
|
|
|
|
Assert.Equal(PcmSynth.CueRegistry.Count, wetClips.Count);
|
|
Assert.Equal(PcmSynth.CueRegistry.Count, dryClips.Count);
|
|
|
|
foreach (var (_, key) in PcmSynth.CueRegistry)
|
|
{
|
|
PcmClipData wet = wetClips[key];
|
|
PcmClipData dry = dryClips[key];
|
|
|
|
Assert.Equal(44100, wet.SampleRate);
|
|
Assert.Equal(44100, dry.SampleRate);
|
|
Assert.Equal(wet.IsLoop, dry.IsLoop);
|
|
|
|
AssertValidPcmBounds(wet, key + " (wet)");
|
|
AssertValidPcmBounds(dry, key + " (dry)");
|
|
|
|
if (wet.IsLoop)
|
|
{
|
|
Assert.Equal(44100, wet.Samples.Length);
|
|
Assert.Equal(44100, dry.Samples.Length);
|
|
float wetWrapDiff = MathF.Abs(wet.Samples[^1] - wet.Samples[0]);
|
|
float dryWrapDiff = MathF.Abs(dry.Samples[^1] - dry.Samples[0]);
|
|
Assert.True(wetWrapDiff < 0.02f, $"Wet loop '{key}' wrap click: {wetWrapDiff:F5}");
|
|
Assert.True(dryWrapDiff < 0.02f, $"Dry loop '{key}' wrap click: {dryWrapDiff:F5}");
|
|
|
|
// Wet room stage alters loop signal measurably vs dry
|
|
double diffSq = 0.0;
|
|
for (int i = 0; i < wet.Samples.Length; i++)
|
|
{
|
|
double d = wet.Samples[i] - dry.Samples[i];
|
|
diffSq += d * d;
|
|
}
|
|
Assert.True(Math.Sqrt(diffSq / wet.Samples.Length) > 0.005, $"Wet loop '{key}' did not measurably differ from dry.");
|
|
}
|
|
else
|
|
{
|
|
// Wet one-shots carry real diffused reverb tail beyond the pure dry buffer length
|
|
// and measurably higher late/tail energy than the pure dry buffer.
|
|
Assert.True(wet.Samples.Length > dry.Samples.Length, $"Wet one-shot '{key}' should include reverb tail.");
|
|
int lateStart = (int)(dry.Samples.Length * 0.90);
|
|
double dryLateEnergy = 0.0;
|
|
for (int i = lateStart; i < dry.Samples.Length; i++)
|
|
{
|
|
dryLateEnergy += dry.Samples[i] * dry.Samples[i];
|
|
}
|
|
double wetLateEnergy = 0.0;
|
|
for (int i = lateStart; i < wet.Samples.Length; i++)
|
|
{
|
|
wetLateEnergy += wet.Samples[i] * wet.Samples[i];
|
|
}
|
|
double postDryEnergy = 0.0;
|
|
for (int i = dry.Samples.Length; i < wet.Samples.Length; i++)
|
|
{
|
|
postDryEnergy += wet.Samples[i] * wet.Samples[i];
|
|
}
|
|
Assert.True(postDryEnergy > 0.001, $"Wet one-shot '{key}' has zero post-dry tail energy ({postDryEnergy:F6}).");
|
|
Assert.True(wetLateEnergy > dryLateEnergy * 1.15 + 0.001,
|
|
$"Wet one-shot '{key}' lacks measurable reverb tail energy (dryLate={dryLateEnergy:F4}, wetLate={wetLateEnergy:F4}).");
|
|
}
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void WalkerFootstepTracker_TriggersStrictlyOnStanceTouchdownEdges()
|
|
{
|
|
var tracker = new WalkerFootstepTracker();
|
|
var terrain = new TerrainField(seed: 42);
|
|
var pulses = new List<FootstepPulse>();
|
|
|
|
var snap = new WalkerVisualSnapshot
|
|
{
|
|
LegCount = 2,
|
|
GeomScale = 1f,
|
|
ComPos = new Vector3(10f, 3f, 20f),
|
|
ComRot = Quaternion.Identity
|
|
};
|
|
|
|
// 1. Standing still with high load: first sighting + 20 frames -> 0 footsteps (no spawn pop, no spam)
|
|
snap.LoadG[0] = 1.0f;
|
|
snap.LoadG[1] = 1.0f;
|
|
for (int f = 0; f < 20; f++)
|
|
{
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
|
|
}
|
|
Assert.Empty(pulses);
|
|
|
|
// 2. Airborne (swing) across 20 frames -> 0 footsteps, legs become armed
|
|
snap.LoadG[0] = 0.0f;
|
|
snap.LoadG[1] = 0.0f;
|
|
for (int f = 0; f < 20; f++)
|
|
{
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
|
|
}
|
|
Assert.Empty(pulses);
|
|
|
|
// 3. Touchdown leg 0 rising across sub-frames -> fires EXACTLY ONCE
|
|
snap.LoadG[0] = 0.25f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
|
|
snap.LoadG[0] = 0.80f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
|
|
snap.LoadG[0] = 1.40f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
|
|
Assert.Single(pulses);
|
|
Assert.Equal(0, pulses[0].LegIndex);
|
|
Assert.InRange(MathF.Abs(pulses[0].WorldPos.Y - terrain.SampleHeight(pulses[0].WorldPos.X, pulses[0].WorldPos.Z)), 0f, 0.01f);
|
|
|
|
// 4. Re-arm and bounce faster than 0.18s cooldown -> suppressed by cooldown
|
|
pulses.Clear();
|
|
snap.LoadG[0] = 0.02f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
|
|
snap.LoadG[0] = 0.50f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
|
|
Assert.Empty(pulses);
|
|
|
|
// 5. After cooldown expires (> 0.18s), re-arm + touchdown fires again
|
|
snap.LoadG[0] = 0.02f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.20f, pulses);
|
|
snap.LoadG[0] = 0.60f;
|
|
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
|
|
Assert.Single(pulses);
|
|
}
|
|
|
|
[Fact]
|
|
public void ClientArenaSession_DrainSimEvents_WorksInSoloAndLoopbackRemote()
|
|
{
|
|
using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester", skipInitialDrop: true);
|
|
IClientArenaSession localIface = local;
|
|
var events = new List<ISimEvent>();
|
|
|
|
var player = local.Inner.State.Contenders[0];
|
|
var input = new PlayerInput(
|
|
Throttle: 0f,
|
|
Steer: 0f,
|
|
AimWorldX: player.X + 25f,
|
|
AimWorldZ: player.Z,
|
|
Fire: true,
|
|
InteractPickup: false,
|
|
Brake: false);
|
|
|
|
for (int i = 0; i < 10; i++)
|
|
{
|
|
localIface.SubmitLocalInput(in input, isPhysicsTick: true);
|
|
}
|
|
localIface.DrainSimEvents(events);
|
|
Assert.Contains(events, e => e is ShotFiredEvent s && !s.IsSpectatorShooter && s.ShooterId == 0);
|
|
|
|
// Draining again returns empty until new steps occur
|
|
events.Clear();
|
|
localIface.DrainSimEvents(events);
|
|
Assert.Empty(events);
|
|
|
|
// Loopback host + remote receives ShotFiredEvent through IClientArenaSession.DrainSimEvents
|
|
using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert);
|
|
using var remote = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "AudioRemote");
|
|
IClientArenaSession remoteIface = remote;
|
|
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
for (int t = 0; t < 15 && !remote.IsJoined; t++)
|
|
{
|
|
host.StepOnce(nowMs + t * 16);
|
|
remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
}
|
|
Assert.True(remote.IsJoined);
|
|
host.Session.SetContenderPose(remote.LocalContenderId, 0f, 0f, 0f);
|
|
for (int s = 0; s < 4; s++)
|
|
{
|
|
host.StepOnce(nowMs + 240 + s * 16);
|
|
remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
}
|
|
|
|
var rLocal = remoteIface.LocalContender;
|
|
var fireInput = new PlayerInput(0f, 0f, rLocal.X + 30f, rLocal.Z, true, false, false);
|
|
for (int t = 0; t < 10; t++)
|
|
{
|
|
remoteIface.SubmitLocalInput(in fireInput, isPhysicsTick: true);
|
|
host.StepOnce(nowMs + 300 + t * 16);
|
|
remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
}
|
|
events.Clear();
|
|
remoteIface.DrainSimEvents(events);
|
|
Assert.Contains(events, e => e is ShotFiredEvent);
|
|
}
|
|
|
|
[Fact]
|
|
public void RemoteArenaSession_UpdatesRemoteContenderSpeedAndYawFromSnapshot()
|
|
{
|
|
using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert);
|
|
using var remoteA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Observer");
|
|
using var remoteB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Driver");
|
|
IClientArenaSession ifaceA = remoteA;
|
|
IClientArenaSession ifaceB = remoteB;
|
|
|
|
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
for (int t = 0; t < 20 && (!remoteA.IsJoined || !remoteB.IsJoined); t++)
|
|
{
|
|
host.StepOnce(nowMs + t * 16);
|
|
ifaceA.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
ifaceB.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
}
|
|
Assert.True(remoteA.IsJoined && remoteB.IsJoined);
|
|
|
|
int idA = ifaceA.LocalContenderId;
|
|
int idB = ifaceB.LocalContenderId;
|
|
var hostA = host.Session.State.Contenders[idA];
|
|
var hostB = host.Session.State.Contenders[idB];
|
|
hostB.Grid.SwapChassis(Catalog.Jackal);
|
|
host.Session.SetContenderPose(idB, hostA.X + 20f, hostA.Z + 20f, 0.75f);
|
|
|
|
for (int t = 0; t < 25; t++)
|
|
{
|
|
ifaceA.SubmitLocalInput(new PlayerInput(0f, 0f, hostA.X, hostA.Z + 20f, false, false, false), isPhysicsTick: true);
|
|
ifaceB.SubmitLocalInput(new PlayerInput(1.0f, 0.25f, hostB.X + 30f, hostB.Z + 30f, false, false, false), isPhysicsTick: true);
|
|
host.StepOnce(nowMs + 350 + t * 16);
|
|
ifaceA.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
ifaceB.BeginRenderFrame(1.0 / 60.0, 1.0f);
|
|
}
|
|
|
|
Assert.True(ifaceA.IsContenderVisible(idB));
|
|
var rivalOnA = ifaceA.ViewState.Contenders[idB];
|
|
float expectedSpeed = MathF.Sqrt(rivalOnA.VelX * rivalOnA.VelX + rivalOnA.VelZ * rivalOnA.VelZ);
|
|
Assert.True(rivalOnA.Speed > 2.0f, $"Expected remote moving Jackal Speed > 2.0, got {rivalOnA.Speed}");
|
|
Assert.InRange(MathF.Abs(rivalOnA.Speed - expectedSpeed), 0f, 0.01f);
|
|
|
|
var q = Quaternion.Normalize(new Quaternion(rivalOnA.CurrRotX, rivalOnA.CurrRotY, rivalOnA.CurrRotZ, rivalOnA.CurrRotW));
|
|
var fwd = Vector3.Transform(Vector3.UnitZ, q);
|
|
float expectedYaw = MathF.Atan2(fwd.X, fwd.Z);
|
|
Assert.InRange(MathF.Abs(MatchRules.NormalizeAngle(rivalOnA.Yaw - expectedYaw)), 0f, 0.01f);
|
|
}
|
|
|
|
private static void AssertValidPcmBounds(PcmClipData clip, string label)
|
|
{
|
|
Assert.True(clip.Samples.Length > 0, $"{label} empty");
|
|
float peak = 0f;
|
|
double sumSq = 0.0;
|
|
for (int i = 0; i < clip.Samples.Length; i++)
|
|
{
|
|
float s = clip.Samples[i];
|
|
Assert.True(float.IsFinite(s), $"{label} has non-finite sample at {i}");
|
|
float a = MathF.Abs(s);
|
|
if (a > peak) peak = a;
|
|
sumSq += s * s;
|
|
}
|
|
double rms = Math.Sqrt(sumSq / clip.Samples.Length);
|
|
Assert.True(rms > 0.01, $"{label} is silent (RMS={rms:F5})");
|
|
Assert.True(peak <= 0.98f, $"{label} clips (peak={peak:F4})");
|
|
}
|
|
}
|