ハーネスプロジェクトを追加する

このコミットが含まれているのは:
routersys committed 2026-10-12 01:09:18 +09:00
1 親 5c9252fba6
コミット ce6e6a7374
12ファイル変更
+1072

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

+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace SpectrumColorShift.Harness;
internal sealed record GoldenCase(string Name, IReadOnlyList<int> Frames, string Hash);
internal sealed record Golden(string Adapter, string Driver, string Input, string Canvas, IReadOnlyList<GoldenCase> Cases)
{
const string FileName = "golden.json";
const string DirectoryKey = "HarnessDirectory";
static readonly JsonSerializerOptions Options = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
NewLine = "\n",
};
public static string PathFor(HarnessImage image)
=> Path.Combine(ReadDirectory(), image.Key is null ? FileName : $"golden-{image.Key}.json");
public static Golden Load(string path)
{
if (!File.Exists(path))
throw new HarnessException($"基準値がありません。先に --golden で書いてください。{path}");
Golden? golden;
try
{
golden = JsonSerializer.Deserialize<Golden>(File.ReadAllBytes(path), Options);
}
catch (JsonException exception)
{
throw new HarnessException($"基準値を読めません。{path} {exception.Message}");
}
if (golden is not { Adapter: not null, Driver: not null, Input: not null, Canvas: not null, Cases: not null }
|| golden.Cases.Any(item => item is not { Name: not null, Frames: not null, Hash: not null }))
throw new HarnessException($"基準値の項目が足りません。{path}");
if (golden.Cases.Select(item => item.Name).Distinct(StringComparer.Ordinal).Count() != golden.Cases.Count)
throw new HarnessException($"基準値のケース名が重複しています。{path}");
return golden;
}
public void Save(string path) => File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, Options));
static string ReadDirectory()
=> typeof(Golden).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => string.Equals(attribute.Key, DirectoryKey, StringComparison.Ordinal))
?.Value ?? throw new HarnessException($"アセンブリに {DirectoryKey} がありません。");
}
+63
ファイルの表示
@@ -0,0 +1,63 @@
using System.Diagnostics;
using Vortice.Direct3D11;
namespace SpectrumColorShift.Harness;
internal sealed class GpuTimer : IDisposable
{
static readonly TimeSpan ResolveTimeout = TimeSpan.FromSeconds(5);
readonly ID3D11DeviceContext context;
readonly ID3D11Query disjoint;
readonly ID3D11Query start;
readonly ID3D11Query stop;
public GpuTimer(ID3D11Device device, ID3D11DeviceContext context)
{
this.context = context;
disjoint = device.CreateQuery(new QueryDescription(QueryType.TimestampDisjoint, QueryFlags.None));
start = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
stop = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
}
public void Begin()
{
context.Begin(disjoint);
context.End(start);
}
public void End()
{
context.End(stop);
context.End(disjoint);
}
public TimeSpan? Resolve()
{
if (!Wait<QueryDataTimestampDisjoint>(disjoint, out var timing) || timing.Disjoint || timing.Frequency == 0UL)
return null;
if (!Wait<ulong>(start, out var began) || !Wait<ulong>(stop, out var ended) || ended < began)
return null;
return TimeSpan.FromSeconds((ended - began) / (double)timing.Frequency);
}
bool Wait<T>(ID3D11Query query, out T value) where T : unmanaged
{
var elapsed = Stopwatch.StartNew();
while (!context.GetData(query, out value))
{
if (elapsed.Elapsed > ResolveTimeout)
return false;
Thread.Yield();
}
return true;
}
public void Dispose()
{
stop.Dispose();
start.Dispose();
disjoint.Dispose();
}
}
+88
ファイルの表示
@@ -0,0 +1,88 @@
namespace SpectrumColorShift.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
}
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After)
{
public const string Usage = """
使い方:
[<出力先>] [--input <画像>] ケースを描き、PNG とハッシュを出します
--golden [--input <画像>] 基準値を golden.json に書きます
--verify [--input <画像>] 基準値と照合します
--transition [<出力先>] [--input <画像>] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
--benchmark [--input <画像>] 描画を計測します
""";
public static HarnessArguments Parse(string[] arguments)
{
HarnessMode? mode = null;
string? input = null;
var positionals = new List<string>();
for (var index = 0; index < arguments.Length; index++)
{
var argument = arguments[index];
switch (argument)
{
case "--golden":
mode = Select(mode, HarnessMode.Golden);
break;
case "--verify":
mode = Select(mode, HarnessMode.Verify);
break;
case "--transition":
mode = Select(mode, HarnessMode.Transition);
break;
case "--compare":
mode = Select(mode, HarnessMode.Compare);
break;
case "--benchmark":
mode = Select(mode, HarnessMode.Benchmark);
break;
case "--input":
if (index + 1 >= arguments.Length)
throw new HarnessException("--input には画像のパスを続けてください。");
input = arguments[++index];
break;
default:
if (argument.StartsWith('-'))
throw new HarnessException($"不明なオプションです。{argument}");
positionals.Add(argument);
break;
}
}
var selected = mode ?? HarnessMode.Render;
switch (selected)
{
case HarnessMode.Compare:
if (positionals.Count != 2)
throw new HarnessException("--compare には前と後の出力先を続けてください。");
if (input is not null)
throw new HarnessException("--compare に --input は使えません。");
return new HarnessArguments(HarnessMode.Compare, null, null, positionals[0], positionals[1]);
case HarnessMode.Render:
case HarnessMode.Transition:
if (positionals.Count > 1)
throw new HarnessException($"余分な引数です。{positionals[1]}");
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null);
default:
if (positionals.Count > 0)
throw new HarnessException($"余分な引数です。{positionals[0]}");
return new HarnessArguments(selected, input, null, null, null);
}
}
static HarnessMode Select(HarnessMode? current, HarnessMode next)
=> current is null ? next : throw new HarnessException("モードは 1 つだけ指定してください。");
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
using YukkuriMovieMaker.Plugin.Effects;
namespace SpectrumColorShift.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, IVideoEffect Effect, IReadOnlyList<int> Frames)> All()
{
yield break;
}
public static IEnumerable<(string Name, Func<IVideoEffect> Create, Action<IVideoEffect> Change, int Frame)> Transitions()
{
yield break;
}
public static IEnumerable<(string Name, IVideoEffect Effect)> Benchmarks()
{
yield break;
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System.IO;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SpectrumColorShift.Harness;
internal sealed record HarnessImage(int Width, int Height, byte[] Pixels, string Identity, string? Key)
{
public const int BytesPerPixel = 4;
const int KeyLength = 16;
public static HarnessImage Synthetic(int width, int height)
{
var pixels = SyntheticImage.Create(width, height);
return new HarnessImage(width, height, pixels, $"synthetic {width}x{height} {Convert.ToHexString(SHA256.HashData(pixels))[..KeyLength]}", null);
}
public static HarnessImage Load(string path)
{
if (!File.Exists(path))
throw new HarnessException($"入力の画像がありません。{path}");
var bytes = File.ReadAllBytes(path);
var (width, height, pixels) = Decode(bytes, path);
var hash = Convert.ToHexString(SHA256.HashData(bytes));
return new HarnessImage(width, height, pixels, $"{hash} {width}x{height}", hash[..KeyLength]);
}
public static (int Width, int Height, byte[] Pixels) LoadPremultiplied(string path) => Decode(File.ReadAllBytes(path), path);
public static void Save(string path, byte[] pixels, int width, int height)
{
var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * BytesPerPixel);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
using var stream = File.Create(path);
encoder.Save(stream);
}
static (int Width, int Height, byte[] Pixels) Decode(byte[] bytes, string path)
{
using var stream = new MemoryStream(bytes);
BitmapDecoder decoder;
try
{
decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
}
catch (Exception exception) when (exception is NotSupportedException or FileFormatException)
{
throw new HarnessException($"画像として読めません。{path}");
}
var converted = new FormatConvertedBitmap(decoder.Frames[0], PixelFormats.Pbgra32, null, 0d);
var pixels = new byte[converted.PixelWidth * converted.PixelHeight * BytesPerPixel];
converted.CopyPixels(pixels, converted.PixelWidth * BytesPerPixel, 0);
return (converted.PixelWidth, converted.PixelHeight, pixels);
}
}
+262
ファイルの表示
@@ -0,0 +1,262 @@
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace SpectrumColorShift.Harness;
internal sealed class HarnessRenderer : IDisposable
{
const int Fps = 30;
const int Length = 300;
const int WarmupUpdates = 2000;
const int UpdateRepeats = 20;
const float Dpi = 96f;
static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
readonly GraphicsDevices devices;
readonly IGraphicsDevicesAndContext context;
readonly ID2D1Bitmap1 image;
readonly ID2D1Bitmap1 target;
readonly ID2D1Bitmap1 readback;
readonly ID2D1Bitmap1 sync;
readonly GpuTimer timer;
readonly AffineTransform2D placement;
readonly ID2D1Image centered;
public HarnessRenderer(int canvasWidth, int canvasHeight, HarnessImage source)
{
CanvasWidth = canvasWidth;
CanvasHeight = canvasHeight;
devices = new GraphicsDevices();
context = devices.CreateContext();
var deviceContext = context.DeviceContext;
var adapter = devices.DXGI.Adapter;
Adapter = adapter.Description.Description;
Driver = adapter.CheckInterfaceSupport<IDXGIDevice>(out var version) ? FormatDriverVersion(version) : "不明";
image = CreateBitmap(deviceContext, source.Width, source.Height, BitmapOptions.None);
image.CopyFromMemory(source.Pixels, source.Width * HarnessImage.BytesPerPixel);
target = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.Target);
readback = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
sync = CreateBitmap(deviceContext, 1, 1, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
timer = new GpuTimer(devices.D3D.Device, devices.D3D.DeviceContext);
placement = new AffineTransform2D(deviceContext)
{
TransformMatrix = Matrix3x2.CreateTranslation(-source.Width * 0.5f, -source.Height * 0.5f),
};
placement.SetInput(0, image, true);
centered = placement.Output;
}
public int CanvasWidth { get; }
public int CanvasHeight { get; }
public string Adapter { get; }
public string Driver { get; }
public byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames)
{
if (frames.Count == 0)
throw new ArgumentException("フレームを 1 つ以上指定してください。", nameof(frames));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(centered);
try
{
var rendered = new byte[frames.Count][];
for (var index = 0; index < frames.Count; index++)
{
processor.Update(Describe(frames[index]));
rendered[index] = Capture(processor.Output);
}
return rendered;
}
finally
{
processor.ClearInput();
}
}
public (byte[] Direct, byte[] Transitioned) RenderTransition<TEffect>(Func<TEffect> create, Action<TEffect> change, int frame)
where TEffect : IVideoEffect
{
var settled = create();
change(settled);
var direct = Render(settled, [frame])[0];
var live = create();
using var processor = live.CreateVideoEffect(context);
processor.SetInput(centered);
try
{
processor.Update(Describe(frame));
_ = Capture(processor.Output);
change(live);
processor.Update(Describe(frame));
return (direct, Capture(processor.Output));
}
finally
{
processor.ClearInput();
}
}
public Measurement Measure(IVideoEffect effect, int frames, bool moving)
{
var descriptions = new EffectDescription[frames];
for (var frame = 0; frame < frames; frame++)
descriptions[frame] = Describe(moving ? frame : 0);
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(centered);
var output = processor.Output;
try
{
for (var index = 0; index < WarmupUpdates; index++)
processor.Update(descriptions[index % frames]);
for (var frame = 0; frame < frames; frame++)
{
processor.Update(descriptions[frame]);
Submit(output);
}
Synchronize();
var cpu = TimeSpan.MaxValue;
for (var frame = 0; frame < frames; frame++)
{
var elapsed = Stopwatch.StartNew();
processor.Update(descriptions[frame]);
Submit(output);
elapsed.Stop();
cpu = elapsed.Elapsed < cpu ? elapsed.Elapsed : cpu;
}
Synchronize();
TimeSpan? gpu = null;
for (var frame = 0; frame < frames; frame++)
{
processor.Update(descriptions[frame]);
timer.Begin();
Submit(output);
timer.End();
if (timer.Resolve() is { } resolved && (gpu is null || resolved < gpu))
gpu = resolved;
}
Synchronize();
var repeats = frames * UpdateRepeats;
var updates = Stopwatch.StartNew();
for (var index = 0; index < repeats; index++)
processor.Update(descriptions[index % frames]);
updates.Stop();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = GC.GetAllocatedBytesForCurrentThread();
var collections = GC.CollectionCount(0);
for (var frame = 0; frame < frames; frame++)
processor.Update(descriptions[frame]);
var allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / frames;
var gen0 = GC.CollectionCount(0) - collections;
return new Measurement(gpu, cpu, updates.Elapsed / repeats, allocated, gen0);
}
finally
{
processor.ClearInput();
}
}
byte[] Capture(ID2D1Image output)
{
Submit(output);
readback.CopyFromBitmap(target);
var stride = CanvasWidth * HarnessImage.BytesPerPixel;
var pixels = new byte[stride * CanvasHeight];
var mapped = readback.Map(MapOptions.Read);
try
{
for (var y = 0; y < CanvasHeight; y++)
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
}
finally
{
readback.Unmap();
}
return pixels;
}
void Submit(ID2D1Image output)
{
var deviceContext = context.DeviceContext;
deviceContext.Target = target;
deviceContext.BeginDraw();
deviceContext.Clear(new Color4(0f, 0f, 0f, 0f));
deviceContext.DrawImage(output, new Vector2(CanvasWidth * 0.5f, CanvasHeight * 0.5f), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceOver);
deviceContext.EndDraw();
deviceContext.Target = null;
}
void Synchronize()
{
sync.CopyFromBitmap(Int2.Zero, target, new RectI(0, 0, 1, 1));
_ = sync.Map(MapOptions.Read);
sync.Unmap();
}
EffectDescription Describe(int frame)
{
var timeline = new TimelineSourceDescription(
new System.Drawing.Size(CanvasWidth, CanvasHeight),
new YukkuriMovieMaker.Player.Video.FrameTime(frame, Fps),
new YukkuriMovieMaker.Player.Video.FrameTime(Length, Fps),
Fps,
TimelineSourceUsage.Playing,
Guid.Empty,
[]);
var item = new TimelineItemSourceDescription(timeline, frame, Length, 0);
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
return new EffectDescription(item, draw, 0, 1, 0, 1);
}
static ID2D1Bitmap1 CreateBitmap(ID2D1DeviceContext6 deviceContext, int width, int height, BitmapOptions options)
=> deviceContext.CreateBitmap(
new SizeI(width, height), nint.Zero, width * HarnessImage.BytesPerPixel,
new BitmapProperties1(PixelFormat, Dpi, Dpi, options));
static string FormatDriverVersion(long version)
=> $"{(version >> 48) & 0xFFFF}.{(version >> 32) & 0xFFFF}.{(version >> 16) & 0xFFFF}.{version & 0xFFFF}";
public void Dispose()
{
placement.SetInput(0, null, true);
centered.Dispose();
placement.Dispose();
timer.Dispose();
sync.Dispose();
readback.Dispose();
target.Dispose();
image.Dispose();
context.Dispose();
devices.Dispose();
}
public readonly record struct Measurement(TimeSpan? Gpu, TimeSpan Cpu, TimeSpan Update, long Allocated, int Gen0);
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace SpectrumColorShift.Harness;
internal static class HostAssemblyResolver
{
const string MetadataKey = "HostDirectory";
const string AssemblyExtension = ".dll";
public static string Directory { get; } = ReadDirectory();
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
[ModuleInitializer]
internal static void Initialize()
{
if (!IsConfigured)
return;
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
{
var name = new AssemblyName(arguments.Name).Name;
if (name is null)
return null;
var candidate = Path.Combine(Directory, name + AssemblyExtension);
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
};
}
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
?.Value ?? string.Empty;
}
+46
ファイルの表示
@@ -0,0 +1,46 @@
namespace SpectrumColorShift.Harness;
internal readonly record struct ImageDifference(int Differing, int MaxDelta, int Left, int Top, int Right, int Bottom)
{
public bool IsEmpty => Differing == 0;
public override string ToString()
=> IsEmpty ? "一致" : $"differing={Differing} maxDelta={MaxDelta} box=({Left},{Top})-({Right},{Bottom})";
}
internal static class ImageComparison
{
public static ImageDifference Of(byte[] first, byte[] second, int width, int height)
{
if (first.Length != second.Length || first.Length != width * height * HarnessImage.BytesPerPixel)
throw new ArgumentException("画像の寸法が一致しません。");
var differing = 0;
var maxDelta = 0;
var left = width;
var top = height;
var right = -1;
var bottom = -1;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
var delta = 0;
for (var channel = 0; channel < HarnessImage.BytesPerPixel; channel++)
delta = Math.Max(delta, Math.Abs(first[offset + channel] - second[offset + channel]));
if (delta == 0)
continue;
differing++;
maxDelta = Math.Max(maxDelta, delta);
left = Math.Min(left, x);
top = Math.Min(top, y);
right = Math.Max(right, x);
bottom = Math.Max(bottom, y);
}
}
return differing == 0 ? default : new ImageDifference(differing, maxDelta, left, top, right, bottom);
}
}
+328
ファイルの表示
@@ -0,0 +1,328 @@
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using SpectrumColorShift.Harness;
using SharpGen.Runtime;
const int CanvasWidth = 1280;
const int CanvasHeight = 720;
const int ImageWidth = 640;
const int ImageHeight = 480;
const int FullHdWidth = 1920;
const int FullHdHeight = 1080;
_ = PackUriHelper.UriSchemePack;
HarnessArguments arguments;
try
{
arguments = HarnessArguments.Parse(args);
}
catch (HarnessException exception)
{
Console.Error.WriteLine(exception.Message);
Console.Error.WriteLine(HarnessArguments.Usage);
return 2;
}
try
{
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
var outputDirectory = arguments.OutputDirectory ?? Path.Combine(AppContext.BaseDirectory, "harness-output");
if (arguments.Mode == HarnessMode.Benchmark)
{
if (arguments.Input is { } benchmarkInput)
{
Benchmark(HarnessImage.Load(benchmarkInput));
}
else
{
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
}
return 0;
}
var image = arguments.Input is { } input ? HarnessImage.Load(input) : HarnessImage.Synthetic(ImageWidth, ImageHeight);
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image);
return arguments.Mode switch
{
HarnessMode.Golden => WriteGolden(renderer, image),
HarnessMode.Verify => Verify(renderer, image),
HarnessMode.Transition => Transition(renderer, outputDirectory),
_ => Render(renderer, outputDirectory),
};
}
catch (Exception exception) when (exception is HarnessException or SharpGenException)
{
Console.Error.WriteLine(exception.Message);
return 2;
}
static int Render(HarnessRenderer renderer, string outputDirectory)
{
Directory.CreateDirectory(outputDirectory);
var failures = 0;
var cases = Evaluate(renderer, (golden, files, frames) =>
{
Console.WriteLine($"{golden.Name}: {golden.Hash}");
for (var index = 0; index < files.Length; index++)
{
HarnessImage.Save(Path.Combine(outputDirectory, files[index]), frames[index], renderer.CanvasWidth, renderer.CanvasHeight);
var opaque = CountOpaque(frames[index]);
Console.WriteLine($" {files[index]} opaque={opaque}");
if (opaque == 0)
{
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
failures++;
}
}
});
Console.WriteLine($"-> {outputDirectory}");
return failures + CountDuplicates(cases) == 0 ? 0 : 1;
}
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
{
var cases = Evaluate(renderer, null);
if (CountDuplicates(cases) != 0)
return 1;
if (cases.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
var golden = new Golden(renderer.Adapter, renderer.Driver, image.Identity, $"{renderer.CanvasWidth}x{renderer.CanvasHeight}", cases);
var path = Golden.PathFor(image);
golden.Save(path);
Console.WriteLine($"adapter: {golden.Adapter} (driver {golden.Driver})");
Console.WriteLine($"input: {golden.Input}");
foreach (var (name, _, hash) in cases)
Console.WriteLine($"{name}: {hash}");
Console.WriteLine($"-> {path}");
return 0;
}
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var golden = Golden.Load(Golden.PathFor(image));
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
if (golden.Input != image.Identity || golden.Canvas != canvas)
{
Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。");
return 1;
}
if (golden.Adapter != renderer.Adapter || golden.Driver != renderer.Driver)
Console.Error.WriteLine($"基準値は {golden.Adapter} (driver {golden.Driver}) で書かれています。今回は {renderer.Adapter} (driver {renderer.Driver}) です。画素の差はこの違いから来ることがあります。");
var failures = 0;
var current = Evaluate(renderer, null).ToDictionary(item => item.Name, StringComparer.Ordinal);
if (golden.Cases.Count == 0 && current.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, frames, hash) in golden.Cases)
{
if (!current.Remove(name, out var actual))
{
Console.Error.WriteLine($"{name}: ケースがありません。基準値を書き直してください。");
failures++;
}
else if (!actual.Frames.SequenceEqual(frames))
{
Console.Error.WriteLine($"{name}: フレームが違います。基準値 [{string.Join(", ", frames)}]、今回 [{string.Join(", ", actual.Frames)}]。基準値を書き直してください。");
failures++;
}
else if (actual.Hash != hash)
{
Console.Error.WriteLine($"{name}: 一致しません。基準値 {hash}、今回 {actual.Hash}");
failures++;
}
else
{
Console.WriteLine($"{name}: 一致");
}
}
foreach (var name in current.Keys)
{
Console.Error.WriteLine($"{name}: 基準値にありません。基準値を書き直してください。");
failures++;
}
return failures == 0 ? 0 : 1;
}
static int Transition(HarnessRenderer renderer, string outputDirectory)
{
var failures = 0;
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
{
var (direct, transitioned) = renderer.RenderTransition(create, change, frame);
var difference = ImageComparison.Of(direct, transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
if (difference.IsEmpty)
{
Console.WriteLine($"{name}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-direct.png"), direct, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-transitioned.png"), transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{name}: {difference}。設定を変えた後の描画が作り直した場合と違います。-> {outputDirectory}");
}
if (!HarnessCases.Transitions().Any() && !HarnessCases.All().Any(item => item.Frames.Count > 1))
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, effect, frames) in HarnessCases.All())
{
if (frames.Count < 2)
continue;
var sequential = renderer.Render(effect, frames);
for (var index = 0; index < frames.Count; index++)
{
var fresh = renderer.Render(effect, [frames[index]])[0];
var difference = ImageComparison.Of(fresh, sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
var label = $"{name}-f{frames[index]:D3}";
if (difference.IsEmpty)
{
Console.WriteLine($"{label}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-direct.png"), fresh, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-transitioned.png"), sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{label}: {difference}。前のフレームから進めた描画が作り直した場合と違います。-> {outputDirectory}");
}
}
return failures == 0 ? 0 : 1;
}
static int Compare(string beforeDirectory, string afterDirectory)
{
if (!Directory.Exists(beforeDirectory) || !Directory.Exists(afterDirectory))
throw new HarnessException("比べる出力先がありません。");
var failures = 0;
var names = Directory.EnumerateFiles(beforeDirectory, "*.png")
.Concat(Directory.EnumerateFiles(afterDirectory, "*.png"))
.Select(path => Path.GetFileName(path))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Order(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (names.Length == 0)
throw new HarnessException("比べる PNG がありません。");
foreach (var name in names)
{
var before = Path.Combine(beforeDirectory, name);
var after = Path.Combine(afterDirectory, name);
if (!File.Exists(before) || !File.Exists(after))
{
Console.Error.WriteLine($"{name}: {(File.Exists(before) ? "後" : "前")}にありません。");
failures++;
continue;
}
var (beforeWidth, beforeHeight, beforePixels) = HarnessImage.LoadPremultiplied(before);
var (afterWidth, afterHeight, afterPixels) = HarnessImage.LoadPremultiplied(after);
if (beforeWidth != afterWidth || beforeHeight != afterHeight)
{
Console.Error.WriteLine($"{name}: 寸法が違います。前 {beforeWidth}x{beforeHeight}、後 {afterWidth}x{afterHeight}");
failures++;
continue;
}
var difference = ImageComparison.Of(beforePixels, afterPixels, beforeWidth, beforeHeight);
Console.WriteLine($"{name}: {difference}");
if (!difference.IsEmpty)
failures++;
}
return failures == 0 ? 0 : 1;
}
static void Benchmark(HarnessImage image)
{
const int Frames = 60;
using var renderer = new HarnessRenderer(image.Width, image.Height, image);
Console.WriteLine($"adapter: {renderer.Adapter} (driver {renderer.Driver})");
foreach (var (name, effect) in HarnessCases.Benchmarks())
{
Report(image, name, "still", renderer.Measure(effect, Frames, moving: false));
Report(image, name, "moving", renderer.Measure(effect, Frames, moving: true));
}
}
static void Report(HarnessImage image, string name, string motion, HarnessRenderer.Measurement measurement)
=> Console.WriteLine(
$"{image.Width}x{image.Height} {name,-15} {motion,-6} " +
$"gpu={(measurement.Gpu is { } gpu ? gpu.TotalMilliseconds.ToString("F3") : "n/a"),7} " +
$"cpu={measurement.Cpu.TotalMilliseconds,7:F3} " +
$"update={measurement.Update.TotalMilliseconds,6:F3} " +
$"alloc={measurement.Allocated,6} gen0={measurement.Gen0}");
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
{
var cases = new List<GoldenCase>();
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var (name, effect, frames) in HarnessCases.All())
{
if (!names.Add(name))
throw new HarnessException($"ケース名が重複しています。{name}");
var rendered = renderer.Render(effect, frames);
var files = new string[frames.Count];
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
for (var index = 0; index < frames.Count; index++)
{
hash.AppendData(rendered[index]);
files[index] = frames.Count == 1 ? name + ".png" : $"{name}-f{frames[index]:D3}.png";
}
var golden = new GoldenCase(name, frames, Convert.ToHexString(hash.GetHashAndReset()));
cases.Add(golden);
report?.Invoke(golden, files, rendered);
}
return cases;
}
static int CountDuplicates(IReadOnlyList<GoldenCase> cases)
{
var duplicates = 0;
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (name, _, hash) in cases)
{
if (seen.TryGetValue(hash, out var first))
{
Console.Error.WriteLine($"{name}: {first} と出力が一致します。設定がシェーダーへ届いていません。");
duplicates++;
}
else
{
seen.Add(hash, name);
}
}
return duplicates;
}
static int CountOpaque(byte[] pixels)
{
var count = 0;
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
{
if (pixels[offset] != 0)
count++;
}
return count;
}
+61
ファイルの表示
@@ -0,0 +1,61 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<AssemblyName>SpectrumColorShift.Harness</AssemblyName>
<RootNamespace>SpectrumColorShift.Harness</RootNamespace>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SpectrumColorShift\SpectrumColorShift.csproj" SetConfiguration="Configuration=$(Configuration)">
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
<AssemblyMetadata Include="HarnessDirectory" Value="$(MSBuildProjectDirectory)" />
</ItemGroup>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct2D1">
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Controls">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>
+51
ファイルの表示
@@ -0,0 +1,51 @@
namespace SpectrumColorShift.Harness;
internal static class SyntheticImage
{
const int GridPitch = 32;
public static byte[] Create(int width, int height)
{
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
var plateLeft = width * 0.10f;
var plateRight = width * 0.56f;
var plateTop = height * 0.14f;
var plateBottom = height * 0.86f;
var discCenterX = width * 0.70f;
var discCenterY = height * 0.50f;
var discRadius = MathF.Min(width, height) * 0.28f;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var positionX = x + 0.5f;
var positionY = y + 0.5f;
var plateInset = MathF.Min(MathF.Min(positionX - plateLeft, plateRight - positionX), MathF.Min(positionY - plateTop, plateBottom - positionY));
var plateCoverage = Math.Clamp(plateInset + 0.5f, 0f, 1f);
var distance = MathF.Sqrt((positionX - discCenterX) * (positionX - discCenterX) + (positionY - discCenterY) * (positionY - discCenterY));
var discCoverage = Math.Clamp(discRadius - distance + 0.5f, 0f, 1f);
if (plateCoverage == 0f && discCoverage == 0f)
continue;
var onGrid = x % GridPitch == 0 || y % GridPitch == 0;
var plateWeight = plateCoverage * (1f - discCoverage);
var shade = 1f - distance / discRadius * 0.5f;
var red = (onGrid ? 0.25f : 0.82f) * plateWeight + 0.90f * shade * discCoverage;
var green = (onGrid ? 0.30f : 0.86f) * plateWeight + 0.45f * shade * discCoverage;
var blue = (onGrid ? 0.40f : 0.90f) * plateWeight + 0.30f * shade * discCoverage;
var alpha = plateWeight + discCoverage;
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
pixels[offset] = ToByte(blue);
pixels[offset + 1] = ToByte(green);
pixels[offset + 2] = ToByte(red);
pixels[offset + 3] = ToByte(alpha);
}
}
return pixels;
}
static byte ToByte(float premultiplied) => (byte)MathF.Round(Math.Clamp(premultiplied, 0f, 1f) * byte.MaxValue);
}
+1
ファイルの表示
@@ -10,6 +10,7 @@
<BuildDependency Project="SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj" />
</Project>
<Project Path="SpectrumColorShift.Tests/SpectrumColorShift.Tests.csproj" />
<Project Path="SpectrumColorShift.Harness/SpectrumColorShift.Harness.csproj" />
<Project Path="SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj">
<BuildType Solution="*|*" Project="Release" />
<Platform Solution="*|*" Project="Win32" />