ステップ数ごとに展開したシェーダーで描画を速くする

・ステップ数に合わせて展開したシェーダーを選んで使うよう変更-M
このコミットが含まれているのは:
routersys committed 2026-10-13 09:39:27 +09:00
1 親 1505b0e1c8
コミット 15fda80d2d
12ファイル変更
+248 -83

検索条件に一致するファイルはありません

+19 -12
ファイルの表示
@@ -144,18 +144,6 @@
</FxCompile>
</ItemDefinitionGroup>
<ItemGroup>
<FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
</FxCompile>
<FxCompile Include="SpectrumColorShiftLinearize.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
@@ -164,8 +152,27 @@
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="SpectrumColorShift.hlsl" />
<None Include="SpectrumColorShiftPhysical.hlsl" />
<None Include="Srgb.hlsli" />
</ItemGroup>
<ItemGroup>
<StepCount Include="8;12;16;20;24;28;32;36;40;44;48;52;56;60;64" />
</ItemGroup>
<Target Name="AddStepCountShaders" BeforeTargets="FxCompile">
<ItemGroup>
<FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShift%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysical%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
</ItemGroup>
</Target>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
+6 -6
ファイルの表示
@@ -15,17 +15,17 @@
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="SpectrumColorShift.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
<FxCompile Include="SpectrumColorShiftLinearize.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="SpectrumColorShift.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="SpectrumColorShiftPhysical.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="Srgb.hlsli">
<Filter>ヘッダー ファイル</Filter>
</None>
+36 -23
ファイルの表示
@@ -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);
+10 -22
ファイルの表示
@@ -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);
-1
ファイルの表示
@@ -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"));
+2 -2
ファイルの表示
@@ -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]
+48
ファイルの表示
@@ -0,0 +1,48 @@
using System.Numerics;
using YukkuriMovieMaker.Commons;
namespace SpectrumColorShift.Tests;
[Collection("Direct2D")]
public sealed class StepCountRenderingTests
{
public static readonly TheoryData<ShiftMode, bool> 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<int, int, Vector4> 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}");
}
}
}
}
+61
ファイルの表示
@@ -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(@"<StepCount Include=""(?<counts>[^""]+)""")]
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)}");
}
}
}
+2 -2
ファイルの表示
@@ -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);
+1 -3
ファイルの表示
@@ -61,9 +61,7 @@
</ItemGroup>
<ItemGroup>
<Resource Include="$(ShaderDirPath)SpectrumColorShift.cso" Link="Resources\Shader\SpectrumColorShift.cso" />
<Resource Include="$(ShaderDirPath)SpectrumColorShiftPhysical.cso" Link="Resources\Shader\SpectrumColorShiftPhysical.cso" />
<Resource Include="$(ShaderDirPath)SpectrumColorShiftLinearize.cso" Link="Resources\Shader\SpectrumColorShiftLinearize.cso" />
<Resource Include="$(ShaderDirPath)SpectrumColorShift*.cso" Link="Resources\Shader\%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
+7 -12
ファイルの表示
@@ -71,10 +71,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
[CustomEffect(2)]
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
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)
+56
ファイルの表示
@@ -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<int> 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<byte[]>[] _bytes = [.. Enumerable.Range(0, Length).Select(index => new Lazy<byte[]>(() => 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}"));
}
}