From 66b0f80a36196c8de9566c55522d8b787393daff Mon Sep 17 00:00:00 2001 From: routersys Date: Tue, 22 Sep 2026 12:31:28 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=8F=E3=83=BC=E3=83=8D=E3=82=B9=E3=82=92?= =?UTF-8?q?=E5=AE=9F=E6=A9=9F=E6=8F=8F=E7=94=BB=E3=81=AB=E3=82=88=E3=82=8B?= =?UTF-8?q?=E3=82=B4=E3=83=BC=E3=83=AB=E3=83=87=E3=83=B3=E6=A4=9C=E8=A8=BC?= =?UTF-8?q?=E5=9F=BA=E7=9B=A4=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- InkDispersion.Harness/Golden.cs | 55 ++ InkDispersion.Harness/GpuTimer.cs | 63 +++ InkDispersion.Harness/HarnessArguments.cs | 88 ++++ InkDispersion.Harness/HarnessCases.cs | 67 +++ InkDispersion.Harness/HarnessImage.cs | 59 +++ InkDispersion.Harness/HarnessRenderer.cs | 262 ++++++++++ InkDispersion.Harness/HostAssemblyResolver.cs | 37 ++ InkDispersion.Harness/ImageComparison.cs | 46 ++ .../InkDispersion.Harness.csproj | 39 +- InkDispersion.Harness/Program.cs | 480 +++++++++++------- InkDispersion.Harness/SyntheticImage.cs | 51 ++ InkDispersion.Harness/golden.json | 184 +++++++ 12 files changed, 1246 insertions(+), 185 deletions(-) create mode 100644 InkDispersion.Harness/Golden.cs create mode 100644 InkDispersion.Harness/GpuTimer.cs create mode 100644 InkDispersion.Harness/HarnessArguments.cs create mode 100644 InkDispersion.Harness/HarnessCases.cs create mode 100644 InkDispersion.Harness/HarnessImage.cs create mode 100644 InkDispersion.Harness/HarnessRenderer.cs create mode 100644 InkDispersion.Harness/HostAssemblyResolver.cs create mode 100644 InkDispersion.Harness/ImageComparison.cs create mode 100644 InkDispersion.Harness/SyntheticImage.cs create mode 100644 InkDispersion.Harness/golden.json diff --git a/InkDispersion.Harness/Golden.cs b/InkDispersion.Harness/Golden.cs new file mode 100644 index 0000000..185560e --- /dev/null +++ b/InkDispersion.Harness/Golden.cs @@ -0,0 +1,55 @@ +using System.IO; +using System.Reflection; +using System.Text.Encodings.Web; +using System.Text.Json; + +namespace InkDispersion.Harness; + +internal sealed record GoldenCase(string Name, IReadOnlyList Frames, string Hash); + +internal sealed record Golden(string Adapter, string Driver, string Input, string Canvas, IReadOnlyList 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(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() + .FirstOrDefault(attribute => string.Equals(attribute.Key, DirectoryKey, StringComparison.Ordinal)) + ?.Value ?? throw new HarnessException($"アセンブリに {DirectoryKey} がありません。"); +} diff --git a/InkDispersion.Harness/GpuTimer.cs b/InkDispersion.Harness/GpuTimer.cs new file mode 100644 index 0000000..6cd412f --- /dev/null +++ b/InkDispersion.Harness/GpuTimer.cs @@ -0,0 +1,63 @@ +using System.Diagnostics; +using Vortice.Direct3D11; + +namespace InkDispersion.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(disjoint, out var timing) || timing.Disjoint || timing.Frequency == 0UL) + return null; + if (!Wait(start, out var began) || !Wait(stop, out var ended) || ended < began) + return null; + return TimeSpan.FromSeconds((ended - began) / (double)timing.Frequency); + } + + bool Wait(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(); + } +} diff --git a/InkDispersion.Harness/HarnessArguments.cs b/InkDispersion.Harness/HarnessArguments.cs new file mode 100644 index 0000000..36364a9 --- /dev/null +++ b/InkDispersion.Harness/HarnessArguments.cs @@ -0,0 +1,88 @@ +namespace InkDispersion.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(); + 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 つだけ指定してください。"); +} diff --git a/InkDispersion.Harness/HarnessCases.cs b/InkDispersion.Harness/HarnessCases.cs new file mode 100644 index 0000000..90d75bd --- /dev/null +++ b/InkDispersion.Harness/HarnessCases.cs @@ -0,0 +1,67 @@ +using System.Windows.Media; + +namespace InkDispersion.Harness; + +internal static class HarnessCases +{ + public static IEnumerable<(string Name, InkDispersionEffect Effect, IReadOnlyList Frames)> All() + { + yield return ("default", Create(), [0]); + yield return ("default-frames-0-8", Create(), Enumerable.Range(0, 9).ToArray()); + yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0), [0]); + yield return ("spread-35", Create(effect => effect.Spread.Values[0].Value = 35), [0]); + yield return ("quality-balanced", Create(effect => effect.Quality = InkDispersionQuality.Balanced), [0]); + yield return ("quality-ultra", Create(effect => effect.Quality = InkDispersionQuality.Ultra), [0]); + yield return ("water-0", Create(effect => effect.Water.Values[0].Value = 0), [0]); + yield return ("water-100", Create(effect => effect.Water.Values[0].Value = 100), [0]); + yield return ("reach-5", Create(effect => effect.Reach.Values[0].Value = 5), [0]); + yield return ("reach-100", Create(effect => effect.Reach.Values[0].Value = 100), [0]); + yield return ("fiber-0", Create(effect => effect.Fiber.Values[0].Value = 0), [0]); + yield return ("fiber-100", Create(effect => effect.Fiber.Values[0].Value = 100), [0]); + yield return ("sizing-0", Create(effect => effect.Sizing.Values[0].Value = 0), [0]); + yield return ("sizing-100", Create(effect => effect.Sizing.Values[0].Value = 100), [0]); + yield return ("viscosity-0", Create(effect => effect.Viscosity.Values[0].Value = 0), [0]); + yield return ("viscosity-100", Create(effect => effect.Viscosity.Values[0].Value = 100), [0]); + yield return ("drying-0", Create(effect => effect.Drying.Values[0].Value = 0), [0]); + yield return ("drying-100", Create(effect => effect.Drying.Values[0].Value = 100), [0]); + yield return ("density-20", Create(effect => effect.Density.Values[0].Value = 20), [0]); + yield return ("density-100", Create(effect => effect.Density.Values[0].Value = 100), [0]); + yield return ("grain-0", Create(effect => effect.Grain.Values[0].Value = 0), [0]); + yield return ("grain-100", Create(effect => effect.Grain.Values[0].Value = 100), [0]); + yield return ("seed-42", Create(effect => effect.Seed = 42), [0]); + yield return ("ink-color", Create(effect => effect.InkColor = Color.FromArgb(255, 200, 20, 20)), [0]); + } + + public static IEnumerable<(string Name, Func Create, Action Change, int Frame)> Transitions() + { + yield return ("spread-100-to-35", () => Create(), effect => effect.Spread.Values[0].Value = 35, 0); + yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = InkDispersionQuality.Ultra, 0); + yield return ("water-60-to-100", () => Create(), effect => effect.Water.Values[0].Value = 100, 0); + yield return ("reach-25-to-100", () => Create(), effect => effect.Reach.Values[0].Value = 100, 0); + yield return ("fiber-50-to-100", () => Create(), effect => effect.Fiber.Values[0].Value = 100, 0); + yield return ("sizing-30-to-100", () => Create(), effect => effect.Sizing.Values[0].Value = 100, 0); + yield return ("viscosity-30-to-100", () => Create(), effect => effect.Viscosity.Values[0].Value = 100, 0); + yield return ("drying-40-to-100", () => Create(), effect => effect.Drying.Values[0].Value = 100, 0); + yield return ("density-80-to-20", () => Create(), effect => effect.Density.Values[0].Value = 20, 0); + yield return ("grain-40-to-100", () => Create(), effect => effect.Grain.Values[0].Value = 100, 0); + yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0); + yield return ("ink-color-change", () => Create(), effect => effect.InkColor = Color.FromArgb(255, 200, 20, 20), 0); + yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0); + } + + public static IEnumerable<(string Name, InkDispersionEffect Effect)> Benchmarks() + { + yield return ("quality-balanced", Create(effect => effect.Quality = InkDispersionQuality.Balanced)); + yield return ("default", Create()); + yield return ("quality-ultra", Create(effect => effect.Quality = InkDispersionQuality.Ultra)); + yield return ("reach-100", Create(effect => effect.Reach.Values[0].Value = 100)); + yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0)); + } + + public static InkDispersionEffect Create(Action? configure = null) + { + var effect = new InkDispersionEffect(); + configure?.Invoke(effect); + return effect; + } +} diff --git a/InkDispersion.Harness/HarnessImage.cs b/InkDispersion.Harness/HarnessImage.cs new file mode 100644 index 0000000..eb4b6ab --- /dev/null +++ b/InkDispersion.Harness/HarnessImage.cs @@ -0,0 +1,59 @@ +using System.IO; +using System.Security.Cryptography; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace InkDispersion.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); + } +} diff --git a/InkDispersion.Harness/HarnessRenderer.cs b/InkDispersion.Harness/HarnessRenderer.cs new file mode 100644 index 0000000..a5077d9 --- /dev/null +++ b/InkDispersion.Harness/HarnessRenderer.cs @@ -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 InkDispersion.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(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 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(Func create, Action 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); +} diff --git a/InkDispersion.Harness/HostAssemblyResolver.cs b/InkDispersion.Harness/HostAssemblyResolver.cs new file mode 100644 index 0000000..0c8ab43 --- /dev/null +++ b/InkDispersion.Harness/HostAssemblyResolver.cs @@ -0,0 +1,37 @@ +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace InkDispersion.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() + .FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal)) + ?.Value ?? string.Empty; +} diff --git a/InkDispersion.Harness/ImageComparison.cs b/InkDispersion.Harness/ImageComparison.cs new file mode 100644 index 0000000..98074dd --- /dev/null +++ b/InkDispersion.Harness/ImageComparison.cs @@ -0,0 +1,46 @@ +namespace InkDispersion.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); + } +} diff --git a/InkDispersion.Harness/InkDispersion.Harness.csproj b/InkDispersion.Harness/InkDispersion.Harness.csproj index d2f0969..b386323 100644 --- a/InkDispersion.Harness/InkDispersion.Harness.csproj +++ b/InkDispersion.Harness/InkDispersion.Harness.csproj @@ -1,14 +1,16 @@ - + Exe net10.0-windows10.0.19041.0 + true enable enable false InkDispersion.Harness InkDispersion.Harness x64 + false @@ -18,11 +20,42 @@ - - $(YMM4DirPath)YukkuriMovieMaker.Plugin.dll + + + + + + + $(YMM4DirPath)SharpGen.Runtime.dll + false + + + $(YMM4DirPath)Vortice.Direct2D1.dll + false + + + $(YMM4DirPath)Vortice.Direct3D11.dll + false + + + $(YMM4DirPath)Vortice.DirectX.dll + false + + + $(YMM4DirPath)Vortice.DXGI.dll + false + + + $(YMM4DirPath)Vortice.Mathematics.dll + false $(YMM4DirPath)YukkuriMovieMaker.Controls.dll + false + + + $(YMM4DirPath)YukkuriMovieMaker.Plugin.dll + false diff --git a/InkDispersion.Harness/Program.cs b/InkDispersion.Harness/Program.cs index 548a8b7..29861bb 100644 --- a/InkDispersion.Harness/Program.cs +++ b/InkDispersion.Harness/Program.cs @@ -1,212 +1,328 @@ -using System.Diagnostics; -using ComputeWeave; -using InkDispersion; +using System.IO; +using System.IO.Packaging; +using System.Security.Cryptography; +using InkDispersion.Harness; +using SharpGen.Runtime; -var width = 1280; -var height = 720; -var outputDirectory = args.Length > 0 && !args[0].StartsWith("--") ? args[0] : Path.Combine(AppContext.BaseDirectory, "harness-output"); -Directory.CreateDirectory(outputDirectory); +const int CanvasWidth = 1280; +const int CanvasHeight = 720; +const int ImageWidth = 640; +const int ImageHeight = 480; +const int FullHdWidth = 1920; +const int FullHdHeight = 1080; -using var pipeline = InkDispersionPipeline.TryCreate(); -if (pipeline is null) +_ = PackUriHelper.UriSchemePack; + +HarnessArguments arguments; +try { - Console.WriteLine("Direct3D 12 is unavailable."); - return 1; + arguments = HarnessArguments.Parse(args); +} +catch (HarnessException exception) +{ + Console.Error.WriteLine(exception.Message); + Console.Error.WriteLine(HarnessArguments.Usage); + return 2; } -var source = CreateTestImage(width, height); -var destination = new int[source.Length]; - -if (args.Contains("--golden")) +try { - var goldenCases = new (string Name, InkDispersionPipeline.Parameters Parameters)[] + 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) { - ("balanced-default", new(InkDispersionQuality.Balanced, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 120f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7)), - ("high-default", new(InkDispersionQuality.High, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 120f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7)), - ("seed-42", new(InkDispersionQuality.Balanced, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 120f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 42)), - ("partial-spread", new(InkDispersionQuality.Balanced, 0.35f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 120f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7)), - ("smooth", new(InkDispersionQuality.Balanced, 1f, 0.6f, 0f, 0f, 0.3f, 0.4f, 120f, 0.8f, 0f, 0.12f, 0.1f, 0.09f, 7)), - ("branching", new(InkDispersionQuality.Balanced, 1f, 1f, 1f, 0.8f, 0f, 0.2f, 120f, 1f, 1f, 0.12f, 0.1f, 0.09f, 7)), - ("viscous", new(InkDispersionQuality.Balanced, 1f, 0.6f, 0.5f, 0.3f, 1f, 0.8f, 120f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7)), - ("short-reach", new(InkDispersionQuality.Balanced, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 24f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7)), - }; - foreach (var (name, goldenParameters) in goldenCases) - { - var parameters = goldenParameters; - pipeline.Process(source, destination, width, height, in parameters); - var bytes = new byte[destination.Length * sizeof(int)]; - Buffer.BlockCopy(destination, 0, bytes, 0, bytes.Length); - Console.WriteLine($"{name}: {Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes))}"); + 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; } -foreach (var quality in new[] { InkDispersionQuality.Balanced, InkDispersionQuality.High, InkDispersionQuality.Ultra }) +static int Verify(HarnessRenderer renderer, HarnessImage image) { - var parameters = new InkDispersionPipeline.Parameters(quality, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - pipeline.Process(source, destination, width, height, in parameters); - pipeline.Process(source, destination, width, height, in parameters); - var stopwatch = Stopwatch.StartNew(); - const int frames = 5; - for (var frame = 0; frame < frames; frame++) - pipeline.Process(source, destination, width, height, in parameters); - stopwatch.Stop(); - Console.WriteLine($"{quality}: {stopwatch.Elapsed.TotalMilliseconds / frames:F2} ms/frame ({width}x{height}) litPixels={CountLit(destination)}"); -} - -{ - var device = GraphicsDevice.GetDefault(); - using var sourceTexture = device.AllocateReadWriteTexture2D(width, height); - var pixels = new Bgra32[source.Length]; - for (var index = 0; index < source.Length; index++) - pixels[index].PackedValue = unchecked((uint)source[index]); - sourceTexture.CopyFrom(pixels); - var parameters = new InkDispersionPipeline.Parameters(InkDispersionQuality.High, 1f, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - - pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters); - var stopwatch = Stopwatch.StartNew(); - pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, parameters with { Seed = 8 }); - stopwatch.Stop(); - Console.WriteLine($"structure recompute: {stopwatch.Elapsed.TotalMilliseconds:F2} ms"); - - if (pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect)) + var golden = Golden.Load(Golden.PathFor(image)); + var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}"; + if (golden.Input != image.Identity || golden.Canvas != canvas) { - using var rectOutput = device.AllocateReadWriteTexture2D(rect.Width, rect.Height); - pipeline.RenderVisible(rectOutput, width, height, rect, in parameters); - pipeline.WaitForCompletion(); - stopwatch.Restart(); - const int rectFrames = 20; - for (var frame = 0; frame < rectFrames; frame++) - { - pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters); - pipeline.TryGetVisibleBounds(width, height, in parameters, out rect); - pipeline.RenderVisible(rectOutput, width, height, rect, in parameters); - } - pipeline.WaitForCompletion(); - stopwatch.Stop(); - Console.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / rectFrames:F2} ms/frame"); + Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。"); + return 1; } -} -foreach (var spread in new[] { 0.25f, 0.5f, 0.75f, 1f }) -{ - var parameters = new InkDispersionPipeline.Parameters(InkDispersionQuality.High, spread, 0.6f, 0.5f, 0.3f, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - pipeline.Process(source, destination, width, height, in parameters); - Console.WriteLine($"spread={spread:F2} litPixels={CountLit(destination)}"); - WriteBmp(Path.Combine(outputDirectory, $"spread{(int)(spread * 100):D3}.bmp"), Composite(source, destination), width, height); -} + if (golden.Adapter != renderer.Adapter || golden.Driver != renderer.Driver) + Console.Error.WriteLine($"基準値は {golden.Adapter} (driver {golden.Driver}) で書かれています。今回は {renderer.Adapter} (driver {renderer.Driver}) です。画素の差はこの違いから来ることがあります。"); -foreach (var fiber in new[] { 0f, 0.5f, 1f }) -{ - var parameters = new InkDispersionPipeline.Parameters(InkDispersionQuality.High, 1f, 0.6f, fiber, 0.3f, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - pipeline.Process(source, destination, width, height, in parameters); - Console.WriteLine($"fiber={fiber:F2} litPixels={CountLit(destination)}"); - WriteBmp(Path.Combine(outputDirectory, $"fiber{(int)(fiber * 100):D3}.bmp"), Composite(source, destination), width, height); -} - -foreach (var sizing in new[] { 0f, 0.5f, 1f }) -{ - var parameters = new InkDispersionPipeline.Parameters(InkDispersionQuality.High, 1f, 0.6f, 0.5f, sizing, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - pipeline.Process(source, destination, width, height, in parameters); - Console.WriteLine($"sizing={sizing:F2} litPixels={CountLit(destination)}"); - WriteBmp(Path.Combine(outputDirectory, $"sizing{(int)(sizing * 100):D3}.bmp"), Composite(source, destination), width, height); -} - -foreach (var water in new[] { 0f, 0.5f, 1f }) -{ - var parameters = new InkDispersionPipeline.Parameters(InkDispersionQuality.High, 1f, water, 0.5f, 0.3f, 0.3f, 0.4f, 160f, 0.8f, 0.4f, 0.12f, 0.1f, 0.09f, 7); - pipeline.Process(source, destination, width, height, in parameters); - Console.WriteLine($"water={water:F2} litPixels={CountLit(destination)}"); - WriteBmp(Path.Combine(outputDirectory, $"water{(int)(water * 100):D3}.bmp"), Composite(source, destination), width, height); -} - -WriteBmp(Path.Combine(outputDirectory, "source.bmp"), source, width, height); -Console.WriteLine($"images written to {outputDirectory}"); -return 0; - -static int[] CreateTestImage(int width, int height) -{ - var pixels = new int[width * height]; - var left = width / 2 - 100; - var top = height / 2 - 40; - for (var y = top; y < top + 80; y++) + 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) { - for (var x = left; x < left + 200; x++) + if (!current.Remove(name, out var actual)) { - if (x < 0 || x >= width || y < 0 || y >= height) + 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; - pixels[y * width + x] = unchecked((int)0xFF303030); + } + + 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 pixels; + + return failures == 0 ? 0 : 1; } -static int CountLit(int[] pixels) +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 Evaluate(HarnessRenderer renderer, Action? report) +{ + var cases = new List(); + var names = new HashSet(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 cases) +{ + var duplicates = 0; + var seen = new Dictionary(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; - foreach (var pixel in pixels) + for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel) { - if (((pixel >> 24) & 255) > 8) + if (pixels[offset] != 0) count++; } + return count; } - -static int[] Composite(int[] source, int[] ink) -{ - var result = new int[source.Length]; - for (var index = 0; index < source.Length; index++) - { - var s = source[index]; - var i = ink[index]; - var sa = (s >> 24) & 255; - var ia = (i >> 24) & 255; - var a = Math.Min(ia + sa * (255 - ia) / 255, 255); - var r = Over((s >> 16) & 255, (i >> 16) & 255, ia); - var g = Over((s >> 8) & 255, (i >> 8) & 255, ia); - var b = Over(s & 255, i & 255, ia); - result[index] = 255 << 24 | OverWhite(r, a) << 16 | OverWhite(g, a) << 8 | OverWhite(b, a); - } - return result; - - static int Over(int s, int i, int ia) => Math.Min(i + s * (255 - ia) / 255, 255); - - static int OverWhite(int c, int a) => Math.Min(c + 255 - a, 255); -} - -static void WriteBmp(string path, int[] pixels, int width, int height) -{ - var stride = width * 3; - var padding = (4 - stride % 4) % 4; - var dataSize = (stride + padding) * height; - using var stream = new FileStream(path, FileMode.Create, FileAccess.Write); - using var writer = new BinaryWriter(stream); - writer.Write((byte)'B'); - writer.Write((byte)'M'); - writer.Write(54 + dataSize); - writer.Write(0); - writer.Write(54); - writer.Write(40); - writer.Write(width); - writer.Write(height); - writer.Write((short)1); - writer.Write((short)24); - writer.Write(0); - writer.Write(dataSize); - writer.Write(2835); - writer.Write(2835); - writer.Write(0); - writer.Write(0); - var pad = new byte[padding]; - for (var y = height - 1; y >= 0; y--) - { - for (var x = 0; x < width; x++) - { - var pixel = pixels[y * width + x]; - writer.Write((byte)(pixel & 255)); - writer.Write((byte)((pixel >> 8) & 255)); - writer.Write((byte)((pixel >> 16) & 255)); - } - writer.Write(pad); - } -} diff --git a/InkDispersion.Harness/SyntheticImage.cs b/InkDispersion.Harness/SyntheticImage.cs new file mode 100644 index 0000000..3cdb984 --- /dev/null +++ b/InkDispersion.Harness/SyntheticImage.cs @@ -0,0 +1,51 @@ +namespace InkDispersion.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); +} diff --git a/InkDispersion.Harness/golden.json b/InkDispersion.Harness/golden.json new file mode 100644 index 0000000..32a96c2 --- /dev/null +++ b/InkDispersion.Harness/golden.json @@ -0,0 +1,184 @@ +{ + "adapter": "Intel(R) Iris(R) Xe Graphics", + "driver": "32.0.101.7085", + "input": "synthetic 640x480 89838D8976198E40", + "canvas": "1280x720", + "cases": [ + { + "name": "default", + "frames": [ + 0 + ], + "hash": "113DFDEA266926477973E98AE6206E6E298E742156AA4C6D1A8081FC99165B0F" + }, + { + "name": "default-frames-0-8", + "frames": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8 + ], + "hash": "4653381D89BBF5C2D9F29E1FAEB2822DAF4A44531FB86D41A652D4A7D58A2DDA" + }, + { + "name": "amount-0", + "frames": [ + 0 + ], + "hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020" + }, + { + "name": "spread-35", + "frames": [ + 0 + ], + "hash": "2044C449FFA2EF1710F87E316F67A84FF0C65A4D702C361F616BE54DB1CB0D14" + }, + { + "name": "quality-balanced", + "frames": [ + 0 + ], + "hash": "E92F4034561AC95343AD3219F3A3136BB4EC837B2821E7BEBB0F01041426D614" + }, + { + "name": "quality-ultra", + "frames": [ + 0 + ], + "hash": "A2EF7866CAF0DE8DD6956B87DA0201CA09B5756D6E86589A4A0A4987329BE99B" + }, + { + "name": "water-0", + "frames": [ + 0 + ], + "hash": "6EEE4F9E922BE90793EBAC22294CE3D4FD93AD558B7F4871A0C4AF19B7E8052C" + }, + { + "name": "water-100", + "frames": [ + 0 + ], + "hash": "DBC385C9E9D360CD7389F8BF246029B3755BC45D6C096DD13F1FD93AEBF08048" + }, + { + "name": "reach-5", + "frames": [ + 0 + ], + "hash": "4BBE0349A16CE6900E0FE6A7C377DDD067ACE06EC874F7DBA29E82DD4D8D70A2" + }, + { + "name": "reach-100", + "frames": [ + 0 + ], + "hash": "35E77F455F45CC4D77E29E28C57E961632817D6D091C626B6F3D10FD9AA00CBB" + }, + { + "name": "fiber-0", + "frames": [ + 0 + ], + "hash": "04A35B75273746A7D5C75FD95C54D0AC7BA22E218FD204D2C8C0B1B04ABC6F16" + }, + { + "name": "fiber-100", + "frames": [ + 0 + ], + "hash": "6E6A13A2375BD6921BCEB73E1645F01F264415D9F93C624E2FCEFF09313EE765" + }, + { + "name": "sizing-0", + "frames": [ + 0 + ], + "hash": "C6C5845EE3137EFF91466779BEC27BD99A20D67AD9AF0A51F13E5A396B78A2E7" + }, + { + "name": "sizing-100", + "frames": [ + 0 + ], + "hash": "596DE879C4F54E499A66BBFA297F3E6E4606B3D41EE217BB3E06181B131D5F54" + }, + { + "name": "viscosity-0", + "frames": [ + 0 + ], + "hash": "3F2C41AA4D05FF0705CB6A4BE8319720A8C2B5D14AA3E6E08A15FD1D6EFA1706" + }, + { + "name": "viscosity-100", + "frames": [ + 0 + ], + "hash": "6E6A03CA3974EAFB62F13733A0E0FB32EA5DC1F66F46F6EC9D81B1E4366FEA08" + }, + { + "name": "drying-0", + "frames": [ + 0 + ], + "hash": "85E2D827928F912387FD99F1E823A9D7BC818165F2AD584EE92AD892F30C4616" + }, + { + "name": "drying-100", + "frames": [ + 0 + ], + "hash": "693FB39C5E31205DA071B5A25A727DD0D9E43F3B7FEE0C8F9675A2E279639F60" + }, + { + "name": "density-20", + "frames": [ + 0 + ], + "hash": "3A9AD2B483E1FEC9CE17F89DB4A644A861303F40F2156A0DD53C1D1B3D81ED0B" + }, + { + "name": "density-100", + "frames": [ + 0 + ], + "hash": "1062F6A23B59C4BD299A8A1D2DFDE67A7DF408DA253539852E8CD6DE4B6325E6" + }, + { + "name": "grain-0", + "frames": [ + 0 + ], + "hash": "8A28925D962C7E78663F013D0C762B55FE2F1814726C38F5256E5BA4B4943F8A" + }, + { + "name": "grain-100", + "frames": [ + 0 + ], + "hash": "BEC09BDABBFA8BAA56724AC155B08B27216C570D88F5C17C56EB0461F09AEBC7" + }, + { + "name": "seed-42", + "frames": [ + 0 + ], + "hash": "EBC1618FEA6112B2A7A90F770495E920773D1685D048B336460C573870DD0DE0" + }, + { + "name": "ink-color", + "frames": [ + 0 + ], + "hash": "7F958DC79DC050C1A41B763BF3E6BC8E93126948F95AD864D685F2A9D472EF0C" + } + ] +} \ No newline at end of file