色の計算の方式を選ぶ物理ベースを追加する

・映像の色から推定したスペクトルを動かす「物理ベース」を追加-A
このコミットが含まれているのは:
routersys committed 2026-10-12 20:39:18 +09:00
1 親 ee2a0c9120
コミット a1150d0ee8
11ファイル変更
+1102 -8

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

+71
ファイルの表示
@@ -44,6 +44,50 @@ internal static class HarnessCases
yield return ("reference-650", Create(effect => effect.ReferenceWavelength.Values[0].Value = 650), [0]);
yield return ("steps-8", Create(effect => effect.Steps = 8), [0]);
yield return ("strength-50", Create(effect => effect.Strength.Values[0].Value = 50), [0]);
yield return ("physical", Create(effect => effect.Physical = true), [0]);
yield return ("physical-distance-24", Create(effect =>
{
effect.Physical = true;
effect.Distance.Values[0].Value = 24;
}), [0]);
yield return ("physical-distance-100-steps-64", Create(effect =>
{
effect.Physical = true;
effect.Distance.Values[0].Value = 100;
effect.Steps = 64;
}), [0]);
yield return ("physical-radial-24", Create(effect =>
{
effect.Physical = true;
effect.Mode = ShiftMode.Radial;
effect.Distance.Values[0].Value = 24;
}), [0]);
yield return ("physical-rotational-24", Create(effect =>
{
effect.Physical = true;
effect.Mode = ShiftMode.Rotational;
effect.Distance.Values[0].Value = 24;
}), [0]);
yield return ("physical-prism", Create(effect =>
{
effect.Physical = true;
effect.Dispersion = DispersionLaw.Prism;
}), [0]);
yield return ("physical-reference-450", Create(effect =>
{
effect.Physical = true;
effect.ReferenceWavelength.Values[0].Value = 450;
}), [0]);
yield return ("physical-steps-8", Create(effect =>
{
effect.Physical = true;
effect.Steps = 8;
}), [0]);
yield return ("physical-strength-50", Create(effect =>
{
effect.Physical = true;
effect.Strength.Values[0].Value = 50;
}), [0]);
}
public static IEnumerable<(string Name, Func<SpectrumColorShiftEffect> Create, Action<SpectrumColorShiftEffect> Change, int Frame)> Transitions()
@@ -60,6 +104,9 @@ internal static class HarnessCases
yield return ("reference-550-to-450", () => Create(), effect => effect.ReferenceWavelength.Values[0].Value = 450, 0);
yield return ("steps-32-to-8", () => Create(), effect => effect.Steps = 8, 0);
yield return ("steps-8-to-64", () => Create(effect => effect.Steps = 8), effect => effect.Steps = 64, 0);
yield return ("physical-off-to-on", () => Create(), effect => effect.Physical = true, 0);
yield return ("physical-on-to-off", () => Create(effect => effect.Physical = true), effect => effect.Physical = false, 0);
yield return ("physical-steps-32-to-8", () => Create(effect => effect.Physical = true), effect => effect.Steps = 8, 0);
}
public static IEnumerable<(string Name, SpectrumColorShiftEffect Effect)> Benchmarks()
@@ -76,6 +123,30 @@ internal static class HarnessCases
effect.Mode = ShiftMode.Rotational;
effect.Distance.Values[0].Value = 24;
}));
yield return ("physical", Create(effect => effect.Physical = true));
yield return ("physical-steps-64", Create(effect =>
{
effect.Physical = true;
effect.Steps = 64;
}));
yield return ("physical-distance-48-steps-64", Create(effect =>
{
effect.Physical = true;
effect.Distance.Values[0].Value = 48;
effect.Steps = 64;
}));
yield return ("physical-radial-24", Create(effect =>
{
effect.Physical = true;
effect.Mode = ShiftMode.Radial;
effect.Distance.Values[0].Value = 24;
}));
yield return ("physical-rotational-24", Create(effect =>
{
effect.Physical = true;
effect.Mode = ShiftMode.Rotational;
effect.Distance.Values[0].Value = 24;
}));
}
static SpectrumColorShiftEffect Create(Action<SpectrumColorShiftEffect>? configure = null)
+63
ファイルの表示
@@ -115,6 +115,69 @@
0
],
"hash": "C2D79B67A9585C913BFBB67E70038229CC7D9596CAB67FFD366FAA0C7BCF5F2D"
},
{
"name": "physical",
"frames": [
0
],
"hash": "16D9D6B646BCF4AFA1B3C6D959487EBA73257EB967478A24560CC0A7156A3BB9"
},
{
"name": "physical-distance-24",
"frames": [
0
],
"hash": "DAE1580D442344C99B8492735767A627DD7F61CA41F72FF655BD996D8F10518B"
},
{
"name": "physical-distance-100-steps-64",
"frames": [
0
],
"hash": "E67EAB5E79A39DD2A148E88699749B87791A446E9EBA60552DFD1899F923B39C"
},
{
"name": "physical-radial-24",
"frames": [
0
],
"hash": "AECA3F2441B29DF59BC63142B34F6A6E9F1BC59F7FD3599D4EA947AE34C392DC"
},
{
"name": "physical-rotational-24",
"frames": [
0
],
"hash": "B9ECB23D9F4AC9BD4D720331FAB459BBEDF2CC9137BE2AB4E2830955C33D6A75"
},
{
"name": "physical-prism",
"frames": [
0
],
"hash": "17C539709E188E6DECF8E0DB4C1B0974CC118F5D063845CE9AE863BE51464482"
},
{
"name": "physical-reference-450",
"frames": [
0
],
"hash": "0B0D9C03EA35F2F301574FEE3EA68828FF7689A78FAEC216D3BC27B0135D33CE"
},
{
"name": "physical-steps-8",
"frames": [
0
],
"hash": "F5507D6B98A2D4AE9622DE0F478B5CC28BA7C78A29DB9DA2504658E17B5BDFDF"
},
{
"name": "physical-strength-50",
"frames": [
0
],
"hash": "0EE7E79190F70A7B2CC0D24C89512E8ACF4E4C135751E187876B18D80EC0BC44"
}
]
}
+1
ファイルの表示
@@ -46,6 +46,7 @@ public sealed class AllocationTests
impl.Dispersion = step & 1;
impl.ReferenceWavelength = 400f + step % 300;
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
impl.Physical = step & 1;
});
Assert.Equal(0, allocated);
+107
ファイルの表示
@@ -0,0 +1,107 @@
using System.Numerics;
namespace SpectrumColorShift.Tests;
internal sealed class SpectralReferenceRenderer
{
readonly SourceImage source;
readonly ShiftSettings settings;
readonly Vector4[] table = new Vector4[Spectrum.SpectralTableLength];
readonly Vector2 direction;
readonly Vector2 center;
readonly float radius;
readonly int steps;
public SpectralReferenceRenderer(SourceImage source, ShiftSettings settings)
{
this.source = source;
this.settings = settings;
steps = Spectrum.ClampSteps(settings.Steps);
Spectrum.FillSpectral(table, steps, settings.ReferenceWavelength, settings.Dispersion);
var radians = settings.Angle * MathF.PI / 180f;
direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
var rect = new Vortice.RawRect(0, 0, source.Width, source.Height);
center = ShiftGeometry.Center(rect, settings.Center);
radius = ShiftGeometry.Radius(rect, center);
}
public Vector4 Pixel(int x, int y)
{
var position = new Vector2(x + 0.5f, y + 0.5f);
var original = Covered(position);
if (settings.Distance == 0f || settings.Strength <= 0f)
return original;
var (color, alpha) = Accumulated(position);
var positive = Vector3.Max(color, Vector3.Zero);
var resolved = Math.Clamp(Math.Max(alpha, Math.Max(positive.X, Math.Max(positive.Y, positive.Z))), 0f, 1f);
var result = new Vector4(Vector3.SquareRoot(Vector3.Min(positive, new Vector3(resolved)) * resolved), resolved);
return Vector4.Lerp(original, result, Math.Clamp(settings.Strength, 0f, 1f));
}
public (Vector3 Color, float Alpha) Accumulated(Vector2 position)
{
var color = Vector3.Zero;
var alpha = 0f;
for (var index = 0; index < steps; index++)
{
var gain = table[index * Spectrum.EntriesPerStep];
var basis = table[index * Spectrum.EntriesPerStep + 1];
var target = ShiftReference.SamplePosition(settings.Mode, position, basis.W, settings.Distance, direction, center, radius);
var lit = Linear(target);
color += new Vector3(gain.X, gain.Y, gain.Z) * Vector3.Dot(new Vector3(basis.X, basis.Y, basis.Z), new Vector3(lit.X, lit.Y, lit.Z));
alpha += gain.W * lit.W;
}
return (color, alpha);
}
Vector4 Linear(Vector2 target)
{
var (raw, coverage) = Sample(target);
if (raw.W <= 0f)
return Vector4.Zero;
var premultiplied = new Vector3(raw.X, raw.Y, raw.Z);
return new Vector4(premultiplied * premultiplied / raw.W, raw.W) * coverage;
}
Vector4 Covered(Vector2 target)
{
var (raw, coverage) = Sample(target);
return raw * coverage;
}
(Vector4 Raw, float Coverage) Sample(Vector2 target)
{
var size = new Vector2(source.Width, source.Height);
var clamped = Vector2.Clamp(target, new Vector2(0.5f), size - new Vector2(0.5f));
var edge = Vector2.Min(target, size - target) + new Vector2(0.5f);
var coverage = Vector2.Clamp(edge, Vector2.Zero, Vector2.One);
return (Bilinear(clamped), coverage.X * coverage.Y);
}
Vector4 Bilinear(Vector2 position)
{
var shifted = position - new Vector2(0.5f);
var x = (int)MathF.Floor(shifted.X);
var y = (int)MathF.Floor(shifted.Y);
var fraction = new Vector2(shifted.X - x, shifted.Y - y);
return Vector4.Lerp(
Vector4.Lerp(Texel(x, y), Texel(x + 1, y), fraction.X),
Vector4.Lerp(Texel(x, y + 1), Texel(x + 1, y + 1), fraction.X),
fraction.Y);
}
Vector4 Texel(int x, int y)
{
var pixel = source[Math.Clamp(x, 0, source.Width - 1), Math.Clamp(y, 0, source.Height - 1)];
return new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f;
}
}
+672
ファイルの表示
@@ -0,0 +1,672 @@
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace SpectrumColorShift.Tests;
[Collection("Direct2D")]
public sealed class SpectralRenderingTests
{
const int Seam = 32;
static ShiftSettings Settings(
ShiftMode Mode = ShiftMode.Linear,
float Distance = 8f,
float Angle = 0f,
Vector2 Center = default,
float Strength = 1f,
DispersionLaw Dispersion = DispersionLaw.Grating,
float ReferenceWavelength = 550f,
int Steps = 32)
=> new(Mode, Distance, Angle, Center, Strength, Dispersion, ReferenceWavelength, Steps, true);
static Bgra HalfAndHalf(int x, int y) => x < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
static Bgra TopAndBottom(int x, int y) => y < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
static Bgra Stripes(int x, int y) => Math.Abs(x + 0.5 - 64) is >= 30 and < 34 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
static Bgra Dot(int x, int y) => Math.Abs(x + 0.5 - 104) < 3 && Math.Abs(y + 0.5 - 64) < 3 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
static Bgra Textured(int x, int y)
{
if ((x / 8 + y / 8) % 5 == 4)
return Bgra.Transparent;
return new Bgra((byte)(40 + x * 3 % 200), (byte)(30 + y * 5 % 210), (byte)(255 - (x + y) * 2 % 220), (byte)(110 + (x * 7 + y * 11) % 146));
}
static Bgra PointSymmetric(int x, int y, int mirroredX, int mirroredY)
{
var value = Math.Min(x * 3 + y * 5, mirroredX * 3 + mirroredY * 5);
return Bgra.Opaque((byte)(40 + value * 7 % 200), (byte)(30 + value * 11 % 210), (byte)(255 - value * 13 % 220));
}
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
{
using var effect = new SpectrumColorShiftCustomEffect(devices);
effect.SetInput(0, source.Bitmap, true);
settings.Apply(effect);
using var output = effect.Output;
return Rendering.Capture(devices, output);
}
static bool WithinRounding(Bgra expected, Bgra actual, int tolerance = 1)
=> Math.Abs(expected.Blue - actual.Blue) <= tolerance && Math.Abs(expected.Green - actual.Green) <= tolerance && Math.Abs(expected.Red - actual.Red) <= tolerance && Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
static double DistanceToBorder(SourceImage source, int x, int y)
=> Math.Min(Math.Min(x, source.Width - 1 - x), Math.Min(y, source.Height - 1 - y));
static double Crossing(Func<int, byte> value, int from, int to)
{
for (var index = from; index < to; index++)
{
double a = value(index);
double b = value(index + 1);
if (a >= 127.5 && b < 127.5)
return index + 0.5 + (a - 127.5) / (a - b);
}
return double.NaN;
}
static double EdgeWidth(Func<int, byte> value, int from, int to)
{
double high = double.NaN;
double low = double.NaN;
for (var index = from; index < to; index++)
{
double a = value(index);
double b = value(index + 1);
if (double.IsNaN(high) && a >= 230 && b < 230)
high = index + 0.5 + (a - 230) / (a - b);
if (double.IsNaN(low) && a >= 25 && b < 25)
low = index + 0.5 + (a - 25) / (a - b);
}
return low - high;
}
static Func<int, byte> ExpectedProfile(ShiftSettings settings, int channel, float axisDirection)
{
var table = new Vector4[Spectrum.SpectralTableLength];
Spectrum.FillSpectral(table, settings.Steps, settings.ReferenceWavelength, settings.Dispersion);
var steps = Spectrum.ClampSteps(settings.Steps);
return index =>
{
var sum = 0d;
for (var step = 0; step < steps; step++)
{
var gain = table[step * Spectrum.EntriesPerStep];
var basis = table[step * Spectrum.EntriesPerStep + 1];
var position = index + 0.5 - basis.W * settings.Distance * axisDirection;
var value = Math.Clamp(Seam + 0.5 - position, 0d, 1d);
sum += (channel switch { 0 => gain.X, 1 => gain.Y, _ => gain.Z }) * (basis.X + basis.Y + basis.Z) * value * value;
}
return (byte)Math.Round(Math.Sqrt(Math.Clamp(sum, 0d, 1d)) * 255d);
};
}
static Func<int, byte> Channel(Rendering rendering, int channel, Func<int, (int X, int Y)> position)
=> index =>
{
var (x, y) = position(index);
var pixel = rendering[x, y];
return channel switch { 0 => pixel.Red, 1 => pixel.Green, _ => pixel.Blue };
};
static int PeakAt(Rendering rendering, int channel, int from, int to, Func<int, (int X, int Y)> position)
{
var value = Channel(rendering, channel, position);
return Enumerable.Range(from, to - from + 1).MaxBy(index => value(index));
}
public static readonly TheoryData<ShiftMode> Modes = new() { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational };
[Theory]
[MemberData(nameof(Modes))]
public void WithoutADistanceTheImagePassesThroughUntouched(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 0f, Center: new Vector2(9f, -5f)));
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
}
[Theory]
[MemberData(nameof(Modes))]
public void WithoutStrengthTheImageIsUntouchedAndTheSpillStaysTransparent(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Strength: 0f));
Assert.True(rendering.Left < 0 && rendering.Top < 0);
Assert.All(rendering.Coordinates(), point => Assert.Equal(source.Contains(point.X, point.Y) ? source[point.X, point.Y] : Bgra.Transparent, rendering[point.X, point.Y]));
}
[Theory]
[InlineData(ShiftMode.Linear, DispersionLaw.Grating, 8)]
[InlineData(ShiftMode.Linear, DispersionLaw.Prism, 33)]
[InlineData(ShiftMode.Radial, DispersionLaw.Grating, 32)]
[InlineData(ShiftMode.Radial, DispersionLaw.Prism, 64)]
[InlineData(ShiftMode.Rotational, DispersionLaw.Grating, 17)]
[InlineData(ShiftMode.Rotational, DispersionLaw.Prism, 32)]
public void AUniformImageKeepsItsColorInTheInterior(ShiftMode mode, DispersionLaw law, int steps)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
var color = new Bgra(200, 90, 30, 255);
using var source = SourceImage.Solid(context, 96, 96, color);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Dispersion: law, Steps: steps, ReferenceWavelength: 600f));
var checkedPixels = 0;
foreach (var (x, y) in rendering.Coordinates())
{
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
{
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
checkedPixels++;
}
}
Assert.True(checkedPixels > 3000, $"{checkedPixels}");
}
public static readonly TheoryData<ShiftMode, int> DarkLevels = [.. from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } from level in new[] { 1, 2, 3, 5, 8, 16, 40 } select (mode, level)];
[Theory]
[MemberData(nameof(DarkLevels))]
public void ADarkUniformImageKeepsItsColorInTheInterior(ShiftMode mode, int level)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
var color = Bgra.Opaque((byte)level, (byte)level, (byte)level);
using var source = SourceImage.Solid(context, 96, 96, color);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
foreach (var (x, y) in rendering.Coordinates())
{
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
}
}
[Theory]
[MemberData(nameof(Modes))]
public void ASemiTransparentUniformImageKeepsItsPremultipliedColor(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
var color = new Bgra(200, 90, 30, 128);
using var source = SourceImage.Solid(context, 96, 96, color);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
foreach (var (x, y) in rendering.Coordinates())
{
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
Assert.True(WithinRounding(color.Premultiplied(), rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
}
}
[Theory]
[InlineData(8f, 0f, DispersionLaw.Grating, 550f, 32)]
[InlineData(8f, 0f, DispersionLaw.Prism, 550f, 32)]
[InlineData(8f, 0f, DispersionLaw.Grating, 450f, 32)]
[InlineData(8f, 0f, DispersionLaw.Grating, 650f, 32)]
[InlineData(8f, 180f, DispersionLaw.Grating, 550f, 32)]
[InlineData(-8f, 0f, DispersionLaw.Grating, 550f, 32)]
[InlineData(16f, 0f, DispersionLaw.Grating, 550f, 64)]
[InlineData(6f, 0f, DispersionLaw.Prism, 500f, 16)]
public void TheEdgeOfEachChannelFollowsTheOneDimensionalModelAlongTheAngle(float distance, float angle, DispersionLaw law, float reference, int steps)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, ReferenceWavelength: reference, Steps: steps);
var direction = MathF.Cos(angle * MathF.PI / 180f);
var rendering = Render(context, source, settings);
for (var channel = 0; channel < 3; channel++)
{
var crossing = Crossing(Channel(rendering, channel, x => (x, 16)), 4, 58);
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
}
}
[Theory]
[InlineData(90f)]
[InlineData(-90f)]
public void AVerticalAngleMovesTheEdgesOfAHorizontalSeam(float angle)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 32, 64, TopAndBottom);
var settings = Settings(Distance: 8f, Angle: angle);
var direction = MathF.Sin(angle * MathF.PI / 180f);
var rendering = Render(context, source, settings);
for (var channel = 0; channel < 3; channel++)
{
var crossing = Crossing(Channel(rendering, channel, y => (16, y)), 4, 58);
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
}
}
[Fact]
public void BlueMovesAheadOfGreenAndRedAlongTheDirection()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
var rendering = Render(context, source, Settings());
var red = Crossing(Channel(rendering, 0, x => (x, 16)), 4, 58);
var green = Crossing(Channel(rendering, 1, x => (x, 16)), 4, 58);
var blue = Crossing(Channel(rendering, 2, x => (x, 16)), 4, 58);
Assert.InRange(red, 27d, 30.5d);
Assert.InRange(green, 31.5d, 33.5d);
Assert.InRange(blue, 36d, 38.5d);
}
[Theory]
[InlineData(0f)]
[InlineData(37f)]
[InlineData(90f)]
[InlineData(200f)]
public void ANegativeDistanceMirrorsAPositiveOneAtTheOppositeAngle(float angle)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var negative = Render(context, source, Settings(Distance: -10f, Angle: angle));
var opposite = Render(context, source, Settings(Distance: 10f, Angle: angle + 180f));
Assert.Equal((negative.Left, negative.Top, negative.Width, negative.Height), (opposite.Left, opposite.Top, opposite.Width, opposite.Height));
Assert.All(negative.Coordinates(), point => Assert.True(WithinRounding(negative[point.X, point.Y], opposite[point.X, point.Y]), $"({point.X}, {point.Y})"));
}
[Fact]
public void ThePrismLawNarrowsTheRedEdgeComparedWithTheGrating()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
var grating = Render(context, source, Settings(Dispersion: DispersionLaw.Grating));
var prism = Render(context, source, Settings(Dispersion: DispersionLaw.Prism));
var gratingWidth = EdgeWidth(Channel(grating, 0, x => (x, 16)), 4, 58);
var prismWidth = EdgeWidth(Channel(prism, 0, x => (x, 16)), 4, 58);
Assert.True(prismWidth < gratingWidth * 0.6, $"prism {prismWidth}, grating {gratingWidth}");
}
[Fact]
public void MoreStepsConvergeTowardsTheDenseSpectrum()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var dense = Render(context, source, Settings(Distance: 24f, Steps: 64));
long Distance(int steps)
{
var coarse = Render(context, source, Settings(Distance: 24f, Steps: steps));
return dense.Coordinates().Sum(point =>
{
var a = dense[point.X, point.Y];
var b = coarse[point.X, point.Y];
return (long)(Math.Abs(a.Blue - b.Blue) + Math.Abs(a.Green - b.Green) + Math.Abs(a.Red - b.Red) + Math.Abs(a.Alpha - b.Alpha));
});
}
var eight = Distance(8);
var sixteen = Distance(16);
var thirtyTwo = Distance(32);
Assert.True(eight > sixteen, $"8: {eight}, 16: {sixteen}");
Assert.True(sixteen > thirtyTwo, $"16: {sixteen}, 32: {thirtyTwo}");
}
static readonly ShiftSettings[] ReferenceSettings =
[
Settings(),
Settings(Distance: 20f, Angle: 37f),
Settings(Distance: -14f, Angle: 215f, Dispersion: DispersionLaw.Prism),
Settings(Mode: ShiftMode.Radial, Distance: 20f),
Settings(Mode: ShiftMode.Radial, Distance: -18f, Center: new Vector2(30f, -12f)),
Settings(Mode: ShiftMode.Rotational, Distance: 20f, Center: new Vector2(12f, -9f)),
Settings(Mode: ShiftMode.Rotational, Distance: 35f),
Settings(Mode: ShiftMode.Radial, Distance: 60f),
Settings(Mode: ShiftMode.Radial, Distance: -75f, Center: new Vector2(-25f, 10f), Steps: 16),
Settings(Mode: ShiftMode.Rotational, Distance: 90f, Center: new Vector2(20f, 14f), Steps: 64),
Settings(Distance: 14f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 480f, Steps: 8, Strength: 0.6f),
Settings(Distance: 18f, Angle: 120f, Steps: 13),
Settings(Mode: ShiftMode.Radial, Distance: 30f, Center: new Vector2(-10f, 6f), Steps: 33),
Settings(Mode: ShiftMode.Rotational, Distance: 50f, Dispersion: DispersionLaw.Prism, Steps: 21),
Settings(Distance: 40f, Angle: 200f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 650f, Steps: 64),
];
public static readonly TheoryData<int> ReferenceCases = [.. Enumerable.Range(0, ReferenceSettings.Length)];
[Theory]
[MemberData(nameof(ReferenceCases))]
public void TheOutputMatchesAnIndependentCpuRendering(int index)
{
var settings = ReferenceSettings[index];
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var reference = new SpectralReferenceRenderer(source, settings);
var rendering = Render(context, source, settings);
foreach (var (x, y) in rendering.Coordinates())
{
var expected = reference.Pixel(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,
$"({x}, {y}) expected {expected}, actual {actual}");
}
}
[Theory]
[MemberData(nameof(ReferenceCases))]
public void NothingVisibleLiesBeyondTheOutputBounds(int index)
{
var settings = ReferenceSettings[index];
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var reference = new SpectralReferenceRenderer(source, settings);
var rendering = Render(context, source, settings);
for (var y = rendering.Top - 8; y < rendering.Bottom + 8; y++)
{
for (var x = rendering.Left - 8; x < rendering.Right + 8; x++)
{
if (!rendering.Contains(x, y))
Assert.True(reference.Pixel(x, y).W * 255f <= 1f, $"({x}, {y}) {reference.Pixel(x, y)}");
}
}
}
[Fact]
public void BlueSpillsOutwardAndRedInwardOfARadialStripe()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 128, 128, Stripes);
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
var red = PeakAt(rendering, 0, 80, 120, x => (x, 64));
var green = PeakAt(rendering, 1, 80, 120, x => (x, 64));
var blue = PeakAt(rendering, 2, 80, 120, x => (x, 64));
Assert.True(red < 94 && green is >= 94 and <= 97 && blue > 98, $"red {red}, green {green}, blue {blue}");
}
[Fact]
public void ARadialShiftKeepsTheMirrorSymmetryOfTheImage()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 128, 128, Stripes);
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
Assert.Equal(rendering.Left + rendering.Right, source.Width);
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, point.Y]), $"({point.X}, {point.Y})"));
}
[Fact]
public void BlueTurnsClockwiseAndRedCounterclockwiseAroundTheCenter()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 160, 128, Dot);
var rendering = Render(context, source, Settings(Mode: ShiftMode.Rotational, Distance: 40f));
var red = PeakAt(rendering, 0, 40, 90, y => (104, y));
var green = PeakAt(rendering, 1, 40, 90, y => (104, y));
var blue = PeakAt(rendering, 2, 40, 90, y => (104, y));
Assert.True(red < 62 && green is >= 62 and <= 66 && blue > 66, $"red {red}, green {green}, blue {blue}");
}
[Theory]
[InlineData(ShiftMode.Radial)]
[InlineData(ShiftMode.Rotational)]
public void APointSymmetricImageStaysPointSymmetric(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 127 - x, 127 - y));
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
Assert.Equal((rendering.Left + rendering.Right, rendering.Top + rendering.Bottom), (source.Width, source.Height));
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, source.Height - 1 - point.Y]), $"({point.X}, {point.Y})"));
}
[Theory]
[InlineData(ShiftMode.Radial)]
[InlineData(ShiftMode.Rotational)]
public void TheCenterOffsetMovesThePointOfSymmetry(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 167 - x, 107 - y));
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f, Center: new Vector2(20f, -10f)));
var compared = 0;
foreach (var (x, y) in rendering.Coordinates())
{
var mirroredX = 167 - x;
var mirroredY = 107 - y;
if (DistanceToBorder(source, x, y) > 24 && source.Contains(mirroredX, mirroredY) && DistanceToBorder(source, mirroredX, mirroredY) > 24)
{
Assert.True(WithinRounding(rendering[x, y], rendering[mirroredX, mirroredY]), $"({x}, {y})");
compared++;
}
}
Assert.True(compared > 1000, $"{compared}");
}
[Theory]
[InlineData(ShiftMode.Linear, 100, 50)]
[InlineData(ShiftMode.Linear, -37, 21)]
[InlineData(ShiftMode.Radial, 100, 50)]
[InlineData(ShiftMode.Radial, -37, 21)]
[InlineData(ShiftMode.Rotational, 100, 50)]
[InlineData(ShiftMode.Rotational, -37, 21)]
public void TheShiftTravelsWithTheImage(ShiftMode mode, int dx, int dy)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
using var moved = new AffineTransform2D(context.DeviceContext)
{
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
BorderMode = BorderMode.Hard,
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
};
moved.SetInput(0, source.Bitmap, true);
using var movedOutput = moved.Output;
var settings = Settings(Mode: mode, Distance: 16f, Angle: 30f, Center: new Vector2(6f, -4f));
var inPlace = Render(context, source, settings);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, movedOutput, true);
settings.Apply(effect);
using var output = effect.Output;
var travelled = Rendering.Capture(context, output);
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
Assert.All(inPlace.Coordinates(), point => Assert.True(WithinRounding(inPlace[point.X, point.Y], travelled[point.X + dx, point.Y + dy]), $"({point.X}, {point.Y})"));
}
[Fact]
public void TheSpectrumSpillsOverTheEdgesInTheDirectionOfTheShift()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, 40, 24, Bgra.Opaque(255, 255, 255));
var rendering = Render(context, source, Settings(Distance: 20f));
var left = rendering[-5, 12];
var right = rendering[44, 12];
Assert.True(left.Alpha > 100 && left.Red > left.Blue + 100, $"{left}");
Assert.True(right.Alpha > 100 && right.Blue > right.Red + 100, $"{right}");
Assert.True(rendering[rendering.Left, 12].Alpha <= 2 && rendering[rendering.Right - 1, 12].Alpha <= 2);
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Top]);
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Bottom - 1]);
}
[Fact]
public void PixelsBeyondTheReachOfTheDistanceStayUnchanged()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
var rendering = Render(context, source, Settings(Distance: 8f));
var checkedPixels = 0;
foreach (var (x, y) in rendering.Coordinates())
{
if (source.Contains(x, y) && Math.Abs(x + 0.5 - Seam) > 9 && DistanceToBorder(source, x, y) > 9 && y > 9 && y < 22)
{
Assert.True(WithinRounding(source[x, y], rendering[x, y]), $"({x}, {y})");
checkedPixels++;
}
}
Assert.True(checkedPixels > 100, $"{checkedPixels}");
}
[Theory]
[MemberData(nameof(Modes))]
public void ATransparentImageStaysTransparent(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, 48, 32, Bgra.Transparent);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
Assert.All(rendering.Coordinates(), point => Assert.Equal(Bgra.Transparent, rendering[point.X, point.Y]));
}
[Theory]
[MemberData(nameof(Modes))]
public void EveryPixelIsAValidPremultipliedColor(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var rendering = Render(context, source, Settings(Mode: mode, Distance: 24f, Strength: 0.8f));
Assert.All(rendering.Coordinates(), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.True(pixel.Red <= pixel.Alpha + 1 && pixel.Green <= pixel.Alpha + 1 && pixel.Blue <= pixel.Alpha + 1, $"({point.X}, {point.Y}) {pixel}");
});
}
[Theory]
[MemberData(nameof(Modes))]
public void AnOverbrightInputIsClampedToItsAlpha(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
var stride = 96 * SourceImage.BytesPerPixel;
var pixels = new byte[stride * 96];
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
{
pixels[offset + 2] = 255;
pixels[offset + 3] = 64;
}
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
bitmap.CopyFromMemory(pixels, stride);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, bitmap, true);
Settings(Mode: mode, Distance: 12f).Apply(effect);
using var output = effect.Output;
var rendering = Rendering.Capture(context, output);
var interior = rendering[48, 48];
Assert.Equal(64, interior.Alpha);
Assert.True(interior.Red <= interior.Alpha && interior.Green <= interior.Alpha && interior.Blue <= interior.Alpha, $"{interior}");
Assert.True(interior.Red >= interior.Alpha - 1, $"{interior}");
}
[Fact]
public void TheSameSettingsAlwaysProduceTheSamePixels()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var settings = Settings(Mode: ShiftMode.Rotational, Distance: 18f, Dispersion: DispersionLaw.Prism);
var first = Render(context, source, settings);
var second = Render(context, source, settings);
Assert.True(first.SamePixelsAs(second));
}
[Theory]
[MemberData(nameof(Modes))]
public void TurningTheToggleOnAndOffRestoresTheLegacyImage(ShiftMode mode)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 48, Textured);
var legacy = new ShiftSettings(Mode: mode, Distance: 14f);
var expected = Render(context, source, legacy);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
legacy.Apply(effect);
effect.Physical = 1;
using var output = effect.Output;
var physical = Rendering.Capture(context, output);
effect.Physical = 0;
var restored = Rendering.Capture(context, output);
Assert.Contains(physical.Coordinates(), point => physical[point.X, point.Y] != expected[point.X, point.Y]);
Assert.Equal((expected.Left, expected.Top, expected.Width, expected.Height), (restored.Left, restored.Top, restored.Width, restored.Height));
Assert.All(expected.Coordinates(), point => Assert.Equal(expected[point.X, point.Y], restored[point.X, point.Y]));
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
namespace SpectrumColorShift.Tests;
public sealed partial class SpectralShaderContractTests
{
static readonly Dictionary<string, string> Fields = new()
{
["inputBounds"] = "InputBounds",
["direction"] = "Direction",
["center"] = "Center",
["shiftDistance"] = "Distance",
["radius"] = "Radius",
["strength"] = "Strength",
["mode"] = "Mode",
["steps"] = "Steps",
["spreadScale"] = "SpreadScale",
["samples"] = "Samples",
};
static string Source { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShiftPhysical.hlsl"));
static string Here([CallerFilePath] string path = "") => path;
static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!;
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
private static partial Regex ConstantPattern();
[GeneratedRegex(@"^\s*(?:float4|float2|float|int)\s+(?<name>\w+)(?:\[\w+\])?\s*:\s*packoffset\(c(?<register>\d+)(?:\.(?<component>[xyzw]))?\);", RegexOptions.Multiline)]
private static partial Regex MemberPattern();
static float Constant(string name)
=> float.Parse(ConstantPattern().Matches(Source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
[Fact]
public void TheShaderAndTheEffectAgreeOnTheConstants()
{
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"));
}
[Fact]
public void TheConstantBufferMatchesTheShaderLayout()
{
var members = MemberPattern().Matches(Source)
.ToDictionary(
match => match.Groups["name"].Value,
match => int.Parse(match.Groups["register"].Value, CultureInfo.InvariantCulture) * 16
+ (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
Assert.All(members, member => Assert.Equal(member.Value, (int)Marshal.OffsetOf(ConstantBuffer, Fields[member.Key])));
}
[Fact]
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
{
var size = (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(ConstantBuffer).Invoke(null, null)!;
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength), size);
}
}
+3 -1
ファイルの表示
@@ -10,7 +10,8 @@ internal sealed record ShiftSettings(
float Strength = 1f,
DispersionLaw Dispersion = DispersionLaw.Grating,
float ReferenceWavelength = 550f,
int Steps = 32)
int Steps = 32,
bool Physical = false)
{
public void Apply(SpectrumColorShiftCustomEffect effect)
{
@@ -23,6 +24,7 @@ internal sealed record ShiftSettings(
effect.Dispersion = (int)Dispersion;
effect.ReferenceWavelength = ReferenceWavelength;
effect.Steps = Steps;
effect.Physical = Physical ? 1 : 0;
}
}
+95 -5
ファイルの表示
@@ -21,6 +21,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
Dispersion,
ReferenceWavelength,
Steps,
Physical,
}
public float Distance { set => SetValue((int)PropertyIndex.Distance, value); }
@@ -32,17 +33,26 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
public int Dispersion { set => SetValue((int)PropertyIndex.Dispersion, value); }
public float ReferenceWavelength { set => SetValue((int)PropertyIndex.ReferenceWavelength, value); }
public int Steps { set => SetValue((int)PropertyIndex.Steps, value); }
public int Physical { set => SetValue((int)PropertyIndex.Physical, value); }
[CustomEffect(1)]
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;
private DispersionLaw _dispersion = DispersionLaw.Grating;
private Vector2 _centerOffset;
private float _referenceWavelength = Spectrum.DefaultReferenceWavelength;
private int _steps = Spectrum.DefaultSteps;
private bool _tableStale = true;
private bool _spectralStale = true;
private bool _physical;
private bool _physicalShaderApplied;
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)]
public float Distance
@@ -122,6 +132,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
{
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
_tableStale = true;
_spectralStale = true;
UpdateConstants();
}
}
@@ -134,6 +145,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
{
_referenceWavelength = Spectrum.ClampReference(value);
_tableStale = true;
_spectralStale = true;
UpdateConstants();
}
}
@@ -147,6 +159,18 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
_steps = Spectrum.ClampSteps(value);
_cb.Steps = _steps;
_tableStale = true;
_spectralStale = true;
UpdateConstants();
}
}
[CustomEffectProperty(PropertyType.Int32, (int)PropertyIndex.Physical)]
public int Physical
{
get => _physical ? 1 : 0;
set
{
_physical = value != 0;
UpdateConstants();
}
}
@@ -160,6 +184,14 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
_cb.Steps = Spectrum.DefaultSteps;
}
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);
}
protected override void UpdateConstants()
{
if (drawInformation is null)
@@ -167,14 +199,18 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
try
{
if (_tableStale)
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
if (_physical != _physicalShaderApplied)
{
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
_tableStale = false;
drawInformation.SetPixelShader(_physical ? PhysicalShaderId : GUID_PixelShader, PixelOptions.None);
_physicalShaderApplied = _physical;
}
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
drawInformation.SetPixelShaderConstantBuffer(_cb);
if (_physical)
SendPhysicalConstants();
else
SendConstants();
}
catch (Exception exception)
{
@@ -183,6 +219,37 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
}
}
private void SendConstants()
{
if (_tableStale)
{
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
_tableStale = false;
}
drawInformation!.SetPixelShaderConstantBuffer(_cb);
}
private void SendPhysicalConstants()
{
if (_spectralStale)
{
Spectrum.FillSpectral(_physicalCb.Samples, _steps, _referenceWavelength, _dispersion);
_spectralStale = false;
}
_physicalCb.InputBounds = _cb.InputBounds;
_physicalCb.Direction = _cb.Direction;
_physicalCb.Center = _cb.Center;
_physicalCb.Distance = _cb.Distance;
_physicalCb.Radius = _cb.Radius;
_physicalCb.Strength = _cb.Strength;
_physicalCb.Mode = _cb.Mode;
_physicalCb.Steps = Spectrum.Padded(_steps);
_physicalCb.SpreadScale = _cb.SpreadScale;
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
}
public override void MapInputRectsToOutputRect(
RawRect[] inputRects,
RawRect[] inputOpaqueSubRects,
@@ -240,6 +307,29 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
private Vector4 _element;
}
[InlineArray(Spectrum.SpectralTableLength)]
private struct SpectralSampleTable
{
private Vector4 _element;
}
[StructLayout(LayoutKind.Sequential)]
private struct PhysicalConstantBuffer
{
public Vector4 InputBounds;
public Vector2 Direction;
public Vector2 Center;
public float Distance;
public float Radius;
public float Strength;
public int Mode;
public int Steps;
public float SpreadScale;
public float Pad1;
public float Pad2;
public SpectralSampleTable Samples;
}
[StructLayout(LayoutKind.Sequential)]
private struct ConstantBuffer
{
+9
ファイルの表示
@@ -78,6 +78,15 @@ public sealed class SpectrumColorShiftEffect : VideoEffectBase
}
private int _steps = Spectrum.DefaultSteps;
[Display(GroupName = nameof(Texts.SpectrumGroup), Name = nameof(Texts.Physical), Description = nameof(Texts.PhysicalDescription), Order = 9, ResourceType = typeof(Texts))]
[ToggleSlider]
public bool Physical
{
get => _physical;
set => Set(ref _physical, value);
}
private bool _physical;
private IAnimatable[]? _animatables;
public override IEnumerable<string> CreateExoVideoFilters(
+6 -2
ファイルの表示
@@ -46,7 +46,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
(float)(_item.Strength.GetValue(frame, length, fps) / 100.0),
(int)_item.Dispersion,
(float)_item.ReferenceWavelength.GetValue(frame, length, fps),
_item.Steps);
_item.Steps,
_item.Physical);
if (_isFirst || _parameters.Distance != parameters.Distance)
_effect.Distance = parameters.Distance;
@@ -66,6 +67,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
_effect.ReferenceWavelength = parameters.ReferenceWavelength;
if (_isFirst || _parameters.Steps != parameters.Steps)
_effect.Steps = parameters.Steps;
if (_isFirst || _parameters.Physical != parameters.Physical)
_effect.Physical = parameters.Physical ? 1 : 0;
_parameters = parameters;
_isFirst = false;
@@ -122,5 +125,6 @@ internal sealed class SpectrumColorShiftEffectProcessor(
float Strength,
int Dispersion,
float ReferenceWavelength,
int Steps);
int Steps,
bool Physical);
}
+2
ファイルの表示
@@ -30,6 +30,8 @@ ReferenceWavelength,,基準波長,Reference Wavelength,基准波长,基準波長
ReferenceWavelengthDescription,,ずれずにその位置に残る色の波長です。単位はnmで、450付近が青、550付近が緑、650付近が赤です,"Sets the wavelength in nm of the color that stays in place. Around 450 is blue, 550 is green, and 650 is red.",设置保持原位的颜色的波长,单位为nm。450附近为蓝色,550附近为绿色,650附近为红色。,設定保持原位的顏色的波長,單位為nm。450附近為藍色,550附近為綠色,650附近為紅色。,"제자리에 남는 색의 파장입니다. 단위는 nm이며 450 부근이 파랑, 550 부근이 초록, 650 부근이 빨강입니다.","Establece la longitud de onda, en nm, del color que permanece en su sitio. Alrededor de 450 es azul, 550 verde y 650 rojo.",يحدد الطول الموجي، بوحدة nm، للون الذي يبقى في مكانه. حوالي 450 أزرق و550 أخضر و650 أحمر.,"Mengatur panjang gelombang warna yang tetap di tempatnya, dalam nm. Sekitar 450 biru, 550 hijau, dan 650 merah."
Steps,,ステップ数,Steps,步数,步數,단계 수,Pasos,عدد الخطوات,Langkah
StepsDescription,,スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます,"Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies.",设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。,設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。,스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다.,"Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas.",يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة.,"Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah."
Physical,,物理ベース,Physically Based,基于物理,基於物理,물리 기반,Basado en física,قائم على الفيزياء,Berbasis fisika
PhysicalDescription,,オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量に近い値で行います。オフでは、赤、緑、青を別々にずらします,"When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed in values close to the amount of light. When off, red, green and blue are shifted separately.",开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加使用接近光量的值进行。关闭时,红、绿、蓝分别错开。,開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加使用接近光量的值進行。關閉時,紅、綠、藍分別錯開。,"켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양에 가까운 값으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다.","Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman con valores cercanos a la cantidad de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado.",عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بقيم قريبة من كمية الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل.,"Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan dengan nilai yang mendekati jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah."
TagColorShift,,色ずれ,color shift,色偏,色偏,색 어긋남,desfase de color,إزاحة اللون,pergeseran warna
TagChromaticAberration,,色収差,chromatic aberration,色差,色差,색수차,aberración cromática,الزيغ اللوني,aberasi kromatik
TagSpectrum,,スペクトル,spectrum,光谱,光譜,스펙트럼,espectro,الطيف,spektrum
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
30 ReferenceWavelengthDescription ずれずにその位置に残る色の波長です。単位はnmで、450付近が青、550付近が緑、650付近が赤です Sets the wavelength in nm of the color that stays in place. Around 450 is blue, 550 is green, and 650 is red. 设置保持原位的颜色的波长,单位为nm。450附近为蓝色,550附近为绿色,650附近为红色。 設定保持原位的顏色的波長,單位為nm。450附近為藍色,550附近為綠色,650附近為紅色。 제자리에 남는 색의 파장입니다. 단위는 nm이며 450 부근이 파랑, 550 부근이 초록, 650 부근이 빨강입니다. Establece la longitud de onda, en nm, del color que permanece en su sitio. Alrededor de 450 es azul, 550 verde y 650 rojo. يحدد الطول الموجي، بوحدة nm، للون الذي يبقى في مكانه. حوالي 450 أزرق و550 أخضر و650 أحمر. Mengatur panjang gelombang warna yang tetap di tempatnya, dalam nm. Sekitar 450 biru, 550 hijau, dan 650 merah.
31 Steps ステップ数 Steps 步数 步數 단계 수 Pasos عدد الخطوات Langkah
32 StepsDescription スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies. 设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。 設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。 스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다. Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas. يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة. Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah.
33 Physical 物理ベース Physically Based 基于物理 基於物理 물리 기반 Basado en física قائم على الفيزياء Berbasis fisika
34 PhysicalDescription オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量に近い値で行います。オフでは、赤、緑、青を別々にずらします When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed in values close to the amount of light. When off, red, green and blue are shifted separately. 开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加使用接近光量的值进行。关闭时,红、绿、蓝分别错开。 開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加使用接近光量的值進行。關閉時,紅、綠、藍分別錯開。 켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양에 가까운 값으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다. Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman con valores cercanos a la cantidad de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado. عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بقيم قريبة من كمية الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل. Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan dengan nilai yang mendekati jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah.
35 TagColorShift 色ずれ color shift 色偏 色偏 색 어긋남 desfase de color إزاحة اللون pergeseran warna
36 TagChromaticAberration 色収差 chromatic aberration 色差 色差 색수차 aberración cromática الزيغ اللوني aberasi kromatik
37 TagSpectrum スペクトル spectrum 光谱 光譜 스펙트럼 espectro الطيف spektrum