diff --git a/WaveOptics.Tests/WaveOpticsCpuPipelineTests.cs b/WaveOptics.Tests/WaveOpticsCpuPipelineTests.cs new file mode 100644 index 0000000..a831c1e --- /dev/null +++ b/WaveOptics.Tests/WaveOpticsCpuPipelineTests.cs @@ -0,0 +1,180 @@ +using System.Runtime.InteropServices; +using WaveOptics.Effects; +using WaveOptics.Rendering; + +namespace WaveOptics.Tests; + +[Collection("Direct3D12")] +public sealed class WaveOpticsCpuPipelineTests +{ + const int Opaque = unchecked((int)0xFFC0C0C0); + + static WaveOpticsPipeline.Parameters Parameters(float gain = 1f, float defocus = 0f) + => new(gain, new WaveOpticsPipeline.PsfParameters( + WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f)); + + static int[] Square(int width, int height, int left, int top, int size) + { + var pixels = new int[width * height]; + for (var y = top; y < top + size; y++) + { + for (var x = left; x < left + size; x++) + pixels[y * width + x] = Opaque; + } + + return pixels; + } + + static byte[] Bytes(int[] pixels) => MemoryMarshal.AsBytes(pixels.AsSpan()).ToArray(); + + static byte[] RenderFrame(WaveOpticsCpuPipeline pipeline, byte[] source, int width, int height, int margin, in WaveOpticsPipeline.Parameters parameters, out WaveOpticsPipeline.PixelRect rect) + { + pipeline.Simulate(source, width + margin * 2, height + margin * 2, margin, margin, width, height, in parameters); + Assert.True(pipeline.TryGetVisibleBounds(width + margin * 2, height + margin * 2, in parameters, out rect)); + return pipeline.RenderVisible(rect, in parameters).ToArray(); + } + + [Fact] + public void TheCpuAndTheGpuDrawTheSameImageWithinTwoLevels() + { + using var cpu = new WaveOpticsCpuPipeline(3); + using var gpu = WaveOpticsPipeline.TryCreate(); + Assert.NotNull(gpu); + var source = Square(128, 128, 40, 44, 40); + var parameters = Parameters(defocus: 0.7f); + var expected = new int[source.Length]; + var actual = new int[source.Length]; + + gpu.Process(source, expected, 128, 128, in parameters); + cpu.Process(source, actual, 128, 128, in parameters); + + var expectedBytes = MemoryMarshal.AsBytes(expected.AsSpan()); + var actualBytes = MemoryMarshal.AsBytes(actual.AsSpan()); + for (var index = 0; index < expectedBytes.Length; index++) + Assert.InRange(actualBytes[index] - expectedBytes[index], -2, 2); + Assert.Contains(actualBytes.ToArray(), value => value > 0); + } + + [Fact] + public void TheImageDoesNotDependOnTheNumberOfThreads() + { + using var single = new WaveOpticsCpuPipeline(1); + using var several = new WaveOpticsCpuPipeline(5); + var source = Bytes(Square(150, 120, 30, 20, 70)); + var parameters = Parameters(gain: 1.5f, defocus: 1f); + + var first = RenderFrame(single, source, 150, 120, 16, in parameters, out _); + var second = RenderFrame(several, source, 150, 120, 16, in parameters, out _); + + Assert.Equal(first, second); + } + + [Fact] + public void TheConvolutionIsRecomputedOnlyWhenTheSourceOrTheOpticsChange() + { + using var pipeline = new WaveOpticsCpuPipeline(2); + var source = Bytes(Square(96, 96, 32, 32, 32)); + var parameters = Parameters(); + + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters)); + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters)); + var gainChanged = parameters with { Gain = 2f }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in gainChanged)); + var bladesChanged = parameters with { Psf = parameters.Psf with { BladeCount = 9 } }; + Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in bladesChanged)); + var opticsChanged = parameters with { Psf = parameters.Psf with { Defocus = 0.5f } }; + Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in opticsChanged)); + var moved = Bytes(Square(96, 96, 31, 32, 32)); + Assert.True(pipeline.Simulate(moved, 128, 128, 16, 16, 96, 96, in opticsChanged)); + } + + [Fact] + public void ChangingOnlyTheGainDrawsTheSameImageAsAFreshConvolution() + { + using var pipeline = new WaveOpticsCpuPipeline(2); + var source = Bytes(Square(96, 96, 30, 28, 36)); + var first = Parameters(defocus: 0.5f); + RenderFrame(pipeline, source, 96, 96, 16, in first, out var rect); + + foreach (var gain in new[] { 2.5f, 0.75f, 1f }) + { + var changed = first with { Gain = gain }; + 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); + var expected = RenderFrame(fresh, source, 96, 96, 16, in changed, out _); + + Assert.True(pipeline.HasStore); + Assert.Equal(expected, reused); + } + } + + [Fact] + public void ANewSourceLetsTheStoreGo() + { + using var pipeline = new WaveOpticsCpuPipeline(2); + var source = Bytes(Square(96, 96, 30, 28, 36)); + var parameters = Parameters(); + RenderFrame(pipeline, source, 96, 96, 16, in parameters, out var rect); + var brighter = parameters with { Gain = 2f }; + pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in brighter); + pipeline.RenderVisible(rect, in brighter); + Assert.True(pipeline.HasStore); + + RenderFrame(pipeline, Bytes(Square(96, 96, 20, 28, 36)), 96, 96, 16, in brighter, out _); + + Assert.False(pipeline.HasStore); + } + + [Fact] + public void NothingIsVisibleForATransparentSource() + { + using var pipeline = new WaveOpticsCpuPipeline(1); + var parameters = Parameters(); + + Assert.False(pipeline.Simulate(new byte[64 * 64 * 4], 96, 96, 16, 16, 64, 64, in parameters)); + Assert.False(pipeline.TryGetVisibleBounds(96, 96, in parameters, out _)); + } + + [Fact] + public void AClosedApertureLeavesNoKernel() + { + using var pipeline = new WaveOpticsCpuPipeline(1); + var source = Bytes(Square(64, 64, 20, 20, 20)); + var open = Parameters(); + var closed = open with { Psf = open.Psf with { Quality = WaveOpticsQuality.Draft, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 4, BladeRotation = -357.5f, Obstruction = 0.95f } }; + + Assert.False(pipeline.Simulate(source, 96, 96, 16, 16, 64, 64, in closed)); + Assert.False(pipeline.HasKernel); + } + + [Fact] + public void AWarmFrameAllocatesNothingOnTheCallingThread() + { + using var pipeline = new WaveOpticsCpuPipeline(3); + var sources = new[] { Bytes(Square(96, 96, 30, 28, 36)), Bytes(Square(96, 96, 31, 28, 36)) }; + var parameters = Parameters(); + for (var warmUp = 0; warmUp < 4; warmUp++) + RenderFrame(pipeline, sources[warmUp % 2], 96, 96, 16, in parameters, out _); + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var frame = 0; frame < 8; frame++) + { + pipeline.Simulate(sources[frame % 2], 128, 128, 16, 16, 96, 96, in parameters); + pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect); + pipeline.RenderVisible(rect, in parameters); + } + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(0L, allocated); + } + + [Fact] + public void RenderingBeforeAConvolutionIsRejected() + { + using var pipeline = new WaveOpticsCpuPipeline(1); + var parameters = Parameters(); + + Assert.Throws(() => pipeline.RenderVisible(new WaveOpticsPipeline.PixelRect(0, 0, 4, 4), in parameters)); + } +} diff --git a/WaveOptics/Rendering/WaveOpticsCpuPipeline.cs b/WaveOptics/Rendering/WaveOpticsCpuPipeline.cs new file mode 100644 index 0000000..0042df6 --- /dev/null +++ b/WaveOptics/Rendering/WaveOpticsCpuPipeline.cs @@ -0,0 +1,148 @@ +using System.Runtime.InteropServices; +using SpectralConvolution; + +namespace WaveOptics.Rendering; + +internal sealed class WaveOpticsCpuPipeline : IDisposable +{ + private const int Channels = 4; + + private readonly CpuTileConvolver _convolver; + private readonly WaveOpticsKernel _kernel = new(); + private readonly WaveOpticsRenderTracker _tracker = new(); + private WaveOpticsConvolutionKey? _convolutionKey; + private WaveOpticsSourceHash _sourceHash = WaveOpticsSourceHash.Empty; + private WaveOpticsPipeline.PixelRect _sourceRect; + private int _canvasWidth; + private int _canvasHeight; + private byte[] _source = []; + private byte[] _packed = []; + private byte[] _output = []; + private float[] _store = []; + + public WaveOpticsCpuPipeline() + : this(Environment.ProcessorCount) + { + } + + public WaveOpticsCpuPipeline(int threads) + { + _convolver = new CpuTileConvolver(threads); + } + + public bool HasKernel => _kernel.IsValid; + + public bool HasStore => _tracker.HasStore; + + public WaveOpticsSourceHash SourceHash => _sourceHash; + + public void Process(ReadOnlySpan source, Span destination, int width, int height, in WaveOpticsPipeline.Parameters parameters) + { + var length = checked(width * height * Channels); + if (!_kernel.TryUpdate(parameters.Psf)) + throw new InvalidOperationException(); + if (_packed.Length < length) + _packed = new byte[length]; + if (_output.Length < length) + _output = new byte[length]; + MemoryMarshal.AsBytes(source[..(width * height)]).CopyTo(_packed); + var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, 0, 0, width, height); + _convolver.Convolve(_packed, 0, 0, width, height, _kernel.Spectrum, plan, _output, parameters.Gain, null); + _output.AsSpan(0, length).CopyTo(MemoryMarshal.AsBytes(destination[..(width * height)])); + } + + public bool Simulate( + byte[] source, + int canvasWidth, + int canvasHeight, + int sourceOffsetX, + int sourceOffsetY, + int sourceWidth, + int sourceHeight, + in WaveOpticsPipeline.Parameters parameters) + { + ArgumentNullException.ThrowIfNull(source); + if (_canvasWidth != canvasWidth || _canvasHeight != canvasHeight) + { + _canvasWidth = canvasWidth; + _canvasHeight = canvasHeight; + _convolutionKey = null; + if (_tracker.Reset()) + _store = []; + } + + _source = source; + _sourceHash = WaveOpticsSourceHash.Compute(source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight); + var sourceRect = new WaveOpticsPipeline.PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight); + var key = new WaveOpticsConvolutionKey(_sourceHash.Sum, _sourceHash.Mix, canvasWidth, canvasHeight, sourceRect, WaveOpticsKernel.KeyOf(parameters.Psf)); + if (_convolutionKey == key || !TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out _)) + return false; + + if (!_kernel.TryUpdate(parameters.Psf)) + { + _convolutionKey = null; + return false; + } + + _convolutionKey = key; + _sourceRect = sourceRect; + return true; + } + + public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in WaveOpticsPipeline.Parameters parameters, out WaveOpticsPipeline.PixelRect rect) + => _sourceHash.TryGetVisibleBounds(canvasWidth, canvasHeight, parameters.Psf.KernelRadius, out rect); + + public ReadOnlySpan RenderVisible(WaveOpticsPipeline.PixelRect rect, in WaveOpticsPipeline.Parameters parameters) + { + if (_convolutionKey is not { } key || !_kernel.IsValid) + throw new InvalidOperationException(); + + var mode = _tracker.Next(key, rect, parameters.Gain, out var releaseStore); + if (releaseStore) + _store = []; + + var length = checked(rect.Width * rect.Height * Channels); + if (_output.Length < length) + _output = new byte[length]; + + if (mode == WaveOpticsRenderMode.Stored) + { + RenderStored(_store.AsSpan(0, length), parameters.Gain, _output.AsSpan(0, length)); + return _output.AsSpan(0, length); + } + + float[]? store = null; + if (mode == WaveOpticsRenderMode.ConvolveAndStore) + { + if (_store.Length < length) + _store = new float[length]; + store = _store; + } + + var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height); + _convolver.Convolve(_source, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, _kernel.Spectrum, plan, _output, parameters.Gain, store); + return _output.AsSpan(0, length); + } + + public void Dispose() + { + _convolver.Dispose(); + _source = []; + _packed = []; + _output = []; + _store = []; + _convolutionKey = null; + _tracker.Reset(); + } + + private static void RenderStored(ReadOnlySpan store, float gain, Span output) + { + for (var index = 0; index < store.Length; index += Channels) + { + output[index] = CpuTileConvolver.ToUnorm(store[index + 2] * gain); + output[index + 1] = CpuTileConvolver.ToUnorm(store[index + 1] * gain); + output[index + 2] = CpuTileConvolver.ToUnorm(store[index] * gain); + output[index + 3] = CpuTileConvolver.ToUnorm(store[index + 3] * gain); + } + } +}