diff --git a/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs b/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs new file mode 100644 index 0000000..3b399d5 --- /dev/null +++ b/WaveOptics.Tests/WaveOpticsRenderTrackerTests.cs @@ -0,0 +1,86 @@ +using WaveOptics.Effects; +using WaveOptics.Rendering; + +namespace WaveOptics.Tests; + +public sealed class WaveOpticsRenderTrackerTests +{ + static readonly WaveOpticsPipeline.PsfParameters Psf = new( + WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f); + + static readonly WaveOpticsConvolutionKey First = new(1, 2, 100, 100, new WaveOpticsPipeline.PixelRect(16, 16, 68, 68), Psf); + + static readonly WaveOpticsConvolutionKey Second = First with { HashSum = 3 }; + + static readonly WaveOpticsPipeline.PixelRect Rect = new(0, 0, 100, 100); + + [Fact] + public void ANewConvolutionIsComputedWithoutAStore() + { + var tracker = new WaveOpticsRenderTracker(); + + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, out var release)); + + Assert.False(release); + Assert.False(tracker.HasStore); + } + + [Fact] + public void TheFirstGainChangeStoresAndLaterOnesDrawFromTheStore() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, out _); + + Assert.Equal(WaveOpticsRenderMode.ConvolveAndStore, tracker.Next(First, Rect, 1.5f, out _)); + Assert.True(tracker.HasStore); + Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 2f, out _)); + Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 2f, out _)); + } + + [Fact] + public void RedrawingTheSameFrameWithoutAStoreConvolvesAgain() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, out _); + + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, out _)); + Assert.False(tracker.HasStore); + } + + [Fact] + public void ANewSourceOrRectangleLetsTheStoreGo() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, out _); + tracker.Next(First, Rect, 2f, out _); + + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(Second, Rect, 2f, out var releasedForSource)); + Assert.True(releasedForSource); + Assert.False(tracker.HasStore); + + tracker.Next(Second, Rect, 3f, out _); + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(Second, Rect with { Width = 96 }, 3f, out var releasedForRect)); + Assert.True(releasedForRect); + } + + [Fact] + public void AResetForgetsTheFrameAndReportsTheStore() + { + var tracker = new WaveOpticsRenderTracker(); + tracker.Next(First, Rect, 1f, out _); + tracker.Next(First, Rect, 2f, out _); + + Assert.True(tracker.Reset()); + Assert.False(tracker.Reset()); + Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 2f, out var release)); + Assert.False(release); + } + + [Fact] + public void TheSamplingKeyComesFromTheSourceHash() + { + Assert.Equal(1UL << 32 | 2UL, First.SamplingKey); + Assert.NotEqual(First.SamplingKey, Second.SamplingKey); + Assert.Equal(First.SamplingKey, (First with { Psf = Psf with { Defocus = 1f } }).SamplingKey); + } +} diff --git a/WaveOptics.Tests/WaveOpticsSourceHashTests.cs b/WaveOptics.Tests/WaveOpticsSourceHashTests.cs new file mode 100644 index 0000000..7d8bbae --- /dev/null +++ b/WaveOptics.Tests/WaveOpticsSourceHashTests.cs @@ -0,0 +1,73 @@ +using System.Runtime.InteropServices; +using ComputeWeave; +using WaveOptics.Effects; +using WaveOptics.Rendering; + +namespace WaveOptics.Tests; + +[Collection("Direct3D12")] +public sealed class WaveOpticsSourceHashTests +{ + static readonly WaveOpticsPipeline.Parameters Defaults = new(1f, new WaveOpticsPipeline.PsfParameters( + WaveOpticsQuality.Draft, 3, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)); + + static int[] RandomPixels(int width, int height, int seed, double litFraction) + { + var random = new Random(seed); + var pixels = new int[width * height]; + for (var index = 0; index < pixels.Length; index++) + { + if (random.NextDouble() < litFraction) + pixels[index] = random.Next(int.MinValue, int.MaxValue) | 1; + } + + return pixels; + } + + [Theory] + [InlineData(37, 21, 0, 0, 0.3)] + [InlineData(64, 48, 16, 12, 0.05)] + [InlineData(19, 33, 4, 8, 1.0)] + public void TheCpuHashMatchesTheGpuHash(int width, int height, int offsetX, int offsetY, double litFraction) + { + using var pipeline = WaveOpticsPipeline.TryCreate(); + Assert.NotNull(pipeline); + var pixels = RandomPixels(width, height, width * height, litFraction); + using var texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D(width, height); + texture.CopyFrom(MemoryMarshal.Cast(pixels.AsSpan())); + var parameters = Defaults; + + pipeline.Simulate(texture, width + offsetX * 2, height + offsetY * 2, offsetX, offsetY, width, height, in parameters); + + var cpu = WaveOpticsSourceHash.Compute(MemoryMarshal.AsBytes(pixels.AsSpan()), offsetX, offsetY, width, height); + Assert.Equal(pipeline.SourceHash, cpu); + } + + [Fact] + public void ATransparentSourceHasNothingToShow() + { + var hash = WaveOpticsSourceHash.Compute(new byte[16 * 16 * 4], 4, 4, 16, 16); + + Assert.Equal(0, hash.LitCount); + Assert.False(hash.TryGetVisibleBounds(24, 24, 3, out _)); + Assert.Equal(WaveOpticsSourceHash.Empty, hash); + } + + [Fact] + public void TheBoundsAreReportedInCanvasCoordinates() + { + var pixels = new int[10 * 8]; + pixels[2 * 10 + 3] = -1; + pixels[5 * 10 + 7] = 1 << 24; + + var hash = WaveOpticsSourceHash.Compute(MemoryMarshal.AsBytes(pixels.AsSpan()), 20, 30, 10, 8); + + Assert.Equal((2, 23, 32, 27, 35), (hash.LitCount, hash.MinimumX, hash.MinimumY, hash.MaximumX, hash.MaximumY)); + } + + [Fact] + public void AShortSourceIsRejected() + { + Assert.Throws(() => WaveOpticsSourceHash.Compute(new byte[15], 0, 0, 2, 2)); + } +} diff --git a/WaveOptics/Rendering/WaveOpticsPipeline.cs b/WaveOptics/Rendering/WaveOpticsPipeline.cs index 9705360..fda1631 100644 --- a/WaveOptics/Rendering/WaveOpticsPipeline.cs +++ b/WaveOptics/Rendering/WaveOpticsPipeline.cs @@ -14,19 +14,12 @@ internal sealed class WaveOpticsPipeline : IDisposable private readonly ReadBackBuffer _scratchReadBack; private readonly GpuTileConvolver _convolver; private readonly WaveOpticsKernel _kernel = new(); + private readonly WaveOpticsRenderTracker _tracker = new(); private int _uploadedKernelVersion; - private ConvolutionKey? _convolutionKey; - private ConvolutionKey? _renderedKey; - private PixelRect _renderedRect; - private float _renderedGain; - private bool _storeIsValid; + private WaveOpticsConvolutionKey? _convolutionKey; private GpuTileJob _storedJob; private PixelRect _sourceRect; - private int _cachedLitCount; - private int _cachedBoundsMinX; - private int _cachedBoundsMinY; - private int _cachedBoundsMaxX; - private int _cachedBoundsMaxY; + private WaveOpticsSourceHash _sourceHash = WaveOpticsSourceHash.Empty; private int _canvasWidth; private int _canvasHeight; private ReadWriteTexture2D? _packedSource; @@ -151,16 +144,11 @@ internal sealed class WaveOpticsPipeline : IDisposable private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters) { _scratchReadBack.CopyFrom(_scratch); - var hashed = _scratchReadBack.Span; - _cachedLitCount = hashed[WaveOpticsSettings.ScratchLitCount]; - _cachedBoundsMinX = hashed[WaveOpticsSettings.ScratchBoundsMinX]; - _cachedBoundsMinY = hashed[WaveOpticsSettings.ScratchBoundsMinY]; - _cachedBoundsMaxX = hashed[WaveOpticsSettings.ScratchBoundsMaxX]; - _cachedBoundsMaxY = hashed[WaveOpticsSettings.ScratchBoundsMaxY]; + _sourceHash = WaveOpticsSourceHash.FromScratch(_scratchReadBack.Span); - var key = new ConvolutionKey( - hashed[WaveOpticsSettings.ScratchHashSum], - hashed[WaveOpticsSettings.ScratchHashMix], + var key = new WaveOpticsConvolutionKey( + _sourceHash.Sum, + _sourceHash.Mix, _canvasWidth, _canvasHeight, sourceRect, @@ -181,25 +169,10 @@ internal sealed class WaveOpticsPipeline : IDisposable internal bool HasKernel => _kernel.IsValid; + internal WaveOpticsSourceHash SourceHash => _sourceHash; + internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect) - { - rect = default; - if (_cachedLitCount <= 0 || _cachedBoundsMinX > _cachedBoundsMaxX) - return false; - - var radius = parameters.Psf.KernelRadius; - var left = Math.Clamp((_cachedBoundsMinX - radius) & ~3, 0, canvasWidth); - var top = Math.Clamp((_cachedBoundsMinY - radius) & ~3, 0, canvasHeight); - var right = Math.Clamp(_cachedBoundsMaxX + 1 + radius, 0, canvasWidth); - var bottom = Math.Clamp(_cachedBoundsMaxY + 1 + radius, 0, canvasHeight); - var width = Math.Min((right - left + 3) & ~3, canvasWidth - left); - var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top); - if (width <= 0 || height <= 0) - return false; - - rect = new PixelRect(left, top, width, height); - return true; - } + => _sourceHash.TryGetVisibleBounds(canvasWidth, canvasHeight, parameters.Psf.KernelRadius, out rect); internal void RenderVisible( ReadWriteTexture2D source, @@ -208,11 +181,11 @@ internal sealed class WaveOpticsPipeline : IDisposable in Parameters parameters) { var mode = BeginRender(rect, parameters.Gain); - if (mode == RenderMode.Stored) + if (mode == WaveOpticsRenderMode.Stored) _host.RecordStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait(); else { - var job = PrepareConvolution(rect, parameters.Gain, mode == RenderMode.ConvolveAndStore); + var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore); _host.RecordConvolution( source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum, _convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait(); @@ -226,36 +199,25 @@ internal sealed class WaveOpticsPipeline : IDisposable in Parameters parameters) { var mode = BeginRender(rect, parameters.Gain); - if (mode == RenderMode.Stored) + if (mode == WaveOpticsRenderMode.Stored) _host.RecordSharedStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait(); else { - var job = PrepareConvolution(rect, parameters.Gain, mode == RenderMode.ConvolveAndStore); + var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore); _host.RecordSharedConvolution( source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum, _convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait(); } } - private RenderMode BeginRender(PixelRect rect, float gain) + private WaveOpticsRenderMode BeginRender(PixelRect rect, float gain) { if (_convolutionKey is not { } key || !_kernel.IsValid) throw new InvalidOperationException(); - RenderMode mode; - if (_renderedKey != key || _renderedRect != rect) - { - ReleaseStore(); - mode = RenderMode.Convolve; - } - else if (_storeIsValid) - mode = RenderMode.Stored; - else - mode = gain != _renderedGain ? RenderMode.ConvolveAndStore : RenderMode.Convolve; - - _renderedKey = key; - _renderedRect = rect; - _renderedGain = gain; + var mode = _tracker.Next(key, rect, gain, out var releaseStore); + if (releaseStore) + ReleaseStoreBuffer(); return mode; } @@ -270,20 +232,20 @@ internal sealed class WaveOpticsPipeline : IDisposable var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height); var job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, [], store); if (store) - { _storedJob = job; - _storeIsValid = true; - } return job; } - private void ReleaseStore() + private void ResetRendering() + { + if (_tracker.Reset()) + ReleaseStoreBuffer(); + } + + private void ReleaseStoreBuffer() { - if (!_storeIsValid) - return; _convolver.ReleaseStore(); - _storeIsValid = false; _storedJob = default; } @@ -298,8 +260,7 @@ internal sealed class WaveOpticsPipeline : IDisposable if (!_kernel.TryUpdate(parameters.Psf)) throw new InvalidOperationException(); _convolutionKey = null; - _renderedKey = null; - ReleaseStore(); + ResetRendering(); _sourceRect = new PixelRect(0, 0, width, height); var job = PrepareConvolution(_sourceRect, parameters.Gain, false); return _host.RecordConvolution( @@ -312,14 +273,9 @@ internal sealed class WaveOpticsPipeline : IDisposable if (_canvasWidth == canvasWidth && _canvasHeight == canvasHeight) return; - _cachedLitCount = 0; - _cachedBoundsMinX = int.MaxValue; - _cachedBoundsMinY = int.MaxValue; - _cachedBoundsMaxX = int.MinValue; - _cachedBoundsMaxY = int.MinValue; + _sourceHash = WaveOpticsSourceHash.Empty; _convolutionKey = null; - _renderedKey = null; - ReleaseStore(); + ResetRendering(); _canvasWidth = canvasWidth; _canvasHeight = canvasHeight; } @@ -348,8 +304,7 @@ internal sealed class WaveOpticsPipeline : IDisposable _packedWidth = 0; _packedHeight = 0; _convolutionKey = null; - _renderedKey = null; - _storeIsValid = false; + _tracker.Reset(); _canvasWidth = 0; _canvasHeight = 0; _convolver.Dispose(); @@ -357,23 +312,8 @@ internal sealed class WaveOpticsPipeline : IDisposable _scratch.Dispose(); } - private enum RenderMode - { - Convolve, - ConvolveAndStore, - Stored, - } - internal readonly record struct PixelRect(int X, int Y, int Width, int Height); - private readonly record struct ConvolutionKey( - int HashSum, - int HashMix, - int CanvasWidth, - int CanvasHeight, - PixelRect Source, - PsfParameters Psf); - internal readonly record struct PsfParameters( WaveOpticsQuality Quality, int KernelRadius, diff --git a/WaveOptics/Rendering/WaveOpticsRenderTracker.cs b/WaveOptics/Rendering/WaveOpticsRenderTracker.cs new file mode 100644 index 0000000..b0bb807 --- /dev/null +++ b/WaveOptics/Rendering/WaveOpticsRenderTracker.cs @@ -0,0 +1,62 @@ +namespace WaveOptics.Rendering; + +internal readonly record struct WaveOpticsConvolutionKey( + int HashSum, + int HashMix, + int CanvasWidth, + int CanvasHeight, + WaveOpticsPipeline.PixelRect Source, + WaveOpticsPipeline.PsfParameters Psf) +{ + public ulong SamplingKey => (ulong)(uint)HashSum << 32 | (uint)HashMix; +} + +internal enum WaveOpticsRenderMode +{ + Convolve, + ConvolveAndStore, + Stored, +} + +internal sealed class WaveOpticsRenderTracker +{ + private WaveOpticsConvolutionKey? _renderedKey; + private WaveOpticsPipeline.PixelRect _renderedRect; + private float _renderedGain; + + public bool HasStore { get; private set; } + + public WaveOpticsRenderMode Next(in WaveOpticsConvolutionKey key, WaveOpticsPipeline.PixelRect rect, float gain, out bool releaseStore) + { + WaveOpticsRenderMode mode; + releaseStore = false; + if (_renderedKey != key || _renderedRect != rect) + { + releaseStore = HasStore; + HasStore = false; + mode = WaveOpticsRenderMode.Convolve; + } + else if (HasStore) + mode = WaveOpticsRenderMode.Stored; + else if (gain != _renderedGain) + { + HasStore = true; + mode = WaveOpticsRenderMode.ConvolveAndStore; + } + else + mode = WaveOpticsRenderMode.Convolve; + + _renderedKey = key; + _renderedRect = rect; + _renderedGain = gain; + return mode; + } + + public bool Reset() + { + var hadStore = HasStore; + _renderedKey = null; + HasStore = false; + return hadStore; + } +} diff --git a/WaveOptics/Rendering/WaveOpticsSourceHash.cs b/WaveOptics/Rendering/WaveOpticsSourceHash.cs new file mode 100644 index 0000000..14c98cf --- /dev/null +++ b/WaveOptics/Rendering/WaveOpticsSourceHash.cs @@ -0,0 +1,73 @@ +namespace WaveOptics.Rendering; + +internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX, int MinimumY, int MaximumX, int MaximumY, int Sum, int Mix) +{ + public static WaveOpticsSourceHash Empty { get; } = new(0, int.MaxValue, int.MaxValue, int.MinValue, int.MinValue, 0, 0); + + public static WaveOpticsSourceHash FromScratch(ReadOnlySpan scratch) + => new( + scratch[WaveOpticsSettings.ScratchLitCount], + scratch[WaveOpticsSettings.ScratchBoundsMinX], + scratch[WaveOpticsSettings.ScratchBoundsMinY], + scratch[WaveOpticsSettings.ScratchBoundsMaxX], + scratch[WaveOpticsSettings.ScratchBoundsMaxY], + scratch[WaveOpticsSettings.ScratchHashSum], + scratch[WaveOpticsSettings.ScratchHashMix]); + + public static WaveOpticsSourceHash Compute(ReadOnlySpan bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight) + { + if (bgra.Length < (long)sourceWidth * sourceHeight * 4) + throw new ArgumentException(null, nameof(bgra)); + + var count = 0; + var sum = 0; + var mix = 0; + var minimumX = int.MaxValue; + var minimumY = int.MaxValue; + var maximumX = int.MinValue; + var maximumY = int.MinValue; + for (var y = 0; y < sourceHeight; y++) + { + var row = bgra.Slice(y * sourceWidth * 4, sourceWidth * 4); + for (var x = 0; x < sourceWidth; x++) + { + var quantized = (uint)row[x * 4 + 2] << 24 | (uint)row[x * 4 + 1] << 16 | (uint)row[x * 4] << 8 | row[x * 4 + 3]; + if (quantized == 0u) + continue; + + var mixed = unchecked((uint)(y * sourceWidth + x) * 0x9E3779B9u ^ quantized * 0x85EBCA6Bu); + mixed ^= mixed >> 16; + mixed = unchecked(mixed * 0x85EBCA6Bu); + mixed ^= mixed >> 13; + sum = unchecked(sum + (int)mixed); + mix ^= unchecked((int)(mixed * 0xC2B2AE35u)); + count++; + minimumX = Math.Min(minimumX, sourceX + x); + maximumX = Math.Max(maximumX, sourceX + x); + minimumY = Math.Min(minimumY, sourceY + y); + maximumY = Math.Max(maximumY, sourceY + y); + } + } + + return new WaveOpticsSourceHash(count, minimumX, minimumY, maximumX, maximumY, sum, mix); + } + + public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, int radius, out WaveOpticsPipeline.PixelRect rect) + { + rect = default; + if (LitCount <= 0 || MinimumX > MaximumX) + return false; + + var left = Math.Clamp((MinimumX - radius) & ~3, 0, canvasWidth); + var top = Math.Clamp((MinimumY - radius) & ~3, 0, canvasHeight); + var right = Math.Clamp(MaximumX + 1 + radius, 0, canvasWidth); + var bottom = Math.Clamp(MaximumY + 1 + radius, 0, canvasHeight); + var width = Math.Min((right - left + 3) & ~3, canvasWidth - left); + var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top); + if (width <= 0 || height <= 0) + return false; + + rect = new WaveOpticsPipeline.PixelRect(left, top, width, height); + return true; + } +}