diff --git a/WaveOptics.Shader/WaveOptics.Shader.vcxproj b/WaveOptics.Shader/WaveOptics.Shader.vcxproj
index fc7b161..a6b846b 100644
--- a/WaveOptics.Shader/WaveOptics.Shader.vcxproj
+++ b/WaveOptics.Shader/WaveOptics.Shader.vcxproj
@@ -144,13 +144,7 @@
-
- Pixel
- Pixel
- Pixel
- Pixel
-
-
+
Pixel
Pixel
Pixel
diff --git a/WaveOptics.Shader/WaveOptics.Shader.vcxproj.filters b/WaveOptics.Shader/WaveOptics.Shader.vcxproj.filters
index 8cf3558..309e335 100644
--- a/WaveOptics.Shader/WaveOptics.Shader.vcxproj.filters
+++ b/WaveOptics.Shader/WaveOptics.Shader.vcxproj.filters
@@ -15,10 +15,7 @@
-
- ソース ファイル
-
-
+
ソース ファイル
diff --git a/WaveOptics.Shader/WaveOptics.hlsl b/WaveOptics.Shader/WaveOptics.hlsl
new file mode 100644
index 0000000..6f7ca2c
--- /dev/null
+++ b/WaveOptics.Shader/WaveOptics.hlsl
@@ -0,0 +1,28 @@
+Texture2D SourceTexture : register(t0);
+SamplerState SourceSampler : register(s0);
+Texture2D ConvolvedTexture : register(t1);
+SamplerState ConvolvedSampler : register(s1);
+
+cbuffer Constants : register(b0)
+{
+ float amount : packoffset(c0.x);
+ float pad0 : packoffset(c0.y);
+ float pad1 : packoffset(c0.z);
+ float pad2 : packoffset(c0.w);
+};
+
+float4 main(
+ float4 position : SV_POSITION,
+ float4 scenePosition : SCENE_POSITION,
+ float4 uv0 : TEXCOORD0,
+ float4 uv1 : TEXCOORD1
+) : SV_TARGET
+{
+ float4 source = SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0);
+ if (amount <= 0.0)
+ return source;
+
+ float4 convolved = ConvolvedTexture.SampleLevel(ConvolvedSampler, uv1.xy, 0);
+ convolved.rgb = min(convolved.rgb, convolved.a.xxx);
+ return lerp(source, convolved, amount);
+}
diff --git a/WaveOptics.Shader/WaveOpticsSeparablePass.hlsl b/WaveOptics.Shader/WaveOpticsSeparablePass.hlsl
deleted file mode 100644
index b435fb6..0000000
--- a/WaveOptics.Shader/WaveOpticsSeparablePass.hlsl
+++ /dev/null
@@ -1,41 +0,0 @@
-Texture2D InputTexture : register(t0);
-Texture2D WeightTexture : register(t1);
-SamplerState InputSampler : register(s0);
-
-static const int MaximumRadius = 15;
-
-cbuffer Constants : register(b0)
-{
- int radius : packoffset(c0.x);
- int axis : packoffset(c0.y);
- float4 inputBounds : packoffset(c1);
-};
-
-float4 SampleInput(float2 uv, float2 scenePosition)
-{
- if (scenePosition.x < inputBounds.x || scenePosition.y < inputBounds.y ||
- scenePosition.x >= inputBounds.z || scenePosition.y >= inputBounds.w)
- return (float4)0;
- return InputTexture.SampleLevel(InputSampler, uv, 0);
-}
-
-float4 main(
- float4 position : SV_POSITION,
- float4 scenePosition : SCENE_POSITION,
- float4 uv0 : TEXCOORD0,
- float4 uv1 : TEXCOORD1
-) : SV_TARGET
-{
- int clamped = clamp(radius, 0, MaximumRadius);
- float4 accumulated = (float4)0;
-
- [loop]
- for (int d = -clamped; d <= clamped; d++)
- {
- float weight = WeightTexture.Load(int3(d + clamped, 0, 0)).r;
- float2 offset = axis == 0 ? float2(d, 0) : float2(0, d);
- accumulated += SampleInput(uv0.xy + offset * uv0.zw, scenePosition.xy + offset) * weight;
- }
-
- return accumulated;
-}
diff --git a/WaveOptics.Shader/WaveOpticsSeparableResolve.hlsl b/WaveOptics.Shader/WaveOpticsSeparableResolve.hlsl
deleted file mode 100644
index 1d78e2d..0000000
--- a/WaveOptics.Shader/WaveOpticsSeparableResolve.hlsl
+++ /dev/null
@@ -1,44 +0,0 @@
-Texture2D Term0 : register(t0);
-Texture2D Term1 : register(t1);
-Texture2D Term2 : register(t2);
-Texture2D Term3 : register(t3);
-Texture2D SourceTexture : register(t4);
-SamplerState InputSampler : register(s0);
-
-cbuffer Constants : register(b0)
-{
- int rank : packoffset(c0.x);
- float amount : packoffset(c0.y);
- float gain : packoffset(c0.z);
- float4 inputBounds : packoffset(c1);
-};
-
-float4 main(
- float4 position : SV_POSITION,
- float4 scenePosition : SCENE_POSITION,
- float4 uv0 : TEXCOORD0,
- float4 uv1 : TEXCOORD1,
- float4 uv2 : TEXCOORD2,
- float4 uv3 : TEXCOORD3,
- float4 uv4 : TEXCOORD4
-) : SV_TARGET
-{
- float4 source = (float4)0;
- if (scenePosition.x >= inputBounds.x && scenePosition.y >= inputBounds.y &&
- scenePosition.x < inputBounds.z && scenePosition.y < inputBounds.w)
- source = SourceTexture.SampleLevel(InputSampler, uv4.xy, 0);
-
- if (amount <= 0.0f || rank <= 0)
- return source;
-
- float4 convolved = Term0.SampleLevel(InputSampler, uv0.xy, 0);
- if (rank > 1)
- convolved += Term1.SampleLevel(InputSampler, uv1.xy, 0);
- if (rank > 2)
- convolved += Term2.SampleLevel(InputSampler, uv2.xy, 0);
- if (rank > 3)
- convolved += Term3.SampleLevel(InputSampler, uv3.xy, 0);
-
- convolved *= gain;
- return lerp(source, convolved, amount);
-}
diff --git a/WaveOptics/Effects/WaveOpticsEffectProcessor.cs b/WaveOptics/Effects/WaveOpticsEffectProcessor.cs
index 356115c..45e6cc7 100644
--- a/WaveOptics/Effects/WaveOpticsEffectProcessor.cs
+++ b/WaveOptics/Effects/WaveOpticsEffectProcessor.cs
@@ -1,6 +1,8 @@
+using System.ComponentModel;
+using System.Numerics;
+using ComputeWeave;
using Vortice.Direct2D1;
-using WaveOptics.Abstractions;
-using WaveOptics.Optics;
+using Vortice.Direct2D1.Effects;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
@@ -8,216 +10,363 @@ using YukkuriMovieMaker.Player.Video.Effects;
namespace WaveOptics.Effects;
-internal sealed class WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item) : VideoEffectProcessorBase(devices)
+internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
{
- const double SeparableResidualRatio = 1e-4;
- const int MaximumRank = WaveOpticsSeparableResolveEffect.MaximumRank;
+ private readonly IGraphicsDevicesAndContext _devices;
+ private readonly WaveOpticsEffect _item;
+ private ComputeExternalQueueScheduler? _scheduler;
+ private WaveOpticsInteropProvider? _interopProvider;
+ private ComputeInteropDomain? _interopDomain;
+ private WaveOpticsResourceSet? _resourceSet;
+ private ExternalTextureLease? _outputLease;
+ private WaveOpticsPipeline? _pipeline;
+ private WaveOpticsCustomEffect? _effect;
+ private Crop? _outputCrop;
+ private ID2D1Image? _outputCropOutput;
+ private AffineTransform2D? _outputTransform;
+ private ID2D1Image? _outputTransformOutput;
+ private bool _isFirst = true;
+ private bool _hasOutput;
+ private bool _hasOutputOffset;
+ private bool _hasCropRect;
+ private bool _hasRenderState;
+ private Vector2 _outputOffset;
+ private Vector4 _cropRect;
+ private float _amount;
+ private RenderState _renderState;
- readonly IGraphicsDevicesAndContext devices = devices;
- readonly WaveOpticsEffect item = item;
- readonly FraunhoferPsfGenerator generator = new();
- readonly WaveOpticsSeparablePassEffect[] horizontalPasses = new WaveOpticsSeparablePassEffect[MaximumRank];
- readonly WaveOpticsSeparablePassEffect[] verticalPasses = new WaveOpticsSeparablePassEffect[MaximumRank];
- readonly ID2D1Bitmap?[] horizontalWeights = new ID2D1Bitmap?[MaximumRank];
- readonly ID2D1Bitmap?[] verticalWeights = new ID2D1Bitmap?[MaximumRank];
-
- WaveOpticsSeparableResolveEffect? resolve;
- Parameters? currentParameters;
- float amount;
- float gain;
- bool isFirst = true;
+ public WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item)
+ : base(devices)
+ {
+ _devices = devices;
+ _item = item;
+ }
public override DrawDescription Update(EffectDescription effectDescription)
{
- if (IsPassThroughEffect || resolve 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;
var length = effectDescription.ItemDuration.Frame;
var fps = effectDescription.FPS;
- var amount = Sanitize(item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
- var gain = Sanitize(item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1);
- var parameters = new Parameters(
- GetGridSize(item.Quality),
- item.KernelRadius * 2 + 1,
- Sanitize(item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
- Sanitize(item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
- Sanitize(item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
- item.ApertureShape,
- Math.Clamp(item.BladeCount, 3, 32),
- Sanitize(item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
- Sanitize(item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
- Sanitize(item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
- Sanitize(item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
- Sanitize(item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
- Sanitize(item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
- Sanitize(item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
- Sanitize(item.Spherical.GetValue(frame, length, fps), -10, 10, 0));
+ var amount = Sanitize(_item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
+ var parameters = new WaveOpticsPipeline.Parameters(
+ Sanitize(_item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1),
+ new WaveOpticsPipeline.PsfParameters(
+ _item.Quality,
+ Math.Clamp(_item.KernelRadius, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius),
+ Sanitize(_item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
+ Sanitize(_item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
+ Sanitize(_item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
+ _item.ApertureShape,
+ Math.Clamp(_item.BladeCount, 3, 32),
+ Sanitize(_item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
+ Sanitize(_item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
+ Sanitize(_item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
+ Sanitize(_item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
+ Sanitize(_item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
+ Sanitize(_item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
+ Sanitize(_item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
+ Sanitize(_item.Spherical.GetValue(frame, length, fps), -10, 10, 0)));
- if (currentParameters != parameters)
- UpdateKernel(parameters);
- if (isFirst || this.amount != amount)
- resolve.Amount = amount;
- if (isFirst || this.gain != gain)
- resolve.Gain = gain;
+ if (_isFirst || _amount != amount)
+ _effect.Amount = amount;
- isFirst = false;
- this.amount = amount;
- this.gain = gain;
- currentParameters = parameters;
+ if (amount <= 0f)
+ {
+ _effect.Amount = 0f;
+ _amount = amount;
+ _isFirst = true;
+ return effectDescription.DrawDescription;
+ }
+
+ var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
+ var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
+ var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top);
+ if (!double.IsFinite(widthValue) || !double.IsFinite(heightValue) ||
+ !float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
+ widthValue <= 0d || heightValue <= 0d)
+ {
+ _effect.Amount = 0f;
+ _isFirst = true;
+ return effectDescription.DrawDescription;
+ }
+
+ var margin = WaveOpticsSettings.CanvasMargin;
+ var longSide = Math.Max(widthValue, heightValue);
+ if ((WaveOpticsSettings.MaximumCanvasSize - longSide) / 2d < margin)
+ {
+ _effect.Amount = 0f;
+ _isFirst = true;
+ return effectDescription.DrawDescription;
+ }
+ var canvasWidth = (int)widthValue + margin * 2;
+ var canvasHeight = (int)heightValue + margin * 2;
+ var itemWidth = (int)widthValue;
+ var itemHeight = (int)heightValue;
+
+ 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 convolutionChanged = _pipeline.Simulate(
+ _resourceSet.GetSourceComputeBinding(),
+ canvasWidth,
+ canvasHeight,
+ margin,
+ margin,
+ itemWidth,
+ itemHeight,
+ in parameters);
+
+ if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out var rect))
+ {
+ _effect.Amount = 0f;
+ _amount = amount;
+ _isFirst = true;
+ _hasRenderState = false;
+ return effectDescription.DrawDescription;
+ }
+
+ if (!OutputCovers(rect.Width, rect.Height))
+ _outputCrop.SetInput(0, null, true);
+ if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
+ {
+ _effect.Amount = 0f;
+ _amount = amount;
+ _isFirst = true;
+ _hasRenderState = false;
+ return effectDescription.DrawDescription;
+ }
+ var renderState = new RenderState(parameters.Gain, rect);
+ if (convolutionChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
+ {
+ _pipeline.RenderVisible(_resourceSet.GetOutputComputeBinding(), rect, in parameters);
+ _renderState = renderState;
+ _hasRenderState = true;
+ }
+
+ _outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
+
+ if (outputChanged || !_hasOutput)
+ {
+ 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);
+ if (!_hasCropRect || _cropRect != cropRect)
+ {
+ _outputCrop.Rectangle = cropRect;
+ _cropRect = cropRect;
+ _hasCropRect = true;
+ }
+ var outputOffset = new Vector2(bounds.Left - margin + rect.X, bounds.Top - margin + rect.Y);
+ if (!_hasOutputOffset || _outputOffset != outputOffset)
+ {
+ _outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
+ _outputOffset = outputOffset;
+ _hasOutputOffset = true;
+ }
+ _hasOutput = true;
+ _amount = amount;
+ _isFirst = false;
return effectDescription.DrawDescription;
}
- void UpdateKernel(Parameters parameters)
+ private bool EnsureSource(int width, int height)
{
- if (resolve is null)
- return;
-
- var aberration = new WavefrontAberration(
- defocusWaves: parameters.Defocus,
- astigmatismVerticalWaves: parameters.AstigmatismVertical,
- astigmatismObliqueWaves: parameters.AstigmatismOblique,
- comaHorizontalWaves: parameters.ComaHorizontal,
- comaVerticalWaves: parameters.ComaVertical,
- sphericalWaves: parameters.Spherical);
- var descriptor = new PsfDescriptor(
- parameters.GridSize,
- parameters.GridSize / 4,
- parameters.KernelSize,
- parameters.Wavelength,
- parameters.FNumber,
- parameters.PixelPitch,
- parameters.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
- parameters.BladeCount,
- parameters.BladeRotation,
- parameters.Obstruction,
- aberration);
- var result = generator.Generate(descriptor);
- var separable = SeparableKernel.Decompose(result.Kernel.Values.Span, result.Kernel.Size, SeparableResidualRatio, MaximumRank);
-
- var size = separable.Size;
- var radius = size / 2;
- ReadOnlySpan passthrough = [1f];
-
- for (var term = 0; term < MaximumRank; term++)
- {
- if (term < separable.Rank)
- {
- ConfigurePass(horizontalPasses[term], ref horizontalWeights[term], separable.Horizontal.AsSpan(term * size, size), radius, 0);
- ConfigurePass(verticalPasses[term], ref verticalWeights[term], separable.Vertical.AsSpan(term * size, size), radius, 1);
- }
- else
- {
- ConfigurePass(horizontalPasses[term], ref horizontalWeights[term], passthrough, 0, 0);
- ConfigurePass(verticalPasses[term], ref verticalWeights[term], passthrough, 0, 1);
- }
- }
-
- resolve.Rank = separable.Rank;
+ return _resourceSet!.TryEnsureSource(width, height, out _);
}
- void ConfigurePass(WaveOpticsSeparablePassEffect pass, ref ID2D1Bitmap? slot, ReadOnlySpan weights, int radius, int axis)
+ 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)
{
- var next = PsfBitmapFactory.CreateWeights(devices.DeviceContext, weights);
- pass.SetWeights(null);
- disposer.RemoveAndDispose(ref slot);
- slot = next;
- disposer.Collect(slot);
- pass.Axis = axis;
- pass.Radius = radius;
- pass.SetWeights(slot);
+ changed = false;
+ if (OutputCovers(width, height))
+ return true;
+
+ _outputLease?.Dispose();
+ _outputLease = null;
+ return _resourceSet!.TryEnsureOutput(width, height, out changed);
}
- static int GetGridSize(WaveOpticsQuality quality)
+ private void RenderInput(Vortice.RawRectF bounds)
{
- return quality switch
- {
- WaveOpticsQuality.Draft => 128,
- WaveOpticsQuality.High => 512,
- _ => 256,
- };
+ 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;
}
- static float Sanitize(double value, double minimum, double maximum, double fallback)
+ private static float Sanitize(double value, double minimum, double maximum, double fallback)
{
if (!double.IsFinite(value))
return (float)fallback;
return (float)Math.Clamp(value, minimum, maximum);
}
- protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
+ private void ReleaseInterop()
{
- resolve = new WaveOpticsSeparableResolveEffect(devices);
- if (!resolve.IsEnabled)
- {
- resolve.Dispose();
- resolve = null;
- return null;
- }
- disposer.Collect(resolve);
-
- for (var term = 0; term < MaximumRank; term++)
- {
- var horizontal = new WaveOpticsSeparablePassEffect(devices);
- var vertical = new WaveOpticsSeparablePassEffect(devices);
- if (!horizontal.IsEnabled || !vertical.IsEnabled)
- {
- horizontal.Dispose();
- vertical.Dispose();
- resolve = null;
- return null;
- }
- disposer.Collect(horizontal);
- disposer.Collect(vertical);
- horizontal.Axis = 0;
- vertical.Axis = 1;
- vertical.SetSource(horizontal.Output);
- resolve.SetTerm(term, vertical.Output);
- horizontalPasses[term] = horizontal;
- verticalPasses[term] = vertical;
- }
-
- var output = resolve.Output;
- disposer.Collect(output);
- return output;
+ _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 void setInput(ID2D1Image? input)
+ protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
- foreach (var pass in horizontalPasses)
- pass?.SetSource(input);
- resolve?.SetSource(input);
+ var scheduler = ComputeExternalQueueScheduler.Create();
+ var interopProvider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
+ if (interopProvider is null || interopDevice is null)
+ {
+ scheduler.Dispose();
+ return null;
+ }
+
+ _scheduler = scheduler;
+
+ try
+ {
+ _interopProvider = interopProvider;
+ _interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
+ _resourceSet = WaveOpticsResourceSet.Create(interopDevice, _interopDomain);
+ _pipeline = WaveOpticsPipeline.TryCreate(interopDevice);
+ }
+ catch (Win32Exception)
+ {
+ ReleaseInterop();
+ return null;
+ }
+ catch
+ {
+ ReleaseInterop();
+ throw;
+ }
+
+ if (_pipeline is null)
+ {
+ ReleaseInterop();
+ return null;
+ }
+
+ WaveOpticsCustomEffect? effect = null;
+ Crop? outputCrop = null;
+ ID2D1Image? outputCropOutput = null;
+ AffineTransform2D? outputTransform = null;
+ ID2D1Image? outputTransformOutput = null;
+ ID2D1Image? output = null;
+ try
+ {
+ effect = new WaveOpticsCustomEffect(devices);
+ if (!effect.IsEnabled)
+ {
+ effect.Dispose();
+ ReleaseInterop();
+ return null;
+ }
+ outputCrop = new Crop(devices.DeviceContext);
+ outputCropOutput = outputCrop.Output;
+ outputTransform = new AffineTransform2D(devices.DeviceContext)
+ {
+ BorderMode = BorderMode.Hard,
+ };
+ outputTransform.SetInput(0, outputCropOutput, true);
+ outputTransformOutput = outputTransform.Output;
+ output = effect.Output;
+ _effect = effect;
+ _outputCrop = outputCrop;
+ _outputCropOutput = outputCropOutput;
+ _outputTransform = outputTransform;
+ _outputTransformOutput = outputTransformOutput;
+ disposer.Collect(effect);
+ disposer.Collect(outputCrop);
+ disposer.Collect(outputCropOutput);
+ disposer.Collect(outputTransform);
+ disposer.Collect(outputTransformOutput);
+ disposer.Collect(output);
+ return output;
+ }
+ catch
+ {
+ output?.Dispose();
+ outputTransformOutput?.Dispose();
+ outputTransform?.Dispose();
+ outputCropOutput?.Dispose();
+ outputCrop?.Dispose();
+ effect?.Dispose();
+ ReleaseInterop();
+ throw;
+ }
+ }
+
+ protected override void setInput(ID2D1Image? inputImage)
+ {
+ _effect?.SetInput(0, inputImage, true);
+ if (!_hasOutput)
+ _effect?.SetInput(1, inputImage, true);
}
protected override void ClearEffectChain()
{
- for (var term = 0; term < MaximumRank; term++)
- {
- horizontalPasses[term]?.SetSource(null);
- horizontalPasses[term]?.SetWeights(null);
- verticalPasses[term]?.SetSource(null);
- verticalPasses[term]?.SetWeights(null);
- resolve?.SetTerm(term, null);
- }
- resolve?.SetSource(null);
- currentParameters = null;
- isFirst = true;
+ _effect?.SetInput(0, null, true);
+ _effect?.SetInput(1, null, true);
+ _outputCrop?.SetInput(0, null, true);
+ _isFirst = true;
+ _hasOutput = false;
+ _hasOutputOffset = false;
+ _hasCropRect = false;
+ _hasRenderState = false;
}
- readonly record struct Parameters(
- int GridSize,
- int KernelSize,
- float Wavelength,
- float FNumber,
- float PixelPitch,
- WaveOpticsApertureShape ApertureShape,
- int BladeCount,
- float BladeRotation,
- float Obstruction,
- float Defocus,
- float AstigmatismVertical,
- float AstigmatismOblique,
- float ComaHorizontal,
- float ComaVertical,
- float Spherical);
+ protected override void Dispose(bool disposing)
+ {
+ try
+ {
+ if (disposing)
+ {
+ ClearEffectChain();
+ ReleaseInterop();
+ }
+ }
+ finally
+ {
+ base.Dispose(disposing);
+ }
+ }
+
+ private readonly record struct RenderState(
+ float Gain,
+ WaveOpticsPipeline.PixelRect Rect);
}
diff --git a/WaveOptics/Rendering/PsfBitmapFactory.cs b/WaveOptics/Rendering/PsfBitmapFactory.cs
deleted file mode 100644
index 0360f52..0000000
--- a/WaveOptics/Rendering/PsfBitmapFactory.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using System.Buffers;
-using System.Runtime.InteropServices;
-using Vortice.DCommon;
-using Vortice.Direct2D1;
-using Vortice.DXGI;
-using Vortice.Mathematics;
-
-namespace WaveOptics.Rendering;
-
-internal static class PsfBitmapFactory
-{
- public static ID2D1Bitmap CreateWeights(ID2D1DeviceContext deviceContext, ReadOnlySpan weights)
- {
- var width = weights.Length;
- var pixels = ArrayPool.Shared.Rent(width * 4);
- try
- {
- for (var index = 0; index < width; index++)
- {
- var value = weights[index];
- var offset = index * 4;
- pixels[offset] = value;
- pixels[offset + 1] = value;
- pixels[offset + 2] = value;
- pixels[offset + 3] = 1;
- }
-
- var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
- try
- {
- var properties = new BitmapProperties1(
- new PixelFormat(Format.R32G32B32A32_Float, Vortice.DCommon.AlphaMode.Ignore),
- 96,
- 96,
- BitmapOptions.None);
- return ((ID2D1DeviceContext1)deviceContext).CreateBitmap(
- new SizeI(width, 1),
- handle.AddrOfPinnedObject(),
- width * 4 * sizeof(float),
- properties);
- }
- finally
- {
- handle.Free();
- }
- }
- finally
- {
- ArrayPool.Shared.Return(pixels);
- }
- }
-}
diff --git a/WaveOptics/Rendering/WaveOpticsCustomEffect.cs b/WaveOptics/Rendering/WaveOpticsCustomEffect.cs
new file mode 100644
index 0000000..192794d
--- /dev/null
+++ b/WaveOptics/Rendering/WaveOpticsCustomEffect.cs
@@ -0,0 +1,89 @@
+using System.Runtime.InteropServices;
+using Vortice;
+using Vortice.Direct2D1;
+using YukkuriMovieMaker.Commons;
+using YukkuriMovieMaker.Player.Video;
+
+namespace WaveOptics.Rendering;
+
+internal sealed class WaveOpticsCustomEffect(IGraphicsDevicesAndContext devices)
+ : D2D1CustomShaderEffectBase(Create(devices))
+{
+ public float Amount { set => SetValue((int)EffectImpl.Properties.Amount, value); }
+
+ [CustomEffect(2)]
+ private sealed class EffectImpl : D2D1CustomShaderEffectImplBase
+ {
+ private ConstantBuffer _cb;
+
+ [CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
+ public float Amount
+ {
+ get => _cb.Amount;
+ set
+ {
+ _cb.Amount = Math.Clamp(value, 0f, 1f);
+ UpdateConstants();
+ }
+ }
+
+ public EffectImpl() : base(ShaderResourceUri.Get("WaveOptics"))
+ {
+ }
+
+ protected override void UpdateConstants()
+ {
+ if (drawInformation is null)
+ return;
+
+ drawInformation.SetPixelShaderConstantBuffer(_cb);
+ }
+
+ public override void MapInputRectsToOutputRect(
+ RawRect[] inputRects,
+ RawRect[] inputOpaqueSubRects,
+ out RawRect outputRect,
+ out RawRect outputOpaqueSubRect)
+ {
+ if (inputRects.Length == 0)
+ {
+ outputRect = default;
+ outputOpaqueSubRect = default;
+ return;
+ }
+
+ var union = inputRects[0];
+ for (var i = 1; i < inputRects.Length; i++)
+ {
+ var rect = inputRects[i];
+ union = new RawRect(
+ Math.Min(union.Left, rect.Left),
+ Math.Min(union.Top, rect.Top),
+ Math.Max(union.Right, rect.Right),
+ Math.Max(union.Bottom, rect.Bottom));
+ }
+ outputRect = union;
+ outputOpaqueSubRect = default;
+ }
+
+ public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
+ {
+ for (var i = 0; i < inputRects.Length; i++)
+ inputRects[i] = outputRect;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ConstantBuffer
+ {
+ public float Amount;
+ public float Pad0;
+ public float Pad1;
+ public float Pad2;
+ }
+
+ public enum Properties
+ {
+ Amount = 0,
+ }
+ }
+}
diff --git a/WaveOptics/Rendering/WaveOpticsSeparablePassEffect.cs b/WaveOptics/Rendering/WaveOpticsSeparablePassEffect.cs
deleted file mode 100644
index b975663..0000000
--- a/WaveOptics/Rendering/WaveOpticsSeparablePassEffect.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-using System.Numerics;
-using System.Runtime.InteropServices;
-using Vortice;
-using Vortice.Direct2D1;
-using YukkuriMovieMaker.Commons;
-using YukkuriMovieMaker.Player.Video;
-
-namespace WaveOptics.Rendering;
-
-internal sealed class WaveOpticsSeparablePassEffect(IGraphicsDevicesAndContext devices)
- : D2D1CustomShaderEffectBase(Create(devices))
-{
- public const int MaximumRadius = 15;
-
- public int Radius
- {
- get => GetIntValue((int)EffectImpl.Properties.Radius);
- set => SetValue((int)EffectImpl.Properties.Radius, value);
- }
-
- public int Axis
- {
- get => GetIntValue((int)EffectImpl.Properties.Axis);
- set => SetValue((int)EffectImpl.Properties.Axis, value);
- }
-
- public void SetSource(ID2D1Image? image) => SetInput(0, image, true);
- public void SetWeights(ID2D1Image? image) => SetInput(1, image, true);
-
- [CustomEffect(2)]
- sealed class EffectImpl : D2D1CustomShaderEffectImplBase
- {
- ConstantBuffer constants;
- RawRect weightRect;
-
- [CustomEffectProperty(PropertyType.Int32, (int)Properties.Radius)]
- public int Radius
- {
- get => constants.Radius;
- set
- {
- constants.Radius = Math.Clamp(value, 0, MaximumRadius);
- UpdateConstants();
- }
- }
-
- [CustomEffectProperty(PropertyType.Int32, (int)Properties.Axis)]
- public int Axis
- {
- get => constants.Axis;
- set
- {
- constants.Axis = value != 0 ? 1 : 0;
- UpdateConstants();
- }
- }
-
- public EffectImpl() : base(ShaderResourceUri.Get("WaveOpticsSeparablePass"))
- {
- }
-
- protected override void UpdateConstants()
- {
- drawInformation?.SetPixelShaderConstantBuffer(constants);
- drawInformation?.SetOutputBuffer(BufferPrecision.PerChannel32Float, ChannelDepth.Four);
- }
-
- public override void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
- {
- inputRect = inputRects[0];
- weightRect = inputRects[1];
- constants.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
- UpdateConstants();
- outputRect = Inflate(inputRect);
- outputOpaqueSubRect = default;
- }
-
- public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
- {
- inputRects[0] = Inflate(outputRect);
- inputRects[1] = weightRect;
- }
-
- RawRect Inflate(RawRect rect)
- {
- var horizontal = constants.Axis == 0 ? constants.Radius : 0;
- var vertical = constants.Axis == 0 ? 0 : constants.Radius;
- return new RawRect(
- Saturate((long)rect.Left - horizontal),
- Saturate((long)rect.Top - vertical),
- Saturate((long)rect.Right + horizontal),
- Saturate((long)rect.Bottom + vertical));
- }
-
- static int Saturate(long value) => (int)Math.Clamp(value, int.MinValue, int.MaxValue);
-
- [StructLayout(LayoutKind.Sequential)]
- struct ConstantBuffer
- {
- public int Radius;
- public int Axis;
- public float Padding0;
- public float Padding1;
- public Vector4 InputBounds;
- }
-
- public enum Properties
- {
- Radius,
- Axis,
- }
- }
-}
diff --git a/WaveOptics/Rendering/WaveOpticsSeparableResolveEffect.cs b/WaveOptics/Rendering/WaveOpticsSeparableResolveEffect.cs
deleted file mode 100644
index e87e99e..0000000
--- a/WaveOptics/Rendering/WaveOpticsSeparableResolveEffect.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using System.Numerics;
-using System.Runtime.InteropServices;
-using Vortice;
-using Vortice.Direct2D1;
-using YukkuriMovieMaker.Commons;
-using YukkuriMovieMaker.Player.Video;
-
-namespace WaveOptics.Rendering;
-
-internal sealed class WaveOpticsSeparableResolveEffect(IGraphicsDevicesAndContext devices)
- : D2D1CustomShaderEffectBase(Create(devices))
-{
- public const int MaximumRank = 4;
-
- public int Rank
- {
- get => GetIntValue((int)EffectImpl.Properties.Rank);
- set => SetValue((int)EffectImpl.Properties.Rank, value);
- }
-
- public float Amount
- {
- get => GetFloatValue((int)EffectImpl.Properties.Amount);
- set => SetValue((int)EffectImpl.Properties.Amount, value);
- }
-
- public float Gain
- {
- get => GetFloatValue((int)EffectImpl.Properties.Gain);
- set => SetValue((int)EffectImpl.Properties.Gain, value);
- }
-
- public void SetTerm(int index, ID2D1Image? image) => SetInput(index, image, true);
- public void SetSource(ID2D1Image? image) => SetInput(MaximumRank, image, true);
-
- [CustomEffect(MaximumRank + 1)]
- sealed class EffectImpl : D2D1CustomShaderEffectImplBase
- {
- ConstantBuffer constants;
-
- [CustomEffectProperty(PropertyType.Int32, (int)Properties.Rank)]
- public int Rank
- {
- get => constants.Rank;
- set
- {
- constants.Rank = Math.Clamp(value, 0, MaximumRank);
- UpdateConstants();
- }
- }
-
- [CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
- public float Amount
- {
- get => constants.Amount;
- set
- {
- constants.Amount = float.IsFinite(value) ? Math.Clamp(value, 0, 1) : 0;
- UpdateConstants();
- }
- }
-
- [CustomEffectProperty(PropertyType.Float, (int)Properties.Gain)]
- public float Gain
- {
- get => constants.Gain;
- set
- {
- constants.Gain = float.IsFinite(value) ? Math.Clamp(value, 0, 4) : 1;
- UpdateConstants();
- }
- }
-
- public EffectImpl() : base(ShaderResourceUri.Get("WaveOpticsSeparableResolve"))
- {
- constants.Gain = 1;
- }
-
- protected override void UpdateConstants()
- {
- drawInformation?.SetPixelShaderConstantBuffer(constants);
- }
-
- public override void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
- {
- inputRect = inputRects[0];
- var source = inputRects[MaximumRank];
- constants.InputBounds = new Vector4(source.Left, source.Top, source.Right, source.Bottom);
- UpdateConstants();
- outputRect = inputRects[0];
- outputOpaqueSubRect = default;
- }
-
- public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
- {
- for (var index = 0; index < inputRects.Length; index++)
- inputRects[index] = outputRect;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- struct ConstantBuffer
- {
- public int Rank;
- public float Amount;
- public float Gain;
- public float Padding;
- public Vector4 InputBounds;
- }
-
- public enum Properties
- {
- Rank,
- Amount,
- Gain,
- }
- }
-}
diff --git a/WaveOptics/WaveOptics.csproj b/WaveOptics/WaveOptics.csproj
index cf4ab46..f8be9c6 100644
--- a/WaveOptics/WaveOptics.csproj
+++ b/WaveOptics/WaveOptics.csproj
@@ -16,8 +16,7 @@
-
-
+