diff --git a/WaveOptics.Tests/WaveOpticsEffectTests.cs b/WaveOptics.Tests/WaveOpticsEffectTests.cs index 47fbbe6..d8f2d17 100644 --- a/WaveOptics.Tests/WaveOpticsEffectTests.cs +++ b/WaveOptics.Tests/WaveOpticsEffectTests.cs @@ -18,7 +18,7 @@ public sealed class WaveOpticsEffectTests static T Attribute(string property) where T : Attribute => Property(property).GetCustomAttribute()!; static Animation[] Animations(WaveOpticsEffect effect) - => [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical]; + => [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical, effect.HighlightThreshold, effect.HighlightBoost]; [Theory] [InlineData(nameof(WaveOpticsEffect.Amount), 100d, 0d, 100d)] @@ -34,6 +34,8 @@ public sealed class WaveOpticsEffectTests [InlineData(nameof(WaveOpticsEffect.ComaHorizontal), 0d, -10d, 10d)] [InlineData(nameof(WaveOpticsEffect.ComaVertical), 0d, -10d, 10d)] [InlineData(nameof(WaveOpticsEffect.Spherical), 0d, -10d, 10d)] + [InlineData(nameof(WaveOpticsEffect.HighlightThreshold), 95d, 0d, 100d)] + [InlineData(nameof(WaveOpticsEffect.HighlightBoost), 1d, 1d, 1000d)] public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum) { var effect = new WaveOpticsEffect(); @@ -46,6 +48,15 @@ public sealed class WaveOpticsEffectTests Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps)); } + [Fact] + public void LinearLightAndDitherAreOffByDefault() + { + var effect = new WaveOpticsEffect(); + + Assert.False(effect.Linear); + Assert.False(effect.Dither); + } + [Fact] public void KernelRadiusQualityApertureAndBladesStartFromTheirDefaults() { @@ -106,14 +117,16 @@ public sealed class WaveOpticsEffectTests effect.Quality = WaveOpticsQuality.High; effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon; effect.BladeCount = 9; + effect.Linear = true; + effect.Dither = true; - Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount)], changed); + Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount), nameof(WaveOpticsEffect.Linear), nameof(WaveOpticsEffect.Dither)], changed); } [Fact] public void AssigningAnUnchangedOrClampedValueDoesNotNotify() { - var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius }; + var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius, Linear = true, Dither = true }; var changed = new List(); effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName); @@ -122,6 +135,8 @@ public sealed class WaveOpticsEffectTests effect.Quality = WaveOpticsQuality.Standard; effect.ApertureShape = WaveOpticsApertureShape.Circular; effect.BladeCount = 6; + effect.Linear = true; + effect.Dither = true; Assert.Empty(changed); } @@ -135,7 +150,7 @@ public sealed class WaveOpticsEffectTests } [Fact] - public void TheThirteenNumericParametersReceiveTheAnimationParameters() + public void TheFifteenNumericParametersReceiveTheAnimationParameters() { var effect = new WaveOpticsEffect(); @@ -174,6 +189,10 @@ public sealed class WaveOpticsEffectTests [Theory] [InlineData(nameof(WaveOpticsEffect.Amount), nameof(Texts.OutputGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)] [InlineData(nameof(WaveOpticsEffect.Gain), nameof(Texts.OutputGroup), nameof(Texts.Gain), nameof(Texts.GainDescription), 1)] + [InlineData(nameof(WaveOpticsEffect.Linear), nameof(Texts.OutputGroup), nameof(Texts.Linear), nameof(Texts.LinearDescription), 2)] + [InlineData(nameof(WaveOpticsEffect.HighlightThreshold), nameof(Texts.OutputGroup), nameof(Texts.HighlightThreshold), nameof(Texts.HighlightThresholdDescription), 3)] + [InlineData(nameof(WaveOpticsEffect.HighlightBoost), nameof(Texts.OutputGroup), nameof(Texts.HighlightBoost), nameof(Texts.HighlightBoostDescription), 4)] + [InlineData(nameof(WaveOpticsEffect.Dither), nameof(Texts.OutputGroup), nameof(Texts.Dither), nameof(Texts.DitherDescription), 5)] [InlineData(nameof(WaveOpticsEffect.Wavelength), nameof(Texts.OpticsGroup), nameof(Texts.Wavelength), nameof(Texts.WavelengthDescription), 10)] [InlineData(nameof(WaveOpticsEffect.FNumber), nameof(Texts.OpticsGroup), nameof(Texts.FNumber), nameof(Texts.FNumberDescription), 11)] [InlineData(nameof(WaveOpticsEffect.PixelPitch), nameof(Texts.OpticsGroup), nameof(Texts.PixelPitch), nameof(Texts.PixelPitchDescription), 12)] @@ -214,6 +233,8 @@ public sealed class WaveOpticsEffectTests [InlineData(nameof(WaveOpticsEffect.ComaHorizontal), "F3", "waves", -3d, 3d)] [InlineData(nameof(WaveOpticsEffect.ComaVertical), "F3", "waves", -3d, 3d)] [InlineData(nameof(WaveOpticsEffect.Spherical), "F3", "waves", -3d, 3d)] + [InlineData(nameof(WaveOpticsEffect.HighlightThreshold), "F1", "%", 0d, 100d)] + [InlineData(nameof(WaveOpticsEffect.HighlightBoost), "F1", "x", 1d, 100d)] public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum) { var slider = Attribute(property); @@ -241,6 +262,15 @@ public sealed class WaveOpticsEffectTests Assert.Equal(defaultValue, Attribute(property).Value); } + [Theory] + [InlineData(nameof(WaveOpticsEffect.Linear))] + [InlineData(nameof(WaveOpticsEffect.Dither))] + public void TheLightSwitchesAreEditedWithToggleSliders(string property) + { + Assert.NotNull(Property(property).GetCustomAttribute()); + Assert.Equal(typeof(bool), Property(property).PropertyType); + } + [Fact] public void TheQualityAndTheApertureShapeAreChosenFromCombos() { @@ -267,8 +297,8 @@ public sealed class WaveOpticsEffectTests [Fact] public void EverySettingSurvivesAProjectRoundTrip() { - var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9 }; - var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d }; + var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9, Linear = true, Dither = true }; + var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d, 80d, 12d }; foreach (var (animation, value) in Animations(effect).Zip(values)) animation.Values[0].Value = value; @@ -279,6 +309,8 @@ public sealed class WaveOpticsEffectTests Assert.Equal(WaveOpticsQuality.High, clone.Quality); Assert.Equal(WaveOpticsApertureShape.RegularPolygon, clone.ApertureShape); Assert.Equal(9, clone.BladeCount); + Assert.True(clone.Linear); + Assert.True(clone.Dither); Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps))); } @@ -294,6 +326,10 @@ public sealed class WaveOpticsEffectTests Assert.Equal(WaveOpticsApertureShape.RegularPolygon, effect.ApertureShape); Assert.Equal(9, effect.BladeCount); Assert.Equal(1.5d, effect.Defocus.GetValue(0, 1, EffectDescriptions.Fps)); + Assert.False(effect.Linear); + Assert.False(effect.Dither); + Assert.Equal(95d, effect.HighlightThreshold.GetValue(0, 1, EffectDescriptions.Fps)); + Assert.Equal(1d, effect.HighlightBoost.GetValue(0, 1, EffectDescriptions.Fps)); } [Fact] diff --git a/WaveOptics.Tests/WaveOpticsLightTests.cs b/WaveOptics.Tests/WaveOpticsLightTests.cs new file mode 100644 index 0000000..e5756c7 --- /dev/null +++ b/WaveOptics.Tests/WaveOpticsLightTests.cs @@ -0,0 +1,250 @@ +using ComputeWeave; +using System.Runtime.InteropServices; +using SpectralConvolution; +using WaveOptics.Effects; +using WaveOptics.Rendering; + +namespace WaveOptics.Tests; + +[Collection("Direct3D12")] +public sealed class WaveOpticsLightTests +{ + const int Black = unchecked((int)0xFF000000); + const int White = unchecked((int)0xFFFFFFFF); + + static WaveOpticsPipeline.Parameters Parameters(LightOptions light = default, float gain = 1f, float defocus = 0f, int kernelRadius = 15) + => new(gain, new WaveOpticsPipeline.PsfParameters( + WaveOpticsQuality.Standard, kernelRadius, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f), light); + + static int[] Checkerboard(int width, int height) + { + var pixels = new int[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + pixels[y * width + x] = (x + y & 1) == 0 ? White : Black; + } + + return pixels; + } + + static int[] BrightPoint(int width, int height) + { + var pixels = new int[width * height]; + Array.Fill(pixels, Black); + pixels[(height / 2) * width + width / 2] = White; + return pixels; + } + + static byte[] Bytes(int[] pixels) => MemoryMarshal.AsBytes(pixels.AsSpan()).ToArray(); + + static int GreenAt(int[] pixels, int width, int x, int y) => (pixels[y * width + x] >> 8) & 255; + + static int LitCount(int[] pixels) => pixels.Count(pixel => ((pixel >> 8) & 255) > 0); + + static int[] RenderGpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters) + { + using var pipeline = WaveOpticsPipeline.TryCreate(); + Assert.NotNull(pipeline); + var destination = new int[source.Length]; + pipeline.Process(source, destination, width, height, in parameters); + return destination; + } + + static int[] RenderCpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters) + { + using var pipeline = new WaveOpticsCpuPipeline(3); + var destination = new int[source.Length]; + pipeline.Process(source, destination, width, height, in parameters); + return destination; + } + + [Fact] + public void LinearLightAveragesABlackAndWhiteCheckerboardByLightIntensity() + { + var source = Checkerboard(160, 160); + var plain = Parameters(defocus: 3f, kernelRadius: 40); + var linear = Parameters(new LightOptions(true, false, 0f, 0f), defocus: 3f, kernelRadius: 40); + + foreach (var render in new Func[] + { + (pixels, parameters) => RenderGpu(pixels, 160, 160, in parameters), + (pixels, parameters) => RenderCpu(pixels, 160, 160, in parameters), + }) + { + var gamma = GreenAt(render(source, plain), 160, 80, 80); + var light = GreenAt(render(source, linear), 160, 80, 80); + + Assert.InRange(gamma, 116, 140); + Assert.InRange(light, 176, 200); + } + } + + [Fact] + public void HighlightsSpreadABrightPointFartherOnBothRoutes() + { + var source = BrightPoint(121, 121); + var plain = Parameters(new LightOptions(true, false, 0f, 0f), kernelRadius: 20); + var boosted = Parameters(new LightOptions(true, false, 0.9f, 400f), kernelRadius: 20); + + var gpuPlain = LitCount(RenderGpu(source, 121, 121, in plain)); + var gpuBoosted = LitCount(RenderGpu(source, 121, 121, in boosted)); + var cpuPlain = LitCount(RenderCpu(source, 121, 121, in plain)); + var cpuBoosted = LitCount(RenderCpu(source, 121, 121, in boosted)); + + Assert.True(gpuBoosted > gpuPlain * 2, $"{gpuPlain} {gpuBoosted}"); + Assert.True(cpuBoosted > cpuPlain * 2, $"{cpuPlain} {cpuBoosted}"); + } + + [Theory] + [InlineData(false, true, 0f, 0f)] + [InlineData(true, false, 0f, 0f)] + [InlineData(true, true, 0.8f, 10f)] + public void TheCpuAndTheGpuDrawTheSameLightImageWithinTwoLevels(bool linear, bool dither, float threshold, float boost) + { + var random = new Random(9); + var source = new int[128 * 128]; + for (var index = 0; index < source.Length; index++) + { + if (random.NextDouble() < 0.25) + { + var value = random.Next(40, 256); + source[index] = unchecked((int)(0xFF000000u | (uint)value << 16 | (uint)Math.Max(0, value - random.Next(60)) << 8 | (uint)Math.Max(0, value - random.Next(120)))); + } + else + source[index] = Black; + } + + var parameters = Parameters(new LightOptions(linear, dither, threshold, boost), 1.3f, 0.7f); + + var expected = Bytes(RenderGpu(source, 128, 128, in parameters)); + var actual = Bytes(RenderCpu(source, 128, 128, in parameters)); + + for (var index = 0; index < expected.Length; index++) + Assert.InRange(actual[index] - expected[index], -2, 2); + Assert.Contains(actual, value => value > 0); + } + + [Fact] + public void DitheringChangesTheOutputByAtMostOneLevelAndRepeats() + { + var source = BrightPoint(121, 121); + var plain = Parameters(defocus: 1f); + var dithered = Parameters(new LightOptions(false, true, 0f, 0f), defocus: 1f); + + var rounded = Bytes(RenderCpu(source, 121, 121, in plain)); + var first = Bytes(RenderCpu(source, 121, 121, in dithered)); + var second = Bytes(RenderCpu(source, 121, 121, in dithered)); + + Assert.Equal(first, second); + Assert.NotEqual(rounded, first); + for (var index = 0; index < rounded.Length; index++) + Assert.InRange(first[index] - rounded[index], -1, 1); + } + + [Fact] + public void ChangingOnlyTheDitherDrawsFromTheStoreAndMatchesAFreshConvolution() + { + using var pipeline = new WaveOpticsCpuPipeline(2); + var source = Bytes(BrightPoint(96, 96)); + var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f); + pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in plain); + Assert.True(pipeline.TryGetVisibleBounds(128, 128, in plain, out var rect)); + pipeline.RenderVisible(rect, in plain); + + foreach (var dither in new[] { true, false, true }) + { + var changed = plain with { Light = plain.Light with { Dither = dither } }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in changed)); + var reused = pipeline.RenderVisible(rect, in changed).ToArray(); + using var fresh = new WaveOpticsCpuPipeline(2); + fresh.Simulate(source, 128, 128, 16, 16, 96, 96, in changed); + fresh.TryGetVisibleBounds(128, 128, in changed, out var freshRect); + var expected = fresh.RenderVisible(freshRect, in changed).ToArray(); + + Assert.True(pipeline.HasStore); + Assert.Equal(expected, reused); + } + } + + [Fact] + public void TheConvolutionIsRecomputedOnlyWhenTheLightSettingsAffectTheInput() + { + using var pipeline = new WaveOpticsCpuPipeline(2); + var source = Bytes(BrightPoint(96, 96)); + var parameters = Parameters(); + + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters)); + var dither = parameters with { Light = new LightOptions(false, true, 0.9f, 20f) }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dither)); + var linear = parameters with { Light = new LightOptions(true, false, 0.9f, 20f) }; + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in linear)); + var dithered = linear with { Light = linear.Light with { Dither = true } }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dithered)); + var otherBoost = linear with { Light = linear.Light with { Boost = 40f } }; + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in otherBoost)); + var unusedBoost = otherBoost with { Light = new LightOptions(true, false, 0.9f, 1f) }; + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedBoost)); + var unusedThreshold = unusedBoost with { Light = unusedBoost.Light with { Threshold = 0.5f } }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedThreshold)); + } + + [Fact] + public void TheGpuRedrawsFromTheStoreWhenOnlyTheDitherChanges() + { + using var pipeline = WaveOpticsPipeline.TryCreate(); + Assert.NotNull(pipeline); + var device = ComputeWeave.GraphicsDevice.GetDefault(); + var source = BrightPoint(96, 96); + using var texture = device.AllocateReadWriteTexture2D(96, 96); + texture.CopyFrom(source.Select(pixel => new ComputeWeave.Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray()); + var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f); + + int[] Draw(WaveOpticsPipeline.Parameters parameters, out bool convolved) + { + convolved = pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in parameters); + Assert.True(pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect)); + using var output = device.AllocateReadWriteTexture2D(rect.Width, rect.Height); + pipeline.RenderVisible(texture, output, rect, in parameters); + var pixels = new ComputeWeave.Bgra32[rect.Width * rect.Height]; + output.CopyTo(pixels); + return pixels.Select(pixel => unchecked((int)pixel.PackedValue)).ToArray(); + } + + var first = Draw(plain, out var firstConvolved); + var dithered = plain with { Light = plain.Light with { Dither = true } }; + var second = Draw(dithered, out var secondConvolved); + var third = Draw(plain, out var thirdConvolved); + + Assert.True(firstConvolved); + Assert.False(secondConvolved); + Assert.False(thirdConvolved); + Assert.NotEqual(first, second); + Assert.Equal(first, third); + } + + [Fact] + public void AWarmLightPipelineAllocatesNoManagedMemory() + { + using var pipeline = WaveOpticsPipeline.TryCreate(); + Assert.NotNull(pipeline); + var source = BrightPoint(64, 64); + var destination = new int[source.Length]; + var parameters = Parameters(new LightOptions(true, true, 0.9f, 30f)); + for (var iteration = 0; iteration < 4; iteration++) + pipeline.Process(source, destination, 64, 64, in parameters); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + var minimum = long.MaxValue; + for (var iteration = 0; iteration < 16; iteration++) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + pipeline.Process(source, destination, 64, 64, in parameters); + minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before); + } + + Assert.Equal(0, minimum); + } +} diff --git a/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs b/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs index 3b399d5..12f9a3a 100644 --- a/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs +++ b/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs @@ -83,4 +83,39 @@ public sealed class WaveOpticsRenderTrackerTests Assert.NotEqual(First.SamplingKey, Second.SamplingKey); Assert.Equal(First.SamplingKey, (First with { Psf = Psf with { Defocus = 1f } }).SamplingKey); } + + [Fact] + public void ChangingTheDitherStoresLikeAGainChange() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, false, out _); + + Assert.Equal(WaveOpticsRenderMode.ConvolveAndStore, tracker.Next(First, Rect, 1f, true, out _)); + Assert.True(tracker.HasStore); + Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _)); + Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _)); + } + + [Fact] + public void TheSameDitherWithoutAStoreConvolvesAgain() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, true, out _); + + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, true, out _)); + Assert.False(tracker.HasStore); + } + + [Fact] + public void AnotherLightSettingIsAnotherConvolution() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, out _); + tracker.Next(First, Rect, 1.5f, out _); + var light = First with { Light = new SpectralConvolution.LightOptions(true, false, 0.9f, 10f) }; + + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(light, Rect, 1.5f, out var release)); + Assert.True(release); + Assert.False(tracker.HasStore); + } }