From 0db60b534eb6d0c78ee7918d3b492722667e1bf8 Mon Sep 17 00:00:00 2001 From: routersys Date: Tue, 22 Sep 2026 12:11:10 +0900 Subject: [PATCH] =?UTF-8?q?=E7=9B=B8=E4=BA=92=E9=81=8B=E7=94=A8=E3=82=92?= =?UTF-8?q?=E5=A4=96=E9=83=A8=E6=8F=90=E4=BE=9B=E8=80=85=E3=81=A8=E5=85=B1?= =?UTF-8?q?=E6=9C=89=E3=83=86=E3=82=AF=E3=82=B9=E3=83=81=E3=83=A3=E9=9B=86?= =?UTF-8?q?=E5=90=88=E3=81=B8=E7=A7=BB=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../InkDispersionEffectTests.cs | 58 ++- InkDispersion/InkDispersionEffectProcessor.cs | 185 +++++++--- InkDispersion/InkDispersionGpuInterop.cs | 344 +++--------------- InkDispersion/InkDispersionPipeline.cs | 41 ++- InkDispersion/InkDispersionPipelineHost.cs | 40 ++ 5 files changed, 302 insertions(+), 366 deletions(-) diff --git a/InkDispersion.Tests/InkDispersionEffectTests.cs b/InkDispersion.Tests/InkDispersionEffectTests.cs index ca379a3..4ade535 100644 --- a/InkDispersion.Tests/InkDispersionEffectTests.cs +++ b/InkDispersion.Tests/InkDispersionEffectTests.cs @@ -548,14 +548,17 @@ public sealed class InkDispersionEffectTests { using var devices = new GraphicsDevices(); using var graphicsContext = devices.CreateContext(); - using var interop = InkDispersionGpuInterop.TryCreate(graphicsContext); - if (interop is null) + using var scheduler = ComputeExternalQueueScheduler.Create(); + using var provider = InkDispersionInteropProvider.TryCreate(graphicsContext, scheduler, out var interopDevice); + if (provider is null || interopDevice is null) { Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable."); return; } - using var pipeline = InkDispersionPipeline.TryCreate(interop.Device); + using var domain = interopDevice.RegisterExternalDomain(provider); + using var resourceSet = InkDispersionResourceSet.Create(interopDevice, domain); + using var pipeline = InkDispersionPipeline.TryCreate(interopDevice); Assert.NotNull(pipeline); const int width = 96; @@ -578,39 +581,56 @@ public sealed class InkDispersionEffectTests handle.Free(); } - Assert.True(interop.EnsureResources(width, height)); - var bounds = new RawRectF(0f, 0f, width, height); + Assert.True(resourceSet.TryEnsureSource(width, height, out _)); var parameters = CreateParameters(); + var renderContext = provider.RenderContext; + InkDispersionPipeline.PixelRect visible = default; for (var iteration = 0; iteration < 2; iteration++) { - interop.RenderInput(inputBitmap, bounds); - interop.BeginCompute(); - try + using (var borrow = resourceSet.BeginSourceExternalOperation()) { - pipeline!.Process(interop.SourceTexture, interop.OutputTexture, width, height, in parameters); + var previousTarget = renderContext.Target; + using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap()); + renderContext.Target = sourceBitmap; + renderContext.BeginDraw(); + renderContext.Clear(null); + renderContext.DrawImage( + inputBitmap, + new System.Numerics.Vector2(0f, 0f), + null, + InterpolationMode.NearestNeighbor, + CompositeMode.SourceCopy); + renderContext.EndDraw(); + renderContext.Target = previousTarget; } - finally - { - interop.EndCompute(); - } - } - interop.WaitForIdle(); + pipeline!.Simulate( + resourceSet.GetSourceComputeBinding(), width, height, 0, 0, width, height, in parameters); + Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out visible)); + Assert.True(resourceSet.TryEnsureOutput(visible.Width, visible.Height, out _)); + pipeline.RenderVisible( + resourceSet.GetOutputComputeBinding(), width, height, visible, in parameters); + } + + using var outputLease = resourceSet.AcquireOutputExternalViewLease(); + Assert.Equal(visible.Width, outputLease.Width); + Assert.Equal(visible.Height, outputLease.Height); using var staging = graphicsContext.DeviceContext.CreateBitmap( - new SizeI(width, height), + new SizeI(visible.Width, visible.Height), new BitmapProperties1( new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied), 96f, 96f, BitmapOptions.CpuRead | BitmapOptions.CannotDraw)); - staging.CopyFromBitmap(interop.OutputBitmap); + using var outputBitmap = new ID2D1Bitmap1(outputLease.DangerousGetView().AddRefBitmap()); + staging.CopyFromBitmap(outputBitmap); var mapped = staging.Map(MapOptions.Read); try { var lit = 0; - for (var y = 0; y < height; y++) + for (var y = 0; y < visible.Height; y++) { - for (var x = 0; x < width; x++) + for (var x = 0; x < visible.Width; x++) { var actual = Marshal.ReadInt32(mapped.Bits + (nint)(y * mapped.Pitch + x * sizeof(int))); var alpha = (actual >> 24) & 255; diff --git a/InkDispersion/InkDispersionEffectProcessor.cs b/InkDispersion/InkDispersionEffectProcessor.cs index bf5dd7f..728ff5d 100644 --- a/InkDispersion/InkDispersionEffectProcessor.cs +++ b/InkDispersion/InkDispersionEffectProcessor.cs @@ -1,4 +1,5 @@ using System.Numerics; +using ComputeWeave; using Vortice.Direct2D1; using Vortice.Direct2D1.Effects; using YukkuriMovieMaker.Commons; @@ -11,7 +12,11 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase { private readonly IGraphicsDevicesAndContext _devices; private readonly InkDispersionEffect _item; - private InkDispersionGpuInterop? _interop; + private ComputeExternalQueueScheduler? _scheduler; + private InkDispersionInteropProvider? _interopProvider; + private ComputeInteropDomain? _interopDomain; + private InkDispersionResourceSet? _resourceSet; + private ExternalTextureLease? _outputLease; private InkDispersionPipeline? _pipeline; private InkDispersionCustomEffect? _effect; private Crop? _outputCrop; @@ -37,7 +42,7 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase public override DrawDescription Update(EffectDescription effectDescription) { - if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null) + if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null) return effectDescription.DrawDescription; var frame = effectDescription.ItemPosition.Frame; @@ -106,8 +111,14 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase var itemWidth = (int)widthValue; var itemHeight = (int)heightValue; - _interop.EnsureSource(itemWidth, itemHeight); - _interop.RenderInput(input, new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight)); + if (!EnsureSource(itemWidth, itemHeight)) + { + _effect.Amount = 0f; + _isFirst = true; + return effectDescription.DrawDescription; + } + + RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight)); var pipelineParameters = new InkDispersionPipeline.Parameters( parameters.Quality, @@ -125,24 +136,15 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase parameters.Color.B / 255f, Math.Max(parameters.Seed, 0)); - bool structureChanged; - _interop.BeginCompute(); - try - { - structureChanged = _pipeline.Simulate( - _interop.SourceTexture, - canvasWidth, - canvasHeight, - margin, - margin, - itemWidth, - itemHeight, - in pipelineParameters); - } - finally - { - _interop.EndCompute(); - } + var structureChanged = _pipeline.Simulate( + _resourceSet.GetSourceComputeBinding(), + canvasWidth, + canvasHeight, + margin, + margin, + itemWidth, + itemHeight, + in pipelineParameters); if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in pipelineParameters, out var rect)) { @@ -153,9 +155,16 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase return effectDescription.DrawDescription; } - if (!_interop.OutputCovers(rect.Width, rect.Height)) + if (!OutputCovers(rect.Width, rect.Height)) _outputCrop.SetInput(0, null, true); - var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height); + if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged)) + { + _effect.Amount = 0f; + _parameters = parameters; + _isFirst = true; + _hasRenderState = false; + return effectDescription.DrawDescription; + } var renderState = new RenderState( pipelineParameters.Spread, pipelineParameters.Density, @@ -166,27 +175,22 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase rect); if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState) { - _interop.BeginCompute(); - try - { - _pipeline.RenderVisible( - _interop.OutputTexture, - canvasWidth, - canvasHeight, - rect, - in pipelineParameters); - } - finally - { - _interop.EndCompute(); - } + _pipeline.RenderVisible( + _resourceSet.GetOutputComputeBinding(), + canvasWidth, + canvasHeight, + rect, + in pipelineParameters); _renderState = renderState; _hasRenderState = true; } + _outputLease ??= _resourceSet.AcquireOutputExternalViewLease(); + if (outputChanged || !_hasOutput) { - _outputCrop.SetInput(0, _interop.OutputBitmap, true); + using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap()); + _outputCrop.SetInput(0, outputBitmap, true); _effect.SetInput(1, _outputTransformOutput, true); } var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height); @@ -209,15 +213,92 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase return effectDescription.DrawDescription; } + private bool EnsureSource(int width, int height) + { + return _resourceSet!.TryEnsureSource(width, height, out _); + } + + private bool OutputCovers(int width, int height) + => _outputLease is { IsDisposed: false } lease && + lease.Width >= width && + lease.Height >= height; + + private bool EnsureOutput(int width, int height, out bool changed) + { + changed = false; + if (OutputCovers(width, height)) + return true; + + _outputLease?.Dispose(); + _outputLease = null; + return _resourceSet!.TryEnsureOutput(width, height, out changed); + } + + private void RenderInput(Vortice.RawRectF bounds) + { + var renderContext = _interopProvider!.RenderContext; + using var borrow = _resourceSet!.BeginSourceExternalOperation(); + var previousTarget = renderContext.Target; + using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap()); + renderContext.Target = sourceBitmap; + renderContext.BeginDraw(); + renderContext.Clear(null); + renderContext.DrawImage( + input, + new Vector2(-bounds.Left, -bounds.Top), + null, + InterpolationMode.NearestNeighbor, + CompositeMode.SourceCopy); + renderContext.EndDraw(); + renderContext.Target = previousTarget; + } + + private void ReleaseInterop() + { + _outputLease?.Dispose(); + _outputLease = null; + _pipeline?.Dispose(); + _pipeline = null; + _resourceSet?.Dispose(); + _resourceSet?.WaitForDisposal(); + _resourceSet = null; + _interopDomain?.Dispose(); + _interopDomain?.WaitForDisposal(); + _interopDomain = null; + _interopProvider?.Dispose(); + _interopProvider = null; + _scheduler?.Dispose(); + _scheduler = null; + } + protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) { - var interop = InkDispersionGpuInterop.TryCreate(devices); - if (interop is null) - return null; - var pipeline = InkDispersionPipeline.TryCreate(interop.Device); - if (pipeline is null) + var scheduler = ComputeExternalQueueScheduler.Create(); + var interopProvider = InkDispersionInteropProvider.TryCreate(devices, scheduler, out var interopDevice); + if (interopProvider is null || interopDevice is null) { - interop.Dispose(); + scheduler.Dispose(); + return null; + } + + _scheduler = scheduler; + + try + { + _interopProvider = interopProvider; + _interopDomain = interopDevice.RegisterExternalDomain(interopProvider); + _resourceSet = InkDispersionResourceSet.Create(interopDevice, _interopDomain); + _pipeline = InkDispersionPipeline.TryCreate(interopDevice); + } + catch + { + ReleaseInterop(); + throw; + } + + if (_pipeline is null) + { + ReleaseInterop(); return null; } @@ -233,8 +314,7 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase if (!effect.IsEnabled) { effect.Dispose(); - pipeline.Dispose(); - interop.Dispose(); + ReleaseInterop(); return null; } outputCrop = new Crop(devices.DeviceContext); @@ -246,8 +326,6 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase outputTransform.SetInput(0, outputCropOutput, true); outputTransformOutput = outputTransform.Output; output = effect.Output; - _interop = interop; - _pipeline = pipeline; _effect = effect; _outputCrop = outputCrop; _outputCropOutput = outputCropOutput; @@ -269,8 +347,7 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase outputCropOutput?.Dispose(); outputCrop?.Dispose(); effect?.Dispose(); - pipeline.Dispose(); - interop.Dispose(); + ReleaseInterop(); throw; } } @@ -301,11 +378,7 @@ internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase if (disposing) { ClearEffectChain(); - _interop?.WaitForIdle(); - _pipeline?.Dispose(); - _pipeline = null; - _interop?.Dispose(); - _interop = null; + ReleaseInterop(); } } finally diff --git a/InkDispersion/InkDispersionGpuInterop.cs b/InkDispersion/InkDispersionGpuInterop.cs index 4de8c29..6c6a825 100644 --- a/InkDispersion/InkDispersionGpuInterop.cs +++ b/InkDispersion/InkDispersionGpuInterop.cs @@ -1,323 +1,89 @@ -using System.Runtime.InteropServices; using ComputeWeave; -using ComputeWeave.Interop; -using Vortice; using Vortice.Direct2D1; using Vortice.Direct3D11; -using Vortice.DXGI; using YukkuriMovieMaker.Commons; -using PixelFormat = Vortice.DCommon.PixelFormat; namespace InkDispersion; -internal sealed class InkDispersionGpuInterop : IDisposable +internal sealed class InkDispersionInteropProvider : ComputeExternalDirect3D11Provider { - private static readonly Guid D3D12FenceGuid = new("0a753dcf-c4d8-4b91-adf6-be5a60d95a76"); - - private readonly GraphicsDevice _device; - private readonly ID3D11Device1 _d3dDevice; - private readonly ID3D11DeviceContext4 _d3dContext; - private readonly ID3D11Fence _fence; private readonly ID2D1DeviceContext6 _renderContext; - private nint _d3d12Fence; - private ReadWriteTexture2D? _sourceTexture; - private ReadWriteTexture2D? _outputTexture; - private ID3D11Texture2D? _sourceD3D11Texture; - private ID3D11Texture2D? _outputD3D11Texture; - private ID2D1Bitmap1? _sourceBitmap; - private ID2D1Bitmap1? _outputBitmap; - private int _sourceWidth; - private int _sourceHeight; - private int _outputWidth; - private int _outputHeight; - private ulong _fenceValue; - private bool _computeActive; - private bool _disposed; - private InkDispersionGpuInterop( - GraphicsDevice device, - ID3D11Device1 d3dDevice, - ID3D11DeviceContext4 d3dContext, - ID3D11Fence fence, + private InkDispersionInteropProvider( + ID3D11Device1 device, + ID3D11DeviceContext4 context, ID2D1DeviceContext6 renderContext, - nint d3d12Fence) + ComputeExternalQueueScheduler scheduler) + : base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler) { - _device = device; - _d3dDevice = d3dDevice; - _d3dContext = d3dContext; - _fence = fence; _renderContext = renderContext; - _d3d12Fence = d3d12Fence; } - public GraphicsDevice Device => _device; + public ID2D1DeviceContext6 RenderContext => _renderContext; - public ReadWriteTexture2D SourceTexture => _sourceTexture!; - - public ReadWriteTexture2D OutputTexture => _outputTexture!; - - public ID2D1Bitmap1 OutputBitmap => _outputBitmap!; - - public bool SourceMatches(int width, int height) - => _sourceTexture is not null && _sourceWidth == width && _sourceHeight == height; - - public bool OutputCovers(int width, int height) - => _outputTexture is not null && _outputWidth >= width && _outputHeight >= height; - - public static unsafe InkDispersionGpuInterop? TryCreate(IGraphicsDevicesAndContext devices) + public static InkDispersionInteropProvider? TryCreate( + IGraphicsDevicesAndContext devices, + ComputeExternalQueueScheduler scheduler, + out GraphicsDevice? graphicsDevice) { - ID3D11Device1? d3dDevice = null; - ID3D11DeviceContext4? d3dContext = null; - ID3D11Fence? fence = null; + ArgumentNullException.ThrowIfNull(scheduler); + + graphicsDevice = null; + + ID3D11Device1? device = null; + ID3D11DeviceContext4? context = null; ID2D1DeviceContext6? renderContext = null; - nint d3d12Fence = 0; - nint fenceHandle = 0; try { - var device = GetMatchingDevice(devices); - d3dDevice = devices.D3D.Device.QueryInterface(); - d3dContext = devices.D3D.DeviceContext.QueryInterface(); - using var d3dDevice5 = devices.D3D.Device.QueryInterface(); - var fenceGuid = D3D12FenceGuid; - InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle); - fence = d3dDevice5.OpenSharedFence(fenceHandle); + if (!GraphicsDevice.TryGetDevice(new ExternalAdapterIdentity(devices.DXGI.Adapter.Description.Luid), out graphicsDevice)) + return null; + + device = devices.D3D.Device.QueryInterface(); + context = devices.D3D.DeviceContext.QueryInterface(); renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations); - return new InkDispersionGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence); + var provider = new InkDispersionInteropProvider(device, context, renderContext, scheduler); + renderContext = null; + return provider; } catch { - renderContext?.Dispose(); - fence?.Dispose(); - d3dContext?.Dispose(); - d3dDevice?.Dispose(); - if (d3d12Fence != 0) - Marshal.Release(d3d12Fence); + graphicsDevice = null; return null; } finally { - if (fenceHandle != 0) - CloseHandle(fenceHandle); + renderContext?.Dispose(); + context?.Dispose(); + device?.Dispose(); } } - public bool EnsureResources(int width, int height) + protected override void DisposeCore() { - var sourceChanged = EnsureSource(width, height); - var outputChanged = EnsureOutput(width, height); - return sourceChanged || outputChanged; + _renderContext.Dispose(); } - - public bool EnsureSource(int width, int height) - { - if (SourceMatches(width, height)) - return false; - - if (_sourceTexture is not null) - WaitForIdle(); - ReleaseSourceResources(); - CreateSourceResources(width, height); - return true; - } - - public bool EnsureOutput(int width, int height) - { - if (OutputCovers(width, height)) - return false; - - var capacityWidth = Math.Max(width, _outputWidth); - var capacityHeight = Math.Max(height, _outputHeight); - if (_outputTexture is not null) - WaitForIdle(); - ReleaseOutputResources(); - CreateOutputResources(capacityWidth, capacityHeight); - return true; - } - - public void RenderInput(ID2D1Image source, RawRectF bounds) - { - _renderContext.BeginDraw(); - _renderContext.Clear(null); - _renderContext.DrawImage( - source, - new System.Numerics.Vector2(-bounds.Left, -bounds.Top), - null, - InterpolationMode.NearestNeighbor, - CompositeMode.SourceCopy); - _renderContext.EndDraw(); - } - - public unsafe void BeginCompute() - { - if (_computeActive) - throw new InvalidOperationException(); - var value = ++_fenceValue; - _d3dContext.Signal(_fence, value); - _d3dContext.Flush(); - InteropServices.WaitForSharedFence(_device, (void*)_d3d12Fence, value); - _computeActive = true; - } - - public unsafe void EndCompute() - { - if (!_computeActive) - throw new InvalidOperationException(); - try - { - var value = ++_fenceValue; - InteropServices.SignalSharedFence(_device, (void*)_d3d12Fence, value); - _d3dContext.Wait(_fence, value); - } - finally - { - _computeActive = false; - } - } - - public void WaitForIdle() - { - if (_computeActive) - throw new InvalidOperationException(); - var value = ++_fenceValue; - _d3dContext.Signal(_fence, value); - _d3dContext.Flush(); - _fence.SetEventOnCompletion(value, 0); - } - - private static GraphicsDevice GetMatchingDevice(IGraphicsDevicesAndContext devices) - { - var adapterLuid = devices.DXGI.Adapter.Description.Luid.ToString(); - using var enumerator = GraphicsDevice.QueryDevices( - device => string.Equals(device.Luid.ToString(), adapterLuid, StringComparison.Ordinal)).GetEnumerator(); - if (!enumerator.MoveNext()) - throw new NotSupportedException(); - return enumerator.Current; - } - - private void CreateSourceResources(int width, int height) - { - ReadWriteTexture2D? sourceTexture = null; - ID3D11Texture2D? sourceD3D11Texture = null; - ID2D1Bitmap1? sourceBitmap = null; - nint sourceHandle = 0; - try - { - sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D(_device, width, height); - sourceHandle = InteropServices.CreateSharedHandle(sourceTexture); - sourceD3D11Texture = _d3dDevice.OpenSharedResource1(sourceHandle); - using var sourceSurface = sourceD3D11Texture.QueryInterface(); - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); - sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface( - sourceSurface, - new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target)); - _renderContext.Target = sourceBitmap; - - _sourceTexture = sourceTexture; - _sourceD3D11Texture = sourceD3D11Texture; - _sourceBitmap = sourceBitmap; - _sourceWidth = width; - _sourceHeight = height; - sourceTexture = null; - sourceD3D11Texture = null; - sourceBitmap = null; - } - finally - { - if (sourceHandle != 0) - CloseHandle(sourceHandle); - sourceBitmap?.Dispose(); - sourceD3D11Texture?.Dispose(); - sourceTexture?.Dispose(); - } - } - - private void CreateOutputResources(int width, int height) - { - ReadWriteTexture2D? outputTexture = null; - ID3D11Texture2D? outputD3D11Texture = null; - ID2D1Bitmap1? outputBitmap = null; - nint outputHandle = 0; - try - { - outputTexture = InteropServices.AllocateSharedReadWriteTexture2D(_device, width, height); - outputHandle = InteropServices.CreateSharedHandle(outputTexture); - outputD3D11Texture = _d3dDevice.OpenSharedResource1(outputHandle); - using var outputSurface = outputD3D11Texture.QueryInterface(); - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); - outputBitmap = _renderContext.CreateBitmapFromDxgiSurface( - outputSurface, - new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None)); - - _outputTexture = outputTexture; - _outputD3D11Texture = outputD3D11Texture; - _outputBitmap = outputBitmap; - _outputWidth = width; - _outputHeight = height; - outputTexture = null; - outputD3D11Texture = null; - outputBitmap = null; - } - finally - { - if (outputHandle != 0) - CloseHandle(outputHandle); - outputBitmap?.Dispose(); - outputD3D11Texture?.Dispose(); - outputTexture?.Dispose(); - } - } - - private void ReleaseSourceResources() - { - _renderContext.Target = null; - _sourceBitmap?.Dispose(); - _sourceD3D11Texture?.Dispose(); - _sourceTexture?.Dispose(); - _sourceBitmap = null; - _sourceD3D11Texture = null; - _sourceTexture = null; - _sourceWidth = 0; - _sourceHeight = 0; - } - - private void ReleaseOutputResources() - { - _outputBitmap?.Dispose(); - _outputD3D11Texture?.Dispose(); - _outputTexture?.Dispose(); - _outputBitmap = null; - _outputD3D11Texture = null; - _outputTexture = null; - _outputWidth = 0; - _outputHeight = 0; - } - - public void Dispose() - { - if (_disposed) - return; - try - { - WaitForIdle(); - } - finally - { - _disposed = true; - ReleaseOutputResources(); - ReleaseSourceResources(); - _renderContext.Dispose(); - _fence.Dispose(); - _d3dContext.Dispose(); - _d3dDevice.Dispose(); - if (_d3d12Fence != 0) - { - Marshal.Release(_d3d12Fence); - _d3d12Fence = 0; - } - } - } - - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool CloseHandle(nint handle); +} + +[ComputeInteropResourceSet] +internal sealed partial class InkDispersionResourceSet +{ + [ComputeSharedTexture( + ComputeResourceResizePolicy.Exact, + ComputeResourceAccess.ReadWrite, + ExternalResourceAccess.Write, + ExternalTextureUsage.RenderTarget, + ComputeAlphaMode.Premultiplied, + ComputeSharedTextureInitialOwner.External, + ComputeResourceRecovery.RecreateFromHost)] + private readonly SharedTextureSlot _source; + + [ComputeSharedTexture( + ComputeResourceResizePolicy.GrowOnly, + ComputeResourceAccess.ReadWrite, + ExternalResourceAccess.Read, + ExternalTextureUsage.Sampled, + ComputeAlphaMode.Premultiplied, + ComputeSharedTextureInitialOwner.Compute, + ComputeResourceRecovery.Recompute)] + private readonly SharedTextureSlot _output; } diff --git a/InkDispersion/InkDispersionPipeline.cs b/InkDispersion/InkDispersionPipeline.cs index d297c11..6c8012c 100644 --- a/InkDispersion/InkDispersionPipeline.cs +++ b/InkDispersion/InkDispersionPipeline.cs @@ -115,10 +115,36 @@ internal sealed class InkDispersionPipeline : IDisposable int sourceHeight, in Parameters parameters) { - EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality); - var derived = Derive(canvasWidth, canvasHeight, in parameters); + var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters); _host.RecordSilhouetteAndMaskHash( source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived).Wait(); + return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived); + } + + internal bool Simulate( + ComputeResourceBinding> source, + int canvasWidth, + int canvasHeight, + int sourceOffsetX, + int sourceOffsetY, + int sourceWidth, + int sourceHeight, + in Parameters parameters) + { + var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters); + _host.RecordSharedSilhouetteAndMaskHash( + source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived).Wait(); + return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived); + } + + private DerivedValues BeginSimulate(int canvasWidth, int canvasHeight, in Parameters parameters) + { + EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality); + return Derive(canvasWidth, canvasHeight, in parameters); + } + + private bool CompleteSimulate(int canvasWidth, int canvasHeight, in Parameters parameters, in DerivedValues derived) + { _scratchReadBack.CopyFrom(_scratch); var hashed = _scratchReadBack.Span; var key = new StructureKey( @@ -190,6 +216,17 @@ internal sealed class InkDispersionPipeline : IDisposable _host.RecordRender(output, _scratch, _inkStep!, in rect, _gridWidth, _gridHeight, in derived, in parameters).Wait(); } + internal void RenderVisible( + ComputeResourceBinding> output, + int canvasWidth, + int canvasHeight, + PixelRect rect, + in Parameters parameters) + { + var derived = Derive(canvasWidth, canvasHeight, in parameters); + _host.RecordSharedRender(output, _scratch, _inkStep!, in rect, _gridWidth, _gridHeight, in derived, in parameters).Wait(); + } + private ComputeSubmission SubmitFullPipeline( ReadWriteTexture2D source, ReadWriteTexture2D output, diff --git a/InkDispersion/InkDispersionPipelineHost.cs b/InkDispersion/InkDispersionPipelineHost.cs index 4a187f9..3b82dd9 100644 --- a/InkDispersion/InkDispersionPipelineHost.cs +++ b/InkDispersion/InkDispersionPipelineHost.cs @@ -101,6 +101,46 @@ internal sealed partial class InkDispersionPipelineHost RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight); } + [ComputePipeline] + [ComputeInterop] + private void RecordSharedSilhouetteAndMaskHash( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InkDispersionGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D source, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer scratch, + int sourceOffsetX, + int sourceOffsetY, + int sourceWidth, + int sourceHeight, + int gridWidth, + int gridHeight, + in InkDispersionPipeline.DerivedValues derived) + { + _ = _device; + + RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived); + RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight); + } + + [ComputePipeline] + [ComputeInterop] + private void RecordSharedRender( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InkDispersionGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D output, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer scratch, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer inkStep, + in InkDispersionPipeline.PixelRect rect, + int gridWidth, + int gridHeight, + in InkDispersionPipeline.DerivedValues derived, + in InkDispersionPipeline.Parameters parameters) + { + _ = _device; + + RecordRenderStage(in context, grid, output, scratch, inkStep, rect, gridWidth, gridHeight, in derived, in parameters); + } + [ComputePipeline] private void RecordFlow( in ComputeContext context,