diff --git a/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj b/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj index 2253d57..a1f85a1 100644 --- a/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj +++ b/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj @@ -144,18 +144,6 @@ - - Pixel - Pixel - Pixel - Pixel - - - Pixel - Pixel - Pixel - Pixel - Pixel Pixel @@ -164,8 +152,27 @@ + + + + + + + + + Pixel + StepCount=%(StepCount.Identity) + $(OutDir)SpectrumColorShift%(StepCount.Identity).cso + + + Pixel + StepCount=%(StepCount.Identity) + $(OutDir)SpectrumColorShiftPhysical%(StepCount.Identity).cso + + + diff --git a/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj.filters b/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj.filters index f943c89..8c78b22 100644 --- a/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj.filters +++ b/SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj.filters @@ -15,17 +15,17 @@ - - ソース ファイル - - - ソース ファイル - ソース ファイル + + ソース ファイル + + + ソース ファイル + ヘッダー ファイル diff --git a/SpectrumColorShift.Shader/SpectrumColorShift.hlsl b/SpectrumColorShift.Shader/SpectrumColorShift.hlsl index f722c27..aced186 100644 --- a/SpectrumColorShift.Shader/SpectrumColorShift.hlsl +++ b/SpectrumColorShift.Shader/SpectrumColorShift.hlsl @@ -1,3 +1,7 @@ +#ifndef StepCount +#error StepCount must be defined by the build. +#endif + Texture2D SourceTexture : register(t0); SamplerState SourceSampler : register(s0); @@ -69,6 +73,29 @@ void Accumulate(float4 entry, float4 shifted, inout float3 color, inout float3 c coverage += entry.rgb * shifted.a; } +void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float3 coverage) +{ + float4 entry = samples[index]; + float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift); + Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage); +} + +void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float3 coverage) +{ + float4 entry = samples[index]; + float sine; + float cosine; + sincos(entry.w * rate, sine, cosine); + float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x); + Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage); +} + +void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float3 coverage) +{ + float4 entry = samples[index]; + Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage); +} + float4 Resolve(float3 color, float3 coverage) { float alpha = max(coverage.r, max(coverage.g, coverage.b)); @@ -102,39 +129,25 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition) float2 offsetStep = offset * pixelStep; float rate = shiftDistance / radius; - [loop] - for (int index = 0; index < steps; index++) - { - float4 entry = samples[index]; - float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift); - Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage); - } + [unroll] + for (int index = 0; index < StepCount; index++) + AccumulateRadial(index, uv, offsetStep, rate, color, coverage); } else if (mode == ModeRotational) { float rate = shiftDistance / radius; - [loop] - for (int index = 0; index < steps; index++) - { - float4 entry = samples[index]; - float sine; - float cosine; - sincos(entry.w * rate, sine, cosine); - float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x); - Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage); - } + [unroll] + for (int index = 0; index < StepCount; index++) + AccumulateRotational(index, uv, offset, pixelStep, rate, color, coverage); } else { float2 stride = shiftDistance * direction * pixelStep; - [loop] - for (int index = 0; index < steps; index++) - { - float4 entry = samples[index]; - Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage); - } + [unroll] + for (int index = 0; index < StepCount; index++) + AccumulateLinear(index, uv, stride, color, coverage); } return Resolve(color, coverage); diff --git a/SpectrumColorShift.Shader/SpectrumColorShiftPhysical.hlsl b/SpectrumColorShift.Shader/SpectrumColorShiftPhysical.hlsl index 7ae9e89..fce0fb1 100644 --- a/SpectrumColorShift.Shader/SpectrumColorShiftPhysical.hlsl +++ b/SpectrumColorShift.Shader/SpectrumColorShiftPhysical.hlsl @@ -1,3 +1,7 @@ +#ifndef StepCount +#error StepCount must be defined by the build. +#endif + #include "Srgb.hlsli" Texture2D LinearTexture : register(t1); @@ -5,7 +9,6 @@ SamplerState LinearSampler : register(s1); static const int MaxSteps = 64; static const int TableSize = 128; -static const int Unroll = 4; static const int ModeRadial = 2; static const int ModeRotational = 4; static const float MaxRadialShift = 0.5; @@ -137,40 +140,25 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition) float2 offsetStep = offset * pixelStep; float rate = shiftDistance / radius; - [loop] - for (int index = 0; index < steps; index += Unroll) - { + [unroll] + for (int index = 0; index < StepCount; index++) AccumulateRadial(index, uv, offsetStep, rate, color, alpha); - AccumulateRadial(index + 1, uv, offsetStep, rate, color, alpha); - AccumulateRadial(index + 2, uv, offsetStep, rate, color, alpha); - AccumulateRadial(index + 3, uv, offsetStep, rate, color, alpha); - } } else if (mode == ModeRotational) { float rate = shiftDistance / radius; - [loop] - for (int index = 0; index < steps; index += Unroll) - { + [unroll] + for (int index = 0; index < StepCount; index++) AccumulateRotational(index, uv, offset, pixelStep, rate, color, alpha); - AccumulateRotational(index + 1, uv, offset, pixelStep, rate, color, alpha); - AccumulateRotational(index + 2, uv, offset, pixelStep, rate, color, alpha); - AccumulateRotational(index + 3, uv, offset, pixelStep, rate, color, alpha); - } } else { float2 stride = shiftDistance * direction * pixelStep; - [loop] - for (int index = 0; index < steps; index += Unroll) - { + [unroll] + for (int index = 0; index < StepCount; index++) AccumulateLinear(index, uv, stride, color, alpha); - AccumulateLinear(index + 1, uv, stride, color, alpha); - AccumulateLinear(index + 2, uv, stride, color, alpha); - AccumulateLinear(index + 3, uv, stride, color, alpha); - } } return Resolve(color, alpha); diff --git a/SpectrumColorShift.Tests/SpectralShaderContractTests.cs b/SpectrumColorShift.Tests/SpectralShaderContractTests.cs index 092f792..2e5f67c 100644 --- a/SpectrumColorShift.Tests/SpectralShaderContractTests.cs +++ b/SpectrumColorShift.Tests/SpectralShaderContractTests.cs @@ -58,7 +58,6 @@ public sealed partial class SpectralShaderContractTests { Assert.Equal(Spectrum.MaxSteps, Constant("MaxSteps")); Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize")); - Assert.Equal(Spectrum.Unroll, Constant("Unroll")); Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial")); Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational")); Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift")); diff --git a/SpectrumColorShift.Tests/SpectralSpectrumTests.cs b/SpectrumColorShift.Tests/SpectralSpectrumTests.cs index 5e4bf01..bcc2bf7 100644 --- a/SpectrumColorShift.Tests/SpectralSpectrumTests.cs +++ b/SpectrumColorShift.Tests/SpectralSpectrumTests.cs @@ -335,10 +335,10 @@ public sealed class SpectralSpectrumTests [InlineData(33, 36)] [InlineData(61, 64)] [InlineData(int.MaxValue, 64)] - public void ThePaddedStepsFillWholeUnrolledIterations(int requested, int expected) + public void ThePaddedStepsAreWholeMultiplesOfTheStepQuantum(int requested, int expected) { Assert.Equal(expected, Spectrum.Padded(requested)); - Assert.Equal(0, Spectrum.Padded(requested) % Spectrum.Unroll); + Assert.Equal(0, Spectrum.Padded(requested) % Spectrum.StepQuantum); } [Theory] diff --git a/SpectrumColorShift.Tests/StepCountRenderingTests.cs b/SpectrumColorShift.Tests/StepCountRenderingTests.cs new file mode 100644 index 0000000..70fdcae --- /dev/null +++ b/SpectrumColorShift.Tests/StepCountRenderingTests.cs @@ -0,0 +1,48 @@ +using System.Numerics; +using YukkuriMovieMaker.Commons; + +namespace SpectrumColorShift.Tests; + +[Collection("Direct2D")] +public sealed class StepCountRenderingTests +{ + public static readonly TheoryData Cases = [.. from physical in new[] { false, true } from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } select (mode, physical)]; + + static Bgra Gradient(int x, int y) + { + if ((x / 6 + y / 6) % 4 == 3) + return Bgra.Transparent; + + return new Bgra((byte)(30 + x * 4 % 220), (byte)(20 + y * 7 % 230), (byte)(250 - (x + y) * 3 % 200), (byte)(120 + (x * 5 + y * 9) % 136)); + } + + [Theory] + [MemberData(nameof(Cases))] + public void EveryStepCountMatchesTheCpuRendering(ShiftMode mode, bool physical) + { + using var devices = new GraphicsDevices(); + using var context = devices.CreateContext(); + using var source = new SourceImage(context, 48, 32, Gradient); + using var effect = new SpectrumColorShiftCustomEffect(context); + effect.SetInput(0, source.Bitmap, true); + using var output = effect.Output; + + foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1)) + { + var settings = new ShiftSettings(Mode: mode, Distance: 16f, Angle: 30f, Steps: steps, Physical: physical); + settings.Apply(effect); + Func reference = physical ? new SpectralReferenceRenderer(source, settings).Pixel : new ShiftReferenceRenderer(source, settings).Pixel; + + var rendering = Rendering.Capture(context, output); + + foreach (var (x, y) in rendering.Coordinates()) + { + var expected = reference(x, y) * 255f; + var actual = rendering[x, y]; + Assert.True( + Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f, + $"steps {steps}, ({x}, {y}) expected {expected}, actual {actual}"); + } + } + } +} diff --git a/SpectrumColorShift.Tests/StepShadersTests.cs b/SpectrumColorShift.Tests/StepShadersTests.cs new file mode 100644 index 0000000..32c1730 --- /dev/null +++ b/SpectrumColorShift.Tests/StepShadersTests.cs @@ -0,0 +1,61 @@ +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace SpectrumColorShift.Tests; + +public sealed partial class StepShadersTests +{ + static string Project { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShift.Shader.vcxproj")); + + static string Here([CallerFilePath] string path = "") => path; + + [GeneratedRegex(@"[^""]+)""")] + private static partial Regex CountsPattern(); + + [Fact] + public void TheCountsCoverTheWholeRangeInWholeQuanta() + { + Assert.Equal(0, Spectrum.MinSteps % Spectrum.StepQuantum); + Assert.Equal(0, Spectrum.MaxSteps % Spectrum.StepQuantum); + Assert.Equal(Enumerable.Range(0, (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1).Select(index => Spectrum.MinSteps + index * Spectrum.StepQuantum), StepShaders.Counts); + } + + [Fact] + public void TheShaderProjectCompilesExactlyTheseCounts() + { + var compiled = CountsPattern().Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture)); + + Assert.Equal(StepShaders.Counts, compiled); + } + + [Fact] + public void EveryCountHasItsOwnShaderInEachFamily() + { + var ids = StepShaders.Counts.SelectMany(count => new[] { StepShaders.Select(false, count), StepShaders.Select(true, count) }).ToList(); + + Assert.Equal(2 * StepShaders.Counts.Count(), ids.Distinct().Count()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void StepsShareTheShaderOfTheirPaddedCount(bool physical) + { + foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1)) + Assert.Equal(StepShaders.Select(physical, Spectrum.Padded(steps)), StepShaders.Select(physical, steps)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void EveryCountIsShippedAsAResource(bool physical) + { + foreach (var count in StepShaders.Counts) + { + var bytes = YukkuriMovieMaker.Commons.PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(StepShaders.ResourceName(physical, count))); + Assert.True(bytes.Length > 0, $"{StepShaders.ResourceName(physical, count)}"); + } + } +} diff --git a/SpectrumColorShift/Spectrum.cs b/SpectrumColorShift/Spectrum.cs index 3ddb158..cd40828 100644 --- a/SpectrumColorShift/Spectrum.cs +++ b/SpectrumColorShift/Spectrum.cs @@ -8,7 +8,7 @@ internal static class Spectrum public const int MaxSteps = 64; public const int DefaultSteps = 32; public const int EntriesPerStep = 2; - public const int Unroll = 4; + public const int StepQuantum = 4; public const int SpectralTableLength = MaxSteps * EntriesPerStep; public const float ShortestWavelength = 400f; public const float LongestWavelength = 700f; @@ -16,7 +16,7 @@ internal static class Spectrum public static int ClampSteps(int steps) => Math.Clamp(steps, MinSteps, MaxSteps); - public static int Padded(int steps) => (ClampSteps(steps) + Unroll - 1) / Unroll * Unroll; + public static int Padded(int steps) => (ClampSteps(steps) + StepQuantum - 1) / StepQuantum * StepQuantum; public static float ClampReference(float wavelength) => float.IsNaN(wavelength) ? DefaultReferenceWavelength : Math.Clamp(wavelength, ShortestWavelength, LongestWavelength); diff --git a/SpectrumColorShift/SpectrumColorShift.csproj b/SpectrumColorShift/SpectrumColorShift.csproj index ad2da52..d835c77 100644 --- a/SpectrumColorShift/SpectrumColorShift.csproj +++ b/SpectrumColorShift/SpectrumColorShift.csproj @@ -61,9 +61,7 @@ - - - + diff --git a/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs b/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs index 201560b..d04a6f4 100644 --- a/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs +++ b/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs @@ -71,10 +71,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas [CustomEffect(2)] internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase { - private const string PhysicalShaderName = "SpectrumColorShiftPhysical"; - - private static readonly Guid PhysicalShaderId = Guid.NewGuid(); - private ConstantBuffer _cb; private PhysicalConstantBuffer _physicalCb; private ShiftMode _mode = ShiftMode.Linear; @@ -85,7 +81,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas private bool _tableStale = true; private bool _spectralStale = true; private bool _physical; - private bool _physicalShaderApplied; + private Guid _shader = GUID_PixelShader; [CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)] public float Distance @@ -208,7 +204,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas } } - public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShift")) + public EffectImpl() : base(StepShaders.DefaultBytes) { _cb.Direction = Vector2.UnitX; _cb.Radius = 1f; @@ -220,9 +216,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph) { base.Initialize(effectContext, transformGraph); - - var bytes = PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(PhysicalShaderName)); - effectContext.LoadPixelShader(PhysicalShaderId, bytes, bytes.Length); + StepShaders.Load(effectContext); } protected override void UpdateConstants() @@ -234,10 +228,11 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas { _cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius); - if (_physical != _physicalShaderApplied) + var shader = StepShaders.Select(_physical, _steps); + if (shader != _shader) { - drawInformation.SetPixelShader(_physical ? PhysicalShaderId : GUID_PixelShader, PixelOptions.None); - _physicalShaderApplied = _physical; + drawInformation.SetPixelShader(shader, PixelOptions.None); + _shader = shader; } if (_physical) diff --git a/SpectrumColorShift/StepShaders.cs b/SpectrumColorShift/StepShaders.cs new file mode 100644 index 0000000..bddc2f3 --- /dev/null +++ b/SpectrumColorShift/StepShaders.cs @@ -0,0 +1,56 @@ +using Vortice.Direct2D1; +using YukkuriMovieMaker.Commons; + +namespace SpectrumColorShift; + +internal static class StepShaders +{ + private const string LegacyName = "SpectrumColorShift"; + private const string PhysicalName = "SpectrumColorShiftPhysical"; + + private static readonly Variants Legacy = new(LegacyName); + private static readonly Variants Physical = new(PhysicalName); + + public static IEnumerable Counts => Enumerable.Range(0, Variants.Length).Select(CountAt); + + public static byte[] DefaultBytes => Legacy.Bytes(Spectrum.DefaultSteps); + + public static string ResourceName(bool physical, int count) => (physical ? Physical : Legacy).ResourceName(count); + + public static Guid Select(bool physical, int steps) => (physical ? Physical : Legacy).Id(steps); + + public static void Load(ID2D1EffectContext effectContext) + { + Legacy.Load(effectContext); + Physical.Load(effectContext); + } + + private static int CountAt(int index) => Spectrum.MinSteps + index * Spectrum.StepQuantum; + + private sealed class Variants(string name) + { + public static int Length { get; } = (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1; + + private readonly Guid[] _ids = [.. Enumerable.Range(0, Length).Select(_ => Guid.NewGuid())]; + private readonly Lazy[] _bytes = [.. Enumerable.Range(0, Length).Select(index => new Lazy(() => Read(name, CountAt(index))))]; + + public string ResourceName(int count) => $"{name}{count}"; + + public Guid Id(int steps) => _ids[IndexOf(steps)]; + + public byte[] Bytes(int steps) => _bytes[IndexOf(steps)].Value; + + public void Load(ID2D1EffectContext effectContext) + { + for (var index = 0; index < Length; index++) + { + var bytes = _bytes[index].Value; + effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length); + } + } + + private static int IndexOf(int steps) => (Spectrum.Padded(steps) - Spectrum.MinSteps) / Spectrum.StepQuantum; + + private static byte[] Read(string name, int count) => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get($"{name}{count}")); + } +}