「ローカルラプラシアン」映像エフェクトプラグインファイルを追加
このコミットが含まれているのは:
13ファイル変更
+1780
検索条件に一致するファイルはありません
@@ -0,0 +1,86 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal sealed class LaplacianRemappingCustomEffect(IGraphicsDevicesAndContext devices)
|
||||
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
|
||||
{
|
||||
public float Amount { set => SetValue((int)EffectImpl.Properties.Amount, value); }
|
||||
|
||||
[CustomEffect(2)]
|
||||
private sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
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("LaplacianRemapping"))
|
||||
{
|
||||
}
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
[VideoEffect(nameof(Texts.LaplacianRemapping), [VideoEffectCategories.Filtering], [nameof(Texts.TagClarity), nameof(Texts.TagTone), nameof(Texts.TagDetail)], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
|
||||
public sealed class LaplacianRemappingEffect : VideoEffectBase
|
||||
{
|
||||
public override string Label => Texts.LaplacianRemapping;
|
||||
|
||||
public LaplacianRemappingEffect()
|
||||
{
|
||||
LaplacianRemappingUpdateNotifier.EnsureCheckedOnce();
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Amount), Description = nameof(Texts.AmountDescription), Order = 0, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 100)]
|
||||
public Animation Amount { get; } = new Animation(100, 0, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 1, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public LaplacianRemappingQuality Quality { get => _quality; set => Set(ref _quality, value); }
|
||||
private LaplacianRemappingQuality _quality = LaplacianRemappingQuality.High;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AdjustGroup), Name = nameof(Texts.Detail), Description = nameof(Texts.DetailDescription), Order = 10, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", -100, 100)]
|
||||
public Animation Detail { get; } = new Animation(50, -100, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AdjustGroup), Name = nameof(Texts.Tone), Description = nameof(Texts.ToneDescription), Order = 11, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", -100, 100)]
|
||||
public Animation Tone { get; } = new Animation(0, -100, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AdjustGroup), Name = nameof(Texts.Threshold), Description = nameof(Texts.ThresholdDescription), Order = 12, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 1, 100)]
|
||||
public Animation Threshold { get; } = new Animation(30, 1, 100);
|
||||
|
||||
private IAnimatable[]? _animatables;
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
=> new LaplacianRemappingEffectProcessor(devices, this);
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables()
|
||||
=> _animatables ??= [Amount, Detail, Tone, Threshold];
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Player.Video.Effects;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal sealed class LaplacianRemappingEffectProcessor : VideoEffectProcessorBase
|
||||
{
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly LaplacianRemappingEffect _item;
|
||||
private LaplacianRemappingGpuInterop? _interop;
|
||||
private LaplacianRemappingPipeline? _pipeline;
|
||||
private LaplacianRemappingCustomEffect? _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 Parameters _parameters;
|
||||
private RenderState _renderState;
|
||||
|
||||
public LaplacianRemappingEffectProcessor(IGraphicsDevicesAndContext devices, LaplacianRemappingEffect item)
|
||||
: base(devices)
|
||||
{
|
||||
_devices = devices;
|
||||
_item = item;
|
||||
}
|
||||
|
||||
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)
|
||||
return effectDescription.DrawDescription;
|
||||
|
||||
var frame = effectDescription.ItemPosition.Frame;
|
||||
var length = effectDescription.ItemDuration.Frame;
|
||||
var fps = effectDescription.FPS;
|
||||
var parameters = new Parameters(
|
||||
(float)(_item.Amount.GetValue(frame, length, fps) / 100.0),
|
||||
(float)(_item.Detail.GetValue(frame, length, fps) / 100.0),
|
||||
(float)(_item.Tone.GetValue(frame, length, fps) / 100.0),
|
||||
(float)(_item.Threshold.GetValue(frame, length, fps) / 100.0),
|
||||
_item.Quality);
|
||||
|
||||
if (_isFirst || _parameters.Amount != parameters.Amount)
|
||||
_effect.Amount = parameters.Amount;
|
||||
|
||||
if (parameters.Amount <= 0f || (parameters.Detail == 0f && parameters.Tone == 0f))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_parameters = parameters;
|
||||
_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;
|
||||
}
|
||||
|
||||
if (Math.Max(widthValue, heightValue) > LaplacianRemappingSettings.MaximumCanvasSize ||
|
||||
widthValue * heightValue > LaplacianRemappingSettings.MaximumPixelCount)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
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));
|
||||
|
||||
var pipelineParameters = new LaplacianRemappingPipeline.Parameters(
|
||||
parameters.Quality,
|
||||
Math.Clamp(parameters.Detail, -1f, 1f),
|
||||
Math.Clamp(parameters.Tone, -1f, 1f),
|
||||
Math.Clamp(parameters.Threshold, LaplacianRemappingSettings.MinimumSigma, LaplacianRemappingSettings.MaximumSigma));
|
||||
|
||||
bool structureChanged;
|
||||
_interop.BeginCompute();
|
||||
try
|
||||
{
|
||||
structureChanged = _pipeline.Simulate(_interop.SourceTexture, itemWidth, itemHeight, in pipelineParameters);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_interop.EndCompute();
|
||||
}
|
||||
|
||||
if (!_pipeline.TryGetVisibleBounds(itemWidth, itemHeight, out var rect))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_parameters = parameters;
|
||||
_isFirst = true;
|
||||
_hasRenderState = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
if (!_interop.OutputCovers(rect.Width, rect.Height))
|
||||
_outputCrop.SetInput(0, null, true);
|
||||
var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height);
|
||||
var renderState = new RenderState(rect);
|
||||
if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
_interop.BeginCompute();
|
||||
try
|
||||
{
|
||||
_pipeline.RenderVisible(_interop.SourceTexture, _interop.OutputTexture, itemWidth, itemHeight, rect);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_interop.EndCompute();
|
||||
}
|
||||
_renderState = renderState;
|
||||
_hasRenderState = true;
|
||||
}
|
||||
|
||||
if (outputChanged || !_hasOutput)
|
||||
{
|
||||
_outputCrop.SetInput(0, _interop.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 + rect.X, bounds.Top + rect.Y);
|
||||
if (!_hasOutputOffset || _outputOffset != outputOffset)
|
||||
{
|
||||
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
|
||||
_outputOffset = outputOffset;
|
||||
_hasOutputOffset = true;
|
||||
}
|
||||
_hasOutput = true;
|
||||
_parameters = parameters;
|
||||
_isFirst = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var interop = LaplacianRemappingGpuInterop.TryCreate(devices);
|
||||
if (interop is null)
|
||||
return null;
|
||||
var pipeline = LaplacianRemappingPipeline.TryCreate(interop.Device);
|
||||
if (pipeline is null)
|
||||
{
|
||||
interop.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
LaplacianRemappingCustomEffect? effect = null;
|
||||
Crop? outputCrop = null;
|
||||
ID2D1Image? outputCropOutput = null;
|
||||
AffineTransform2D? outputTransform = null;
|
||||
ID2D1Image? outputTransformOutput = null;
|
||||
ID2D1Image? output = null;
|
||||
try
|
||||
{
|
||||
effect = new LaplacianRemappingCustomEffect(devices);
|
||||
if (!effect.IsEnabled)
|
||||
{
|
||||
effect.Dispose();
|
||||
pipeline.Dispose();
|
||||
interop.Dispose();
|
||||
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;
|
||||
_interop = interop;
|
||||
_pipeline = pipeline;
|
||||
_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();
|
||||
pipeline.Dispose();
|
||||
interop.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? inputImage)
|
||||
{
|
||||
_effect?.SetInput(0, inputImage, true);
|
||||
if (!_hasOutput)
|
||||
_effect?.SetInput(1, inputImage, true);
|
||||
}
|
||||
|
||||
protected override void ClearEffectChain()
|
||||
{
|
||||
_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;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
ClearEffectChain();
|
||||
_interop?.WaitForIdle();
|
||||
_pipeline?.Dispose();
|
||||
_pipeline = null;
|
||||
_interop?.Dispose();
|
||||
_interop = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct RenderState(LaplacianRemappingPipeline.PixelRect Rect);
|
||||
|
||||
private readonly record struct Parameters(
|
||||
float Amount,
|
||||
float Detail,
|
||||
float Tone,
|
||||
float Threshold,
|
||||
LaplacianRemappingQuality Quality);
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.Interop;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using PixelFormat = Vortice.DCommon.PixelFormat;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal sealed class LaplacianRemappingGpuInterop : IDisposable
|
||||
{
|
||||
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<Bgra32, Float4>? _sourceTexture;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _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 LaplacianRemappingGpuInterop(
|
||||
GraphicsDevice device,
|
||||
ID3D11Device1 d3dDevice,
|
||||
ID3D11DeviceContext4 d3dContext,
|
||||
ID3D11Fence fence,
|
||||
ID2D1DeviceContext6 renderContext,
|
||||
nint d3d12Fence)
|
||||
{
|
||||
_device = device;
|
||||
_d3dDevice = d3dDevice;
|
||||
_d3dContext = d3dContext;
|
||||
_fence = fence;
|
||||
_renderContext = renderContext;
|
||||
_d3d12Fence = d3d12Fence;
|
||||
}
|
||||
|
||||
public GraphicsDevice Device => _device;
|
||||
|
||||
public ReadWriteTexture2D<Bgra32, Float4> SourceTexture => _sourceTexture!;
|
||||
|
||||
public ReadWriteTexture2D<Bgra32, Float4> 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 LaplacianRemappingGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
ID3D11Device1? d3dDevice = null;
|
||||
ID3D11DeviceContext4? d3dContext = null;
|
||||
ID3D11Fence? fence = null;
|
||||
ID2D1DeviceContext6? renderContext = null;
|
||||
nint d3d12Fence = 0;
|
||||
nint fenceHandle = 0;
|
||||
try
|
||||
{
|
||||
var device = GetMatchingDevice(devices);
|
||||
d3dDevice = devices.D3D.Device.QueryInterface<ID3D11Device1>();
|
||||
d3dContext = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
|
||||
using var d3dDevice5 = devices.D3D.Device.QueryInterface<ID3D11Device5>();
|
||||
var fenceGuid = D3D12FenceGuid;
|
||||
InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle);
|
||||
fence = d3dDevice5.OpenSharedFence(fenceHandle);
|
||||
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
|
||||
return new LaplacianRemappingGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
|
||||
}
|
||||
catch
|
||||
{
|
||||
renderContext?.Dispose();
|
||||
fence?.Dispose();
|
||||
d3dContext?.Dispose();
|
||||
d3dDevice?.Dispose();
|
||||
if (d3d12Fence != 0)
|
||||
Marshal.Release(d3d12Fence);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (fenceHandle != 0)
|
||||
CloseHandle(fenceHandle);
|
||||
}
|
||||
}
|
||||
|
||||
public bool EnsureResources(int width, int height)
|
||||
{
|
||||
var sourceChanged = EnsureSource(width, height);
|
||||
var outputChanged = EnsureOutput(width, height);
|
||||
return sourceChanged || outputChanged;
|
||||
}
|
||||
|
||||
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<Bgra32, Float4>? sourceTexture = null;
|
||||
ID3D11Texture2D? sourceD3D11Texture = null;
|
||||
ID2D1Bitmap1? sourceBitmap = null;
|
||||
nint sourceHandle = 0;
|
||||
try
|
||||
{
|
||||
sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
|
||||
sourceHandle = InteropServices.CreateSharedHandle(sourceTexture);
|
||||
sourceD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(sourceHandle);
|
||||
using var sourceSurface = sourceD3D11Texture.QueryInterface<IDXGISurface>();
|
||||
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<Bgra32, Float4>? outputTexture = null;
|
||||
ID3D11Texture2D? outputD3D11Texture = null;
|
||||
ID2D1Bitmap1? outputBitmap = null;
|
||||
nint outputHandle = 0;
|
||||
try
|
||||
{
|
||||
outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
|
||||
outputHandle = InteropServices.CreateSharedHandle(outputTexture);
|
||||
outputD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(outputHandle);
|
||||
using var outputSurface = outputD3D11Texture.QueryInterface<IDXGISurface>();
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
using ComputeSharp;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct FillIntShader(
|
||||
ReadWriteBuffer<int> values,
|
||||
int length,
|
||||
int value) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> values = values;
|
||||
private readonly int length = length;
|
||||
private readonly int value = value;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var index = ThreadIds.X;
|
||||
if (index >= length)
|
||||
return;
|
||||
values[index] = value;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct InitScratchShader(
|
||||
ReadWriteBuffer<int> scratch) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> scratch = scratch;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X != 0)
|
||||
return;
|
||||
scratch[0] = 0;
|
||||
scratch[1] = 0;
|
||||
scratch[2] = 2147483647;
|
||||
scratch[3] = 2147483647;
|
||||
scratch[4] = -1;
|
||||
scratch[5] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct HashBoundsShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int width,
|
||||
int height) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteBuffer<int> scratch = scratch;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= width || y >= height)
|
||||
return;
|
||||
|
||||
var pixel = source[new Int2(x, y)];
|
||||
var packed = (uint)(pixel.W * 255f + 0.5f) << 24
|
||||
| (uint)(pixel.X * 255f + 0.5f) << 16
|
||||
| (uint)(pixel.Y * 255f + 0.5f) << 8
|
||||
| (uint)(pixel.Z * 255f + 0.5f);
|
||||
var mixed = packed * 0x9E3779B9u ^ (uint)(y * width + x) * 0x85EBCA6Bu;
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0xC2B2AE35u;
|
||||
mixed ^= mixed >> 13;
|
||||
Hlsl.InterlockedAdd(ref scratch[0], (int)mixed);
|
||||
Hlsl.InterlockedXor(ref scratch[1], (int)(mixed * 0x9E3779B9u));
|
||||
|
||||
if (pixel.W > 0f)
|
||||
{
|
||||
Hlsl.InterlockedMin(ref scratch[2], x);
|
||||
Hlsl.InterlockedMin(ref scratch[3], y);
|
||||
Hlsl.InterlockedMax(ref scratch[4], x);
|
||||
Hlsl.InterlockedMax(ref scratch[5], y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct LuminanceShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<float> gaussian,
|
||||
int width,
|
||||
int height) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteBuffer<float> gaussian = gaussian;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= width || y >= height)
|
||||
return;
|
||||
|
||||
var pixel = source[new Int2(x, y)];
|
||||
var alpha = pixel.W;
|
||||
var luminance = 0f;
|
||||
if (alpha > 0f)
|
||||
{
|
||||
var r = Hlsl.Saturate(pixel.X / alpha);
|
||||
var g = Hlsl.Saturate(pixel.Y / alpha);
|
||||
var b = Hlsl.Saturate(pixel.Z / alpha);
|
||||
luminance = r * LaplacianRemappingSettings.LuminanceWeightR
|
||||
+ g * LaplacianRemappingSettings.LuminanceWeightG
|
||||
+ b * LaplacianRemappingSettings.LuminanceWeightB;
|
||||
}
|
||||
gaussian[y * width + x] = luminance;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct DownsampleShader(
|
||||
ReadWriteBuffer<float> pyramid,
|
||||
int sourceOffset,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
int destinationOffset,
|
||||
int destinationWidth,
|
||||
int destinationHeight) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> pyramid = pyramid;
|
||||
private readonly int sourceOffset = sourceOffset;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
private readonly int destinationOffset = destinationOffset;
|
||||
private readonly int destinationWidth = destinationWidth;
|
||||
private readonly int destinationHeight = destinationHeight;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= destinationWidth || y >= destinationHeight)
|
||||
return;
|
||||
|
||||
var sum = 0f;
|
||||
for (var dy = -2; dy <= 2; dy++)
|
||||
{
|
||||
var weightY = LaplacianRemappingShaderMath.KernelWeight(dy);
|
||||
var sy = Hlsl.Clamp(2 * y + dy, 0, sourceHeight - 1);
|
||||
for (var dx = -2; dx <= 2; dx++)
|
||||
{
|
||||
var weightX = LaplacianRemappingShaderMath.KernelWeight(dx);
|
||||
var sx = Hlsl.Clamp(2 * x + dx, 0, sourceWidth - 1);
|
||||
sum += weightY * weightX * pyramid[sourceOffset + sy * sourceWidth + sx];
|
||||
}
|
||||
}
|
||||
pyramid[destinationOffset + y * destinationWidth + x] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct FillLevelShader(
|
||||
ReadWriteBuffer<float> pyramid,
|
||||
int offset,
|
||||
int width,
|
||||
int height) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> pyramid = pyramid;
|
||||
private readonly int offset = offset;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= width || y >= height)
|
||||
return;
|
||||
pyramid[offset + y * width + x] = 0f;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct CopyLevelShader(
|
||||
ReadWriteBuffer<float> source,
|
||||
ReadWriteBuffer<float> destination,
|
||||
int sourceOffset,
|
||||
int destinationOffset,
|
||||
int width,
|
||||
int height) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> source = source;
|
||||
private readonly ReadWriteBuffer<float> destination = destination;
|
||||
private readonly int sourceOffset = sourceOffset;
|
||||
private readonly int destinationOffset = destinationOffset;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= width || y >= height)
|
||||
return;
|
||||
destination[destinationOffset + y * width + x] = source[sourceOffset + y * width + x];
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct RemapShader(
|
||||
ReadWriteBuffer<float> gaussian,
|
||||
ReadWriteBuffer<float> work,
|
||||
int width,
|
||||
int height,
|
||||
float gamma,
|
||||
float sigma,
|
||||
float alphaExponent,
|
||||
float beta) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> gaussian = gaussian;
|
||||
private readonly ReadWriteBuffer<float> work = work;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
private readonly float gamma = gamma;
|
||||
private readonly float sigma = sigma;
|
||||
private readonly float alphaExponent = alphaExponent;
|
||||
private readonly float beta = beta;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= width || y >= height)
|
||||
return;
|
||||
|
||||
var index = y * width + x;
|
||||
var intensity = gaussian[index];
|
||||
var difference = intensity - gamma;
|
||||
var amplitude = Hlsl.Abs(difference);
|
||||
var sign = difference < 0f ? -1f : 1f;
|
||||
float remapped;
|
||||
if (amplitude <= sigma)
|
||||
{
|
||||
var delta = amplitude / sigma;
|
||||
var detail = Hlsl.Pow(delta, alphaExponent);
|
||||
if (alphaExponent < 1f)
|
||||
{
|
||||
var tau = Hlsl.SmoothStep(
|
||||
LaplacianRemappingSettings.NoiseFloorLow,
|
||||
LaplacianRemappingSettings.NoiseFloorHigh,
|
||||
amplitude);
|
||||
detail = tau * detail + (1f - tau) * delta;
|
||||
}
|
||||
remapped = gamma + sign * sigma * detail;
|
||||
}
|
||||
else
|
||||
{
|
||||
remapped = gamma + sign * (beta * (amplitude - sigma) + sigma);
|
||||
}
|
||||
work[index] = remapped;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct AccumulateShader(
|
||||
ReadWriteBuffer<float> accumulation,
|
||||
ReadWriteBuffer<float> work,
|
||||
ReadWriteBuffer<float> gaussian,
|
||||
int levelOffset,
|
||||
int levelWidth,
|
||||
int levelHeight,
|
||||
int coarseOffset,
|
||||
int coarseWidth,
|
||||
int coarseHeight,
|
||||
float gamma,
|
||||
float inverseSpacing) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> accumulation = accumulation;
|
||||
private readonly ReadWriteBuffer<float> work = work;
|
||||
private readonly ReadWriteBuffer<float> gaussian = gaussian;
|
||||
private readonly int levelOffset = levelOffset;
|
||||
private readonly int levelWidth = levelWidth;
|
||||
private readonly int levelHeight = levelHeight;
|
||||
private readonly int coarseOffset = coarseOffset;
|
||||
private readonly int coarseWidth = coarseWidth;
|
||||
private readonly int coarseHeight = coarseHeight;
|
||||
private readonly float gamma = gamma;
|
||||
private readonly float inverseSpacing = inverseSpacing;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= levelWidth || y >= levelHeight)
|
||||
return;
|
||||
|
||||
var index = levelOffset + y * levelWidth + x;
|
||||
var reference = Hlsl.Saturate(gaussian[index]);
|
||||
var weight = 1f - Hlsl.Abs(reference - gamma) * inverseSpacing;
|
||||
if (weight <= 0f)
|
||||
return;
|
||||
|
||||
var baseX = x >> 1;
|
||||
var baseY = y >> 1;
|
||||
var upsampled = 0f;
|
||||
for (var ky = -1; ky <= 1; ky++)
|
||||
{
|
||||
var weightY = LaplacianRemappingShaderMath.UpsampleWeight(2 * (baseY + ky) - y);
|
||||
if (weightY <= 0f)
|
||||
continue;
|
||||
var cy = Hlsl.Clamp(baseY + ky, 0, coarseHeight - 1);
|
||||
for (var kx = -1; kx <= 1; kx++)
|
||||
{
|
||||
var weightX = LaplacianRemappingShaderMath.UpsampleWeight(2 * (baseX + kx) - x);
|
||||
if (weightX <= 0f)
|
||||
continue;
|
||||
var cx = Hlsl.Clamp(baseX + kx, 0, coarseWidth - 1);
|
||||
upsampled += weightY * weightX * work[coarseOffset + cy * coarseWidth + cx];
|
||||
}
|
||||
}
|
||||
|
||||
var laplacian = work[index] - upsampled;
|
||||
accumulation[index] += weight * laplacian;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct CollapseShader(
|
||||
ReadWriteBuffer<float> work,
|
||||
ReadWriteBuffer<float> accumulation,
|
||||
int levelOffset,
|
||||
int levelWidth,
|
||||
int levelHeight,
|
||||
int coarseOffset,
|
||||
int coarseWidth,
|
||||
int coarseHeight) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> work = work;
|
||||
private readonly ReadWriteBuffer<float> accumulation = accumulation;
|
||||
private readonly int levelOffset = levelOffset;
|
||||
private readonly int levelWidth = levelWidth;
|
||||
private readonly int levelHeight = levelHeight;
|
||||
private readonly int coarseOffset = coarseOffset;
|
||||
private readonly int coarseWidth = coarseWidth;
|
||||
private readonly int coarseHeight = coarseHeight;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= levelWidth || y >= levelHeight)
|
||||
return;
|
||||
|
||||
var baseX = x >> 1;
|
||||
var baseY = y >> 1;
|
||||
var upsampled = 0f;
|
||||
for (var ky = -1; ky <= 1; ky++)
|
||||
{
|
||||
var weightY = LaplacianRemappingShaderMath.UpsampleWeight(2 * (baseY + ky) - y);
|
||||
if (weightY <= 0f)
|
||||
continue;
|
||||
var cy = Hlsl.Clamp(baseY + ky, 0, coarseHeight - 1);
|
||||
for (var kx = -1; kx <= 1; kx++)
|
||||
{
|
||||
var weightX = LaplacianRemappingShaderMath.UpsampleWeight(2 * (baseX + kx) - x);
|
||||
if (weightX <= 0f)
|
||||
continue;
|
||||
var cx = Hlsl.Clamp(baseX + kx, 0, coarseWidth - 1);
|
||||
upsampled += weightY * weightX * work[coarseOffset + cy * coarseWidth + cx];
|
||||
}
|
||||
}
|
||||
|
||||
var index = levelOffset + y * levelWidth + x;
|
||||
work[index] = accumulation[index] + upsampled;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct RenderShader(
|
||||
ReadWriteBuffer<float> work,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int rectOffsetX,
|
||||
int rectOffsetY,
|
||||
int rectWidth,
|
||||
int rectHeight,
|
||||
int width,
|
||||
int height) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> work = work;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int rectOffsetX = rectOffsetX;
|
||||
private readonly int rectOffsetY = rectOffsetY;
|
||||
private readonly int rectWidth = rectWidth;
|
||||
private readonly int rectHeight = rectHeight;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
|
||||
return;
|
||||
var px = ThreadIds.X + rectOffsetX;
|
||||
var py = ThreadIds.Y + rectOffsetY;
|
||||
var pixel = source[new Int2(px, py)];
|
||||
var alpha = pixel.W;
|
||||
if (alpha <= 0f)
|
||||
{
|
||||
output[ThreadIds.XY] = new Float4(0f, 0f, 0f, 0f);
|
||||
return;
|
||||
}
|
||||
|
||||
var r = Hlsl.Saturate(pixel.X / alpha);
|
||||
var g = Hlsl.Saturate(pixel.Y / alpha);
|
||||
var b = Hlsl.Saturate(pixel.Z / alpha);
|
||||
var luminance = r * LaplacianRemappingSettings.LuminanceWeightR
|
||||
+ g * LaplacianRemappingSettings.LuminanceWeightG
|
||||
+ b * LaplacianRemappingSettings.LuminanceWeightB;
|
||||
var filtered = Hlsl.Max(work[py * width + px], 0f);
|
||||
|
||||
Float3 color;
|
||||
if (luminance <= 1e-6f)
|
||||
{
|
||||
var lifted = Hlsl.Saturate(filtered);
|
||||
color = new Float3(lifted, lifted, lifted);
|
||||
}
|
||||
else
|
||||
{
|
||||
var ratio = filtered / luminance;
|
||||
color = Hlsl.Saturate(new Float3(r * ratio, g * ratio, b * ratio));
|
||||
}
|
||||
output[ThreadIds.XY] = new Float4(color.X * alpha, color.Y * alpha, color.Z * alpha, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class LaplacianRemappingShaderMath
|
||||
{
|
||||
public static float KernelWeight(int offset)
|
||||
{
|
||||
if (offset == 0)
|
||||
return LaplacianRemappingSettings.KernelWeightCenter;
|
||||
return offset == -1 || offset == 1
|
||||
? LaplacianRemappingSettings.KernelWeightNear
|
||||
: LaplacianRemappingSettings.KernelWeightFar;
|
||||
}
|
||||
|
||||
public static float UpsampleWeight(int offset)
|
||||
{
|
||||
if (offset == 0)
|
||||
return 2f * LaplacianRemappingSettings.KernelWeightCenter;
|
||||
if (offset == -1 || offset == 1)
|
||||
return 2f * LaplacianRemappingSettings.KernelWeightNear;
|
||||
return offset == -2 || offset == 2 ? 2f * LaplacianRemappingSettings.KernelWeightFar : 0f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal sealed class LaplacianRemappingPipeline : IDisposable
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
private readonly ReadWriteBuffer<int> _scratch;
|
||||
private readonly ReadBackBuffer<int> _scratchReadBack;
|
||||
private readonly int[] _levelOffsets;
|
||||
private readonly int[] _levelWidths;
|
||||
private readonly int[] _levelHeights;
|
||||
private ReadWriteBuffer<float>? _gaussian;
|
||||
private ReadWriteBuffer<float>? _work;
|
||||
private ReadWriteBuffer<float>? _accumulation;
|
||||
private StructureKey? _structureKey;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _depth;
|
||||
private int _cachedMinX;
|
||||
private int _cachedMinY;
|
||||
private int _cachedMaxX;
|
||||
private int _cachedMaxY;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
|
||||
private int _packedWidth;
|
||||
private int _packedHeight;
|
||||
|
||||
private LaplacianRemappingPipeline(GraphicsDevice device)
|
||||
{
|
||||
_device = device;
|
||||
_scratch = device.AllocateReadWriteBuffer<int>(LaplacianRemappingSettings.ScratchLength);
|
||||
_scratchReadBack = device.AllocateReadBackBuffer<int>(LaplacianRemappingSettings.ScratchLength);
|
||||
_levelOffsets = new int[LaplacianRemappingSettings.MaximumPyramidDepth];
|
||||
_levelWidths = new int[LaplacianRemappingSettings.MaximumPyramidDepth];
|
||||
_levelHeights = new int[LaplacianRemappingSettings.MaximumPyramidDepth];
|
||||
}
|
||||
|
||||
public static LaplacianRemappingPipeline? TryCreate()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new LaplacianRemappingPipeline(GraphicsDevice.GetDefault());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static LaplacianRemappingPipeline? TryCreate(GraphicsDevice device)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new LaplacianRemappingPipeline(device);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal void WaitForCompletion()
|
||||
{
|
||||
_device.For(1, new FillIntShader(_scratch, 0, 0));
|
||||
}
|
||||
|
||||
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in Parameters parameters)
|
||||
{
|
||||
var pixelCount = checked(width * height);
|
||||
EnsureGrid(width, height);
|
||||
EnsurePackedTextures(width, height);
|
||||
var sourceTexture = _packedSource!;
|
||||
var outputTexture = _packedOutput!;
|
||||
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
|
||||
using (ComputeContext context = _device.CreateComputeContext())
|
||||
RecordFullPipeline(in context, sourceTexture, outputTexture, width, height, in parameters);
|
||||
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
|
||||
}
|
||||
|
||||
public void Process(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> destination,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
EnsureGrid(width, height);
|
||||
using ComputeContext context = _device.CreateComputeContext();
|
||||
RecordFullPipeline(in context, source, destination, width, height, in parameters);
|
||||
context.Submit();
|
||||
}
|
||||
|
||||
internal void ProcessSharedAndWait(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> destination,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
EnsureGrid(width, height);
|
||||
using ComputeContext context = _device.CreateComputeContext();
|
||||
RecordFullPipeline(in context, source, destination, width, height, in parameters);
|
||||
}
|
||||
|
||||
internal bool Simulate(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
EnsureGrid(width, height);
|
||||
using (ComputeContext context = _device.CreateComputeContext())
|
||||
RecordHashStage(in context, source, width, height);
|
||||
_scratchReadBack.CopyFrom(_scratch);
|
||||
var hashed = _scratchReadBack.Span;
|
||||
_cachedMinX = hashed[LaplacianRemappingSettings.ScratchMinX];
|
||||
_cachedMinY = hashed[LaplacianRemappingSettings.ScratchMinY];
|
||||
_cachedMaxX = hashed[LaplacianRemappingSettings.ScratchMaxX];
|
||||
_cachedMaxY = hashed[LaplacianRemappingSettings.ScratchMaxY];
|
||||
var key = new StructureKey(
|
||||
hashed[LaplacianRemappingSettings.ScratchHashSum],
|
||||
hashed[LaplacianRemappingSettings.ScratchHashMix],
|
||||
width,
|
||||
height,
|
||||
parameters.Quality,
|
||||
parameters.Detail,
|
||||
parameters.Tone,
|
||||
parameters.Threshold);
|
||||
if (_structureKey == key)
|
||||
return false;
|
||||
|
||||
var derived = Derive(in parameters);
|
||||
using (ComputeContext context = _device.CreateComputeContext())
|
||||
{
|
||||
RecordLuminanceStage(in context, source, width, height);
|
||||
RecordFilterStage(in context, in derived);
|
||||
}
|
||||
_structureKey = key;
|
||||
return true;
|
||||
}
|
||||
|
||||
internal bool TryGetVisibleBounds(int width, int height, out PixelRect rect)
|
||||
{
|
||||
rect = default;
|
||||
if (_cachedMaxX < _cachedMinX || _cachedMaxY < _cachedMinY)
|
||||
return false;
|
||||
|
||||
var left = Math.Clamp(_cachedMinX & ~3, 0, width);
|
||||
var top = Math.Clamp(_cachedMinY & ~3, 0, height);
|
||||
var right = Math.Clamp(_cachedMaxX + 1, 0, width);
|
||||
var bottom = Math.Clamp(_cachedMaxY + 1, 0, height);
|
||||
var rectWidth = Math.Min((right - left + 3) & ~3, width - left);
|
||||
var rectHeight = Math.Min((bottom - top + 3) & ~3, height - top);
|
||||
if (rectWidth <= 0 || rectHeight <= 0)
|
||||
return false;
|
||||
|
||||
rect = new PixelRect(left, top, rectWidth, rectHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void RenderVisible(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
PixelRect rect)
|
||||
{
|
||||
using ComputeContext context = _device.CreateComputeContext();
|
||||
RecordRenderStage(in context, source, output, rect, width, height);
|
||||
}
|
||||
|
||||
private void RecordFullPipeline(
|
||||
in ComputeContext context,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
_structureKey = null;
|
||||
var derived = Derive(in parameters);
|
||||
RecordLuminanceStage(in context, source, width, height);
|
||||
RecordFilterStage(in context, in derived);
|
||||
RecordRenderStage(in context, source, output, new PixelRect(0, 0, width, height), width, height);
|
||||
}
|
||||
|
||||
private void RecordHashStage(in ComputeContext context, ReadWriteTexture2D<Bgra32, Float4> source, int width, int height)
|
||||
{
|
||||
context.For(1, new InitScratchShader(_scratch));
|
||||
context.Barrier(_scratch);
|
||||
context.For(width, height, new HashBoundsShader(source, _scratch, width, height));
|
||||
context.Barrier(_scratch);
|
||||
}
|
||||
|
||||
private void RecordLuminanceStage(in ComputeContext context, ReadWriteTexture2D<Bgra32, Float4> source, int width, int height)
|
||||
{
|
||||
context.For(width, height, new LuminanceShader(source, _gaussian!, width, height));
|
||||
context.Barrier(_gaussian!);
|
||||
}
|
||||
|
||||
private void RecordFilterStage(in ComputeContext context, in DerivedValues derived)
|
||||
{
|
||||
var gaussian = _gaussian!;
|
||||
var work = _work!;
|
||||
var accumulation = _accumulation!;
|
||||
var depth = _depth;
|
||||
|
||||
for (var level = 1; level < depth; level++)
|
||||
{
|
||||
context.For(_levelWidths[level], _levelHeights[level], new DownsampleShader(
|
||||
gaussian,
|
||||
_levelOffsets[level - 1], _levelWidths[level - 1], _levelHeights[level - 1],
|
||||
_levelOffsets[level], _levelWidths[level], _levelHeights[level]));
|
||||
context.Barrier(gaussian);
|
||||
}
|
||||
|
||||
for (var level = 0; level < depth - 1; level++)
|
||||
context.For(_levelWidths[level], _levelHeights[level], new FillLevelShader(
|
||||
accumulation, _levelOffsets[level], _levelWidths[level], _levelHeights[level]));
|
||||
context.Barrier(accumulation);
|
||||
|
||||
var spacing = 1f / (derived.SampleCount - 1);
|
||||
var inverseSpacing = derived.SampleCount - 1f;
|
||||
for (var sample = 0; sample < derived.SampleCount; sample++)
|
||||
{
|
||||
var gamma = sample * spacing;
|
||||
context.For(_levelWidths[0], _levelHeights[0], new RemapShader(
|
||||
gaussian, work, _levelWidths[0], _levelHeights[0],
|
||||
gamma, derived.Sigma, derived.AlphaExponent, derived.Beta));
|
||||
context.Barrier(work);
|
||||
for (var level = 1; level < depth; level++)
|
||||
{
|
||||
context.For(_levelWidths[level], _levelHeights[level], new DownsampleShader(
|
||||
work,
|
||||
_levelOffsets[level - 1], _levelWidths[level - 1], _levelHeights[level - 1],
|
||||
_levelOffsets[level], _levelWidths[level], _levelHeights[level]));
|
||||
context.Barrier(work);
|
||||
}
|
||||
for (var level = 0; level < depth - 1; level++)
|
||||
context.For(_levelWidths[level], _levelHeights[level], new AccumulateShader(
|
||||
accumulation, work, gaussian,
|
||||
_levelOffsets[level], _levelWidths[level], _levelHeights[level],
|
||||
_levelOffsets[level + 1], _levelWidths[level + 1], _levelHeights[level + 1],
|
||||
gamma, inverseSpacing));
|
||||
context.Barrier(accumulation);
|
||||
context.Barrier(work);
|
||||
}
|
||||
|
||||
var residual = depth - 1;
|
||||
context.For(_levelWidths[residual], _levelHeights[residual], new CopyLevelShader(
|
||||
gaussian, work, _levelOffsets[residual], _levelOffsets[residual], _levelWidths[residual], _levelHeights[residual]));
|
||||
context.Barrier(work);
|
||||
for (var level = depth - 2; level >= 0; level--)
|
||||
{
|
||||
context.For(_levelWidths[level], _levelHeights[level], new CollapseShader(
|
||||
work, accumulation,
|
||||
_levelOffsets[level], _levelWidths[level], _levelHeights[level],
|
||||
_levelOffsets[level + 1], _levelWidths[level + 1], _levelHeights[level + 1]));
|
||||
context.Barrier(work);
|
||||
}
|
||||
}
|
||||
|
||||
private void RecordRenderStage(
|
||||
in ComputeContext context,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
PixelRect rect,
|
||||
int width,
|
||||
int height)
|
||||
{
|
||||
context.For(rect.Width, rect.Height, new RenderShader(
|
||||
_work!, source, output,
|
||||
rect.X, rect.Y, rect.Width, rect.Height, width, height));
|
||||
}
|
||||
|
||||
private static DerivedValues Derive(in Parameters parameters)
|
||||
{
|
||||
var settings = LaplacianRemappingSettings.GetQuality(parameters.Quality);
|
||||
return new DerivedValues(
|
||||
LaplacianRemappingSettings.GetDetailAlpha(parameters.Detail),
|
||||
LaplacianRemappingSettings.GetToneBeta(parameters.Tone),
|
||||
LaplacianRemappingSettings.GetSigma(parameters.Threshold),
|
||||
settings.SampleCount);
|
||||
}
|
||||
|
||||
private void EnsureGrid(int width, int height)
|
||||
{
|
||||
if (_width == width && _height == height)
|
||||
return;
|
||||
|
||||
DisposeGridBuffers();
|
||||
var depth = LaplacianRemappingSettings.GetPyramidDepth(width, height);
|
||||
var levelWidth = width;
|
||||
var levelHeight = height;
|
||||
var total = 0;
|
||||
for (var level = 0; level < depth; level++)
|
||||
{
|
||||
_levelOffsets[level] = total;
|
||||
_levelWidths[level] = levelWidth;
|
||||
_levelHeights[level] = levelHeight;
|
||||
total = checked(total + levelWidth * levelHeight);
|
||||
levelWidth = (levelWidth + 1) / 2;
|
||||
levelHeight = (levelHeight + 1) / 2;
|
||||
}
|
||||
_gaussian = _device.AllocateReadWriteBuffer<float>(total);
|
||||
_work = _device.AllocateReadWriteBuffer<float>(total);
|
||||
_accumulation = _device.AllocateReadWriteBuffer<float>(total);
|
||||
_width = width;
|
||||
_height = height;
|
||||
_depth = depth;
|
||||
}
|
||||
|
||||
private void EnsurePackedTextures(int width, int height)
|
||||
{
|
||||
if (_packedWidth == width && _packedHeight == height)
|
||||
return;
|
||||
|
||||
_packedSource?.Dispose();
|
||||
_packedOutput?.Dispose();
|
||||
_packedSource = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
_packedOutput = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
_packedWidth = width;
|
||||
_packedHeight = height;
|
||||
}
|
||||
|
||||
private void DisposeGridBuffers()
|
||||
{
|
||||
_gaussian?.Dispose();
|
||||
_work?.Dispose();
|
||||
_accumulation?.Dispose();
|
||||
_gaussian = null;
|
||||
_work = null;
|
||||
_accumulation = null;
|
||||
_structureKey = null;
|
||||
_cachedMinX = 0;
|
||||
_cachedMinY = 0;
|
||||
_cachedMaxX = -1;
|
||||
_cachedMaxY = -1;
|
||||
_width = 0;
|
||||
_height = 0;
|
||||
_depth = 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DisposeGridBuffers();
|
||||
_packedSource?.Dispose();
|
||||
_packedOutput?.Dispose();
|
||||
_packedSource = null;
|
||||
_packedOutput = null;
|
||||
_packedWidth = 0;
|
||||
_packedHeight = 0;
|
||||
_scratchReadBack.Dispose();
|
||||
_scratch.Dispose();
|
||||
}
|
||||
|
||||
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
|
||||
|
||||
private readonly record struct StructureKey(
|
||||
int PixelHashSum,
|
||||
int PixelHashMix,
|
||||
int Width,
|
||||
int Height,
|
||||
LaplacianRemappingQuality Quality,
|
||||
float Detail,
|
||||
float Tone,
|
||||
float Threshold);
|
||||
|
||||
private readonly record struct DerivedValues(
|
||||
float AlphaExponent,
|
||||
float Beta,
|
||||
float Sigma,
|
||||
int SampleCount);
|
||||
|
||||
internal readonly record struct Parameters(
|
||||
LaplacianRemappingQuality Quality,
|
||||
float Detail,
|
||||
float Tone,
|
||||
float Threshold);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
public enum LaplacianRemappingQuality
|
||||
{
|
||||
[Display(Name = nameof(Texts.QualityBalanced), Description = nameof(Texts.QualityBalancedDescription), ResourceType = typeof(Texts))]
|
||||
Balanced,
|
||||
[Display(Name = nameof(Texts.QualityHigh), Description = nameof(Texts.QualityHighDescription), ResourceType = typeof(Texts))]
|
||||
High,
|
||||
[Display(Name = nameof(Texts.QualityUltra), Description = nameof(Texts.QualityUltraDescription), ResourceType = typeof(Texts))]
|
||||
Ultra,
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal static class LaplacianRemappingSettings
|
||||
{
|
||||
public const float MinimumDetailAlpha = 0.25f;
|
||||
public const float MaximumDetailAlpha = 4f;
|
||||
public const float MaximumToneBeta = 2.5f;
|
||||
public const float MinimumSigma = 0.01f;
|
||||
public const float MaximumSigma = 1f;
|
||||
public const float NoiseFloorLow = 0.01f;
|
||||
public const float NoiseFloorHigh = 0.02f;
|
||||
public const float LuminanceWeightR = 0.2126f;
|
||||
public const float LuminanceWeightG = 0.7152f;
|
||||
public const float LuminanceWeightB = 0.0722f;
|
||||
public const float KernelWeightCenter = 0.4f;
|
||||
public const float KernelWeightNear = 0.25f;
|
||||
public const float KernelWeightFar = 0.05f;
|
||||
public const int MinimumTopSize = 2;
|
||||
public const int MaximumPyramidDepth = 16;
|
||||
public const int MaximumCanvasSize = 8192;
|
||||
public const int MaximumPixelCount = 16777216;
|
||||
public const int ScratchLength = 8;
|
||||
public const int ScratchHashSum = 0;
|
||||
public const int ScratchHashMix = 1;
|
||||
public const int ScratchMinX = 2;
|
||||
public const int ScratchMinY = 3;
|
||||
public const int ScratchMaxX = 4;
|
||||
public const int ScratchMaxY = 5;
|
||||
|
||||
public static QualitySettings GetQuality(LaplacianRemappingQuality quality)
|
||||
=> quality switch
|
||||
{
|
||||
LaplacianRemappingQuality.Balanced => new QualitySettings(7),
|
||||
LaplacianRemappingQuality.Ultra => new QualitySettings(15),
|
||||
_ => new QualitySettings(11),
|
||||
};
|
||||
|
||||
public static int GetPyramidDepth(int width, int height)
|
||||
{
|
||||
var side = Math.Min(Math.Max(width, 1), Math.Max(height, 1));
|
||||
var depth = 1;
|
||||
while (side > MinimumTopSize && depth < MaximumPyramidDepth)
|
||||
{
|
||||
side = (side + 1) / 2;
|
||||
depth++;
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
public static float GetDetailAlpha(float detail)
|
||||
{
|
||||
var clamped = Math.Clamp(detail, -1f, 1f);
|
||||
return clamped >= 0f
|
||||
? 1f - clamped * (1f - MinimumDetailAlpha)
|
||||
: 1f - clamped * (MaximumDetailAlpha - 1f);
|
||||
}
|
||||
|
||||
public static float GetToneBeta(float tone)
|
||||
{
|
||||
var clamped = Math.Clamp(tone, -1f, 1f);
|
||||
return clamped >= 0f
|
||||
? 1f + clamped * (MaximumToneBeta - 1f)
|
||||
: 1f + clamped;
|
||||
}
|
||||
|
||||
public static float GetSigma(float threshold)
|
||||
=> Math.Clamp(threshold, MinimumSigma, MaximumSigma);
|
||||
|
||||
internal readonly record struct QualitySettings(int SampleCount);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Windows;
|
||||
using GitHubUpdateNotifier;
|
||||
using YukkuriMovieMaker.Plugin.Update;
|
||||
using Notifier = GitHubUpdateNotifier.GitHubUpdateNotifier;
|
||||
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal static class LaplacianRemappingUpdateNotifier
|
||||
{
|
||||
private const string Owner = "routersys";
|
||||
private const string Repository = "YMM4-LaplacianRemapping";
|
||||
private static int _started;
|
||||
|
||||
public static void EnsureCheckedOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) != 0)
|
||||
return;
|
||||
_ = RunAsync();
|
||||
}
|
||||
|
||||
private static async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new UpdateNotifierOptions
|
||||
{
|
||||
CurrentVersion = PluginVersion.FromAssemblyInformationalVersion(typeof(LaplacianRemappingUpdateNotifier)),
|
||||
IncludePrerelease = false,
|
||||
MessageFormatter = FormatMessage,
|
||||
NotificationHandler = ShowNotificationAsync,
|
||||
};
|
||||
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatMessage(UpdateInfo update)
|
||||
=> string.Format(Texts.UpdateAvailableMessage, update.TagName) + Environment.NewLine + update.ReleaseUrl;
|
||||
|
||||
private static Task ShowNotificationAsync(UpdateNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
var application = Application.Current;
|
||||
if (application is null)
|
||||
return Task.CompletedTask;
|
||||
return application.Dispatcher.InvokeAsync(() =>
|
||||
MessageBox.Show(notification.Message, Texts.LaplacianRemapping, MessageBoxButton.OK, MessageBoxImage.Information)).Task;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace LaplacianRemapping;
|
||||
|
||||
internal static class ShaderResourceUri
|
||||
{
|
||||
public static Uri Get(string shaderName) => new($"pack://application:,,,/LaplacianRemapping;component/Shaders/{shaderName}.cso", UriKind.Absolute);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
Texture2D SourceTexture : register(t0);
|
||||
SamplerState SourceSampler : register(s0);
|
||||
Texture2D ResultTexture : register(t1);
|
||||
SamplerState ResultSampler : 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 result = ResultTexture.SampleLevel(ResultSampler, uv1.xy, 0);
|
||||
result.rgb = min(result.rgb, result.a.xxx);
|
||||
return source + (result - source) * amount;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using YukkuriMovieMaker.Generator;
|
||||
|
||||
namespace LaplacianRemapping
|
||||
{
|
||||
[AutoGenLocalizer]
|
||||
partial class Texts
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
|
||||
LaplacianRemapping,,ローカルラプラシアン,Local Laplacian,局部拉普拉斯,局部拉普拉斯,로컬 라플라시안,Laplaciano local,لابلاسيان محلي,Laplacian Lokal
|
||||
BasicGroup,,基本,Basic,基本,基本,기본,Básico,أساسي,Dasar
|
||||
AdjustGroup,,調整,Adjustment,调整,調整,조정,Ajuste,الضبط,Penyesuaian
|
||||
Amount,,強さ,Amount,强度,強度,강도,Intensidad,الشدة,Intensitas
|
||||
AmountDescription,,効果の合成量です,Blend amount of the effect over the source,效果与源图像的混合量,效果與源圖像的混合量,효과의 합성량입니다,Cantidad de mezcla del efecto sobre la imagen,مقدار مزج التأثير فوق الصورة,Jumlah pencampuran efek di atas citra
|
||||
Quality,,品質,Quality,品质,品質,품질,Calidad,الجودة,Kualitas
|
||||
QualityDescription,,基準輝度のサンプル数を選びます。多いほど正確になります,Selects the number of reference luminance samples. More samples are more accurate,选择基准亮度的采样数。数量越多越精确,選擇基準亮度的取樣數。數量越多越精確,기준 휘도의 샘플 수를 선택합니다. 많을수록 정확해집니다,Selecciona el número de muestras de luminancia de referencia. Más muestras son más precisas,يحدد عدد عينات الإضاءة المرجعية. كلما زادت العينات زادت الدقة,Memilih jumlah sampel luminans referensi. Semakin banyak semakin akurat
|
||||
Detail,,ディテール,Detail,细节,細節,디테일,Detalle,التفاصيل,Detail
|
||||
DetailDescription,,しきい値未満の質感の増減です。正で強調し、負でエッジを保ったまま平滑化します,Boosts or reduces textures below the threshold. Positive values enhance and negative values smooth while preserving edges,增减低于阈值的质感。正值增强,负值在保留边缘的同时平滑,增減低於閾值的質感。正值增強,負值在保留邊緣的同時平滑,임계값 미만 질감의 증감입니다. 양수는 강조하고 음수는 에지를 유지한 채 평활화합니다,Aumenta o reduce las texturas por debajo del umbral. Los valores positivos realzan y los negativos suavizan conservando los bordes,يزيد أو يقلل الملمس دون العتبة. القيم الموجبة تعزز والسالبة تنعم مع الحفاظ على الحواف,Menambah atau mengurangi tekstur di bawah ambang. Nilai positif mempertegas dan nilai negatif menghaluskan sambil menjaga tepi
|
||||
Tone,,トーン,Tone,色调,色調,톤,Tono,الدرجة اللونية,Tona
|
||||
ToneDescription,,しきい値以上の明暗差の増減です。負で白飛びや黒潰れを圧縮し、正でコントラストを拡張します,Compresses or expands luminance differences above the threshold. Negative values recover highlights and shadows and positive values expand contrast,增减高于阈值的明暗差。负值压缩过曝与欠曝,正值扩展对比度,增減高於閾值的明暗差。負值壓縮過曝與欠曝,正值擴展對比度,임계값 이상 명암 차의 증감입니다. 음수는 하이라이트와 섀도를 압축하고 양수는 대비를 확장합니다,Comprime o expande las diferencias de luminancia por encima del umbral. Los valores negativos recuperan luces y sombras y los positivos expanden el contraste,يضغط أو يوسع فروق الإضاءة فوق العتبة. القيم السالبة تستعيد الإضاءات والظلال والموجبة توسع التباين,Menekan atau memperluas perbedaan luminans di atas ambang. Nilai negatif memulihkan sorotan dan bayangan dan nilai positif memperluas kontras
|
||||
Threshold,,しきい値,Threshold,阈值,閾值,임계값,Umbral,العتبة,Ambang
|
||||
ThresholdDescription,,ディテールとエッジを分ける輝度差のしきい値です,Luminance difference threshold that separates details from edges,区分细节与边缘的亮度差阈值,區分細節與邊緣的亮度差閾值,디테일과 에지를 구분하는 휘도 차 임계값입니다,Umbral de diferencia de luminancia que separa los detalles de los bordes,عتبة فرق الإضاءة التي تفصل التفاصيل عن الحواف,Ambang perbedaan luminans yang memisahkan detail dari tepi
|
||||
QualityBalanced,,標準,Balanced,标准,標準,표준,Estándar,قياسي,Standar
|
||||
QualityBalancedDescription,,サンプル数を抑えた設定です,Uses a reduced number of samples,减少采样数的设置,減少取樣數的設定,샘플 수를 줄인 설정입니다,Configuración con un número reducido de muestras,إعداد بعدد عينات مخفض,Pengaturan dengan jumlah sampel yang dikurangi
|
||||
QualityHigh,,高品質,High,高品质,高品質,고품질,Alta,عالية,Tinggi
|
||||
QualityHighDescription,,品質と処理量の基準設定です,The reference balance of quality and cost,品质与处理量的基准设置,品質與處理量的基準設定,품질과 처리량의 기준 설정입니다,Configuración de referencia entre calidad y coste,الإعداد المرجعي للتوازن بين الجودة والتكلفة,Pengaturan acuan antara kualitas dan beban proses
|
||||
QualityUltra,,最高品質,Ultra,最高品质,最高品質,최고 품질,Máxima,قصوى,Ultra
|
||||
QualityUltraDescription,,最大のサンプル数を使用します,Uses the largest number of samples,使用最大的采样数,使用最大的取樣數,최대 샘플 수를 사용합니다,Usa el mayor número de muestras,يستخدم أكبر عدد من العينات,Menggunakan jumlah sampel terbesar
|
||||
TagClarity,,明瞭度,Clarity,清晰度,清晰度,명료도,Claridad,الوضوح,Kejernihan
|
||||
TagTone,,トーン,Tone,色调,色調,톤,Tono,درجة لونية,Tona
|
||||
TagDetail,,質感,Texture,质感,質感,질감,Textura,ملمس,Tekstur
|
||||
UpdateAvailableMessage,,新しいバージョン {0} が公開されています。,A new version {0} is available.,新版本 {0} 已发布。,新版本 {0} 已發布。,새 버전 {0}이(가) 공개되었습니다.,La nueva versión {0} ya está disponible.,تم إصدار نسخة جديدة {0}.,Versi baru {0} telah dirilis.
|
||||
|
新しいイシューから参照
ユーザーをブロックする