106 コミット
作成者 SHA1 メッセージ 日付
routersys 6e4dafb347 過去のタグ用ワークフローを消す 2026-11-08 13:06:34 +09:00
routersys 17bd4d9c90 Gitea Actions のワークフローを直す 2026-11-08 13:06:34 +09:00
routersys 85c4037e2d Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 12:30:27 +09:00
routersys f91254e227 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 12:10:50 +09:00
routersys 3f8bc8f03b 過去のタグ用ワークフローを消す 2026-11-08 11:29:54 +09:00
routersys 6443d0f7b5 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 10:54:43 +09:00
routersys 6428e9ca9b Gitea Actions のワークフローを直す 2026-11-08 10:15:51 +09:00
routersys cf9cb7c545 Gitea Actions のワークフローを直す 2026-11-08 09:48:50 +09:00
routersys 27b142d013 過去のタグ用ワークフローを消す 2026-11-08 03:58:13 +09:00
routersys 84146a13b0 Gitea Actions のワークフローを直す 2026-11-08 03:56:20 +09:00
routersys 9a481abd11 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:34:56 +09:00
routersys 82e422fd42 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:07:28 +09:00
routersys d8f69b3bac Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 23:51:03 +09:00
routersys 1c8584643e Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:36:39 +09:00
routersys ec3691a870 Gitea Actions のワークフローを直す 2026-11-07 22:08:42 +09:00
routersys e90d1cd59b Gitea Actions のワークフローを直す 2026-11-07 21:53:44 +09:00
routersys ee5194cce0 Gitea Actions のワークフローを足す 2026-11-07 19:53:47 +09:00
routersys bca2caae00 画像の参照先をGiteaへ移す 2026-11-07 18:22:22 +09:00
routersys f05f073cbb サブモジュールの参照先をGiteaへ移す 2026-11-07 18:19:30 +09:00
routersys 3a00140289 不具合の報告の説明を送信の上限と項目へ合わせる 2026-11-02 11:35:47 +09:00
routersys 73102b78b3 ハーネスの基準値を計算領域の余白の変更に合わせる 2026-10-03 17:41:15 +09:00
routersys a1071d504a バージョンをv1.2.3へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.3 のコミットから作成しました
2026-10-03 17:22:49 +09:00
routersys 250821f68e 資源が回収された後の処理器の描画の試験を追加する 2026-10-03 17:11:01 +09:00
routersys 4bfa25b4b3 格子の資源が回収された後に計算し直す試験を追加する 2026-10-03 17:11:01 +09:00
routersys cef93c9176 格子の資源が回収された後の描画の試験を追加する 2026-10-03 17:11:00 +09:00
routersys 37152f3011 回収された格子の資源を描画の前に作り直す
・GPUのメモリが逼迫して資源が回収された後に、描画が失敗し続ける不具合を修正-F
2026-10-03 17:11:00 +09:00
routersys 97735cdc13 バージョンをv1.2.2へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.2 のコミットから作成しました
2026-09-29 08:53:43 +09:00
routersys c7fa14c912 v1.2.1以降の変更の分類行を追記する
・版ずれ、線の太さ、線の流れを変えると色面の内側の絵柄まで変わる不具合を修正-F
・エフェクトを作るたびに描画コンテキストが解放されずに残る不具合を修正-F
・パイプラインの作成で起きた想定外の例外を報告せずに素通しにしていた不具合を修正-F
・エフェクトの作成で起きた例外を二重に報告していた不具合を修正-F
・入力のつなぎ直しと破棄で起きた例外も報告するよう変更-M
2026-09-29 08:53:43 +09:00
routersys 9443e5ce1d サムネイル画像を更新する 2026-09-28 22:08:15 +09:00
routersys bc5689b3ed Merge pull request #1 from routersys/develop
試験を既存群に揃え例外と余白の扱いを直し文書を清書する
2026-09-28 18:45:44 +09:00
routersys e750ce30cb Plugin_Readmeに不具合の報告を載せる 2026-09-28 18:36:10 +09:00
routersys f4bbaf8a44 不具合の報告の範囲を実装に合わせる 2026-09-28 18:36:10 +09:00
routersys 6247436fbe 仕組みと各項目の説明を実装に合わせて書き直す 2026-09-28 18:36:10 +09:00
routersys b20417b21f 論文の出典を掲載誌と年の書誌で示す 2026-09-28 18:36:10 +09:00
routersys d4612318a1 Plugin_Readmeの同梱ライブラリをComputeWeaveにする 2026-09-28 18:36:10 +09:00
routersys 0b65e50092 READMEの文字コードをeditorconfigに合わせる 2026-09-28 18:36:10 +09:00
routersys 7164fd97a2 文字コードをeditorconfigに合わせてBOMを除く 2026-09-27 21:12:45 +09:00
routersys af64c7e489 相互運用の描画コンテキストの参照を漏らさない 2026-09-27 20:34:01 +09:00
routersys e4fcb11eba 余白に関わる項目を変えたときの試験を追加する 2026-09-27 20:33:05 +09:00
routersys 4860bddfcd 計算領域の余白を版ずれと主線の設定の最大値で求める 2026-09-27 20:33:05 +09:00
routersys 107b89fa5d 資源確保の失敗だけを素通しにしそれ以外の例外は伝える 2026-09-27 20:27:08 +09:00
routersys a84da190cd 例外の報告をホストからの呼び出し口へ移す 2026-09-27 20:26:00 +09:00
routersys 297469090a 変異試験の並列数と制限時間をGPUに合わせる 2026-09-27 19:57:03 +09:00
routersys f359d47896 シェーダーを変異試験の対象から外す 2026-09-27 18:27:27 +09:00
routersys fa3faf123a リリースワークフローへ試験の段を戻す 2026-09-27 18:23:10 +09:00
routersys 3af72edb39 WPFアプリケーションの外での挙動の試験を追加する 2026-09-27 16:42:57 +09:00
routersys cad669dc34 処理器の試験を追加する 2026-09-27 16:40:58 +09:00
routersys 99f67e4c56 カスタムエフェクトの試験を追加する 2026-09-27 16:38:08 +09:00
routersys 07065ec2d9 文言の試験を追加する 2026-09-27 16:35:58 +09:00
routersys c763d2c030 パラメータの試験を既存群の形で書き直す 2026-09-27 16:31:24 +09:00
routersys a8af131b22 入力を大きな画像へ替えた後の描画の試験を追加する 2026-09-27 16:24:26 +09:00
routersys 22e0ceff96 相互運用の試験を土台の上に書き直す 2026-09-27 16:23:34 +09:00
routersys a24eecd681 パイプラインを作れないときは試験を飛ばさずに失敗させる 2026-09-27 16:21:29 +09:00
routersys d8108d5d88 版画の計算の試験を分ける 2026-09-27 16:20:18 +09:00
routersys 53c4aa7cb3 設定値の試験を分ける 2026-09-27 16:16:30 +09:00
routersys 2636406047 管理メモリの試験を暖機の揺れに左右されない形にする 2026-09-27 16:10:39 +09:00
routersys 5ac7a1468a 試験の土台を追加する 2026-09-27 15:37:57 +09:00
routersys e6830fe96a 本体の参照でプラットフォームを固定しない 2026-09-27 15:37:36 +09:00
routersys 052dc9f2b9 テストプロジェクトの設定を既存群に揃える 2026-09-27 15:37:30 +09:00
routersys 8263ccd56e Stryker.NETで変異試験を行う 2026-09-27 15:37:05 +09:00
routersys 64a13c18f0 テストの依存関係を最新にする 2026-09-27 15:36:54 +09:00
routersys 05bc9268d1 Textsの名前空間をファイル形式にする 2026-09-26 00:36:47 +09:00
routersys 03a6d6fb9c エディターのコード規則を追加する 2026-09-26 00:36:46 +09:00
routersys 132390fd91 プルリクエストのテンプレートを追加する 2026-09-23 14:05:22 +09:00
routersys b74428a22a Issueのテンプレートを追加する 2026-09-23 14:05:22 +09:00
routersys 3c3ab7052d スポンサーの設定を追加する 2026-09-23 14:05:22 +09:00
routersys c5e0520a19 貢献の手引きを追加する 2026-09-23 14:05:21 +09:00
routersys 4dc8c38559 セキュリティポリシーを追加する 2026-09-23 14:05:21 +09:00
routersys ba7211523b 行動規範を追加する 2026-09-23 14:05:20 +09:00
routersys 3beaca71a9 バージョンをv1.2.1へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.1 のコミットから作成しました
2026-09-21 18:12:51 +09:00
routersys ad98682c84 平坦化のディスパッチ切り上げをComputeWeaveへ委ねる 2026-09-21 17:20:00 +09:00
routersys b19841f723 ComputeWeaveを2.6.0へ更新する 2026-09-21 17:18:00 +09:00
routersys 03f63e5266 gitmodulesの先頭のBOMを取り除く
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.0 のコミットから作成しました
・GitHubが認識できなかったサブモジュール定義を修正-F
2026-09-21 16:26:39 +09:00
routersys abcf0c3a2b バージョンをv1.2.0へ更新する 2026-09-21 16:23:09 +09:00
routersys cb449bcae8 リリースノートへ分類の内訳節を加える 2026-09-21 16:10:20 +09:00
routersys df53e08a85 vcxprojファイルへBOMを付ける 2026-09-21 15:44:21 +09:00
routersys c78c5315fe 使われなくなったFxcPathの設定を取り除く 2026-09-21 15:35:21 +09:00
routersys 12d56819b9 ハーネスへ構造再計算の内訳計測を統合する 2026-09-21 15:31:53 +09:00
routersys 6afdd5e63c ハーネスを実機描画によるゴールデン検証基盤にする 2026-09-21 14:56:30 +09:00
routersys 9eee3f6da0 リリースワークフローを既存群と同一の構成にする 2026-09-21 14:35:05 +09:00
routersys 1f64a28b5c Plugin_Readmeの見出しを実際の版へ合わせる
・同梱するReadme.txtの版表記が古いままだった不具合を修正-F
2026-09-21 14:34:20 +09:00
routersys 8728ad1a7b ルートファイルをSolution Itemsへ加える 2026-09-21 14:32:22 +09:00
routersys 92134d27d6 シェーダーの生成をUkiyoe.Shaderへ切り出す 2026-09-21 14:31:35 +09:00
routersys 7c5f566a8b READMEへ不具合の報告を追記する 2026-09-21 14:09:38 +09:00
routersys 4a743b3dc5 更新確認で例外を握り潰さず報告する 2026-09-21 14:09:37 +09:00
routersys 2f8e39c12f 更新確認をWPF起動中に限り行う 2026-09-21 14:08:49 +09:00
routersys 93f15d5839 ホストとDirect2Dからの呼び出し口で例外を報告する
・想定していない例外を開発者へ自動で報告する機能を追加-A
2026-09-21 13:29:07 +09:00
routersys ef5690c3e1 UkiyoeTelemetryを追加する 2026-09-21 13:27:25 +09:00
routersys 29d3e161bb Telemetryをコンパイルに含める 2026-09-21 13:25:44 +09:00
routersys ee96c42dcb YMM4-Telemetryサブモジュールを追加する 2026-09-21 13:24:41 +09:00
routersys ad7d9df207 影の寸法フィールドを資源集合へ委ねる 2026-09-01 15:06:19 +09:00
routersys 7ffb9eaad3 ComputeWeaveを2.3.0へ更新する 2026-09-01 14:24:27 +09:00
routersys 676125b2cb ComputeWeaveを1.8.1へ更新する 2026-08-18 13:41:22 +09:00
routersys 1216404915 Device解決を本体提供のAPIへ替える 2026-08-18 12:15:31 +09:00
routersys be17ba63f1 ComputeWeaveを1.8.0へ更新する 2026-08-18 12:15:31 +09:00
routersys c2e15973b3 ComputeWeaveを1.7.2へ更新する 2026-08-17 23:11:19 +09:00
routersys ee33262486 ComputeWeaveを1.7.1へ更新する 2026-08-17 21:47:31 +09:00
routersys bdd3c2a589 包み方の変更に伴い検証を更新する 2026-08-17 21:15:38 +09:00
routersys 9669a70c26 外部Viewの所有取得でビットマップを包む 2026-08-17 21:15:38 +09:00
routersys f53e354a7e 外部Viewの移行に伴い検証を更新する 2026-08-17 19:54:00 +09:00
routersys 4c348529b6 相互運用Providerを本体提供の基底へ移す 2026-08-17 19:54:00 +09:00
routersys 35ecb2f1ce 構造再計算の内訳を交互測定する 2026-08-17 16:47:43 +09:00
routersys ddb7ebce0c 部分再計算が全再計算と一致することを検証する 2026-08-17 16:47:43 +09:00
routersys 5f410df284 構造の再計算を部分グラフ単位へ分ける 2026-08-17 16:47:35 +09:00
routersys bceb744fee 外部キューSchedulerを本体提供のものへ替える 2026-08-17 15:44:55 +09:00
routersys d222463ca6 ComputeWeaveを1.5.0へ更新する 2026-08-17 15:44:47 +09:00
67個のファイルの変更、5572行の追加、1378行の削除

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

+13
ファイルの表示
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-stryker": {
"version": "5.0.0",
"commands": [
"dotnet-stryker"
],
"rollForward": false
}
}
}
+77
ファイルの表示
@@ -0,0 +1,77 @@
root = true
[*]
indent_style = space
indent_size = 4
tab_width = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,yaml}]
indent_size = 2
[*.{csproj,props,targets,vcxproj,filters,slnx,resx,xml}]
charset = unset
indent_style = unset
indent_size = unset
[*.md]
trim_trailing_whitespace = false
[*.cs]
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
dotnet_style_qualification_for_field = false:error
dotnet_style_qualification_for_property = false:error
dotnet_style_qualification_for_method = false:error
dotnet_style_qualification_for_event = false:error
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
dotnet_style_readonly_field = true:warning
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_code_quality_unused_parameters = all:warning
csharp_style_namespace_declarations = file_scoped:error
csharp_using_directive_placement = outside_namespace:error
csharp_prefer_braces = when_multiline:silent
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_readonly_struct = true:warning
csharp_style_prefer_readonly_struct_member = true:warning
csharp_prefer_static_local_function = true:warning
csharp_style_prefer_primary_constructors = true:silent
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
dotnet_diagnostic.IDE0005.severity = warning
dotnet_diagnostic.IDE0055.severity = warning
dotnet_diagnostic.IDE0161.severity = error
[{YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
[*.{g.cs,designer.cs}]
generated_code = true
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
+538
ファイルの表示
@@ -0,0 +1,538 @@
name: リリース
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: リリースするタグ
required: true
permissions:
contents: write
jobs:
build-and-release:
runs-on: windows-latest
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v7
env:
GIT_CONFIG_COUNT: "2"
GIT_CONFIG_KEY_0: url.https://git.routersys.com/routersys/.insteadOf
GIT_CONFIG_VALUE_0: https://github.com/routersys/
GIT_CONFIG_KEY_1: url.https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.insteadOf
GIT_CONFIG_VALUE_1: https://github.com/manju-summoner/YukkuriMovieMaker.Generator
with:
ref: ${{ inputs.tag || github.ref_name }}
submodules: recursive
fetch-depth: 0
- name: MSBuild のセットアップ
uses: microsoft/setup-msbuild@v3
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
$list = 'C:\runner\cache\ymm4\releases.json'
New-Item -ItemType Directory -Force -Path (Split-Path $list) | Out-Null
if (-not (Test-Path $list) -or (Get-Item $list).Length -lt 1000 -or ((Get-Date) - (Get-Item $list).LastWriteTime).TotalHours -gt 6) {
$fetched = $null
for ($attempt = 1; $attempt -le 6 -and -not $fetched; $attempt++) {
try {
$fetched = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases?per_page=100" `
-Headers @{ "User-Agent" = "Ukiyoe-CI" } -ErrorAction Stop
}
catch {
$message = $_.Exception.Message
Write-Host "リリース一覧の取得に失敗しました($attempt 回目): $($message.Substring(0, [Math]::Min(80, $message.Length)))"
Start-Sleep -Seconds (5 * $attempt)
}
}
if (@($fetched).Count -gt 0) {
$fetched | Select-Object tag_name, published_at, prerelease, draft, assets |
ConvertTo-Json -Depth 6 | Set-Content -Path $list -Encoding UTF8
}
elseif (-not (Test-Path $list)) { throw 'the list of releases could not be fetched' }
else { Write-Host '保存済みのリリース一覧を使います' }
}
$when = [DateTimeOffset](git log -1 --format=%cI)
$releases = @(Get-Content -Raw -Path $list | ConvertFrom-Json | Where-Object { -not $_.draft -and -not $_.prerelease })
$release = $releases | Where-Object { [DateTimeOffset]$_.published_at -le $when } | Select-Object -First 1
if (-not $release) { $release = $releases | Select-Object -Last 1 }
Write-Host "最後のコミット $when に合わせた YMM4: $($release.tag_name)"
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
Write-Host "ダウンロード対象: $($asset.name)"
$cache = Join-Path 'C:\runner\cache\ymm4' $asset.name
$extracted = "$cache.extracted"
$lock = New-Object System.Threading.Mutex($false, 'Global\ci-ymm4-cache')
[void]$lock.WaitOne()
try {
if (-not (Test-Path "$extracted\.complete")) {
New-Item -ItemType Directory -Force -Path (Split-Path $cache) | Out-Null
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $cache
Remove-Item -Recurse -Force $extracted -ErrorAction SilentlyContinue
Expand-Archive -Path $cache -DestinationPath $extracted -Force
New-Item -ItemType File -Path "$extracted\.complete" | Out-Null
}
else {
Write-Host "保存済みの YMM4 を使います: $extracted"
}
}
finally {
$lock.ReleaseMutex()
}
$ymm4Dir = (Get-ChildItem -Path $extracted -Recurse -Filter "YukkuriMovieMaker.dll" |
Select-Object -First 1).DirectoryName
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
id: version
shell: pwsh
run: |
$tag = "${{ inputs.tag || github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: バージョン記載の照合
shell: pwsh
run: |
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "Ukiyoe/Ukiyoe.csproj"
$csproj = Get-Content $csprojPath -Raw
if (-not $csproj.Contains("<Version>$version</Version>")) {
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
}
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" 浮世絵 for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ 浮世絵 for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
if ($problems.Count -eq 0) {
Write-Host "バージョン記載は $tag と一致しています"
exit 0
}
foreach ($problem in $problems) {
Write-Host "::error::$problem"
}
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
exit 1
- name: シェーダーのビルド
shell: pwsh
run: |
msbuild Ukiyoe.Shader/Ukiyoe.Shader.vcxproj `
/p:Configuration=Release `
/p:Platform=Win32 `
/nologo
- name: プロジェクトのビルド
shell: pwsh
run: |
$proj = "Ukiyoe/Ukiyoe.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
- name: テストプロジェクトのビルド
shell: pwsh
run: |
dotnet build Ukiyoe.Tests/Ukiyoe.Tests.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true `
-maxcpucount:1
- name: テストの実行
shell: pwsh
run: |
dotnet test Ukiyoe.Tests/Ukiyoe.Tests.csproj `
--no-build `
--no-restore `
-c Release `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Ukiyoe/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/Ukiyoe"
$pkgName = "Ukiyoe_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
$dll = "$outDir/plugin/Ukiyoe.dll"
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に Ukiyoe.dll が見つかりませんでした: $dll"
exit 1
}
Copy-Item $dll "$stageRoot/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
if (Test-Path $src) {
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" 浮世絵 for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- name: 変更履歴の作成
id: changelog
shell: pwsh
env:
GITEA_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.TAG }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
run: |
$tag = $env:TAG
$repository = $env:REPOSITORY
$server = $env:SERVER_URL
$code = [char]0x60
$fence = [string]::new($code, 3)
$unit = [char]0x1f
$record = [char]0x1e
$previous = ""
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
if ($candidates.Count -gt 0) {
$previous = $candidates[0]
}
Write-Host "直前のタグ: $previous"
$range = if ($previous) { "$previous..$tag" } else { $tag }
$log = (@(git log "--format=%H%x1f%s%x1f%an%x1f%ad%x1f%b%x1e" --date=short $range) -join "`n") -split $record
$commits = @()
foreach ($entry in $log) {
if (-not $entry.Trim()) { continue }
$fields = $entry.TrimStart("`n") -split $unit
if ($fields.Count -lt 5) { continue }
$commits += [pscustomobject]@{
Sha = $fields[0]
Subject = $fields[1]
Name = $fields[2]
Date = $fields[3]
Body = $fields[4]
Login = ""
Avatar = ""
}
}
Write-Host "コミット数: $($commits.Count)"
$categories = [ordered]@{
A = @{ Title = "追加"; Symbol = "+"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
M = @{ Title = "変更"; Symbol = "~"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
D = @{ Title = "削除"; Symbol = "-"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
F = @{ Title = "修正"; Symbol = "!"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
}
foreach ($commit in $commits) {
if (-not $commit.Body) { continue }
foreach ($bodyLine in ($commit.Body -split "`n")) {
$trimmed = $bodyLine.Trim()
if ($trimmed -notmatch '^・(.+)-([AMDF])$') { continue }
$categories[$Matches[2]].Items.Add([pscustomobject]@{ Text = $Matches[1]; Sha = $commit.Sha })
}
}
$pending = [System.Collections.Generic.HashSet[string]]::new()
foreach ($commit in $commits) {
[void]$pending.Add($commit.Sha)
}
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
$accounts = @{}
$page = 1
while ($pending.Count -gt 0 -and $page -le 20) {
$rows = @()
try {
$rows = @(Invoke-RestMethod -Uri "$server/api/v1/repos/$repository/commits?sha=$tag&limit=50&page=$page&stat=false&verification=false&files=false" -Headers $headers)
}
catch {
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
break
}
if ($rows.Count -eq 0) { break }
foreach ($row in $rows) {
if ($pending.Remove($row.sha)) {
$login = ""
$avatar = ""
if ($row.author) {
$login = [string]$row.author.login
$avatar = [string]$row.author.avatar_url
}
$accounts[$row.sha] = @{ Login = $login; Avatar = $avatar }
}
}
if ($rows.Count -lt 50) { break }
$page++
}
foreach ($commit in $commits) {
if ($accounts.ContainsKey($commit.Sha)) {
$commit.Login = $accounts[$commit.Sha].Login
$commit.Avatar = $accounts[$commit.Sha].Avatar
}
}
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
$base = if ($previous) { $previous } else { $emptyTree }
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
$changedFiles = 0
$insertions = 0
$deletions = 0
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
$diffStat = @(git diff --stat $base $tag)
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
$contributors = @($commits |
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
Sort-Object -Property Count -Descending)
function Get-Icon($avatar, $login, $size) {
if (-not $avatar) { return "" }
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
}
$package = Get-Item $env:PACKAGE
$size = [math]::Round($package.Length / 1MB, 2)
$body = [System.Collections.Generic.List[string]]::new()
$body.Add("## 概要")
$body.Add("")
$body.Add("| 項目 | 内容 |")
$body.Add("|---|---|")
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
$body.Add("| 公開日 | $tagDate |")
if ($previous) {
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
}
$body.Add("| コミット数 | $($commits.Count) |")
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
$body.Add("| 変更されたファイル | $changedFiles |")
$body.Add("| 追加された行 | $insertions |")
$body.Add("| 削除された行 | $deletions |")
$hasHighlights = ($categories.Values | ForEach-Object { $_.Items.Count } | Measure-Object -Sum).Sum -gt 0
if ($hasHighlights) {
$body.Add("")
$body.Add("## 主な変更")
foreach ($key in $categories.Keys) {
$category = $categories[$key]
if ($category.Items.Count -eq 0) { continue }
$body.Add("")
$body.Add("### [$($category.Symbol)] $($category.Title)")
$body.Add("")
foreach ($item in $category.Items) {
$short = $item.Sha.Substring(0, 7)
$body.Add("- $($item.Text) ([$code$short$code]($server/$repository/commit/$($item.Sha)))")
}
}
}
$body.Add("")
$body.Add("## ダウンロード")
$body.Add("")
$body.Add("| ファイル | サイズ |")
$body.Add("|---|---|")
$body.Add("| $($package.Name) | $size MB |")
$body.Add("")
$body.Add("## 貢献者")
$body.Add("")
$body.Add("| 貢献者 | コミット数 |")
$body.Add("|---|---|")
foreach ($contributor in $contributors) {
$first = $contributor.Group[0]
if ($first.Login) {
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
}
else {
$name = $first.Name
}
$body.Add("| $name | $($contributor.Count) |")
}
$body.Add("")
$body.Add("## 変更履歴")
$body.Add("")
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
$body.Add("|---|---|---|---|")
$maximumCommits = 300
$listed = 0
foreach ($commit in $commits) {
if ($listed -ge $maximumCommits) { break }
$short = $commit.Sha.Substring(0, 7)
$subject = $commit.Subject -replace '\|', '\|'
if ($commit.Login) {
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
}
else {
$author = $commit.Name
}
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
$listed++
}
if ($commits.Count -gt $maximumCommits) {
$body.Add("")
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
}
if ($diffStat.Count -gt 0) {
$body.Add("")
$body.Add("## 変更されたファイル")
$body.Add("")
$body.Add("<details>")
$body.Add("<summary>差分の統計</summary>")
$body.Add("")
$body.Add($fence)
$maximumStatLines = 200
$shown = 0
foreach ($line in $diffStat) {
if ($shown -ge $maximumStatLines) { break }
$body.Add($line)
$shown++
}
if ($diffStat.Count -gt $maximumStatLines) {
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
}
$body.Add($fence)
$body.Add("")
$body.Add("</details>")
}
if ($previous) {
$body.Add("")
$body.Add("## 全ての変更")
$body.Add("")
$body.Add("$server/$repository/compare/$previous...$tag")
}
$path = "release-body.md"
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
if (-not (Test-Path $path)) {
throw "変更履歴を作成できませんでした。"
}
Write-Host "変更履歴の行数: $($body.Count)"
$global:LASTEXITCODE = 0
- name: Gitea リリースの作成
shell: pwsh
env:
GITEA_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
EVENT_NAME: ${{ github.event_name }}
WORKFLOW_NAME: ${{ github.workflow }}
JOB_NAME: ${{ github.job }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
RELEASE_NAME: ${{ steps.version.outputs.TAG }}
RELEASE_BODY: ''
RELEASE_BODY_PATH: release-body.md
RELEASE_DRAFT: false
RELEASE_PRERELEASE: false
RELEASE_FILES: |
${{ steps.package.outputs.PKG_NAME }}
run: |
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
$api = "$env:SERVER_URL/api/v1/repos/$env:REPOSITORY"
$tag = $env:RELEASE_TAG
$body = $env:RELEASE_BODY
if ($env:RELEASE_BODY_PATH -and (Test-Path $env:RELEASE_BODY_PATH)) {
$body = Get-Content $env:RELEASE_BODY_PATH -Raw -Encoding utf8
}
$files = @()
foreach ($pattern in ($env:RELEASE_FILES -split "[`r`n,]+" | Where-Object { $_.Trim() })) {
$found = @(Get-ChildItem -Path $pattern.Trim() -File -ErrorAction SilentlyContinue)
if ($found.Count -eq 0) { throw "リリースに付けるファイルが見つかりません: $pattern" }
$files += $found
}
$payload = @{
tag_name = $tag
name = $env:RELEASE_NAME
body = [string]$body
draft = ($env:RELEASE_DRAFT -eq 'true')
prerelease = ($env:RELEASE_PRERELEASE -eq 'true')
} | ConvertTo-Json
$bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
$existing = $null
try { $existing = Invoke-RestMethod -Uri "$api/releases/tags/$([System.Uri]::EscapeDataString($tag))" -Headers $headers } catch { }
if ($existing) {
$release = Invoke-RestMethod -Method Patch -Uri "$api/releases/$($existing.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
foreach ($asset in @($existing.assets)) {
Invoke-RestMethod -Method Delete -Uri "$api/releases/$($existing.id)/assets/$($asset.id)" -Headers $headers | Out-Null
}
} else {
$release = Invoke-RestMethod -Method Post -Uri "$api/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
}
foreach ($file in $files) {
$name = [System.Uri]::EscapeDataString($file.Name)
Invoke-RestMethod -Method Post -Uri "$api/releases/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item $file.FullName } | Out-Null
Write-Host "添付しました: $($file.Name)"
}
Write-Host "リリースを作成しました: $($release.html_url)"
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
try {
$sha = (git rev-parse HEAD).Trim()
$status = @{
state = 'success'
context = "$env:WORKFLOW_NAME / $env:JOB_NAME (workflow_dispatch)"
description = "Actions がタグ $tag のコミットから作成しました"
target_url = $env:RUN_URL
} | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "$api/statuses/$sha" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($status)) | Out-Null
Write-Host "タグのコミット $sha に成功の状態を付けました"
}
catch {
Write-Warning "タグのコミットに状態を付けられませんでした: $($_.Exception.Message)"
}
}
-63
ファイルの表示
@@ -1,63 +0,0 @@
# v1.0.1 - 浮世絵 for YMM4
浮世絵エフェクトプラグインの改善リリースです。
L1平坦化の反復で近傍セルの読み取りをグループ共有メモリへ移し、地色の計算を高速化しました。
高品質の1フレームあたりの処理時間は297.8msから177.3msへ短縮しました。
この変更は浮動小数点の丸めが変わるため、出力がv1.0.0と完全には一致しません。根拠と影響の範囲は「3. 等価性について」に記載します。
---
## 改善
### 1. 平坦化反復のグループ共有メモリによるタイル化
L1平坦化の各反復は、1セルにつき近傍24セルの元の色と勾配強度と反復値を読み取ります。隣り合うセルは読み取る範囲が重なるため、同じ値を何度も大域メモリから取得していました。8×8のスレッドグループごとに12×12セルの領域をグループ共有メモリへ一度だけ読み込み、以降の近傍参照をすべて共有メモリから行うようにしました。
- 1セルあたりの大域メモリの読み取りは、色と勾配強度と反復値の3種類で最大75回から、グループ内で分担した約7回へ減りました。
- 近傍の加算の順序と各項の値は変更していません。変わるのは値を読み出す記憶域の種類だけです。
- グループ共有メモリを使うシェーダーは、グループ内のすべてのスレッドが同期に到達する必要があります。ComputeWeaveが生成するシェーダーの入口は`For`へ渡した反復数を上限としてスレッドを間引くため、処理格子の寸法のままディスパッチすると最終グループの一部のスレッドが同期に到達しません。平坦化のディスパッチ範囲は8の倍数へ切り上げています。切り上げで増えたスレッドは格子の範囲外として何も書き込みません。
### 2. 性能
1280×720の素材、検証ハーネス、Releaseビルドによる実測値です。GPUはIntel Iris Xe Graphicsです。1回の実行で10フレームを処理した最小値を取り、新旧のバイナリを交互に3回ずつ実行した最小値を記載します。この環境は実行ごとの変動が大きいため、交互実行で熱状態の影響をそろえています。
| 項目 | v1.0.0 | v1.0.1 |
|---|---:|---:|
| 標準品質の1フレーム | 115.4ms | 70.2ms |
| 高品質の1フレーム | 297.8ms | 177.3ms |
| 最高品質の1フレーム | 452.9ms | 256.3ms |
| 高品質の構造の再計算 | 311.6ms | 168.6ms |
| キャッシュが効いたフレーム | 2.73ms | 2.18ms |
キャッシュが効いたフレームは平坦化を実行しないため、この行の差は環境の変動によるものです。
### 3. 等価性について
検証ハーネスの`--golden`引数で、品質2段階、シード変更、平坦化の両極、色数2、版ずれ最大、太い主線の8条件について、出力全画素のSHA-256をv1.0.0と比較しました。8条件のうち7条件でハッシュが変わります。平坦化を行わない条件だけが一致します。
近傍の加算順序と各項の値を変更していないにもかかわらず出力が変わるのは、HLSLコンパイラーが乗算と加算の融合を、グループ共有メモリからの読み取りと大域バッファーからの読み取りとで別々に判断するためです。融合の有無で丸めが1回分変わり、その差が反復の回数だけ積み重なった後、描画の軟量子化のしきい値で可視化されます。差は色の階調1段に満たない範囲にとどまり、絵柄と形状は変わりません。
決定論は保たれています。同じ入力からは常に同じ出力が得られることを、テストの同一入力2回の全画素一致で確認しています。テスト34件の成功とビルド警告0も確認しています。
### 4. 効果がなく採用しなかった削減
本リリースの作業では、平坦化のタイル化のほかに6つの削減を実装して測定しました。いずれも性能が改善しないため採用していません。同じ試みを繰り返さないように記録します。測定はすべて1280×720と2560×1440で新旧のバイナリを交互に実行し、10フレームの最小値で比較しました。
| 試みた削減 | 内容 | 等価性 | 測定結果 |
|---|---|---|---|
| 素材ハッシュのグループ内集約 | 大域アトミック演算をグループ内で集約してから1回だけ反映する | 保たれる | 改善なし |
| 主線の正規化係数のグループ内共有 | ガウス重みの総和をグループの先頭スレッドが一度だけ求める | 保たれる | 改善なし |
| 平坦化の初期コピーの削減 | 元の色のバッファーを直接反復の初期値にしてディスパッチ1回を省く | 保たれる | 改善なし |
| 意匠が無効なときの模様計算の省略 | 和紙とばれん目が0%のときに繊維場と同心円模様を計算しない | 保たれる | 改善なし |
| エッジ接線流のタイル化 | 半径5セルの近傍参照をグループ共有メモリへ移す | 失われる | 改善なし |
| 特徴量と正規化勾配の事前計算 | 平坦化の反復で不変な値を専用バッファーへ一度だけ書き出す | 失われる | 測定せず |
前半の4つは、ゴールデン8条件のハッシュが一致する完全な等価変更です。演算量と大域メモリの通信量は確かに減りますが、1280×720と2560×1440のどちらでも処理時間は変わらず、グループ同期を追加する2つはむしろ2%から15%遅くなりました。削減した演算量よりも、追加した同期と先頭スレッドへの集約による並列度の低下が上回るためです。
エッジ接線流のタイル化は、平坦化と同じ手法でありながら効果がありません。平坦化の反復が24回から64回であるのに対して、エッジ接線流は2回から3回しかなく、タイルの読み込み費用がその回数では償却されないためです。加えて近傍参照は円形の範囲に限られ、勾配強度が下限を下回るセルは早期に飛ばすため、読み込んだタイルの多くを使いません。
特徴量と正規化勾配の事前計算は、ゴールデンのハッシュが変わった時点で採用の対象から外したため、性能を測定していません。
### 5. ハーネスの測定手法の改善
検証ハーネスの1フレームの測定を、5フレームの平均から10フレームの最小値へ変更しました。構造の再計算の測定も、パラメータを交互に切り替えてGPUの完了待ちを含む12回の最小値へ変更しました。前バージョンの平均値による測定は、GPUのクロック状態の変動と初回のシェーダー構築の影響を受けており、同一のバイナリでも実行ごとに2倍以上ばらつくことがありました。本リリースの性能表は新旧両方のバイナリをこの方法で測定した値です。
+1
ファイルの表示
@@ -0,0 +1 @@
github: routersys
+102
ファイルの表示
@@ -0,0 +1,102 @@
name: 不具合の報告
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
placeholder: v1.0.0
validations:
required: true
- type: input
id: ymm4-version
attributes:
label: YukkuriMovieMaker4 のバージョン
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
placeholder: v4.56.1.0 Lite
validations:
required: true
- type: input
id: os
attributes:
label: Windows のバージョン
description: winver を実行し、ビルド番号まで書いてください。
placeholder: Windows 11 24H2, 26100.2605
validations:
required: true
- type: input
id: gpu
attributes:
label: GPU とドライバー
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
- type: textarea
id: expected
attributes:
label: 期待した動き
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
validations:
required: true
- type: textarea
id: actual
attributes:
label: 実際の動き
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
validations:
required: true
- type: textarea
id: steps
attributes:
label: 再現の手順
description: |
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
placeholder: |
1. 新しいプロジェクトを作る
2. アイテムを置き、本プラグインを使う
3. 設定を変える
4. 不具合が起きる
validations:
required: true
- type: dropdown
id: frequency
attributes:
label: 起きる頻度
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
options:
- 毎回起きる
- ときどき起きる
- 一度だけ起きた
validations:
required: true
- type: textarea
id: context
attributes:
label: その他
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースを使っています。
required: true
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
required: true
+5
ファイルの表示
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: YukkuriMovieMaker4 本体の不具合
url: https://manjubox.net/contact/
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
+63
ファイルの表示
@@ -0,0 +1,63 @@
name: 文書の不備
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
title: "[Docs] "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
- type: dropdown
id: location
attributes:
label: 文書
options:
- README
- 配布パッケージの Readme.txt
- 設定の項目の名前や説明
- 貢献の手引き、セキュリティポリシー、行動規範
- その他
validations:
required: true
- type: input
id: reference
attributes:
label: 文書の中の位置
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
placeholder: README の「制限事項」の 2 つ目の項目
validations:
required: true
- type: textarea
id: says
attributes:
label: 今の記述
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
validations:
required: true
- type: textarea
id: problem
attributes:
label: どこが問題か
description: |
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: 提案する文面
description: 具体的な文面があると、早く直せます。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
required: true
+42
ファイルの表示
@@ -0,0 +1,42 @@
name: 機能の提案
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
title: "[Proposal] "
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: 困っていること
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
validations:
required: true
- type: textarea
id: workaround
attributes:
label: 今はどうしているか
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 提案する動き
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
- type: textarea
id: alternatives
attributes:
label: 検討したほかの方法
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
- type: checkboxes
id: checks
attributes:
label: 提案の前に
options:
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
required: true
- label: 最新のリリースに同じ機能が無いことを確かめました。
required: true
+49
ファイルの表示
@@ -0,0 +1,49 @@
name: 使い方の質問
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
title: "[Question] "
labels: ["question"]
body:
- type: markdown
attributes:
value: |
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
- type: textarea
id: question
attributes:
label: 質問
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
validations:
required: true
- type: textarea
id: goal
attributes:
label: 何をしようとしているか
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
validations:
required: true
- type: textarea
id: tried
attributes:
label: 試したこと
description: 試した設定と、そのとき実際に起きたことを書いてください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
placeholder: v1.0.0
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: 質問の前に
options:
- label: README の該当する節を読みました。
required: true
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
required: true
+123 -33
ファイルの表示
@@ -1,19 +1,20 @@
========================================
浮世絵 for YMM4 v1.0.1
浮世絵 for YMM4 v1.2.3
========================================
YukkuriMovieMaker4上で動作する、素材を浮世絵の多色木版画とみなして
描画する映像エフェクトプラグインです。
輪郭主線はKangらの論文「Coherent Line Drawing」(NPAR 2007)の
エッジ接線流と流れに沿った差分ガウスに基づきます。
地色はBiらの論文「An L1 Image Transform for Edge-Preserving Smoothing
and Scene-Level Intrinsic Decomposition」(SIGGRAPH 2015)の
L1局所平坦化を前向きの反復重み付き最小二乗として解いて均します。
限定パレットの階調化はWinnemöllerらの「Real-Time Video Abstraction」
(SIGGRAPH 2006)の軟量子化に基づきます。
和紙の繊維とばれん目と版ずれはシードから決定論的に決まり、
同じ設定では常に同じ絵になります。
強さ、線の太さ、線の流れ、線の量、線の濃さ、平坦化、版ずれ、
ばれん目、和紙の9項目はアニメーションに対応しています。
YukkuriMovieMaker4上で動作する、素材を多色木版画の原画とみなし、
エッジ接線流に沿った主線と、限定パレットの階調にまとめた色面を刷り重ねて
浮世絵として描画する映像エフェクトプラグインです。
主線の引き方は、Kang, Lee and Chuiの論文「Coherent line drawing」
(NPAR 2007、2007年)に基づきます。
色面の均し方は、Bi, Han and Yuの論文「An L1 image transform for
edge-preserving smoothing and scene-level intrinsic decomposition」
(ACM Transactions on Graphics、2015年)に基づきます。
階調のまとめ方は、Winnemöller, Olsen and Goochの論文「Real-time video
abstraction」(ACM Transactions on Graphics、2006年)に基づきます。
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
描く絵は素材とシードから決定論的に決まり、同じ設定では常に同じ絵になります。
強さ、線の太さ、線の流れ、線の量、線の濃さ、平坦化、版ずれ、ばれん目、和紙の
9項目はアニメーションに対応しています。
エフェクトの種類一覧では「浮世絵」として表示されます。
--------------------------------------------------------------------------------
■ 動作要件
@@ -29,32 +30,68 @@ L1局所平坦化を前向きの反復重み付き最小二乗として解いて
--------------------------------------------------------------------------------
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
- GPU非対応時: Direct3D 12デバイスを取得できない場合や、YMM4が使う
Direct3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない
場合は、エフェクトを適用せず入力映像を表示します。
- GPU非対応時: Direct3D 12デバイスを取得できない場合と、YMM4が使う
Direct3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、
エフェクトを適用せず入力映像を表示します。GPUメモリが足りず
共有テクスチャを確保できない場合も同じです。
- 処理対象: 現在のフレームの色とアルファ値だけを使用します。
- 処理対象: 絵柄の計算には現在のフレームの色と不透明度だけを使用します。
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
セルは、計算に使う格子の1つ1つの区画です。各セルは、区画にかかる
素材の画素について、色と不透明度の平均を持ちます。描画では、セルの色と
不透明度を画素の位置で補間します。
- 計算領域: 素材の範囲に主線の到達範囲と版ずれと描画の余白を加えた
大きさを計算領域とし、長辺は8192画素が上限です。素材が大きく余白を
確保できない場合は、エフェクトを適用せず入力映像を表示します。
- 計算領域: 透明な部分も含む素材全体の上下左右に余白を加えた大きさを
計算領域とし、長辺は8192画素が上限です。素材の長辺が、標準では
7944画素、高品質では8000画素、最高品質では8040画素を超える場合は、
エフェクトを適用せず入力映像を表示します。余白の幅は、版ずれ、線の太さ、
線の流れをそれぞれ最大にしたときに主線と版ずれが届く距離に、8画素を
足して4画素単位に切り上げた値です。届く距離は、見積もったセルの幅で
求めます。このセルの幅は、素材の長辺に128画素を足した長さと品質から
見積もります。そのため余白は、各項目の今の値によらず、素材の大きさと
品質だけで決まります。素材の長辺の上限が品質で違うのは、見積もった
セルの幅が品質で違い、余白の幅が変わるためです。
- 処理負荷: 計算領域の大きさと品質に応じて処理量とGPUメモリ使用量が
増えます。最高品質は処理格子の解像度と反復回数が最も多いため、
高品質と標準より処理負荷が高くなります。描画は素材が存在する最小の
矩形の範囲だけを計算します。
増えます。格子解像度は、1セルの幅を決める数です。1セルの幅は、
計算領域の長辺を格子解像度で割った長さで、1画素より小さくはなりません。
最高品質は格子解像度が最も大きく、反復回数も最も多いため、高品質と標準より
処理負荷が高くなります。描画は、素材の見える部分を囲む矩形を、
主線と版ずれが届く分だけ広げた範囲で行います。
- キャッシュ: 素材の色と形および構造を決めるパラメータが変わらない
フレームでは、輪郭と平坦化の計算を再利用します。
- キャッシュ: 素材と品質が変わらないフレームでは、主線を引く向きを決める
エッジ接線流の計算を再利用します。そのうえで、線の太さ、線の流れ、
線の量が変わらなければ、主線の計算も再利用します。平坦化が
変わらなければ、色面を均すL1平坦化の計算も再利用します。線の濃さ、
主線色、色数、版ずれ、ばれん目、和紙、シードだけを変えたフレームでは、
主線とL1平坦化を計算し直さず、描画だけをやり直します。強さだけを
変えたフレームでは、描き直さず、合成の量だけを変えます。素材が
変わったかどうかは、素材の大きさとハッシュで毎フレーム確かめます。
ハッシュは、セルごとの色と不透明度の平均を8ビットに丸めた値から
作ります。動画のように毎フレーム変わる素材では、すべてを計算し直します。
線の太さ、線の流れ、線の量、平坦化をアニメーションで変えたフレームでは、
変えた項目にかかわる計算をそのたびにやり直します。どちらも処理が
重くなります。
- 強さ0%: 強さが0%のときは入力を変更しません。
- 強さ0%: 強さが0%のときは入力を変更せず、主線と色面の計算も行いません。
強さを0%から上げたフレームでは、最後に計算したときから変わった素材や
項目にかかわる計算だけをやり直します。
- シードと再現性: 和紙の繊維とばれん目と版ずれの形は、シードと画素位置
から決定論的に算出します。時間値は生成に使用しません。
- シードと再現性: 和紙の繊維とばれん目の模様はシードと画素位置から、
版ずれの向きはシードから版ごとに、決定論的に算出します。時間値は
生成に使用しません。画素位置は、計算領域の左上から数えます。
計算領域の左上は、素材の左上から余白の幅だけ外にあります。余白の幅は、
素材の大きさと品質だけで決まります。そのため素材の大きさと品質が
同じなら、シード以外の項目を変えても、模様は素材に対して動きません。
素材の大きさか品質が変わると、模様の位置がずれることがあります。
- 透明部分: 主線と版ずれは素材の外側にもわずかに描画されるため、
出力範囲は素材より広がります。出力は元映像と強さの割合で合成します。
出力範囲は素材より広がります。1セルの幅が1画素より大きいときは、
セルの不透明度を補間するため、素材の縁から外へ最大で1セルの幅の
1.5倍ほどの範囲まで不透明度が付くことがあります。縁に近い画素ほど
不透明になります。紙の地色は付けないため、主線と版ずれのかからない、
素材から離れた透明な部分は透明のままです。出力は、入力映像と描いた絵を
強さの割合で混ぜ合わせたものです。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
@@ -62,6 +99,59 @@ L1局所平坦化を前向きの反復重み付き最小二乗として解いて
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
作成することを推奨します。
--------------------------------------------------------------------------------
■ 不具合の報告
--------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めません。止める設定もありません。
送信する数には上限があります。YMM4の1回の起動で送る報告は、
YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。
例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号、
プラグイン自身のコードかどうか
プラグイン : アセンブリ名、バージョン
実行環境 : OSの名前とバージョン、.NETのバージョン、
CPUのアーキテクチャ、論理プロセッサ数
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
時刻 : 報告を作った時刻(UTC)
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
YMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
YMM4のDirect3D 11デバイスが
相互運用に必要なインターフェースを
持たない、GPUメモリが足りず
共有テクスチャを確保できない、
計算領域が8192画素に収まらないときに、
エフェクトを適用せず入力映像を
表示したとき
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
接続できない
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
退避した報告を1回の起動で10件まで送り直します。
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
ありません。
--------------------------------------------------------------------------------
■ 免責事項
--------------------------------------------------------------------------------
@@ -75,9 +165,9 @@ L1局所平坦化を前向きの反復重み付き最小二乗として解いて
--------------------------------------------------------------------------------
■ サードパーティライセンス
--------------------------------------------------------------------------------
本プラグインはComputeSharp(MIT License)を同梱しています。
ライセンスの全文は同梱のLICENSEフォルダー(ComputeSharp.txt)に収録しています。
ComputeSharp : Copyright (c) 2024 Sergio Pedri
本プラグインはComputeWeave(MIT License)を同梱しています。
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
ComputeWeave : Copyright (c) 2024 Sergio Pedri
--------------------------------------------------------------------------------
■ ライセンス
--------------------------------------------------------------------------------
+87
ファイルの表示
@@ -0,0 +1,87 @@
<!--
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
-->
## 概要
<!--
何をどう変えたか。なぜその変更が必要か。
-->
## 関連する Issue
<!--
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
Issue が無い変更では、下の行を「なし」に書き換えてください。
-->
Closes #
## 変更の種類
<!-- 当てはまるものを残してください。 -->
- 不具合の修正
- 機能の追加
- 動きの変更
- 性能の改善
- テストの追加
- 依存関係の更新
- 文書
- ビルド、リリース
## 動きの変更
<!--
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
-->
## 検証
<!--
手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
-->
使った YukkuriMovieMaker4 のバージョン:
GPU に関わる変更では、使った GPU とドライバー:
## 確認
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
- [ ] どのコミットも、それ単独でビルドが通る。
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
- [ ] 自分の変更で増えたビルドの警告を直した。
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
- [ ] この変更と関係の無い依存関係の更新を含めていない。
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
- [ ] バージョンを上げる変更を含めていない。
## 性能の改善を主張する場合
<!-- それ以外の場合は、この節ごと消してください。 -->
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
- [ ] 正しさの確認と性能の測定を、別々に実行した。
<!--
測定の条件と、測定値。
-->
## レビューで見てほしい点
<!--
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
-->
+307 -46
ファイルの表示
@@ -1,4 +1,4 @@
name: リリース
name: リリース
on:
push:
@@ -14,31 +14,20 @@ jobs:
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
submodules: recursive
fetch-depth: 0
- name: .NET SDKのセットアップ
uses: actions/setup-dotnet@v4
- name: .NET SDK のセットアップ
uses: actions/setup-dotnet@v6
with:
dotnet-version: '10.0.x'
- name: fxc.exeの検索
id: fxc
shell: pwsh
run: |
$fxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin" -Recurse -Filter "fxc.exe" |
Where-Object { $_.FullName -like "*x64*" } |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $fxc) {
Write-Error "fxc.exeが見つかりませんでした。"
exit 1
}
Write-Host "fxc.exeの場所: $($fxc.FullName)"
echo "FXC_PATH=$($fxc.FullName)" >> $env:GITHUB_OUTPUT
- name: MSBuild のセットアップ
uses: microsoft/setup-msbuild@v3
- name: YMM4最新リリースの取得と解凍
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
@@ -48,20 +37,12 @@ jobs:
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
if (-not $asset) {
Write-Error "YMM4のリリースにZIPファイルが見つかりませんでした。"
exit 1
}
Write-Host "ダウンロード対象: $($asset.name)"
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile "ymm4.zip"
Expand-Archive -Path "ymm4.zip" -DestinationPath "ymm4_extracted" -Force
$ymm4Dir = (Get-ChildItem -Path "ymm4_extracted" -Recurse -Filter "YukkuriMovieMaker.dll" |
Select-Object -First 1).DirectoryName
if (-not $ymm4Dir) {
Write-Error "YukkuriMovieMaker.dllが見つかりませんでした。"
exit 1
}
Write-Host "YMM4 DLLディレクトリ: $ymm4Dir"
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
@@ -70,17 +51,47 @@ jobs:
run: |
$tag = "${{ github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: resxファイルの生成
- name: バージョン記載の照合
shell: pwsh
run: |
$proj = "Ukiyoe/Ukiyoe.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "Ukiyoe/Ukiyoe.csproj"
$csproj = Get-Content $csprojPath -Raw
if (-not $csproj.Contains("<Version>$version</Version>")) {
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
}
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" 浮世絵 for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ 浮世絵 for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
if ($problems.Count -eq 0) {
Write-Host "バージョン記載は $tag と一致しています"
exit 0
}
foreach ($problem in $problems) {
Write-Host "::error::$problem"
}
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
exit 1
- name: シェーダーのビルド
shell: pwsh
run: |
msbuild Ukiyoe.Shader/Ukiyoe.Shader.vcxproj `
/p:Configuration=Release `
/p:Platform=Win32 `
/nologo
- name: プロジェクトのビルド
shell: pwsh
@@ -89,7 +100,6 @@ jobs:
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
@@ -99,7 +109,6 @@ jobs:
dotnet build Ukiyoe.Tests/Ukiyoe.Tests.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true `
-maxcpucount:1
@@ -118,15 +127,20 @@ jobs:
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Ukiyoe/bin/x64/Release/net10.0-windows10.0.19041.0"
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Ukiyoe/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/Ukiyoe"
$pkgName = "Ukiyoe_$version.ymme"
$pkgName = "Ukiyoe_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/plugin/Ukiyoe.dll" "$stageRoot/"
$dll = "$outDir/plugin/Ukiyoe.dll"
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に Ukiyoe.dll が見つかりませんでした: $dll"
exit 1
}
Copy-Item $dll "$stageRoot/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
@@ -136,17 +150,264 @@ jobs:
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" 浮世絵 for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- name: GitHubリリースの作成
uses: softprops/action-gh-release@v2
- name: 変更履歴の作成
id: changelog
shell: pwsh
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.TAG }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
run: |
$tag = $env:TAG
$repository = $env:REPOSITORY
$server = $env:SERVER_URL
$code = [char]0x60
$fence = [string]::new($code, 3)
$unit = [char]0x1f
$record = [char]0x1e
$previous = ""
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
if ($candidates.Count -gt 0) {
$previous = $candidates[0]
}
Write-Host "直前のタグ: $previous"
$range = if ($previous) { "$previous..$tag" } else { $tag }
$log = (@(git log "--format=%H%x1f%s%x1f%an%x1f%ad%x1f%b%x1e" --date=short $range) -join "`n") -split $record
$commits = @()
foreach ($entry in $log) {
if (-not $entry.Trim()) { continue }
$fields = $entry.TrimStart("`n") -split $unit
if ($fields.Count -lt 5) { continue }
$commits += [pscustomobject]@{
Sha = $fields[0]
Subject = $fields[1]
Name = $fields[2]
Date = $fields[3]
Body = $fields[4]
Login = ""
Avatar = ""
}
}
Write-Host "コミット数: $($commits.Count)"
$categories = [ordered]@{
A = @{ Title = "追加"; Symbol = "+"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
M = @{ Title = "変更"; Symbol = "~"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
D = @{ Title = "削除"; Symbol = "-"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
F = @{ Title = "修正"; Symbol = "!"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
}
foreach ($commit in $commits) {
if (-not $commit.Body) { continue }
foreach ($bodyLine in ($commit.Body -split "`n")) {
$trimmed = $bodyLine.Trim()
if ($trimmed -notmatch '^・(.+)-([AMDF])$') { continue }
$categories[$Matches[2]].Items.Add([pscustomobject]@{ Text = $Matches[1]; Sha = $commit.Sha })
}
}
$pending = [System.Collections.Generic.HashSet[string]]::new()
foreach ($commit in $commits) {
[void]$pending.Add($commit.Sha)
}
$accounts = @{}
$page = 1
while ($pending.Count -gt 0 -and $page -le 20) {
$rows = @()
try {
$rows = @(gh api "repos/$repository/commits?sha=$tag&per_page=100&page=$page" --jq '.[] | [.sha, (.author.login // ""), (.author.avatar_url // "")] | @tsv')
}
catch {
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
break
}
if ($LASTEXITCODE -ne 0 -or $rows.Count -eq 0) { break }
foreach ($row in $rows) {
$fields = $row -split "`t"
if ($fields.Count -lt 3) { continue }
if ($pending.Remove($fields[0])) {
$accounts[$fields[0]] = @{ Login = $fields[1]; Avatar = $fields[2] }
}
}
if ($rows.Count -lt 100) { break }
$page++
}
foreach ($commit in $commits) {
if ($accounts.ContainsKey($commit.Sha)) {
$commit.Login = $accounts[$commit.Sha].Login
$commit.Avatar = $accounts[$commit.Sha].Avatar
}
}
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
$base = if ($previous) { $previous } else { $emptyTree }
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
$changedFiles = 0
$insertions = 0
$deletions = 0
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
$diffStat = @(git diff --stat $base $tag)
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
$contributors = @($commits |
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
Sort-Object -Property Count -Descending)
function Get-Icon($avatar, $login, $size) {
if (-not $avatar) { return "" }
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
}
$package = Get-Item $env:PACKAGE
$size = [math]::Round($package.Length / 1MB, 2)
$body = [System.Collections.Generic.List[string]]::new()
$body.Add("## 概要")
$body.Add("")
$body.Add("| 項目 | 内容 |")
$body.Add("|---|---|")
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
$body.Add("| 公開日 | $tagDate |")
if ($previous) {
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
}
$body.Add("| コミット数 | $($commits.Count) |")
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
$body.Add("| 変更されたファイル | $changedFiles |")
$body.Add("| 追加された行 | $insertions |")
$body.Add("| 削除された行 | $deletions |")
$hasHighlights = ($categories.Values | ForEach-Object { $_.Items.Count } | Measure-Object -Sum).Sum -gt 0
if ($hasHighlights) {
$body.Add("")
$body.Add("## 主な変更")
foreach ($key in $categories.Keys) {
$category = $categories[$key]
if ($category.Items.Count -eq 0) { continue }
$body.Add("")
$body.Add("### [$($category.Symbol)] $($category.Title)")
$body.Add("")
foreach ($item in $category.Items) {
$short = $item.Sha.Substring(0, 7)
$body.Add("- $($item.Text) ([$code$short$code]($server/$repository/commit/$($item.Sha)))")
}
}
}
$body.Add("")
$body.Add("## ダウンロード")
$body.Add("")
$body.Add("| ファイル | サイズ |")
$body.Add("|---|---|")
$body.Add("| $($package.Name) | $size MB |")
$body.Add("")
$body.Add("## 貢献者")
$body.Add("")
$body.Add("| 貢献者 | コミット数 |")
$body.Add("|---|---|")
foreach ($contributor in $contributors) {
$first = $contributor.Group[0]
if ($first.Login) {
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
}
else {
$name = $first.Name
}
$body.Add("| $name | $($contributor.Count) |")
}
$body.Add("")
$body.Add("## 変更履歴")
$body.Add("")
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
$body.Add("|---|---|---|---|")
$maximumCommits = 300
$listed = 0
foreach ($commit in $commits) {
if ($listed -ge $maximumCommits) { break }
$short = $commit.Sha.Substring(0, 7)
$subject = $commit.Subject -replace '\|', '\|'
if ($commit.Login) {
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
}
else {
$author = $commit.Name
}
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
$listed++
}
if ($commits.Count -gt $maximumCommits) {
$body.Add("")
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
}
if ($diffStat.Count -gt 0) {
$body.Add("")
$body.Add("## 変更されたファイル")
$body.Add("")
$body.Add("<details>")
$body.Add("<summary>差分の統計</summary>")
$body.Add("")
$body.Add($fence)
$maximumStatLines = 200
$shown = 0
foreach ($line in $diffStat) {
if ($shown -ge $maximumStatLines) { break }
$body.Add($line)
$shown++
}
if ($diffStat.Count -gt $maximumStatLines) {
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
}
$body.Add($fence)
$body.Add("")
$body.Add("</details>")
}
if ($previous) {
$body.Add("")
$body.Add("## 全ての変更")
$body.Add("")
$body.Add("$server/$repository/compare/$previous...$tag")
}
$path = "release-body.md"
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
if (-not (Test-Path $path)) {
throw "変更履歴を作成できませんでした。"
}
Write-Host "変更履歴の行数: $($body.Count)"
$global:LASTEXITCODE = 0
- name: GitHub リリースの作成
uses: softprops/action-gh-release@v3
with:
name: ${{ steps.version.outputs.TAG }}
body_path: .github/CHANGELOG.md
body_path: release-body.md
files: ${{ steps.package.outputs.PKG_NAME }}
draft: false
prerelease: false
+3 -1
ファイルの表示
@@ -362,4 +362,6 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
FodyWeavers.xsd
# Stryker.NET
StrykerOutput/
+6 -3
ファイルの表示
@@ -1,6 +1,9 @@
[submodule "YukkuriMovieMaker.Generator"]
[submodule "YukkuriMovieMaker.Generator"]
path = YukkuriMovieMaker.Generator
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
[submodule "YMM4-GitHubUpdateNotifier"]
path = YMM4-GitHubUpdateNotifier
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
url = https://git.routersys.com/routersys/YMM4-GitHubUpdateNotifier.git
[submodule "YMM4-Telemetry"]
path = YMM4-Telemetry
url = https://git.routersys.com/routersys/YMM4-Telemetry.git
+81
ファイルの表示
@@ -0,0 +1,81 @@
# Contributor Covenant 行動規範
## 私たちの約束
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
## 私たちの基準
コミュニティのよい環境を作る行動の例は、次のとおりです。
- ほかの人に共感と思いやりを示す
- 異なる意見、視点、経験を尊重する
- 建設的な意見を伝え、また快く受け入れる
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
受け入れられない行動の例は、次のとおりです。
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
- 公の場か私的な場かを問わない嫌がらせ
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
- 仕事の場で不適切と合理的に考えられるその他の行為
## 執行の責任
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
## 適用範囲
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
## 執行
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
## 執行のガイドライン
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
### 1. 是正
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
### 2. 警告
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
### 3. 一時的な参加禁止
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
### 4. 永久的な参加禁止
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
## 出典
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
[homepage]: https://www.contributor-covenant.org
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
+168
ファイルの表示
@@ -0,0 +1,168 @@
# 貢献の手引き
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
---
## 目次
1. [貢献の進め方](#貢献の進め方)
2. [開発環境](#開発環境)
3. [Issue](#issue)
4. [プルリクエスト](#プルリクエスト)
5. [検証](#検証)
6. [コードの規約](#コードの規約)
7. [コミットの規約](#コミットの規約)
8. [行動規範](#行動規範)
---
## 貢献の進め方
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
Issue とプルリクエストは、日本語か英語で書いてください。
---
## 開発環境
| 項目 | 要件 |
|---|---|
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
| SDK | .NET 10 |
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
### 取得
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
```console
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
```
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
```console
git submodule update --init --recursive
```
作業は `main` から切ったブランチで行ってください。
### YukkuriMovieMaker4 の場所
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
### ビルド
ソリューションを開き、Release でビルドしてください。
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
---
## Issue
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
不具合の報告には、次の内容を書いてください。
- 期待した動きと、実際の動き
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
- エラー画面に出た内容。省略せずに貼ってください
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
---
## プルリクエスト
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
特に注意が要るのは、次の箇所です。
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
- GPU のリソース、ファイル、ハンドルの寿命
- 破棄の処理と、失敗したときの処理
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
---
## 検証
プルリクエストには、手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
性能の改善を主張するときは、1 回の測定で判断しないでください。
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
- ほかのプロセスが GPU を使っていない状態で測ってください。
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
---
## コードの規約
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
---
## コミットの規約
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
---
## 行動規範
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
-10
ファイルの表示
@@ -1,15 +1,5 @@
<Project>
<PropertyGroup>
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
<WindowsKitRoot>C:\Program Files (x86)\Windows Kits\10\bin</WindowsKitRoot>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == ''">fxc.exe</FxcPath>
</PropertyGroup>
</Project>
+135 -50
ファイルの表示
@@ -1,4 +1,4 @@
# 浮世絵 for YMM4
# 浮世絵 for YMM4
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#)
[![.NET](https://img.shields.io/badge/.NET-10.0-purple.svg)](#)
@@ -6,12 +6,12 @@
---
YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原画とみなし、エッジ接線流に沿う輪郭主線とL1平坦化の色面を限定パレットへ刷り重ねて浮世絵として描画する映像エフェクトプラグインです。
YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原画とみなし、エッジ接線流に沿った主線と、限定パレットの階調にまとめた色面を刷り重ねて浮世絵として描画する映像エフェクトプラグインです。
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
和紙の繊維とばれん目と版ずれの形はシードから決定論的に決まり、同じ設定では常に同じ絵になります。
描く絵は素材とシードから決定論的に決まり、同じ設定では常に同じ絵になります。
強さ、線の太さ、線の流れ、線の量、線の濃さ、平坦化、版ずれ、ばれん目、和紙の9項目はアニメーションに対応しています。
![Image](https://github.com/routersys/YMM4-Ukiyoe/blob/main/docs/Ukiyoe.png)
![Image](https://git.routersys.com/routersys/YMM4-Ukiyoe/raw/branch/main/docs/Ukiyoe.png)
---
@@ -21,12 +21,13 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
2. [動作要件](#動作要件)
3. [インストール方法](#インストール方法)
4. [主な機能](#主な機能)
- [1. エッジ接線流と流れに沿った差分ガウスによる主線](#1-エッジ接線流と流れに沿った差分ガウスによる主線)
- [2. L1平坦化による色面](#2-l1平坦化による色面)
- [3. 限定パレットの階調化](#3-限定パレットの階調化)
- [4. 版ずれ](#4-版ずれ)
- [5. ばれん目と和紙](#5-ばれん目と和紙)
- [6. 品質の選択](#6-品質の選択)
- [1. エッジ接線流による主線の向き](#1-エッジ接線流による主線の向き)
- [2. 流れに沿ったガウス差分による主線](#2-流れに沿ったガウス差分による主線)
- [3. L1平坦化による色面](#3-l1平坦化による色面)
- [4. 限定パレットの階調化](#4-限定パレットの階調化)
- [5. 版ずれ](#5-版ずれ)
- [6. ばれん目・和紙・シード](#6-ばれん目和紙シード)
- [7. 品質の選択](#7-品質の選択)
5. [パラメータ一覧](#パラメータ一覧)
- [基本グループ](#基本グループ)
- [主線グループ](#主線グループ)
@@ -34,9 +35,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
- [意匠グループ](#意匠グループ)
6. [制限事項](#制限事項)
7. [注意事項](#注意事項)
8. [免責事項](#免責事項)
9. [サードパーティライセンス](#サードパーティライセンス)
10. [ライセンス](#ライセンス)
8. [不具合の報告](#不具合の報告)
9. [免責事項](#免責事項)
10. [サードパーティライセンス](#サードパーティライセンス)
11. [ライセンス](#ライセンス)
---
@@ -44,9 +46,21 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「浮世絵」として表示されます。カテゴリは加工と装飾です。
入力された現在のフレームの色とアルファ値から素材の絵柄を求め、多色木版画の工程になぞらえて3つの層を刷り重ねます。主線の層は、Kang・Lee・Chuiの論文「Coherent Line Drawing」(NPAR 2007)に基づき、エッジ接線流の非線形ベクトル平滑化で絵柄の流れを求め、流れに直交する方向の差分ガウスを流線に沿って集計して、つながりの良い輪郭線を取り出します。色面の層は、Bi・Han・Yuの論文「An L1 Image Transform for Edge-Preserving Smoothing and Scene-Level Intrinsic Decomposition」(SIGGRAPH 2015)のL1局所平坦化を前向きの反復重み付き最小二乗として解き、細部を消しながら際を保った均質な色面を作り、Winnemöllerらの論文「Real-Time Video Abstraction」(SIGGRAPH 2006)の軟量子化で限定パレットの階調へ寄せます。意匠の層は、階調ごとの刷り位置のずれ、ばれんの擦り跡、和紙の繊維のかすれを決定論的なハッシュ模様として重ねます。
入力された現在のフレームの色と不透明度から、セルを単位に素材の絵柄を求めます。セルは、素材の上下左右に余白を加えた計算領域を、格子状に区切った1つ1つの区画です。各セルは、区画にかかる素材の画素について、色と不透明度の平均を持ちます。色は、不透明度で重み付けして平均します。描画では、セルの色と不透明度と主線を、画素の位置で補間して使います。計算領域の大きさは「制限事項」に、1セルの幅の決め方は「品質の選択」にあります。
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、8個の整数の読み戻しだけで素材の変化を判定します。素材が存在する最小の矩形の範囲だけを描画し、絵柄と構造のパラメータが変わらないフレームでは輪郭と平坦化の計算を再利用します。
描く絵は、多色木版画の工程になぞらえて作ります。主線と色面の2つの層を刷り重ね、刷ったときの跡を意匠グループの項目で加えます。
主線の層では、エッジ接線流で主線を引く向きを求め、この向きに沿ったガウス差分で主線を取り出します。エッジ接線流は、輪郭に沿う向きを各セルで求め、周りの向きと滑らかにつながるように揃えたものです。ガウス差分は、ぼかしの幅が違う2つのガウスぼかしの差を取り、輝度の変わり目を浮かび上がらせる方法です。この2つの方法は、Kang, Lee and Chuiの論文「Coherent line drawing」(NPAR 2007、2007年)に基づきます。
色面の層では、L1平坦化で色を均し、暗さを「色数」で決めた数の階調にまとめます。L1平坦化は、近くの色との差の絶対値が小さくなるように色を寄せ、細部を消しながら輪郭を保つ方法です。この方法は、Bi, Han and Yuの論文「An L1 image transform for edge-preserving smoothing and scene-level intrinsic decomposition」(ACM Transactions on Graphics、2015年)に基づきます。暗さを階調にまとめる処理を階調化と呼びます。本プラグインの階調化は、階調の境目を滑らかにつなぎます。この階調化は、Winnemöller, Olsen and Goochの論文「Real-time video abstraction」(ACM Transactions on Graphics、2006年)に基づきます。
意匠グループの項目では、階調ごとに刷り位置がずれる版ずれと、ばれんでこすった跡のばれん目と、和紙の繊維によるかすれを加えます。ばれんは、版に載せた紙を裏からこすり、版の絵の具を紙へ移す道具です。版ずれとばれん目は色面に、和紙のかすれは色面と主線の両方にかけます。
描いた絵は、「強さ」の割合で入力映像と混ぜ合わせて出力します。
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、8個の整数だけを読み戻します。8個の整数には、セルの色と不透明度から作るハッシュと、見える部分の範囲が含まれます。見える部分は、不透明度の平均が0.4%を超えるセルです。
読み戻したハッシュは素材の変化の判定に、見える部分の範囲は描画の範囲に使います。素材と「品質」が変わらないフレームでは、主線とL1平坦化の計算のうち、変えた項目にかかわる計算だけをやり直し、ほかの計算は再利用します。再利用の条件は「注意事項」にあります。描画は、素材の見える部分を囲む矩形を、主線と版ずれが届く分だけ広げた範囲で行います。
このエフェクトはAviUtl向けのEXO出力には対応していません。
@@ -74,45 +88,79 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
## 主な機能
### 1. エッジ接線流と流れに沿った差分ガウスによる主線
### 1. エッジ接線流による主線の向き
現在のフレームの輝度からソーベル勾配を求め、勾配に直交する接線場を核関数に基づく非線形ベクトル平滑化で整えます。有意なエッジの方向を保ちながら弱い方向を周囲の支配的な流れへ従わせ、勾配のほとんどない領域は近傍の有意な接線の構造テンソルの主固有ベクトルで充填します。この充填により、素材の内部に緩やかな陰影があってもシルエットの輪郭線が途切れません。
主線を引く向きは、各セルの輝度の勾配から求めます。勾配は、輝度が最も大きく変わる向きと、その変わり方の強さです。この勾配を、ソーベル演算子で求めます。ソーベル演算子は、各セルを中心とする3×3のセルの輝度に決まった重みを掛けて足し、横と縦の勾配を求める計算です。勾配に直交する向きを、各セルの接線にします。輝度は、素材の透明な部分を白とみなして求めます。半透明な部分は、不透明度に応じて白と混ぜた輝度にします。
主線は、流れに直交する方向の1次元差分ガウスを流線に沿って集計する、流れに沿った差分ガウスで取り出します。線の太さは差分ガウスの中心幅、線の流れは流線方向の集計の長さ、線の量は二値化のしきい値を決めます。前回の主線を重ねてから再度適用する反復で、線のつながりをさらに強めます。
エッジ接線流では、各セルの接線を周りの接線と揃えます。半径5セルの円に入るセルの接線を平均します。このとき、勾配が強いセルの接線ほど、また中心のセルの接線と向きが近い接線ほど、大きな重みを付けます。
### 2. L1平坦化による色面
格子全体で最も強い勾配を基準に、勾配がその2%に満たないセルでは、平均の代わりに接線を周りから補います。半径5セルの中で勾配が2%以上あるセルの接線を、向きの正負を区別せずに集め、集めた接線と最もよく揃う向きをそのセルの接線にします。周りにそのようなセルが無いセルは、接線を持たず、主線も出ません。この平均する処理と補う処理を1回として、「品質の選択」の表にある回数だけ繰り返します。
地色は、隣接する画素の色の差のL1ノルムと元画像への近さの和を最小化する局所平坦化で均します。似た色の隣接対には大きな重みが付くため差が強く縮み、際をまたぐ対には小さな重みしか付かないため際が保たれます。L1ノルムの性質により、似た色はさらに近づき、異なる色は離れたまま残る区分平坦な色面が得られます。
輝度を求めるときに透明な部分を白とみなすため、透明な部分との境に主線が出るかどうかは、境に接する素材の輝度によります。白い部分と透明な部分の境には勾配ができず、主線は出ません。暗い部分と透明な部分の境には、暗い部分と白い部分の境と同じ勾配ができます。計算領域の余白も透明なため、不透明な素材でも、縁が暗いと縁に沿って主線が出ることがあります。
最小化は反復重み付き最小二乗のヤコビ反復として前向きに解きます。分解や推定を伴わないため、入力によらず常に均質な色面が出ます。平坦化のパラメータは元画像への近さの重みを決め、高いほど細部が消えます。
### 2. 流れに沿ったガウス差分による主線
### 3. 限定パレットの階調化
主線は、各セルで接線に直交する向きに1次元のガウス差分をかけて取り出します。かけた結果の値を応答と呼びます。接線に沿って前後のセルをたどり、たどったセルの応答を、近いセルほど大きくなるガウス関数の重みで平均します。平均した応答をしきい値と比べて、主線にするセルを決めます。
平坦化した色面の暗さを、色数で指定した段数の階調へ軟量子化します。階調の中心が平坦になり、階調の境界だけで滑らかに切り替わるため、木版画の色版のような均質な色面になります。彩度は量子化せず、平坦化とスケールで整えます。
ガウス差分は、「品質の選択」の表にある回数だけかけます。2回目からは、前の回で主線になったセルの輝度を0にしてから、もう一度かけます。
### 4. 版ずれ
「線の太さ」は、ガウス差分の2つのぼかしのうち幅の狭いほうの幅を、0.6画素から3.0画素の間で決めます。このぼかしを中心ガウスと呼びます。中心ガウスの幅は1セルの幅の半分より狭くならないため、1セルの幅が1.2画素より大きいときは、「線の太さ」を下げても主線がそれ以上細くならない範囲があります。1セルの幅が1.2画素より大きくなるのは、計算領域の長辺が、標準では1228画素、高品質では1728画素、最高品質では2457画素を超えるときです。標準では、計算領域の長辺が6144画素以上になると、「線の太さ」をどの値にしても主線は変わりません。高品質と最高品質では、計算領域の長辺が上限の8192画素でも、「線の太さ」で主線が変わる範囲が残ります。
多色木版画の見当ずれを再現します。階調の層ごとにシードから決めた方向へ刷り位置をずらし、各画素で自身より暗い層のずらした標本を調べて最も暗い層の色を採用します。階調の境界に色縁が出て、素材の外側にもわずかにはみ出します。主線の版はずらしません。
たとえば1920×1080の素材を高品質で使うと、余白は上下左右に48画素で、計算領域は2016×1176画素になります。このとき1セルの幅は1.4画素で、「線の太さ」を0%から約4%までの間で変えても、主線は変わりません。
### 5. ばれん目と和紙
「線の流れ」は、たどるときの重みの幅を1セルから6セルの間で決めます。たどる長さは、前後それぞれ、この幅の2倍を切り上げたセル数です。
ばれん目は、ばれんの擦り跡の同心円模様です。セルごとに中心をずらした円環模様を低周波の斑と掛け合わせ、中間調の色面をわずかに明るくします。
「線の量」は、平均した応答を主線とみなすしきい値を決めます。値を上げるほど、弱い応答も主線になります。0%でも強い応答は主線になるため、「線の量」だけでは主線を消せません。
和紙は、3オクターブの値ノイズによる繊維場です。色面と主線を繊維で削り、かすれを作ります。
主線は、「主線色」で色面の上へ重ねます。「主線色」の不透明度は使いません。「線の濃さ」は、主線を重ねる不透明度を決めます。「線の濃さ」が0%のときは主線を描きません。
シードは、和紙の繊維とばれん目と版ずれの形を決める固定値です。シードと画素位置から決定論的に生成するため、同じシードと同じパラメータでは常に同じ絵になります。
### 3. L1平坦化による色面
### 6. 品質の選択
色面は、各セルの色を近くのセルの色へ寄せる反復で均します。近くのセルは、そのセルを中心とする5×5の範囲から、そのセル自身を除いた24個のセルです。各反復では、そのセルの元の色と近くのセルの今の色を、重みを付けて平均します。元の色は反復を始める前の色で、今の色は前の反復までに寄せた色です。元の色と今の色には、不透明度も含めます。反復は、「品質の選択」の表にある回数だけ行います。
品質は、処理格子の解像度と各段階の反復回数をまとめて切り替えます。
近くのセルの重みは、2つのセルの元の色の類似度を、今の色の差で割った値です。今の色の差は、2つのセルの今の色を成分ごとに引き、その絶対値を足した値です。元の色の類似度は、色味と輝度と不透明度の差が小さく、どちらのセルにも強い勾配が無い組ほど大きくなります。この計算は、差の絶対値の和を小さくする問題を、重みを毎回付け直す平均の繰り返しで近似して解くものです。
| 品質 | 格子解像度 | 接線流反復 | 主線反復 | 平坦化反復 |
今の色の差で割るため、差がすでに小さい組ほど重みが大きくなり、差はさらに縮みます。輪郭をまたぐ組は重みが小さいため、差が残ります。こうして細部が消え、輪郭で区切られた範囲ごとに色の揃った色面ができます。
「平坦化」は、平均のときに元の色に付ける重みを決めます。この重みは、「平坦化」が0%のとき100000です。「平坦化」を上げるほど、この重みは指数的に小さくなり、100%で約1になります。近くのセル1つの重みは1000を超えないため、0%では、元の色の重みが近くのセル24個の重みを合わせたものより大きくなります。元の色の重みが小さいほど、色は元の色から離れやすくなり、細部が消えます。
### 4. 限定パレットの階調化
限定パレットは、色面の暗さを、「色数」で決めた数の階調だけに絞ったものです。暗さは、透明な部分を白とみなした輝度を、1から引いた値です。半透明な部分は白と混ぜて暗さを求めるため、同じ色の不透明な部分より暗さが小さくなり、明るい階調に入ることがあります。
各階調の中ほどでは、暗さをその階調の中央の値に揃えます。階調の両端では、それぞれ階調の幅の18%の範囲で、中央の値から端の値へ滑らかにつなぎます。暗さの0と1も階調の端にあたるため、白と黒は階調にまとめても白と黒のままです。
色味は階調にまとめません。平坦化した色の各成分から、その色の輝度を引いた差を色味として残します。色面の色を作るときは、階調にまとめた暗さに、ばれん目と和紙をかけます。色面の色の赤、緑、青の各成分は、この暗さを1から引いた値に、色味を0.9倍して足し、0から1の範囲に収めた値です。色味を残すため、「色数」は、出力に使う色の数ではなく、暗さの階調の数です。
### 5. 版ずれ
版ずれは、多色木版画で、色ごとの版の刷り位置がずれることです。本プラグインは、暗さの階調ごとに1枚の版があるとみなします。各階調の版は、その階調以上に暗い部分を刷ります。最も明るい階調を除く各版を、「シード」から版ごとに決めた向きへずらします。ずらす版の数は、「色数」より1つ少なくなります。ずらす距離はどの版も同じで、「版ずれ」の値に10画素を掛けた長さです。主線はずらしません。
各画素では、ずらした各版がその画素に運ぶ色を調べます。版が運ぶ色は、その画素から、版をずらした向きと逆へ、ずらした距離だけ離れた位置の色です。この色が、その版の階調以上に暗いとき、その版はその画素にかかります。その画素にかかる版のうち、ずらさないときの色の階調より暗い版があれば、最も暗い版が運ぶ色を使います。無ければ、ずらさないときの色を使います。この選び方により、階調の境目に色の縁が出て、ずれた版は素材の外側にもわずかにはみ出します。版が運ぶ色を使う画素では、色面の色の色味と暗さも、平坦化した色の代わりに版が運ぶ色から求めます。
### 6. ばれん目・和紙・シード
ばれん目は、ばれんでこすったときに紙に残る同心円の模様です。140画素四方のます目ごとに、中心をます目の中でずらした同心円を置きます。この同心円に、それより粗いまだら模様を掛け合わせ、中ほどの暗さの色面をわずかに明るくします。「ばれん目」を上げるほど明るくする量が増え、0%ではばれん目は現れません。白と黒に近い色面には、ばれん目はほとんど出ません。
和紙の繊維の模様は、周期の違う3つのバリューノイズを重ねて作ります。バリューノイズは、一定の間隔の点ごとに乱数を置き、その間を滑らかにつないだ模様です。「和紙」を上げるほど、色面の暗さと主線の濃さが繊維に沿って弱まり、かすれが強くなります。0%ではかすれは出ません。紙の地色は付けません。
「シード」は、各版をずらす向きと、ばれん目の同心円とまだら模様と、和紙の繊維の模様を決める固定値です。模様が素材に対して動かない条件は「注意事項」にあります。
### 7. 品質の選択
「品質」は、格子解像度と各処理の反復回数をまとめて切り替えます。
格子解像度は、1セルの幅を決める数です。1セルの幅は、計算領域の長辺の画素数を格子解像度で割った長さで、1画素より小さくはなりません。格子解像度が大きいほど1セルの幅が小さくなり、細部まで表せます。計算領域の長辺の画素数が格子解像度より大きいときは、計算領域が広いほど1セルの幅が大きくなります。計算領域は透明な部分も含む素材全体から決まるため、透明な部分の多い素材では細部が粗くなることがあります。
| 品質 | 格子解像度 | エッジ接線流の反復 | ガウス差分の反復 | L1平坦化の反復 |
|---|---:|---:|---:|---:|
| 標準 | 1024 | 2回 | 2回 | 24回 |
| 高品質 | 1440 | 3回 | 2回 | 40回 |
| 最高品質 | 2048 | 3回 | 3回 | 64回 |
格子解像度は計算領域の長辺のセル数です。短辺のセル数は計算領域の縦横比に合わせて決めます。
「品質」を変えると、反復回数と、場合によっては1セルの幅が変わるため、主線と色面の形も変わります。
エッジ接線流の半径、「線の流れ」で決める重みの幅、L1平坦化で平均する近くのセルの範囲は、セルを単位に決まっています。1セルの幅が大きいほど、これらが画素で占める範囲は広くなります。版ずれの距離、ばれん目、和紙の繊維の模様は、画素を単位に決まっているため、1セルの幅によりません。中心ガウスの幅は、「線の太さ」により画素を単位に決まりますが、1セルの幅の半分より狭くなりません。
---
@@ -122,8 +170,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 強さ | 数値 | 100% | 0〜100% | 対応 | 浮世絵調の合成量です。0%では入力を変更しません。 |
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 処理格子の解像度と反復回数を選択します。 |
| 強さ | 数値 | 100% | 0〜100% | 対応 | 浮世絵調の合成量です。0%では入力を変更せず、100%では描いた絵だけを表示します。 |
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 格子解像度と反復回数を選択します。 |
### 主線グループ
@@ -132,49 +180,86 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
| 線の太さ | 数値 | 50% | 0〜100% | 対応 | 主線の太さです。輪郭検出の中心ガウスの幅を決めます。 |
| 線の流れ | 数値 | 50% | 0〜100% | 対応 | エッジ接線流に沿って応答を集める長さです。高いほど線がつながります。 |
| 線の量 | 数値 | 50% | 0〜100% | 対応 | 二値化のしきい値です。高いほど弱いエッジも主線になります。 |
| 線の濃さ | 数値 | 85% | 0〜100% | 対応 | 主線を重ねる濃さです。 |
| 主線色 | 色 | #1E1A18 | — | 非対応 | 主線の色です。 |
| 線の濃さ | 数値 | 85% | 0〜100% | 対応 | 主線を重ねる濃さです。0%では主線を描きません。 |
| 主線色 | 色 | #1E1A18 | — | 非対応 | 主線の色です。不透明度は使いません。 |
### 色面グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 平坦化 | 数値 | 60% | 0〜100% | 対応 | L1平坦化の強さです。高いほど色面が大きく均されます。 |
| 色数 | 整数 | 6 | 2〜16 | 非対応 | 限定パレットの階調数です。 |
| 色数 | 整数 | 6 | 2〜16 | 非対応 | 限定パレットの階調数です。分けるのは暗さだけで、色味は素材の色を残します。 |
### 意匠グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 版ずれ | 数値 | 30% | 0〜100% | 対応 | 色版の刷りずれの大きさです。100%で最大10画素ずれます。 |
| ばれん目 | 数値 | 40% | 0〜100% | 対応 | ばれんの擦り跡の強さです。色面に同心円状のむらが出ます。 |
| 和紙 | 数値 | 50% | 0〜100% | 対応 | 和紙の繊維によるかすれの強さです。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 和紙の繊維とばれん目と版ずれの形を決める固定値です。直接入力では2147483647まで指定できます。 |
| 版ずれ | 数値 | 30% | 0〜100% | 対応 | 色版の刷りずれの大きさです。100%では10画素ずれます。 |
| ばれん目 | 数値 | 40% | 0〜100% | 対応 | ばれんの擦り跡の強さです。中ほどの暗さの色面に同心円状のむらが出ます。 |
| 和紙 | 数値 | 50% | 0〜100% | 対応 | 和紙の繊維によるかすれの強さです。紙の地色は付けません。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 和紙の繊維とばれん目の模様と、版ずれの向きを決める固定値です。直接入力では2147483647まで指定できます。 |
---
## 制限事項
- AviUtl向けのEXO出力には対応していません。
- Direct3D 12デバイスを取得できない場合や、YMM4が使うDirect3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない場合は、エフェクトを適用せず入力映像を表示します。
- 現在のフレームの色とアルファ値だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
- 計算領域は素材の範囲に主線の到達範囲と版ずれと描画の余白を加えた大きさで、長辺は8192画素が上限です。素材が大きく余白を確保できない場合は、エフェクトを適用せず入力映像を表示します。
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、エフェクトを適用せず入力映像を表示します。GPUメモリが足りず共有テクスチャを確保できない場合も同じです。
- 絵柄の計算には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
- 計算領域は、透明な部分も含む素材全体の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。素材の長辺が、標準では7944画素、高品質では8000画素、最高品質では8040画素を超える場合は、エフェクトを適用せず入力映像を表示します。余白の幅は、版ずれ、線の太さ、線の流れをそれぞれ最大にしたときに主線と版ずれが届く距離に、8画素を足して4画素単位に切り上げた値です。届く距離は、見積もったセルの幅で求めます。このセルの幅は、素材の長辺に128画素を足した長さを格子解像度で割った長さで、1画素より小さくはなりません。このように余白は、各項目の今の値によらず、素材の大きさと品質だけで決まります。素材の長辺の上限が品質で違うのは、見積もったセルの幅が品質で違い、余白の幅が変わるためです。
- 処理量とGPUメモリ使用量は、計算領域の大きさと品質に応じて増えます。
---
## 注意事項
- 処理負荷: 最高品質は処理格子の解像度と反復回数が最も多いため、高品質と標準より処理負荷が高くなります。描画は素材が存在する最小の矩形の範囲だけを計算します。
- キャッシュ: 素材の色と形および構造を決めるパラメータが変わらないフレームでは、輪郭と平坦化の計算を再利用します。色数、版ずれ、ばれん目、和紙、線の濃さ、主線色、シードだけを変えたフレームでは、構造を再計算しません。
- 強さ0%: 強さが0%のときは入力を変更しません。
- シードと再現性: 和紙の繊維とばれん目と版ずれの形は、シードと画素位置から決定論的に算出します。時間値は生成に使用しません。
- 透明部分: 主線と版ずれは素材の外側にもわずかに描画されるため、出力範囲は素材より広がります。出力は元映像と強さの割合で合成します。
- 処理負荷: 最高品質は格子解像度が最も大きく、反復回数も最も多いため、高品質と標準より処理負荷が高くなります。描画は、素材の見える部分を囲む矩形を、主線と版ずれが届く分だけ広げた範囲で行います。
- キャッシュ: 素材と品質が変わらないフレームでは、主線を引く向きを決めるエッジ接線流の計算を再利用します。そのうえで、線の太さ、線の流れ、線の量が変わらなければ、主線の計算も再利用します。平坦化が変わらなければ、色面を均すL1平坦化の計算も再利用します。線の濃さ、主線色、色数、版ずれ、ばれん目、和紙、シードだけを変えたフレームでは、主線とL1平坦化を計算し直さず、描画だけをやり直します。強さだけを変えたフレームでは、描き直さず、合成の量だけを変えます。素材が変わったかどうかは、素材の大きさとハッシュで毎フレーム確かめます。ハッシュは、セルごとの色と不透明度の平均を8ビットに丸めた値から作ります。動画のように毎フレーム変わる素材では、すべてを計算し直します。線の太さ、線の流れ、線の量、平坦化をアニメーションで変えたフレームでは、変えた項目にかかわる計算をそのたびにやり直します。どちらも処理が重くなります。
- 強さ0%: 強さが0%のときは入力を変更せず、主線と色面の計算も行いません。強さを0%から上げたフレームでは、最後に計算したときから変わった素材や項目にかかわる計算だけをやり直します。
- シードと再現性: 和紙の繊維とばれん目の模様はシードと画素位置から、版ずれの向きはシードから版ごとに、決定論的に算出します。時間値は生成に使用しません。画素位置は、計算領域の左上から数えます。計算領域の左上は、素材の左上から余白の幅だけ外にあります。余白の幅は、素材の大きさと品質だけで決まります。そのため素材の大きさと品質が同じなら、シード以外の項目を変えても、模様は素材に対して動きません。素材の大きさか品質が変わると、模様の位置がずれることがあります。
- 透明部分: 主線と版ずれは素材の外側にもわずかに描画されるため、出力範囲は素材より広がります。1セルの幅が1画素より大きいときは、セルの不透明度を補間するため、素材の縁から外へ最大で1セルの幅の1.5倍ほどの範囲まで不透明度が付くことがあります。縁に近い画素ほど不透明になります。紙の地色は付けないため、主線と版ずれのかからない、素材から離れた透明な部分は透明のままです。出力は、入力映像と描いた絵を強さの割合で混ぜ合わせたものです。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めません。止める設定もありません。
送信する数には上限があります。YMM4の1回の起動で送る報告は、YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号、プラグイン自身のコードかどうか |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
| 時刻 | 報告を作った時刻(UTC) |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
| 種類 | 例 |
|---|---|
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、計算領域が8192画素に収まらないときに、エフェクトを適用せず入力映像を表示したとき |
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインはMITライセンスのもとで公開されています。
+46
ファイルの表示
@@ -0,0 +1,46 @@
# セキュリティポリシー
## サポートするバージョン
セキュリティの修正は、最新のリリースだけを対象にします。
| バージョン | サポート |
|---|---|
| 最新のリリース | 対象 |
| それより前のリリース | 対象外 |
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
## 対象とする問題
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
## 報告の方法
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
| 項目 | 内容 |
|---|---|
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
| 影響 | 問題によって何ができてしまうか |
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
## 報告の後
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace Ukiyoe.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 Ukiyoe.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();
}
}
+93
ファイルの表示
@@ -0,0 +1,93 @@
namespace Ukiyoe.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
Structure,
}
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 <画像>] 描画を計測します
--structure 構造の再計算がパラメータごとに掛かる時間を内訳で計測します
""";
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 "--structure":
mode = Select(mode, HarnessMode.Structure);
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 つだけ指定してください。");
}
+64
ファイルの表示
@@ -0,0 +1,64 @@
using System.Windows.Media;
namespace Ukiyoe.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, UkiyoeEffect Effect, IReadOnlyList<int> 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 ("quality-balanced", Create(effect => effect.Quality = UkiyoeQuality.Balanced), [0]);
yield return ("quality-ultra", Create(effect => effect.Quality = UkiyoeQuality.Ultra), [0]);
yield return ("line-width-0", Create(effect => effect.LineWidth.Values[0].Value = 0), [0]);
yield return ("line-width-100", Create(effect => effect.LineWidth.Values[0].Value = 100), [0]);
yield return ("coherence-0", Create(effect => effect.Coherence.Values[0].Value = 0), [0]);
yield return ("coherence-100", Create(effect => effect.Coherence.Values[0].Value = 100), [0]);
yield return ("line-detail-100", Create(effect => effect.LineDetail.Values[0].Value = 100), [0]);
yield return ("line-strength-0", Create(effect => effect.LineStrength.Values[0].Value = 0), [0]);
yield return ("flatten-0", Create(effect => effect.Flatten.Values[0].Value = 0), [0]);
yield return ("flatten-100", Create(effect => effect.Flatten.Values[0].Value = 100), [0]);
yield return ("palette-levels-2", Create(effect => effect.PaletteLevels = 2), [0]);
yield return ("palette-levels-16", Create(effect => effect.PaletteLevels = 16), [0]);
yield return ("misregistration-0", Create(effect => effect.Misregistration.Values[0].Value = 0), [0]);
yield return ("misregistration-100", Create(effect => effect.Misregistration.Values[0].Value = 100), [0]);
yield return ("baren-100", Create(effect => effect.Baren.Values[0].Value = 100), [0]);
yield return ("paper-100", Create(effect => effect.Paper.Values[0].Value = 100), [0]);
yield return ("seed-42", Create(effect => effect.Seed = 42), [0]);
yield return ("line-color", Create(effect => effect.LineColor = Color.FromArgb(255, 200, 20, 20)), [0]);
}
public static IEnumerable<(string Name, Func<UkiyoeEffect> Create, Action<UkiyoeEffect> Change, int Frame)> Transitions()
{
yield return ("line-width-50-to-100", () => Create(), effect => effect.LineWidth.Values[0].Value = 100, 0);
yield return ("coherence-50-to-100", () => Create(), effect => effect.Coherence.Values[0].Value = 100, 0);
yield return ("line-detail-50-to-100", () => Create(), effect => effect.LineDetail.Values[0].Value = 100, 0);
yield return ("flatten-60-to-0", () => Create(), effect => effect.Flatten.Values[0].Value = 0, 0);
yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = UkiyoeQuality.Ultra, 0);
yield return ("palette-levels-6-to-2", () => Create(), effect => effect.PaletteLevels = 2, 0);
yield return ("misregistration-30-to-100", () => Create(), effect => effect.Misregistration.Values[0].Value = 100, 0);
yield return ("baren-40-to-100", () => Create(), effect => effect.Baren.Values[0].Value = 100, 0);
yield return ("paper-50-to-100", () => Create(), effect => effect.Paper.Values[0].Value = 100, 0);
yield return ("line-strength-85-to-0", () => Create(), effect => effect.LineStrength.Values[0].Value = 0, 0);
yield return ("line-color-change", () => Create(), effect => effect.LineColor = Color.FromArgb(255, 200, 20, 20), 0);
yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0);
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
}
public static IEnumerable<(string Name, UkiyoeEffect Effect)> Benchmarks()
{
yield return ("quality-balanced", Create(effect => effect.Quality = UkiyoeQuality.Balanced));
yield return ("default", Create());
yield return ("quality-ultra", Create(effect => effect.Quality = UkiyoeQuality.Ultra));
yield return ("flatten-100", Create(effect => effect.Flatten.Values[0].Value = 100));
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
}
public static UkiyoeEffect Create(Action<UkiyoeEffect>? configure = null)
{
var effect = new UkiyoeEffect();
configure?.Invoke(effect);
return effect;
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System.IO;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Ukiyoe.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 Ukiyoe.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 Ukiyoe.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 Ukiyoe.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);
}
}
+395 -219
ファイルの表示
@@ -1,266 +1,442 @@
using System.Diagnostics;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using ComputeWeave;
using Ukiyoe;
using Ukiyoe.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 = UkiyoePipeline.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, UkiyoePipeline.Parameters Parameters)[]
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
if (arguments.Mode == HarnessMode.Structure)
{
("balanced-default", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("high-default", new(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("seed-42", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 42)),
("flat-none", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("flat-full", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 1f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("palette-2", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 2, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("shift-full", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 1f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("thick-line", new(UkiyoeQuality.Balanced, 1f, 1f, 0.8f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 1f, 0.12f, 0.1f, 0.09f, 0)),
};
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))}");
var structureImage = arguments.Input is { } structureInput ? HarnessImage.Load(structureInput) : HarnessImage.Synthetic(CanvasWidth, CanvasHeight);
return Structure(structureImage);
}
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;
}
foreach (var quality in new[] { UkiyoeQuality.Balanced, UkiyoeQuality.High, UkiyoeQuality.Ultra })
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var parameters = new UkiyoePipeline.Parameters(quality, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
var best = double.MaxValue;
const int frames = 10;
var stopwatch = new Stopwatch();
for (var frame = 0; frame < frames; frame++)
var golden = Golden.Load(Golden.PathFor(image));
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
if (golden.Input != image.Identity || golden.Canvas != canvas)
{
stopwatch.Restart();
pipeline.Process(source, destination, width, height, in parameters);
stopwatch.Stop();
best = Math.Min(best, stopwatch.Elapsed.TotalMilliseconds);
Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。");
return 1;
}
Console.WriteLine($"{quality}: {best:F2} ms/frame ({width}x{height}) litPixels={CountLit(destination)}");
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 device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(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 UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
var stopwatch = new Stopwatch();
var structureBest = double.MaxValue;
for (var round = 0; round < 12; round++)
var failures = 0;
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
{
var recompute = parameters with { Flatten = (round & 1) == 0 ? 0.7f : 0.6f };
stopwatch.Restart();
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in recompute);
pipeline.WaitForCompletion();
stopwatch.Stop();
structureBest = Math.Min(structureBest, stopwatch.Elapsed.TotalMilliseconds);
}
Console.WriteLine($"structure recompute: {structureBest:F2} ms");
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;
}
if (pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
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 Structure(HarnessImage image)
{
const int Rounds = 12;
const int Seed = 17;
const int RectFrames = 20;
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
throw new HarnessException("Direct3D 12を利用できません。");
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
var pixels = new Bgra32[image.Width * image.Height];
for (var index = 0; index < pixels.Length; index++)
{
var offset = index * HarnessImage.BytesPerPixel;
pixels[index] = new Bgra32(image.Pixels[offset + 2], image.Pixels[offset + 1], image.Pixels[offset], image.Pixels[offset + 3]);
}
sourceTexture.CopyFrom(pixels);
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters);
pipeline.WaitForCompletion();
var stopwatch = new Stopwatch();
var variants = new (string Name, Func<bool, UkiyoePipeline.Parameters> Make)[]
{
("cached", _ => parameters),
("flatten", flip => parameters with { Flatten = flip ? 0.70f : 0.60f }),
("lineWidth", flip => parameters with { LineWidth = flip ? 0.60f : 0.50f }),
("coherence", flip => parameters with { Coherence = flip ? 0.60f : 0.50f }),
("lineDetail", flip => parameters with { LineDetail = flip ? 0.60f : 0.50f }),
("all", flip => parameters with
{
Flatten = flip ? 0.70f : 0.60f,
LineWidth = flip ? 0.60f : 0.50f,
Coherence = flip ? 0.60f : 0.50f,
LineDetail = flip ? 0.60f : 0.50f,
}),
};
var samples = new List<double>[variants.Length];
for (var index = 0; index < samples.Length; index++)
samples[index] = new List<double>(Rounds);
foreach (var (_, make) in variants)
{
var warmup = make(true);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in warmup);
pipeline.WaitForCompletion();
}
var order = Enumerable.Range(0, variants.Length).ToArray();
var random = new Random(Seed);
for (var round = 0; round < Rounds; round++)
{
for (var index = order.Length - 1; index > 0; index--)
{
var swap = random.Next(index + 1);
(order[index], order[swap]) = (order[swap], order[index]);
}
foreach (var index in order)
{
var settled = variants[index].Make(false);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in settled);
pipeline.WaitForCompletion();
var measured = variants[index].Make(true);
stopwatch.Restart();
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in measured);
pipeline.WaitForCompletion();
stopwatch.Stop();
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
}
}
Console.WriteLine($"structure recompute over {Rounds} interleaved rounds (ms)");
for (var index = 0; index < variants.Length; index++)
{
var sorted = samples[index].OrderBy(static value => value).ToArray();
var median = sorted[sorted.Length / 2];
Console.WriteLine($" {variants[index].Name,-11} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
}
if (pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out var rect))
{
using var rectOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(rectOutput, width, height, rect, in parameters);
pipeline.RenderVisible(rectOutput, image.Width, image.Height, rect, in parameters);
pipeline.WaitForCompletion();
stopwatch.Restart();
const int rectFrames = 20;
for (var frame = 0; frame < rectFrames; frame++)
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.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters);
pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out rect);
pipeline.RenderVisible(rectOutput, image.Width, image.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.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / RectFrames:F2} ms/frame");
}
return 0;
}
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));
}
}
foreach (var flatten in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, flatten, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"flatten={flatten:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"flatten{(int)(flatten * 100):D3}.bmp"), Composite(source, destination), width, height);
}
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}");
foreach (var palette in new[] { 2, 6, 12 })
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, palette, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"palette={palette} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"palette{palette:D2}.bmp"), Composite(source, destination), width, height);
}
foreach (var shift in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, shift, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"shift={shift:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"shift{(int)(shift * 100):D3}.bmp"), Composite(source, destination), width, height);
}
foreach (var paper in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, paper, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"paper={paper:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"paper{(int)(paper * 100):D3}.bmp"), Composite(source, destination), width, height);
}
foreach (var lineWidth in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, lineWidth, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"lineWidth={lineWidth:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"linewidth{(int)(lineWidth * 100):D3}.bmp"), Composite(source, destination), width, height);
}
WriteBmp(Path.Combine(outputDirectory, "source.bmp"), Composite(source, new int[source.Length]), width, height);
Console.WriteLine($"images written to {outputDirectory}");
return 0;
static int[] CreateTestImage(int width, int height)
{
var pixels = new int[width * height];
var centerX = width * 0.5;
var centerY = height * 0.5;
for (var y = 0; y < height; y++)
var cases = new List<GoldenCase>();
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var (name, effect, frames) in HarnessCases.All())
{
for (var x = 0; x < width; x++)
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++)
{
var inRect = Math.Abs(x - centerX) < 300 && Math.Abs(y - centerY) < 220;
var dx = x - (centerX + 160);
var dy = y - (centerY - 60);
var inCircle = dx * dx + dy * dy < 130 * 130;
if (!inRect && !inCircle)
continue;
int r;
int g;
int b;
if (inCircle)
{
var shade = 1.0 - Math.Sqrt(dx * dx + dy * dy) / 130.0 * 0.6;
r = (int)(220 * shade);
g = (int)(80 * shade);
b = (int)(60 * shade);
}
else
{
var vertical = (y - (centerY - 220)) / 440.0;
r = (int)(70 + 60 * vertical);
g = (int)(110 + 70 * vertical);
b = (int)(170 + 60 * vertical);
if ((x / 3 + y / 7) % 9 == 0)
{
r += 25;
g += 25;
b += 20;
}
}
var hash = (uint)(x * 374761393 + y * 668265263);
hash = (hash ^ (hash >> 13)) * 1274126177u;
var noise = (int)((hash >> 24) & 31) - 16;
r = Math.Clamp(r + noise, 0, 255);
g = Math.Clamp(g + noise, 0, 255);
b = Math.Clamp(b + noise, 0, 255);
pixels[y * width + x] = unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
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 pixels;
return duplicates;
}
static int CountLit(int[] pixels)
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[] print)
{
var result = new int[source.Length];
for (var index = 0; index < source.Length; index++)
{
var s = source[index];
var p = print[index];
var sa = (s >> 24) & 255;
var pa = (p >> 24) & 255;
var a = Math.Min(pa + sa * (255 - pa) / 255, 255);
var r = Over((s >> 16) & 255, (p >> 16) & 255, pa);
var g = Over((s >> 8) & 255, (p >> 8) & 255, pa);
var b = Over(s & 255, p & 255, pa);
result[index] = 255 << 24 | OverWhite(r, a) << 16 | OverWhite(g, a) << 8 | OverWhite(b, a);
}
return result;
static int Over(int s, int p, int pa) => Math.Min(p + s * (255 - pa) / 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);
}
}
+51
ファイルの表示
@@ -0,0 +1,51 @@
namespace Ukiyoe.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);
}
+35 -3
ファイルの表示
@@ -3,12 +3,14 @@
<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>Ukiyoe.Harness</AssemblyName>
<RootNamespace>Ukiyoe.Harness</RootNamespace>
<PlatformTarget>x64</PlatformTarget>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
@@ -18,13 +20,43 @@
</ItemGroup>
<ItemGroup>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<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>
+163
ファイルの表示
@@ -0,0 +1,163 @@
{
"adapter": "Intel(R) Iris(R) Xe Graphics",
"driver": "32.0.101.7085",
"input": "synthetic 640x480 89838D8976198E40",
"canvas": "1280x720",
"cases": [
{
"name": "default",
"frames": [
0
],
"hash": "E4B864BE2AFC0339B2A58053A3750DF794D2967E3FD28B0862608C49E17C8692"
},
{
"name": "default-frames-0-8",
"frames": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"hash": "8E22BF1D9D1D90209C70CA85BAB8A40121BB3FA5E369034BC69FBD4009A095CC"
},
{
"name": "amount-0",
"frames": [
0
],
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
},
{
"name": "quality-balanced",
"frames": [
0
],
"hash": "212F218DD42B2D96AB89CB081BFF9E35C40E1668FD2F5AA46F54A553F58AE77E"
},
{
"name": "quality-ultra",
"frames": [
0
],
"hash": "3B967280899D58288E4A5B02EB0FF326FCE7DA5CFE0ED9223D934D93B5B9C864"
},
{
"name": "line-width-0",
"frames": [
0
],
"hash": "C1CDECBAEDD8E02FF82A3F05791CBC28F528DEC3858D87592BFFCBF57C8A40AB"
},
{
"name": "line-width-100",
"frames": [
0
],
"hash": "A3C8F22815DA7BF166D1FFA50F5125939D7826724FBB7D150970AD07F50CF782"
},
{
"name": "coherence-0",
"frames": [
0
],
"hash": "F5EC6127E07A595B7766CE1128AD49310AC267805F113EBFF87FD284B1F04AE3"
},
{
"name": "coherence-100",
"frames": [
0
],
"hash": "F4DF965CA2FC028DC5C1056098A1C0938D48986BF158CD1FBFE1D0EDF2D41C4B"
},
{
"name": "line-detail-100",
"frames": [
0
],
"hash": "0BD93E3CA89C447B4AC7CDB18660734191D6A9CFF443928C99FF27078EBBC4DA"
},
{
"name": "line-strength-0",
"frames": [
0
],
"hash": "1BDFD04B42D953F94B1902F3D4685DA66833F622B4B63775E5C16ED3A815B224"
},
{
"name": "flatten-0",
"frames": [
0
],
"hash": "784B04C0A8D709CC963B18AD9545B633340465E032A37549133655F6EAEFB0C2"
},
{
"name": "flatten-100",
"frames": [
0
],
"hash": "2A44CDEB5E26164F332D1A7A74B8182FA0800659536324E789245607E3542DBB"
},
{
"name": "palette-levels-2",
"frames": [
0
],
"hash": "84DB0B6D50EBEF365FAA154C0D06882C951920E4D667B3DA2650DA7F153DB632"
},
{
"name": "palette-levels-16",
"frames": [
0
],
"hash": "622CD2477C12900ABDB81A74A85FA60BE720987481D3CEC65446E5425C034038"
},
{
"name": "misregistration-0",
"frames": [
0
],
"hash": "147B753A05E9D4606BA915F54F13D622399C26E97CDE96289F9052528DE81C6A"
},
{
"name": "misregistration-100",
"frames": [
0
],
"hash": "38CCFAEDB34C850E3EEFA94CEBF707DD3E34B3A69D8E93F9C8687AC98A9CFA38"
},
{
"name": "baren-100",
"frames": [
0
],
"hash": "D58BEF962A0CDD1A3467E3795D917FD588B25541E678091A6EB8BBC0BE171F86"
},
{
"name": "paper-100",
"frames": [
0
],
"hash": "520F16F2B9989E0B14A14F94B9B400DFA030FA278C24E107884105C797CC5741"
},
{
"name": "seed-42",
"frames": [
0
],
"hash": "D85638F030A0BAB41CE9E6B151A94665AB5918D54CC8FD350AF95628722C90D6"
},
{
"name": "line-color",
"frames": [
0
],
"hash": "A905D828FFE947704FC7C51E6CAFD5CA3954F1768C7DC29B6723894545F47D6D"
}
]
}
+157
ファイルの表示
@@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{C7DCA1E0-297A-41B2-9B15-8C8593EC861E}</ProjectGuid>
<RootNamespace>UkiyoeShader</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<OutDir>$(MSBuildThisFileDirectory)..\Release\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
<CompileD2DCustomEffect>
</CompileD2DCustomEffect>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemGroup>
<FxCompile Include="Ukiyoe.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
</FxCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+22
ファイルの表示
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="ソース ファイル">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="ヘッダー ファイル">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="リソース ファイル">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="Ukiyoe.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
</Project>
ファイルの表示
差分なしでファイル名を変更。
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace Ukiyoe.Tests;
internal readonly record struct Bgra(byte Blue, byte Green, byte Red, byte Alpha)
{
public static Bgra Transparent => default;
public static Bgra Opaque(byte blue, byte green, byte red) => new(blue, green, red, byte.MaxValue);
public Bgra Premultiplied() => new(Premultiply(Blue), Premultiply(Green), Premultiply(Red), Alpha);
byte Premultiply(byte value) => (byte)Math.Round(value * (double)Alpha / byte.MaxValue, MidpointRounding.AwayFromZero);
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System.Drawing;
using System.Numerics;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Player.Video;
namespace Ukiyoe.Tests;
internal static class EffectDescriptions
{
public const int Fps = 30;
static readonly Size ScreenSize = new(1920, 1080);
public static EffectDescription At(int frame, int length)
{
var timeline = new TimelineSourceDescription(
ScreenSize,
new FrameTime(frame, Fps),
new 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);
}
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Ukiyoe.Tests;
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;
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System.Windows;
using Telemetry;
namespace Ukiyoe.Tests;
public sealed class HostIntegrationTests
{
[Fact]
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
{
Assert.Null(Application.Current);
UkiyoeTelemetry.EnsureStartedOnce();
UkiyoeTelemetry.Report(new InvalidOperationException());
Assert.Null(ProcessState.Read("DrainClaimed"));
Assert.Null(ProcessState.Read("SentCount"));
}
[Fact]
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
{
Assert.Null(Application.Current);
var effect = new UkiyoeEffect();
Assert.Equal(Texts.Ukiyoe, effect.Label);
Assert.Null(ProcessState.Read("DrainClaimed"));
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System.IO.Packaging;
using System.Runtime.CompilerServices;
namespace Ukiyoe.Tests;
internal static class PackUriScheme
{
[ModuleInitializer]
internal static void Register() => _ = PackUriHelper.UriSchemePack;
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.Direct2D1;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace Ukiyoe.Tests;
internal sealed class Rendering
{
readonly byte[] pixels;
public int Left { get; }
public int Top { get; }
public int Width { get; }
public int Height { get; }
public int Right => Left + Width;
public int Bottom => Top + Height;
Rendering(int left, int top, int width, int height, byte[] pixels)
{
Left = left;
Top = top;
Width = width;
Height = height;
this.pixels = pixels;
}
public static Rendering Capture(IGraphicsDevicesAndContext devices, ID2D1Image image)
{
var context = devices.DeviceContext;
var bounds = context.GetImageLocalBounds(image);
var left = (int)Math.Floor(bounds.Left);
var top = (int)Math.Floor(bounds.Top);
var width = (int)Math.Ceiling(bounds.Right) - left;
var height = (int)Math.Ceiling(bounds.Bottom) - top;
var stride = width * SourceImage.BytesPerPixel;
var size = new SizeI(width, height);
using var target = context.CreateBitmap(size, nint.Zero, stride,
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.Target));
using var readback = context.CreateBitmap(size, nint.Zero, stride,
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
context.Target = target;
context.BeginDraw();
context.Clear(new Color4(0f, 0f, 0f, 0f));
context.DrawImage(image, new Vector2(-left, -top), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
context.EndDraw();
context.Target = null;
readback.CopyFromBitmap(target);
var pixels = new byte[stride * height];
var mapped = readback.Map(MapOptions.Read);
try
{
for (var y = 0; y < height; y++)
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
}
finally
{
readback.Unmap();
}
return new Rendering(left, top, width, height, pixels);
}
public Bgra this[int x, int y]
{
get
{
var offset = ((y - Top) * Width + (x - Left)) * SourceImage.BytesPerPixel;
return new Bgra(pixels[offset], pixels[offset + 1], pixels[offset + 2], pixels[offset + 3]);
}
}
public bool Contains(int x, int y) => x >= Left && y >= Top && x < Right && y < Bottom;
public bool SamePixelsAs(Rendering other)
=> Left == other.Left && Top == other.Top && Width == other.Width && Height == other.Height && pixels.AsSpan().SequenceEqual(other.pixels);
public IEnumerable<(int X, int Y)> Coordinates()
{
for (var y = Top; y < Bottom; y++)
{
for (var x = Left; x < Right; x++)
yield return (x, y);
}
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace Ukiyoe.Tests;
internal sealed class SourceImage : IDisposable
{
public const float Dpi = 96f;
public const int BytesPerPixel = 4;
public static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
readonly Func<int, int, Bgra> pixelOf;
public int Width { get; }
public int Height { get; }
public ID2D1Bitmap1 Bitmap { get; }
public SourceImage(IGraphicsDevicesAndContext devices, int width, int height, Func<int, int, Bgra> pixelOf)
{
this.pixelOf = pixelOf;
Width = width;
Height = height;
var stride = width * BytesPerPixel;
var pixels = new byte[stride * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var (blue, green, red, alpha) = pixelOf(x, y).Premultiplied();
var offset = y * stride + x * BytesPerPixel;
pixels[offset] = blue;
pixels[offset + 1] = green;
pixels[offset + 2] = red;
pixels[offset + 3] = alpha;
}
}
Bitmap = devices.DeviceContext.CreateBitmap(
new SizeI(width, height), nint.Zero, stride,
new BitmapProperties1(PixelFormat, Dpi, Dpi, BitmapOptions.None));
Bitmap.CopyFromMemory(pixels, stride);
}
public static SourceImage Solid(IGraphicsDevicesAndContext devices, int width, int height, Bgra color)
=> new(devices, width, height, (_, _) => color);
public Bgra this[int x, int y] => pixelOf(x, y).Premultiplied();
public bool Contains(int x, int y) => x >= 0 && y >= 0 && x < Width && y < Height;
public void Dispose() => Bitmap.Dispose();
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
using System.Collections;
using System.Globalization;
using System.Reflection;
namespace Ukiyoe.Tests;
public sealed class TextsTests
{
public static readonly TheoryData<string> Cultures = ["ja-JP", "en-US", "zh-CN", "zh-TW", "ko-KR", "es-ES", "ar-SA", "id-ID"];
static readonly string[] Keys = typeof(Texts)
.GetProperties(BindingFlags.Public | BindingFlags.Static)
.Where(property => property.PropertyType == typeof(string) && property.Name != nameof(Texts.CurrentCulture))
.Select(property => property.Name)
.ToArray();
[Fact]
public void EveryLocalizedKeyHasAProperty()
{
var resources = Texts.ResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false)!;
var keys = resources.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).Where(key => key != nameof(Texts.CurrentCulture));
Assert.Equal(keys.Order(), Keys.Order());
}
[Theory]
[MemberData(nameof(Cultures))]
public void EveryKeyIsTranslated(string culture)
{
var cultureInfo = CultureInfo.GetCultureInfo(culture);
Assert.All(Keys, key => Assert.False(string.IsNullOrWhiteSpace(Texts.ResourceManager.GetString(key, cultureInfo)), key));
}
[Theory]
[MemberData(nameof(Cultures))]
public void EveryCultureCarriesItsOwnTranslations(string culture)
{
var cultureInfo = CultureInfo.GetCultureInfo(culture);
Assert.Equal(culture.ToLowerInvariant(), Texts.ResourceManager.GetString(nameof(Texts.CurrentCulture), cultureInfo));
}
[Fact]
public void JapaneseIsTheNeutralLanguage()
{
var neutral = Texts.ResourceManager.GetString(nameof(Texts.Ukiyoe), CultureInfo.InvariantCulture);
Assert.Equal("浮世絵", neutral);
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.Ukiyoe), CultureInfo.GetCultureInfo("ja-JP")));
}
[Fact]
public void TheUpdateMessageEmbedsTheVersion()
{
var message = string.Format(CultureInfo.InvariantCulture, Texts.ResourceManager.GetString(nameof(Texts.UpdateAvailableMessage), CultureInfo.InvariantCulture)!, "v1.2.3");
Assert.Contains("v1.2.3", message);
}
}
+28 -11
ファイルの表示
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
@@ -12,50 +13,67 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="3.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ukiyoe\Ukiyoe.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
<ProjectReference Include="..\Ukiyoe\Ukiyoe.csproj" SetConfiguration="Configuration=$(Configuration)">
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
</ItemGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="SharpGen.Runtime.COM">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.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>
</Reference>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.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>
@@ -63,5 +81,4 @@
<Using Include="Xunit" />
</ItemGroup>
</Project>
+158
ファイルの表示
@@ -0,0 +1,158 @@
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
namespace Ukiyoe.Tests;
[Collection("Direct2D")]
public sealed class UkiyoeCustomEffectTests
{
const int AmountIndex = 0;
const int Width = 40;
const int Height = 24;
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
static readonly Bgra HalfPrint = new(0, 0, 0, 128);
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image print, float amount)
{
using var effect = new UkiyoeCustomEffect(devices);
effect.SetInput(0, source, true);
effect.SetInput(1, print, true);
effect.Amount = amount;
using var output = effect.Output;
return Rendering.Capture(devices, output);
}
static AffineTransform2D Translate(IGraphicsDevicesAndContext devices, ID2D1Image image, float dx, float dy)
{
var transform = new AffineTransform2D(devices.DeviceContext)
{
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
BorderMode = BorderMode.Hard,
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
};
transform.SetInput(0, image, true);
return transform;
}
static bool WithinRounding(Bgra expected, Bgra actual)
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
static Bgra Mix(Bgra print, Bgra source, float amount)
{
byte Channel(byte printValue, byte sourceValue) => (byte)Math.Round(printValue * amount + sourceValue * (1d - amount), MidpointRounding.AwayFromZero);
return new Bgra(Channel(print.Blue, source.Blue), Channel(print.Green, source.Green), Channel(print.Red, source.Red), Channel(print.Alpha, source.Alpha));
}
[Fact]
public void TheEffectIsEnabledOnceCreated()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new UkiyoeCustomEffect(context);
Assert.True(effect.IsEnabled);
}
[Fact]
public void TheAmountStartsFromZero()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new UkiyoeCustomEffect(context);
Assert.Equal(0f, effect.GetFloatValue(AmountIndex));
}
[Theory]
[InlineData(-0.5f, 0f)]
[InlineData(0f, 0f)]
[InlineData(0.4f, 0.4f)]
[InlineData(1f, 1f)]
[InlineData(1.5f, 1f)]
[InlineData(float.MaxValue, 1f)]
public void TheAmountIsClampedToTheUnitRange(float value, float expected)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new UkiyoeCustomEffect(context);
effect.Amount = value;
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
}
[Fact]
public void TheOutputBoundsCoverTheSourceAndThePrint()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var print = SourceImage.Solid(context, 8, 8, HalfPrint);
using var moved = Translate(context, print.Bitmap, 50f, -6f);
using var movedOutput = moved.Output;
using var effect = new UkiyoeCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetInput(1, movedOutput, true);
using var output = effect.Output;
var bounds = context.DeviceContext.GetImageLocalBounds(output);
Assert.Equal(0f, bounds.Left);
Assert.Equal(-6f, bounds.Top);
Assert.Equal(58f, bounds.Right);
Assert.Equal((float)Height, bounds.Bottom);
}
[Theory]
[InlineData(0f)]
[InlineData(-1f)]
public void WithoutAmountTheSourcePassesThroughUntouched(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var print = SourceImage.Solid(context, Width, Height, HalfPrint);
var rendering = Render(context, source.Bitmap, print.Bitmap, amount);
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
}
[Theory]
[InlineData(1f)]
[InlineData(0.5f)]
[InlineData(0.25f)]
public void TheSourceGivesWayToThePrintByTheAmount(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var print = SourceImage.Solid(context, Width, Height, HalfPrint);
var expected = Mix(HalfPrint.Premultiplied(), Blue.Premultiplied(), amount);
var rendering = Render(context, source.Bitmap, print.Bitmap, amount);
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
}
[Fact]
public void AtTheFullAmountOnlyThePrintIsDrawn()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var print = SourceImage.Solid(context, 8, 8, HalfPrint);
using var moved = Translate(context, print.Bitmap, 50f, 4f);
using var movedOutput = moved.Output;
var expected = Mix(HalfPrint.Premultiplied(), Bgra.Transparent, 1f);
var rendering = Render(context, source.Bitmap, movedOutput, 1f);
Assert.True(WithinRounding(expected, rendering[53, 7]), $"{rendering[53, 7]}");
Assert.Equal(Bgra.Transparent, rendering[10, 10]);
Assert.Equal(Bgra.Transparent, rendering[45, 10]);
}
}
+300
ファイルの表示
@@ -0,0 +1,300 @@
using System.Globalization;
using System.Windows.Media;
using ComputeWeave;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Player.Video;
namespace Ukiyoe.Tests;
[Collection("Direct2D")]
public sealed class UkiyoeEffectProcessorTests
{
const int Size = 64;
const int Length = 30;
const int Start = 16;
const int End = 48;
static readonly int Margin = UkiyoeSettings.GetMargin(UkiyoeSettings.GetShiftPixels(0.3f), UkiyoeSettings.GetLineSigmaPixels(0.5f), UkiyoeSettings.GetFlowSigma(0.5f), 1f);
static Bgra Pattern(int x, int y)
{
var noise = (int)(((uint)(x * 73856093 ^ y * 19349663) * 0x85EBCA6Bu) >> 26);
return Bgra.Opaque((byte)(64 + x * 2 + noise), (byte)(96 + noise), (byte)(224 - x * 2 - noise));
}
static Bgra CenteredSquare(int x, int y) => x is >= Start and < End && y is >= Start and < End ? Pattern(x, y) : Bgra.Transparent;
static void RequireInterop(IGraphicsDevicesAndContext devices)
{
using var scheduler = ComputeExternalQueueScheduler.Create();
using var provider = UkiyoeInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
static Animation Linear(double from, double to)
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
{
processor.Update(EffectDescriptions.At(frame, Length));
return Rendering.Capture(devices, processor.Output);
}
static void AssertSameAsSource(Rendering rendering, SourceImage source)
{
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]));
}
static bool IsRedrawn(Rendering rendering, SourceImage source)
=> rendering.Coordinates().Any(point => source.Contains(point.X, point.Y) && source[point.X, point.Y].Alpha > 0 && rendering[point.X, point.Y] != source[point.X, point.Y]);
public static readonly TheoryData<string, Action<UkiyoeEffect>> LaterChanges = new()
{
{ nameof(UkiyoeEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
{ nameof(UkiyoeEffect.Quality), effect => effect.Quality = UkiyoeQuality.Balanced },
{ nameof(UkiyoeEffect.LineWidth), effect => effect.LineWidth.Values[0].Value = 100d },
{ nameof(UkiyoeEffect.Coherence), effect => effect.Coherence.Values[0].Value = 0d },
{ nameof(UkiyoeEffect.LineDetail), effect => effect.LineDetail.Values[0].Value = 100d },
{ nameof(UkiyoeEffect.LineStrength), effect => effect.LineStrength.Values[0].Value = 0d },
{ nameof(UkiyoeEffect.LineColor), effect => effect.LineColor = Colors.Crimson },
{ nameof(UkiyoeEffect.Flatten), effect => effect.Flatten.Values[0].Value = 0d },
{ nameof(UkiyoeEffect.PaletteLevels), effect => effect.PaletteLevels = 2 },
{ nameof(UkiyoeEffect.Misregistration), effect => effect.Misregistration.Values[0].Value = 100d },
{ nameof(UkiyoeEffect.Baren), effect => effect.Baren.Values[0].Value = 100d },
{ nameof(UkiyoeEffect.Paper), effect => effect.Paper.Values[0].Value = 100d },
{ nameof(UkiyoeEffect.Seed), effect => effect.Seed = 1 },
};
public static readonly TheoryData<string, Action<UkiyoeEffect>> ReachChanges = new()
{
{ nameof(UkiyoeEffect.Misregistration), effect => effect.Misregistration.Values[0].Value = 40d },
{ nameof(UkiyoeEffect.LineWidth), effect => effect.LineWidth.Values[0].Value = 60d },
{ nameof(UkiyoeEffect.Coherence), effect => effect.Coherence.Values[0].Value = 60d },
};
[Fact]
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var description = EffectDescriptions.At(0, Length);
var draw = processor.Update(description);
Assert.Same(description.DrawDescription, draw);
}
[Fact]
public void TheSquareIsPrintedWithinItsMargin()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.True(IsRedrawn(rendering, source));
Assert.All(rendering.Coordinates(), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
if (point.X < Start - Margin || point.X > End + Margin || point.Y < Start - Margin || point.Y > End + Margin)
Assert.Equal(Bgra.Transparent, pixel);
});
}
[Fact]
public void AZeroAmountPassesTheImageThrough()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new UkiyoeEffect();
effect.Amount.Values[0].Value = 0d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
AssertSameAsSource(rendering, source);
}
[Fact]
public void ASourceBelowTheAlphaThresholdPassesThrough()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, (x, y) => CenteredSquare(x, y) with { Alpha = (byte)(CenteredSquare(x, y).Alpha / byte.MaxValue) });
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
AssertSameAsSource(rendering, source);
}
[Fact]
public void ReturningToAFrameReproducesItExactly()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var first = RenderFrame(context, processor, 4);
RenderFrame(context, processor, 9);
var again = RenderFrame(context, processor, 4);
Assert.True(first.SamePixelsAs(again));
}
[Fact]
public void ANewProcessorDrawsTheSamePrint()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new UkiyoeEffect { Seed = 9 };
using var firstProcessor = effect.CreateVideoEffect(context);
firstProcessor.SetInput(source.Bitmap);
var first = RenderFrame(context, firstProcessor, 0);
using var secondProcessor = effect.CreateVideoEffect(context);
secondProcessor.SetInput(source.Bitmap);
var second = RenderFrame(context, secondProcessor, 0);
Assert.True(first.SamePixelsAs(second));
}
[Fact]
public void AnimatedAmountIsReadAtEachFrame()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new UkiyoeEffect();
effect.Amount.CopyFrom(Linear(0d, 100d));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var start = RenderFrame(context, processor, 0);
var end = RenderFrame(context, processor, Length - 1);
AssertSameAsSource(start, source);
Assert.True(IsRedrawn(end, source));
}
[Theory]
[MemberData(nameof(LaterChanges))]
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<UkiyoeEffect> change)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new UkiyoeEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
change(effect);
var after = RenderFrame(context, processor, 0);
Assert.False(before.SamePixelsAs(after), setting);
}
[Theory]
[MemberData(nameof(ReachChanges))]
public void ChangingHowFarThePrintReachesKeepsTheInsideOfAFlatColor(string setting, Action<UkiyoeEffect> change)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = SourceImage.Solid(context, Size, Size, Bgra.Opaque(96, 128, 192));
var effect = new UkiyoeEffect();
effect.Baren.Values[0].Value = 100d;
effect.Paper.Values[0].Value = 100d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
change(effect);
var after = RenderFrame(context, processor, 0);
Assert.All(
before.Coordinates().Where(point => point.X is >= Start and < End && point.Y is >= Start and < End),
point => Assert.True(before[point.X, point.Y] == after[point.X, point.Y], $"{setting} ({point.X}, {point.Y})"));
}
[Theory]
[InlineData(32, 128)]
[InlineData(128, 32)]
public void AResizedSourceKeepsBeingPrinted(int firstSize, int secondSize)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var first = new SourceImage(context, firstSize, firstSize, (x, y) => Pattern(x * Size / firstSize, y * Size / firstSize));
using var second = new SourceImage(context, secondSize, secondSize, (x, y) => Pattern(x * Size / secondSize, y * Size / secondSize));
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
processor.SetInput(first.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(second.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.True(IsRedrawn(before, first));
Assert.True(IsRedrawn(after, second));
Assert.Equal(secondSize > firstSize, after.Width > before.Width);
}
[Fact(Timeout = 60000)]
public async Task AProcessorDrawsLikeAFreshOneAfterTheDeviceReclaimsIdleMemory()
{
await Task.Run(() =>
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, (x, y) => x is >= 16 and < 48 && y is >= 16 and < 48 ? Bgra.Opaque(80, 200, 255) : Bgra.Transparent);
var effect = new UkiyoeEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
RenderFrame(context, processor, 0);
GraphicsDevice.GetDefault().TrimMemory();
var reclaimed = RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(source.Bitmap);
var expected = RenderFrame(context, fresh, 0);
Assert.True(reclaimed.SamePixelsAs(expected));
}, TestContext.Current.CancellationToken);
}
[Fact]
public void AFailureWhileUpdatingIsNotSwallowed()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var processor = new UkiyoeEffect().CreateVideoEffect(context);
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
}
}
+221 -685
ファイルの表示
@@ -1,51 +1,78 @@
using System.Runtime.InteropServices;
using ComputeWeave;
using ComputeWeave.Interop;
using Vortice;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Windows.Media;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Plugin.Effects;
using YukkuriMovieMaker.Project;
namespace Ukiyoe.Tests;
public sealed class UkiyoeEffectTests
{
private static double ValueAt(YukkuriMovieMaker.Commons.Animation animation) => animation.GetValue(0, 1, 30);
static readonly Color DefaultLineColor = Color.FromArgb(255, 30, 26, 24);
private static UkiyoePipeline.Parameters CreateParameters(
UkiyoeQuality quality = UkiyoeQuality.Balanced,
float lineWidth = 0.5f,
float coherence = 0.5f,
float lineDetail = 0.5f,
float flatten = 0.6f,
int paletteLevels = 6,
float misregistration = 0.3f,
float baren = 0.4f,
float paper = 0.5f,
float lineStrength = 0.85f,
int seed = 0)
=> new(quality, lineWidth, coherence, lineDetail, flatten, paletteLevels, misregistration, baren, paper, lineStrength, 0.12f, 0.1f, 0.09f, seed);
static PropertyInfo Property(string name) => typeof(UkiyoeEffect).GetProperty(name)!;
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
static Animation[] Animations(UkiyoeEffect effect)
=> [effect.Amount, effect.LineWidth, effect.Coherence, effect.LineDetail, effect.LineStrength, effect.Flatten, effect.Misregistration, effect.Baren, effect.Paper];
[Theory]
[InlineData(nameof(UkiyoeEffect.Amount), 100d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.LineWidth), 50d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.Coherence), 50d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.LineDetail), 50d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.LineStrength), 85d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.Flatten), 60d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.Misregistration), 30d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.Baren), 40d, 0d, 100d)]
[InlineData(nameof(UkiyoeEffect.Paper), 50d, 0d, 100d)]
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
{
var effect = new UkiyoeEffect();
var animation = (Animation)Property(name).GetValue(effect)!;
Assert.Equal(defaultValue, animation.DefaultValue);
Assert.Equal(minimum, animation.MinValue);
Assert.Equal(maximum, animation.MaxValue);
Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps));
}
[Fact]
public void DefaultParameterValuesMatchSpecification()
public void QualityLineColorPaletteLevelsAndSeedStartFromTheirDefaults()
{
var effect = new UkiyoeEffect();
Assert.Equal(100d, ValueAt(effect.Amount), 6);
Assert.Equal(50d, ValueAt(effect.LineWidth), 6);
Assert.Equal(50d, ValueAt(effect.Coherence), 6);
Assert.Equal(50d, ValueAt(effect.LineDetail), 6);
Assert.Equal(85d, ValueAt(effect.LineStrength), 6);
Assert.Equal(60d, ValueAt(effect.Flatten), 6);
Assert.Equal(30d, ValueAt(effect.Misregistration), 6);
Assert.Equal(40d, ValueAt(effect.Baren), 6);
Assert.Equal(50d, ValueAt(effect.Paper), 6);
Assert.Equal(UkiyoeQuality.High, effect.Quality);
Assert.Equal(DefaultLineColor, effect.LineColor);
Assert.Equal(6, effect.PaletteLevels);
Assert.Equal(0, effect.Seed);
Assert.Equal(System.Windows.Media.Color.FromArgb(255, 30, 26, 24), effect.LineColor);
}
[Theory]
[InlineData(int.MinValue, 2)]
[InlineData(0, 2)]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(6, 6)]
[InlineData(16, 16)]
[InlineData(17, 16)]
[InlineData(100, 16)]
[InlineData(int.MaxValue, 16)]
public void PaletteLevelsStayBetweenTwoAndSixteen(int value, int expected)
{
var effect = new UkiyoeEffect { PaletteLevels = 5 };
effect.PaletteLevels = value;
Assert.Equal(expected, effect.PaletteLevels);
Assert.False(effect.HasErrors);
}
[Theory]
@@ -53,702 +80,211 @@ public sealed class UkiyoeEffectTests
[InlineData(-1, 0)]
[InlineData(0, 0)]
[InlineData(1234, 1234)]
public void SeedClampsNegativeInputToZero(int input, int expected)
[InlineData(10000, 10000)]
[InlineData(int.MaxValue, int.MaxValue)]
public void SeedNeverDropsBelowZero(int value, int expected)
{
var effect = new UkiyoeEffect { Seed = input };
var effect = new UkiyoeEffect { Seed = 5 };
effect.Seed = value;
Assert.Equal(expected, effect.Seed);
}
[Theory]
[InlineData(int.MinValue, 2)]
[InlineData(0, 2)]
[InlineData(6, 6)]
[InlineData(100, 16)]
public void PaletteLevelsClampToAllowedRange(int input, int expected)
{
var effect = new UkiyoeEffect { PaletteLevels = input };
Assert.Equal(expected, effect.PaletteLevels);
Assert.False(effect.HasErrors);
}
[Fact]
public void CreateExoVideoFiltersReturnsEmpty()
public void ChangingQualityLineColorPaletteLevelsOrSeedNotifiesTheEditor()
{
var effect = new UkiyoeEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.Quality = UkiyoeQuality.Ultra;
effect.LineColor = Colors.Crimson;
effect.PaletteLevels = 9;
effect.Seed = 7;
Assert.Equal([nameof(UkiyoeEffect.Quality), nameof(UkiyoeEffect.LineColor), nameof(UkiyoeEffect.PaletteLevels), nameof(UkiyoeEffect.Seed)], changed);
}
[Fact]
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
{
var effect = new UkiyoeEffect { PaletteLevels = 16 };
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.Quality = UkiyoeQuality.High;
effect.LineColor = DefaultLineColor;
effect.PaletteLevels = 16;
effect.PaletteLevels = 100;
effect.Seed = 0;
effect.Seed = -1;
Assert.Empty(changed);
}
[Fact]
public void TheLabelIsTheLocalizedEffectName()
{
var effect = new UkiyoeEffect();
Assert.Empty(effect.CreateExoVideoFilters(0, null!));
Assert.Equal(Texts.Ukiyoe, effect.Label);
}
[Fact]
public void TheNineNumericParametersReceiveTheAnimationParameters()
{
var effect = new UkiyoeEffect();
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
}
[Theory]
[InlineData(UkiyoeQuality.Balanced, 1024, 2, 2, 24)]
[InlineData(UkiyoeQuality.High, 1440, 3, 2, 40)]
[InlineData(UkiyoeQuality.Ultra, 2048, 3, 3, 64)]
public void QualitySettingsMatchSpecification(UkiyoeQuality quality, int resolution, int etfIterations, int fdogIterations, int flattenIterations)
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
{
var settings = UkiyoeSettings.GetQuality(quality);
var effect = new UkiyoeEffect();
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(etfIterations, settings.EtfIterations);
Assert.Equal(fdogIterations, settings.FdogIterations);
Assert.Equal(flattenIterations, settings.FlattenIterations);
Assert.Equal(0, settings.FlattenIterations % 2);
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
}
[Fact]
public void TheEffectIsRegisteredForFilteringAndDecorationWithoutAviUtlSupport()
{
var attribute = typeof(UkiyoeEffect).GetCustomAttribute<VideoEffectAttribute>()!;
Assert.Equal(nameof(Texts.Ukiyoe), attribute.Name);
Assert.Equal([VideoEffectCategories.Filtering, VideoEffectCategories.Decoration], attribute.Categories);
Assert.Equal([nameof(Texts.TagWoodblock), nameof(Texts.TagPrint), nameof(Texts.TagJapanese)], attribute.Keywords);
Assert.False(attribute.IsAviUtlSupported);
Assert.True(attribute.IsEffectItemSupported);
Assert.Equal(typeof(Texts), attribute.ResourceType);
Assert.Equal(Texts.Ukiyoe, attribute.GetName());
}
[Theory]
[InlineData(1920, 1080, 1440)]
[InlineData(1080, 1920, 1440)]
[InlineData(8, 8, 1440)]
[InlineData(4096, 16, 1024)]
[InlineData(100, 100, 2048)]
public void GridSizeCoversCanvas(int width, int height, int resolution)
[InlineData(nameof(UkiyoeEffect.Amount), nameof(Texts.BasicGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
[InlineData(nameof(UkiyoeEffect.Quality), nameof(Texts.BasicGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 1)]
[InlineData(nameof(UkiyoeEffect.LineWidth), nameof(Texts.LineGroup), nameof(Texts.LineWidth), nameof(Texts.LineWidthDescription), 10)]
[InlineData(nameof(UkiyoeEffect.Coherence), nameof(Texts.LineGroup), nameof(Texts.Coherence), nameof(Texts.CoherenceDescription), 11)]
[InlineData(nameof(UkiyoeEffect.LineDetail), nameof(Texts.LineGroup), nameof(Texts.LineDetail), nameof(Texts.LineDetailDescription), 12)]
[InlineData(nameof(UkiyoeEffect.LineStrength), nameof(Texts.LineGroup), nameof(Texts.LineStrength), nameof(Texts.LineStrengthDescription), 13)]
[InlineData(nameof(UkiyoeEffect.LineColor), nameof(Texts.LineGroup), nameof(Texts.LineColor), nameof(Texts.LineColorDescription), 14)]
[InlineData(nameof(UkiyoeEffect.Flatten), nameof(Texts.ColorGroup), nameof(Texts.Flatten), nameof(Texts.FlattenDescription), 20)]
[InlineData(nameof(UkiyoeEffect.PaletteLevels), nameof(Texts.ColorGroup), nameof(Texts.PaletteLevels), nameof(Texts.PaletteLevelsDescription), 21)]
[InlineData(nameof(UkiyoeEffect.Misregistration), nameof(Texts.CraftGroup), nameof(Texts.Misregistration), nameof(Texts.MisregistrationDescription), 30)]
[InlineData(nameof(UkiyoeEffect.Baren), nameof(Texts.CraftGroup), nameof(Texts.Baren), nameof(Texts.BarenDescription), 31)]
[InlineData(nameof(UkiyoeEffect.Paper), nameof(Texts.CraftGroup), nameof(Texts.Paper), nameof(Texts.PaperDescription), 32)]
[InlineData(nameof(UkiyoeEffect.Seed), nameof(Texts.CraftGroup), nameof(Texts.Seed), nameof(Texts.SeedDescription), 33)]
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
{
var (gridWidth, gridHeight, cellSize) = UkiyoeSettings.GetGridSize(width, height, resolution);
var display = Attribute<DisplayAttribute>(property);
Assert.True(gridWidth >= UkiyoeSettings.MinimumGridSize);
Assert.True(gridHeight >= UkiyoeSettings.MinimumGridSize);
Assert.True(cellSize > 0f);
Assert.True(gridWidth * cellSize >= width);
Assert.True(gridHeight * cellSize >= height);
Assert.Equal(group, display.GroupName);
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(order, display.Order);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Theory]
[InlineData(nameof(UkiyoeEffect.Amount))]
[InlineData(nameof(UkiyoeEffect.LineWidth))]
[InlineData(nameof(UkiyoeEffect.Coherence))]
[InlineData(nameof(UkiyoeEffect.LineDetail))]
[InlineData(nameof(UkiyoeEffect.LineStrength))]
[InlineData(nameof(UkiyoeEffect.Flatten))]
[InlineData(nameof(UkiyoeEffect.Misregistration))]
[InlineData(nameof(UkiyoeEffect.Baren))]
[InlineData(nameof(UkiyoeEffect.Paper))]
public void AnimatedParametersAreEditedAsPercentagesWithAnimationSliders(string property)
{
var slider = Attribute<AnimationSliderAttribute>(property);
Assert.Equal("F1", slider.StringFormat);
Assert.Equal("%", slider.UnitText);
Assert.Equal(0d, slider.DefaultMin);
Assert.Equal(100d, slider.DefaultMax);
}
[Fact]
public void ParameterMappingsAreMonotonicAndBounded()
public void TheQualityIsChosenFromACombo()
{
Assert.Equal(UkiyoeSettings.MinimumLineSigmaPixels, UkiyoeSettings.GetLineSigmaPixels(0f), 5);
Assert.Equal(UkiyoeSettings.MaximumLineSigmaPixels, UkiyoeSettings.GetLineSigmaPixels(1f), 5);
Assert.Equal(UkiyoeSettings.MinimumLineSigmaPixels, UkiyoeSettings.GetLineSigmaPixels(-5f), 5);
Assert.Equal(UkiyoeSettings.MaximumLineSigmaPixels, UkiyoeSettings.GetLineSigmaPixels(5f), 5);
Assert.True(UkiyoeSettings.GetLineSigmaPixels(0.75f) > UkiyoeSettings.GetLineSigmaPixels(0.25f));
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(UkiyoeEffect.Quality)));
Assert.Equal([UkiyoeQuality.Balanced, UkiyoeQuality.High, UkiyoeQuality.Ultra], Enum.GetValues<UkiyoeQuality>());
}
Assert.Equal(UkiyoeSettings.MinimumFlowSigma, UkiyoeSettings.GetFlowSigma(0f), 5);
Assert.Equal(UkiyoeSettings.MaximumFlowSigma, UkiyoeSettings.GetFlowSigma(1f), 5);
Assert.True(UkiyoeSettings.GetFlowSigma(0.75f) > UkiyoeSettings.GetFlowSigma(0.25f));
[Theory]
[InlineData(UkiyoeQuality.Balanced, nameof(Texts.QualityBalanced), nameof(Texts.QualityBalancedDescription))]
[InlineData(UkiyoeQuality.High, nameof(Texts.QualityHigh), nameof(Texts.QualityHighDescription))]
[InlineData(UkiyoeQuality.Ultra, nameof(Texts.QualityUltra), nameof(Texts.QualityUltraDescription))]
public void EveryQualityIsDisplayedWithItsLocalizedName(UkiyoeQuality quality, string name, string description)
{
var display = typeof(UkiyoeQuality).GetField(quality.ToString())!.GetCustomAttribute<DisplayAttribute>()!;
Assert.Equal(UkiyoeSettings.MinimumLineThreshold, UkiyoeSettings.GetLineThreshold(0f), 5);
Assert.Equal(UkiyoeSettings.MinimumLineThreshold + UkiyoeSettings.LineThresholdRange, UkiyoeSettings.GetLineThreshold(1f), 5);
Assert.True(UkiyoeSettings.GetLineThreshold(0.75f) > UkiyoeSettings.GetLineThreshold(0.25f));
Assert.Equal(UkiyoeSettings.MaximumFlattenBeta, UkiyoeSettings.GetFlattenBeta(0f), 1);
Assert.True(UkiyoeSettings.GetFlattenBeta(1f) <= 1.001f);
Assert.True(UkiyoeSettings.GetFlattenBeta(0.25f) > UkiyoeSettings.GetFlattenBeta(0.75f));
Assert.Equal(0f, UkiyoeSettings.GetShiftPixels(0f), 6);
Assert.Equal(UkiyoeSettings.MaximumShiftPixels, UkiyoeSettings.GetShiftPixels(1f), 6);
Assert.Equal(0f, UkiyoeSettings.GetShiftPixels(-1f), 6);
Assert.Equal(UkiyoeSettings.MaximumShiftPixels, UkiyoeSettings.GetShiftPixels(2f), 6);
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Fact]
public void MarginCoversReachAndAlignsToFourPixels()
public void TheLineColorIsPickedWithAColorPicker()
{
var margin = UkiyoeSettings.GetMargin(10f, 3f, 6f, 2f);
Assert.Equal(0, margin % 4);
Assert.True(margin >= 10f + 2f * UkiyoeSettings.SurroundSigmaScale * 3f + 2f * 6f * 2f);
Assert.True(UkiyoeSettings.GetMargin(0f, 0.6f, 1f, 1f) < margin);
Assert.NotNull(Attribute<ColorPickerAttribute>(nameof(UkiyoeEffect.LineColor)));
}
[Fact]
public void TransparentInputYieldsTransparentOutput()
public void ThePaletteLevelsAreEditedWithoutAUnitFromTwoToSixteen()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var slider = Attribute<TextBoxSliderAttribute>(nameof(UkiyoeEffect.PaletteLevels));
var range = Attribute<RangeAttribute>(nameof(UkiyoeEffect.PaletteLevels));
const int width = 64;
const int height = 64;
var source = new int[width * height];
var destination = new int[source.Length];
Array.Fill(destination, -1);
var parameters = CreateParameters();
pipeline.Process(source, destination, width, height, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
Assert.Equal("F0", slider.StringFormat);
Assert.Equal(string.Empty, slider.UnitText);
Assert.Equal(2d, slider.DefaultMin);
Assert.Equal(16d, slider.DefaultMax);
Assert.Equal(2, range.Minimum);
Assert.Equal(16, range.Maximum);
Assert.Equal(6, Attribute<DefaultValueAttribute>(nameof(UkiyoeEffect.PaletteLevels)).Value);
}
[Fact]
public void OpaqueInputProducesOutput()
public void TheSeedIsEditedWithoutAUnitFromZero()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var slider = Attribute<TextBoxSliderAttribute>(nameof(UkiyoeEffect.Seed));
var range = Attribute<RangeAttribute>(nameof(UkiyoeEffect.Seed));
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 32, 32, 64, 64);
var destination = new int[source.Length];
var parameters = CreateParameters();
pipeline.Process(source, destination, width, height, in parameters);
Assert.True(CountLitPixels(destination) > 0);
Assert.Equal("F0", slider.StringFormat);
Assert.Equal(string.Empty, slider.UnitText);
Assert.Equal(0d, slider.DefaultMin);
Assert.Equal(10000d, slider.DefaultMax);
Assert.Equal(0, range.Minimum);
Assert.Equal(int.MaxValue, range.Maximum);
Assert.Equal(0, Attribute<DefaultValueAttribute>(nameof(UkiyoeEffect.Seed)).Value);
}
[Fact]
public void GpuPipelineIsDeterministic()
public void EverySettingSurvivesAProjectRoundTrip()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var effect = new UkiyoeEffect { Quality = UkiyoeQuality.Ultra, LineColor = Colors.Crimson, PaletteLevels = 9, Seed = 42 };
var values = new[] { 55d, 45d, 70d, 20d, 65d, 15d, 85d, 35d, 90d };
foreach (var (animation, value) in Animations(effect).Zip(values))
animation.Values[0].Value = value;
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 24, 24, 80, 80);
var first = new int[source.Length];
var second = new int[source.Length];
var parameters = CreateParameters(seed: 42);
var clone = Json.GetClone(effect)!;
pipeline.Process(source, first, width, height, in parameters);
pipeline.Process(source, second, width, height, in parameters);
Assert.Equal(first, second);
}
[Fact]
public void DifferentSeedsProduceDifferentPrints()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 24, 24, 80, 80);
var first = new int[source.Length];
var second = new int[source.Length];
var parametersA = CreateParameters(misregistration: 1f, seed: 1);
var parametersB = CreateParameters(misregistration: 1f, seed: 2);
pipeline.Process(source, first, width, height, in parametersA);
pipeline.Process(source, second, width, height, in parametersB);
Assert.NotEqual(first, second);
}
[Fact]
public void OutputAlphaStaysPremultipliedAndBounded()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 24, 24, 80, 80);
var destination = new int[source.Length];
var parameters = CreateParameters(paletteLevels: 2, misregistration: 1f, paper: 1f, baren: 1f, lineStrength: 1f);
pipeline.Process(source, destination, width, height, in parameters);
foreach (var pixel in destination)
{
var alpha = (pixel >> 24) & 255;
Assert.InRange((pixel >> 16) & 255, 0, alpha);
Assert.InRange((pixel >> 8) & 255, 0, alpha);
Assert.InRange(pixel & 255, 0, alpha);
}
}
[Fact]
public void FlattenReducesTexture()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 160;
const int height = 160;
var source = CreateNoisySource(width, height, 16, 16, 128, 128);
var weak = new int[source.Length];
var strong = new int[source.Length];
var weakParameters = CreateParameters(flatten: 0f, misregistration: 0f, baren: 0f, paper: 0f, lineStrength: 0f);
var strongParameters = CreateParameters(flatten: 1f, misregistration: 0f, baren: 0f, paper: 0f, lineStrength: 0f);
pipeline.Process(source, weak, width, height, in weakParameters);
pipeline.Process(source, strong, width, height, in strongParameters);
Assert.True(LumaVariance(strong, width, height, 32, 32, 96, 96) < LumaVariance(weak, width, height, 32, 32, 96, 96));
}
[Fact]
public void MisregistrationExpandsLitArea()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 32, 32, 64, 64);
var aligned = new int[source.Length];
var shifted = new int[source.Length];
var alignedParameters = CreateParameters(misregistration: 0f);
var shiftedParameters = CreateParameters(misregistration: 1f);
pipeline.Process(source, aligned, width, height, in alignedParameters);
pipeline.Process(source, shifted, width, height, in shiftedParameters);
Assert.True(CountLitPixels(shifted) > CountLitPixels(aligned));
}
[Fact]
public void LineStrengthDarkensKeyBlockPixels()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 40, 40, 48, 48);
var withLine = new int[source.Length];
var withoutLine = new int[source.Length];
var lineParameters = CreateParameters(misregistration: 0f, lineStrength: 1f);
var noLineParameters = CreateParameters(misregistration: 0f, lineStrength: 0f);
pipeline.Process(source, withLine, width, height, in lineParameters);
pipeline.Process(source, withoutLine, width, height, in noLineParameters);
Assert.NotEqual(withLine, withoutLine);
Assert.True(CountDarkPixels(withLine) > CountDarkPixels(withoutLine));
}
[Fact]
public void GpuPipelineDoesNotAllocateManagedMemoryAfterWarmup()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 64;
const int height = 64;
var source = CreateSquareSource(width, height, 24, 24, 16, 16);
var destination = new int[source.Length];
var parameters = CreateParameters();
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, width, height, in parameters);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(0, allocated);
}
[Fact]
public void SharedTexturePipelineMatchesPackedBufferPipeline()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 96;
const int height = 96;
var source = CreateGradientSource(width, height, 16, 16, 64, 64);
var expected = new int[source.Length];
var parameters = CreateParameters(seed: 11);
pipeline.Process(source, expected, width, height, in parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
var sourcePixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(sourcePixels);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, width, height, in parameters);
var result = new Bgra32[source.Length];
outputTexture.CopyTo(result);
for (var index = 0; index < expected.Length; index++)
Assert.Equal(unchecked((uint)expected[index]), result[index].PackedValue);
}
[Fact]
public void SubmittedSharedTexturePipelineAllocationsAmortizeToZero()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 64;
const int height = 64;
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
var parameters = CreateParameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, width, height, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
[Fact]
public void VisibleBoundsCoverAllLitPixelsAndMatchFullRender()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 192;
const int height = 192;
var source = CreateGradientSource(width, height, 64, 64, 64, 48);
var full = new int[source.Length];
var parameters = CreateParameters(seed: 5);
pipeline.Process(source, full, width, height, in parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
var sourcePixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(sourcePixels);
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect));
Assert.True(rect.Width > 0 && rect.Height > 0);
Assert.True(rect.X >= 0 && rect.Y >= 0);
Assert.True(rect.X + rect.Width <= width && rect.Y + rect.Height <= height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
if (full[y * width + x] == 0)
continue;
Assert.InRange(x, rect.X, rect.X + rect.Width - 1);
Assert.InRange(y, rect.Y, rect.Y + rect.Height - 1);
}
}
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(outputTexture, width, height, rect, in parameters);
var result = new Bgra32[rect.Width * rect.Height];
outputTexture.CopyTo(result);
for (var y = 0; y < rect.Height; y++)
{
for (var x = 0; x < rect.Width; x++)
{
var expected = unchecked((uint)full[(rect.Y + y) * width + rect.X + x]);
Assert.Equal(expected, result[y * rect.Width + x].PackedValue);
}
}
}
[Fact]
public void SimulateCachesStructureUntilInputsChange()
{
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 48, 48, 48, 48);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
var sourcePixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(sourcePixels);
var parameters = CreateParameters(seed: 3);
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
var seedChanged = parameters with { Seed = 4 };
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in seedChanged));
var paletteChanged = parameters with { PaletteLevels = 3 };
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in paletteChanged));
var misregistrationChanged = parameters with { Misregistration = 1f };
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in misregistrationChanged));
var flattenChanged = parameters with { Flatten = 0.9f };
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in flattenChanged));
var lineWidthChanged = flattenChanged with { LineWidth = 0.9f };
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in lineWidthChanged));
var movedSource = CreateGradientSource(width, height, 32, 32, 48, 48);
for (var index = 0; index < movedSource.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)movedSource[index]);
sourceTexture.CopyFrom(sourcePixels);
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in lineWidthChanged));
}
[Fact]
public void Direct2DInteropProducesPrintAfterGrowingFullHdOutput()
{
using var devices = new GraphicsDevices();
using var graphicsContext = devices.CreateContext();
using var provider = UkiyoeInteropProvider.TryCreate(graphicsContext, out var interopDevice);
if (provider is null || interopDevice is null)
{
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
return;
}
using var domain = interopDevice.RegisterExternalDomain(provider);
using var resourceSet = UkiyoeResourceSet.Create(interopDevice, domain);
using var pipeline = UkiyoePipeline.TryCreate(interopDevice);
Assert.NotNull(pipeline);
const int width = 96;
const int height = 96;
var pixels = CreateSquareSource(width, height, 32, 32, 32, 32);
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
using var inputBitmap = graphicsContext.DeviceContext.CreateBitmap(
new SizeI(width, height),
new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f,
96f,
BitmapOptions.None));
try
{
inputBitmap.CopyFromMemory(handle.AddrOfPinnedObject(), width * sizeof(int));
}
finally
{
handle.Free();
}
Assert.True(resourceSet.TryEnsureSource(width, height, out _));
var parameters = CreateParameters();
var renderContext = provider.RenderContext;
for (var iteration = 0; iteration < 2; iteration++)
{
using (var borrow = resourceSet.BeginSourceExternalOperation())
{
var previousTarget = renderContext.Target;
renderContext.Target = borrow.DangerousGetView().Bitmap;
renderContext.BeginDraw();
renderContext.Clear(null);
renderContext.DrawImage(
inputBitmap,
new System.Numerics.Vector2(0f, 0f),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
renderContext.EndDraw();
renderContext.Target = previousTarget;
}
pipeline!.Simulate(
resourceSet.GetSourceComputeBinding(), width, height, 0, 0, width, height, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out var visible));
Assert.True(resourceSet.TryEnsureOutput(
iteration == 0 ? width : 1920,
iteration == 0 ? height : 1080,
out _));
pipeline.RenderVisible(
resourceSet.GetOutputComputeBinding(), width, height, visible, in parameters);
if (iteration == 0)
{
using var retiredLease = resourceSet.AcquireOutputExternalViewLease();
Assert.Equal(width, retiredLease.Width);
Assert.Equal(height, retiredLease.Height);
}
}
using var outputLease = resourceSet.AcquireOutputExternalViewLease();
using var staging = graphicsContext.DeviceContext.CreateBitmap(
new SizeI(width, height),
new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f,
96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
staging.CopyFromBitmap(outputLease.DangerousGetView().Bitmap);
var mapped = staging.Map(MapOptions.Read);
try
{
var lit = 0;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var actual = Marshal.ReadInt32(mapped.Bits + (nint)(y * mapped.Pitch + x * sizeof(int)));
var alpha = (actual >> 24) & 255;
Assert.InRange((actual >> 16) & 255, 0, alpha);
Assert.InRange((actual >> 8) & 255, 0, alpha);
Assert.InRange(actual & 255, 0, alpha);
if (alpha > 0)
lit++;
}
}
Assert.True(lit > 0);
}
finally
{
staging.Unmap();
}
}
private static int[] CreateSquareSource(int width, int height, int left, int top, int squareWidth, int squareHeight)
{
var source = new int[width * height];
for (var y = top; y < top + squareHeight; y++)
{
for (var x = left; x < left + squareWidth; x++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
source[y * width + x] = unchecked((int)0xFFC0C0C0);
}
}
return source;
}
private static int[] CreateGradientSource(int width, int height, int left, int top, int regionWidth, int regionHeight)
{
var source = new int[width * height];
for (var y = top; y < top + regionHeight; y++)
{
for (var x = left; x < left + regionWidth; x++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
var vertical = (y - top) / (double)regionHeight;
var r = (int)(70 + 90 * vertical);
var g = (int)(110 + 60 * vertical);
var b = (int)(170 + 40 * vertical);
source[y * width + x] = unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
return source;
}
private static int[] CreateNoisySource(int width, int height, int left, int top, int regionWidth, int regionHeight)
{
var source = CreateGradientSource(width, height, left, top, regionWidth, regionHeight);
for (var y = top; y < top + regionHeight; y++)
{
for (var x = left; x < left + regionWidth; x++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
var hash = (uint)(x * 374761393 + y * 668265263);
hash = (hash ^ (hash >> 13)) * 1274126177u;
var noise = (int)((hash >> 24) & 63) - 32;
var pixel = source[y * width + x];
var r = Math.Clamp(((pixel >> 16) & 255) + noise, 0, 255);
var g = Math.Clamp(((pixel >> 8) & 255) + noise, 0, 255);
var b = Math.Clamp((pixel & 255) + noise, 0, 255);
source[y * width + x] = unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
return source;
}
private static int CountLitPixels(int[] pixels)
{
var count = 0;
foreach (var pixel in pixels)
{
if (((pixel >> 24) & 255) > 8)
count++;
}
return count;
}
private static int CountDarkPixels(int[] pixels)
{
var count = 0;
foreach (var pixel in pixels)
{
var alpha = (pixel >> 24) & 255;
if (alpha <= 8)
continue;
var luma = 0.299 * ((pixel >> 16) & 255) + 0.587 * ((pixel >> 8) & 255) + 0.114 * (pixel & 255);
if (luma < alpha * 0.35)
count++;
}
return count;
}
private static double LumaVariance(int[] pixels, int width, int height, int left, int top, int regionWidth, int regionHeight)
{
var sum = 0.0;
var squaredSum = 0.0;
var count = 0;
for (var y = top; y < top + regionHeight; y++)
{
for (var x = left; x < left + regionWidth; x++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
var pixel = pixels[y * width + x];
var luma = 0.299 * ((pixel >> 16) & 255) + 0.587 * ((pixel >> 8) & 255) + 0.114 * (pixel & 255);
sum += luma;
squaredSum += luma * luma;
count++;
}
}
if (count == 0)
return 0.0;
var mean = sum / count;
return squaredSum / count - mean * mean;
Assert.NotSame(effect, clone);
Assert.Equal(UkiyoeQuality.Ultra, clone.Quality);
Assert.Equal(Colors.Crimson, clone.LineColor);
Assert.Equal(9, clone.PaletteLevels);
Assert.Equal(42, clone.Seed);
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
}
}
+167
ファイルの表示
@@ -0,0 +1,167 @@
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
namespace Ukiyoe.Tests;
[Collection("Direct2D")]
public sealed class UkiyoeInteropTests
{
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static UkiyoePipeline.Parameters Parameters()
=> new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
static Func<int, int, Bgra> CenteredSquare(int size, int square)
{
var start = (size - square) / 2;
return (x, y) => x >= start && x < start + square && y >= start && y < start + square ? Gray : Bgra.Transparent;
}
sealed class Interop : IDisposable
{
readonly ComputeExternalQueueScheduler scheduler;
readonly UkiyoeInteropProvider provider;
readonly ComputeInteropDomain domain;
public UkiyoeResourceSet Resources { get; }
public UkiyoePipeline Pipeline { get; }
Interop(ComputeExternalQueueScheduler scheduler, UkiyoeInteropProvider provider, GraphicsDevice device)
{
this.scheduler = scheduler;
this.provider = provider;
domain = device.RegisterExternalDomain(provider);
Resources = UkiyoeResourceSet.Create(device, domain);
Pipeline = UkiyoePipeline.TryCreate(device)!;
}
public static Interop Create(IGraphicsDevicesAndContext devices)
{
var scheduler = ComputeExternalQueueScheduler.Create();
var provider = UkiyoeInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
{
scheduler.Dispose();
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
return new Interop(scheduler, provider, device);
}
public void Draw(ID2D1Image image)
{
var context = provider.RenderContext;
using var borrow = Resources.BeginSourceExternalOperation();
var previousTarget = context.Target;
using var target = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
context.Target = target;
context.BeginDraw();
context.Clear(null);
context.DrawImage(image, Vector2.Zero, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
context.EndDraw();
context.Target = previousTarget;
}
public Rendering CaptureOutput(IGraphicsDevicesAndContext devices, out int width, out int height)
{
using var lease = Resources.AcquireOutputExternalViewLease();
width = lease.Width;
height = lease.Height;
using var bitmap = new ID2D1Bitmap1(lease.DangerousGetView().AddRefBitmap());
return Rendering.Capture(devices, bitmap);
}
public void Dispose()
{
Pipeline.Dispose();
Resources.Dispose();
Resources.WaitForDisposal();
domain.Dispose();
domain.WaitForDisposal();
provider.Dispose();
scheduler.Dispose();
}
}
static int LitPixels(Rendering rendering, UkiyoePipeline.PixelRect visible)
{
var lit = 0;
for (var y = 0; y < visible.Height; y++)
{
for (var x = 0; x < visible.Width; x++)
{
var pixel = rendering[x, y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
if (pixel.Alpha > 0)
lit++;
}
}
return lit;
}
[Fact]
public void APrintIsDrawnAfterTheOutputGrowsToFullHd()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 96, 96, CenteredSquare(96, 32));
var parameters = Parameters();
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
UkiyoePipeline.PixelRect RenderInto(Func<UkiyoePipeline.PixelRect, (int Width, int Height)> outputSize)
{
interop.Draw(source.Bitmap);
interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 96, 96, 0, 0, 96, 96, in parameters);
Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible));
var (width, height) = outputSize(visible);
Assert.True(interop.Resources.TryEnsureOutput(width, height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), 96, 96, visible, in parameters);
return visible;
}
RenderInto(_ => (96, 96));
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
var second = RenderInto(_ => (1920, 1080));
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
Assert.Equal((96, 96), (firstWidth, firstHeight));
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
Assert.True(LitPixels(output, second) > 0);
}
[Fact]
public void APrintIsDrawnAfterTheSourceIsReplacedByALargerOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
var parameters = Parameters();
var previous = default(UkiyoePipeline.PixelRect);
var previousArea = 0;
foreach (var (size, square) in new[] { (96, 32), (128, 64) })
{
using var source = new SourceImage(context, size, size, CenteredSquare(size, square));
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
interop.Draw(source.Bitmap);
Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters));
Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible));
Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), size, size, visible, in parameters);
var output = interop.CaptureOutput(context, out var width, out var height);
Assert.True(sourceChanged);
Assert.True(visible.Width > previous.Width && visible.Height > previous.Height);
Assert.Equal((visible.Width, visible.Height), (width, height));
Assert.True(LitPixels(output, visible) > previousArea);
previous = visible;
previousArea = square * square;
}
}
}
+465
ファイルの表示
@@ -0,0 +1,465 @@
using ComputeWeave;
using ComputeWeave.Interop;
namespace Ukiyoe.Tests;
[Collection("Direct3D12")]
public sealed class UkiyoePipelineTests
{
const int Opaque = unchecked((int)0xFFC0C0C0);
static readonly bool Direct3D12IsAvailable = GraphicsDevice.EnumerateDevices().Any();
static UkiyoePipeline CreatePipeline()
{
if (!Direct3D12IsAvailable)
Assert.Skip("Direct3D 12 is unavailable.");
var pipeline = UkiyoePipeline.TryCreate();
Assert.NotNull(pipeline);
return pipeline;
}
static UkiyoePipeline.Parameters Parameters(
UkiyoeQuality quality = UkiyoeQuality.Balanced,
float lineWidth = 0.5f,
float coherence = 0.5f,
float lineDetail = 0.5f,
float flatten = 0.6f,
int paletteLevels = 6,
float misregistration = 0.3f,
float baren = 0.4f,
float paper = 0.5f,
float lineStrength = 0.85f,
int seed = 0)
=> new(quality, lineWidth, coherence, lineDetail, flatten, paletteLevels, misregistration, baren, paper, lineStrength, 0.12f, 0.1f, 0.09f, seed);
static int[] Square(int width, int height, int left, int top, int squareWidth, int squareHeight)
{
var pixels = new int[width * height];
for (var y = Math.Max(top, 0); y < Math.Min(top + squareHeight, height); y++)
{
for (var x = Math.Max(left, 0); x < Math.Min(left + squareWidth, width); x++)
pixels[y * width + x] = Opaque;
}
return pixels;
}
static int[] Gradient(int width, int height, int left, int top, int regionWidth, int regionHeight)
{
var pixels = new int[width * height];
for (var y = Math.Max(top, 0); y < Math.Min(top + regionHeight, height); y++)
{
var vertical = (y - top) / (double)regionHeight;
var red = (int)(70 + 90 * vertical);
var green = (int)(110 + 60 * vertical);
var blue = (int)(170 + 40 * vertical);
for (var x = Math.Max(left, 0); x < Math.Min(left + regionWidth, width); x++)
pixels[y * width + x] = unchecked((int)0xFF000000) | red << 16 | green << 8 | blue;
}
return pixels;
}
static int[] Noisy(int width, int height, int left, int top, int regionWidth, int regionHeight)
{
var pixels = Gradient(width, height, left, top, regionWidth, regionHeight);
for (var y = Math.Max(top, 0); y < Math.Min(top + regionHeight, height); y++)
{
for (var x = Math.Max(left, 0); x < Math.Min(left + regionWidth, width); x++)
{
var hash = (uint)(x * 374761393 + y * 668265263);
hash = (hash ^ (hash >> 13)) * 1274126177u;
var noise = (int)((hash >> 24) & 63) - 32;
var pixel = pixels[y * width + x];
var red = Math.Clamp(((pixel >> 16) & 255) + noise, 0, 255);
var green = Math.Clamp(((pixel >> 8) & 255) + noise, 0, 255);
var blue = Math.Clamp((pixel & 255) + noise, 0, 255);
pixels[y * width + x] = unchecked((int)0xFF000000) | red << 16 | green << 8 | blue;
}
}
return pixels;
}
static int Alpha(int pixel) => (pixel >> 24) & 255;
static double Luma(int pixel) => 0.299 * ((pixel >> 16) & 255) + 0.587 * ((pixel >> 8) & 255) + 0.114 * (pixel & 255);
static int LitPixels(int[] pixels) => pixels.Count(pixel => Alpha(pixel) > 8);
static int DarkPixels(int[] pixels) => pixels.Count(pixel => Alpha(pixel) > 8 && Luma(pixel) < Alpha(pixel) * 0.35);
static double LumaVariance(int[] pixels, int width, int left, int top, int regionWidth, int regionHeight)
{
var lumas = new List<double>();
for (var y = top; y < top + regionHeight; y++)
{
for (var x = left; x < left + regionWidth; x++)
lumas.Add(Luma(pixels[y * width + x]));
}
var mean = lumas.Average();
return lumas.Average(luma => luma * luma) - mean * mean;
}
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
static int[] Render(UkiyoePipeline pipeline, int[] source, int width, int height, UkiyoePipeline.Parameters parameters)
{
var destination = new int[source.Length];
pipeline.Process(source, destination, width, height, in parameters);
return destination;
}
static UkiyoePipeline.Parameters Changed(UkiyoePipeline.Parameters parameters, string setting)
=> setting switch
{
nameof(UkiyoePipeline.Parameters.Quality) => parameters with { Quality = UkiyoeQuality.High },
nameof(UkiyoePipeline.Parameters.LineWidth) => parameters with { LineWidth = 0.95f },
nameof(UkiyoePipeline.Parameters.Coherence) => parameters with { Coherence = 0.05f },
nameof(UkiyoePipeline.Parameters.LineDetail) => parameters with { LineDetail = 0.95f },
nameof(UkiyoePipeline.Parameters.Flatten) => parameters with { Flatten = 0.15f },
nameof(UkiyoePipeline.Parameters.PaletteLevels) => parameters with { PaletteLevels = 3 },
nameof(UkiyoePipeline.Parameters.Misregistration) => parameters with { Misregistration = 1f },
nameof(UkiyoePipeline.Parameters.Baren) => parameters with { Baren = 1f },
nameof(UkiyoePipeline.Parameters.Paper) => parameters with { Paper = 1f },
nameof(UkiyoePipeline.Parameters.LineStrength) => parameters with { LineStrength = 0.2f },
nameof(UkiyoePipeline.Parameters.LineColorR) => parameters with { LineColorR = 0.8f },
nameof(UkiyoePipeline.Parameters.LineColorG) => parameters with { LineColorG = 0.8f },
nameof(UkiyoePipeline.Parameters.LineColorB) => parameters with { LineColorB = 0.8f },
nameof(UkiyoePipeline.Parameters.Seed) => parameters with { Seed = 4 },
_ => throw new ArgumentOutOfRangeException(nameof(setting), setting, null),
};
static ReadWriteTexture2D<Bgra32, Float4> Uploaded(int[] pixels)
{
var texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(texture, pixels);
return texture;
}
[Fact]
public void ATransparentSourceStaysTransparent()
{
using var pipeline = CreatePipeline();
var destination = Enumerable.Repeat(-1, 64 * 64).ToArray();
var parameters = Parameters();
pipeline.Process(new int[64 * 64], destination, 64, 64, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void AnOpaqueSourceProducesAPrint()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Square(128, 128, 32, 32, 64, 64), 128, 128, Parameters());
Assert.True(LitPixels(rendering) > 0);
}
[Fact]
public void TheSameSettingsAlwaysProduceTheSamePrint()
{
using var pipeline = CreatePipeline();
var source = Gradient(128, 128, 24, 24, 80, 80);
var first = Render(pipeline, source, 128, 128, Parameters(seed: 42));
var second = Render(pipeline, source, 128, 128, Parameters(seed: 42));
Assert.Equal(first, second);
}
[Fact]
public void ADifferentSeedPrintsDifferently()
{
using var pipeline = CreatePipeline();
var source = Gradient(128, 128, 24, 24, 80, 80);
var first = Render(pipeline, source, 128, 128, Parameters(misregistration: 1f, seed: 1));
var second = Render(pipeline, source, 128, 128, Parameters(misregistration: 1f, seed: 2));
Assert.NotEqual(first, second);
}
[Fact]
public void ThePrintStaysPremultiplied()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Gradient(128, 128, 24, 24, 80, 80), 128, 128, Parameters(paletteLevels: 2, misregistration: 1f, paper: 1f, baren: 1f, lineStrength: 1f));
Assert.All(rendering, pixel =>
{
Assert.InRange((pixel >> 16) & 255, 0, Alpha(pixel));
Assert.InRange((pixel >> 8) & 255, 0, Alpha(pixel));
Assert.InRange(pixel & 255, 0, Alpha(pixel));
});
}
[Fact]
public void FlatteningEvensOutTheTexture()
{
using var pipeline = CreatePipeline();
var source = Noisy(160, 160, 16, 16, 128, 128);
var weak = Render(pipeline, source, 160, 160, Parameters(flatten: 0f, misregistration: 0f, baren: 0f, paper: 0f, lineStrength: 0f));
var strong = Render(pipeline, source, 160, 160, Parameters(flatten: 1f, misregistration: 0f, baren: 0f, paper: 0f, lineStrength: 0f));
Assert.True(LumaVariance(strong, 160, 32, 32, 96, 96) < LumaVariance(weak, 160, 32, 32, 96, 96));
}
[Fact]
public void MisregistrationSpreadsThePrintOverMorePixels()
{
using var pipeline = CreatePipeline();
var source = Gradient(128, 128, 32, 32, 64, 64);
var aligned = Render(pipeline, source, 128, 128, Parameters(misregistration: 0f));
var shifted = Render(pipeline, source, 128, 128, Parameters(misregistration: 1f));
Assert.True(LitPixels(shifted) > LitPixels(aligned));
}
[Fact]
public void TheKeyBlockLinesDarkenThePrint()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 40, 40, 48, 48);
var withLines = Render(pipeline, source, 128, 128, Parameters(misregistration: 0f, lineStrength: 1f));
var withoutLines = Render(pipeline, source, 128, 128, Parameters(misregistration: 0f, lineStrength: 0f));
Assert.NotEqual(withLines, withoutLines);
Assert.True(DarkPixels(withLines) > DarkPixels(withoutLines));
}
[Fact]
public void APipelineWhoseGridWasReclaimedDrawsLikeAFreshOne()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var source = Gradient(64, 64, 8, 8, 48, 48);
var parameters = Parameters();
Render(pipeline, source, 64, 64, parameters);
GraphicsDevice.GetDefault().TrimMemory();
var reused = Render(pipeline, source, 64, 64, parameters);
var expected = Render(fresh, source, 64, 64, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void AReclaimedGridIsSimulatedAgain()
{
using var pipeline = CreatePipeline();
var parameters = Parameters();
var device = GraphicsDevice.GetDefault();
using var texture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(64, 64);
Upload(texture, Gradient(64, 64, 8, 8, 48, 48));
var first = pipeline.Simulate(texture, 64, 64, 0, 0, 64, 64, in parameters);
var repeated = pipeline.Simulate(texture, 64, 64, 0, 0, 64, 64, in parameters);
device.TrimMemory();
var reclaimed = pipeline.Simulate(texture, 64, 64, 0, 0, 64, 64, in parameters);
Assert.True(first);
Assert.False(repeated);
Assert.True(reclaimed);
}
[Fact]
public void AWarmPipelineAllocatesNoManagedMemory()
{
using var pipeline = CreatePipeline();
var source = Square(64, 64, 24, 24, 16, 16);
var destination = new int[source.Length];
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
Assert.Equal(0, minimum);
}
[Fact]
public void SharedTexturesProduceTheSamePrintAsPackedBuffers()
{
using var pipeline = CreatePipeline();
var source = Gradient(96, 96, 16, 16, 64, 64);
var parameters = Parameters(seed: 11);
var expected = Render(pipeline, source, 96, 96, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
Upload(sourceTexture, source);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 96, 96, in parameters);
var result = new Bgra32[source.Length];
outputTexture.CopyTo(result);
Assert.Equal(expected.Select(pixel => unchecked((uint)pixel)), result.Select(pixel => pixel.PackedValue));
}
[Fact]
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
pipeline.WaitForCompletion();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
[Fact]
public void TheVisibleBoundsHoldEveryLitPixelAndRenderTheSamePrint()
{
using var pipeline = CreatePipeline();
var source = Gradient(192, 192, 64, 64, 64, 48);
var parameters = Parameters(seed: 5);
var full = Render(pipeline, source, 192, 192, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(192, 192);
Upload(sourceTexture, source);
pipeline.Simulate(sourceTexture, 192, 192, 0, 0, 192, 192, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(192, 192, in parameters, out var rect));
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(outputTexture, 192, 192, rect, in parameters);
var visible = new Bgra32[rect.Width * rect.Height];
outputTexture.CopyTo(visible);
Assert.True(rect is { Width: > 0, Height: > 0, X: >= 0, Y: >= 0 });
Assert.True(rect.X + rect.Width <= 192 && rect.Y + rect.Height <= 192);
for (var y = 0; y < 192; y++)
{
for (var x = 0; x < 192; x++)
{
var inside = x >= rect.X && x < rect.X + rect.Width && y >= rect.Y && y < rect.Y + rect.Height;
if (!inside)
Assert.Equal(0, full[y * 192 + x]);
else
Assert.Equal(unchecked((uint)full[y * 192 + x]), visible[(y - rect.Y) * rect.Width + x - rect.X].PackedValue);
}
}
}
[Theory]
[InlineData(nameof(UkiyoePipeline.Parameters.Flatten))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineWidth))]
[InlineData(nameof(UkiyoePipeline.Parameters.Coherence))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineDetail))]
public void APartialRecomputeDrawsLikeAFullRecompute(string setting)
{
using var incremental = CreatePipeline();
using var reference = CreatePipeline();
using var source = Uploaded(Gradient(128, 128, 40, 40, 48, 48));
var device = GraphicsDevice.GetDefault();
var first = Parameters(seed: 7);
var second = Changed(first, setting);
incremental.Simulate(source, 128, 128, 0, 0, 128, 128, in first);
Assert.True(incremental.Simulate(source, 128, 128, 0, 0, 128, 128, in second));
reference.Simulate(source, 128, 128, 0, 0, 128, 128, in second);
Assert.True(incremental.TryGetVisibleBounds(128, 128, in second, out var rect));
Assert.True(reference.TryGetVisibleBounds(128, 128, in second, out var referenceRect));
Assert.Equal(referenceRect, rect);
using var incrementalOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
using var referenceOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
incremental.RenderVisible(incrementalOutput, 128, 128, rect, in second);
reference.RenderVisible(referenceOutput, 128, 128, rect, in second);
var incrementalPixels = new Bgra32[rect.Width * rect.Height];
var referencePixels = new Bgra32[rect.Width * rect.Height];
incrementalOutput.CopyTo(incrementalPixels);
referenceOutput.CopyTo(referencePixels);
Assert.Equal(referencePixels.Select(pixel => pixel.PackedValue), incrementalPixels.Select(pixel => pixel.PackedValue));
}
[Theory]
[InlineData(nameof(UkiyoePipeline.Parameters.PaletteLevels))]
[InlineData(nameof(UkiyoePipeline.Parameters.Misregistration))]
[InlineData(nameof(UkiyoePipeline.Parameters.Baren))]
[InlineData(nameof(UkiyoePipeline.Parameters.Paper))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineStrength))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineColorR))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineColorG))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineColorB))]
[InlineData(nameof(UkiyoePipeline.Parameters.Seed))]
public void ChangingOnlyThePrintingKeepsTheStructure(string setting)
{
using var pipeline = CreatePipeline();
using var source = Uploaded(Gradient(128, 128, 48, 48, 48, 48));
var parameters = Parameters(seed: 3);
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
var changed = Changed(parameters, setting);
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in changed), setting);
}
[Theory]
[InlineData(nameof(UkiyoePipeline.Parameters.Quality))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineWidth))]
[InlineData(nameof(UkiyoePipeline.Parameters.Coherence))]
[InlineData(nameof(UkiyoePipeline.Parameters.LineDetail))]
[InlineData(nameof(UkiyoePipeline.Parameters.Flatten))]
public void ChangingTheStructureSettingsComputesTheStructureAgain(string setting)
{
using var pipeline = CreatePipeline();
using var source = Uploaded(Gradient(128, 128, 48, 48, 48, 48));
var parameters = Parameters(seed: 3);
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
var changed = Changed(parameters, setting);
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in changed), setting);
}
[Fact]
public void MovingTheShapeComputesTheStructureAgain()
{
using var pipeline = CreatePipeline();
using var source = Uploaded(Gradient(128, 128, 48, 48, 48, 48));
var parameters = Parameters(seed: 3);
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
Upload(source, Gradient(128, 128, 32, 32, 48, 48));
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
}
}
+122
ファイルの表示
@@ -0,0 +1,122 @@
namespace Ukiyoe.Tests;
public sealed class UkiyoeSettingsTests
{
[Theory]
[InlineData(UkiyoeQuality.Balanced, 1024, 2, 2, 24)]
[InlineData(UkiyoeQuality.High, 1440, 3, 2, 40)]
[InlineData(UkiyoeQuality.Ultra, 2048, 3, 3, 64)]
public void EveryQualityChoosesItsGridResolutionAndIterations(UkiyoeQuality quality, int resolution, int etfIterations, int fdogIterations, int flattenIterations)
{
var settings = UkiyoeSettings.GetQuality(quality);
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(etfIterations, settings.EtfIterations);
Assert.Equal(fdogIterations, settings.FdogIterations);
Assert.Equal(flattenIterations, settings.FlattenIterations);
}
[Fact]
public void EveryQualityFlattensAnEvenNumberOfTimes()
{
foreach (var quality in Enum.GetValues<UkiyoeQuality>())
Assert.Equal(0, UkiyoeSettings.GetQuality(quality).FlattenIterations % 2);
}
[Theory]
[InlineData(1920, 1080, 1440)]
[InlineData(1080, 1920, 1440)]
[InlineData(8, 8, 1440)]
[InlineData(4096, 16, 1024)]
[InlineData(100, 100, 2048)]
public void TheGridCoversTheWholeCanvas(int width, int height, int resolution)
{
var (gridWidth, gridHeight, cellSize) = UkiyoeSettings.GetGridSize(width, height, resolution);
Assert.True(gridWidth >= UkiyoeSettings.MinimumGridSize);
Assert.True(gridHeight >= UkiyoeSettings.MinimumGridSize);
Assert.True(cellSize > 0f);
Assert.True(gridWidth * cellSize >= width);
Assert.True(gridHeight * cellSize >= height);
}
[Theory]
[InlineData(1920, 1080, 1440, 1440)]
[InlineData(1080, 1920, 1440, 1440)]
[InlineData(8, 8, 1440, 8)]
[InlineData(4096, 16, 1024, 1024)]
[InlineData(100, 100, 2048, 100)]
public void TheLongSideIsSplitIntoTheResolutionOrIntoSinglePixels(int width, int height, int resolution, int cells)
{
var (gridWidth, gridHeight, _) = UkiyoeSettings.GetGridSize(width, height, resolution);
Assert.InRange(Math.Max(gridWidth, gridHeight), cells + 1, cells + 2);
}
[Theory]
[InlineData(-5f, UkiyoeSettings.MinimumLineSigmaPixels)]
[InlineData(0f, UkiyoeSettings.MinimumLineSigmaPixels)]
[InlineData(1f, UkiyoeSettings.MaximumLineSigmaPixels)]
[InlineData(5f, UkiyoeSettings.MaximumLineSigmaPixels)]
public void TheLineSigmaStaysWithinItsRange(float lineWidth, float expected)
=> Assert.Equal(expected, UkiyoeSettings.GetLineSigmaPixels(lineWidth), 5);
[Fact]
public void AWiderLineUsesALargerSigma()
=> Assert.True(UkiyoeSettings.GetLineSigmaPixels(0.75f) > UkiyoeSettings.GetLineSigmaPixels(0.25f));
[Theory]
[InlineData(-1f, UkiyoeSettings.MinimumFlowSigma)]
[InlineData(0f, UkiyoeSettings.MinimumFlowSigma)]
[InlineData(1f, UkiyoeSettings.MaximumFlowSigma)]
[InlineData(2f, UkiyoeSettings.MaximumFlowSigma)]
public void TheFlowSigmaStaysWithinItsRange(float coherence, float expected)
=> Assert.Equal(expected, UkiyoeSettings.GetFlowSigma(coherence), 5);
[Fact]
public void MoreCoherenceFollowsTheFlowFurther()
=> Assert.True(UkiyoeSettings.GetFlowSigma(0.75f) > UkiyoeSettings.GetFlowSigma(0.25f));
[Theory]
[InlineData(-1f, UkiyoeSettings.MinimumLineThreshold)]
[InlineData(0f, UkiyoeSettings.MinimumLineThreshold)]
[InlineData(1f, UkiyoeSettings.MinimumLineThreshold + UkiyoeSettings.LineThresholdRange)]
[InlineData(2f, UkiyoeSettings.MinimumLineThreshold + UkiyoeSettings.LineThresholdRange)]
public void TheLineThresholdStaysWithinItsRange(float lineDetail, float expected)
=> Assert.Equal(expected, UkiyoeSettings.GetLineThreshold(lineDetail), 5);
[Fact]
public void MoreLineDetailRaisesTheThreshold()
=> Assert.True(UkiyoeSettings.GetLineThreshold(0.75f) > UkiyoeSettings.GetLineThreshold(0.25f));
[Theory]
[InlineData(-1f, UkiyoeSettings.MaximumFlattenBeta)]
[InlineData(0f, UkiyoeSettings.MaximumFlattenBeta)]
[InlineData(1f, 1f)]
[InlineData(2f, 1f)]
public void TheFidelityToTheOriginalFallsFromItsMaximumToOne(float flatten, float expected)
=> Assert.Equal(expected, UkiyoeSettings.GetFlattenBeta(flatten), 4);
[Fact]
public void MoreFlatteningHoldsLessToTheOriginal()
=> Assert.True(UkiyoeSettings.GetFlattenBeta(0.25f) > UkiyoeSettings.GetFlattenBeta(0.75f));
[Theory]
[InlineData(-1f, 0f)]
[InlineData(0f, 0f)]
[InlineData(1f, UkiyoeSettings.MaximumShiftPixels)]
[InlineData(2f, UkiyoeSettings.MaximumShiftPixels)]
public void TheMisregistrationShiftStaysWithinItsRange(float misregistration, float expected)
=> Assert.Equal(expected, UkiyoeSettings.GetShiftPixels(misregistration), 6);
[Fact]
public void MoreMisregistrationShiftsTheBlocksFurther()
=> Assert.True(UkiyoeSettings.GetShiftPixels(0.75f) > UkiyoeSettings.GetShiftPixels(0.25f));
[Theory]
[InlineData(10f, 3f, 6f, 2f, 52)]
[InlineData(0f, 0.6f, 1f, 1f, 12)]
[InlineData(1f, 0f, 0f, 1f, 12)]
public void TheMarginCoversTheShiftAndTheLineReachOnAFourPixelGrid(float shiftPixels, float lineSigmaPixels, float flowSigma, float cellSize, int expected)
=> Assert.Equal(expected, UkiyoeSettings.GetMargin(shiftPixels, lineSigmaPixels, flowSigma, cellSize));
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
{
"stryker-config": {
"project": "Ukiyoe.csproj",
"test-runner": "mtp",
"coverage-analysis": "off",
"concurrency": 4,
"additional-timeout": 30000,
"mutate": [
"**/*.cs",
"!**/YMM4-GitHubUpdateNotifier/**",
"!**/YMM4-Telemetry/**",
"!**/UkiyoeTelemetry.cs",
"!**/UkiyoeUpdateNotifier.cs"
],
"reporters": [
"progress",
"cleartext",
"html"
],
"thresholds": {
"high": 80,
"low": 60,
"break": 60
}
}
}
+14
ファイルの表示
@@ -3,10 +3,24 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
<File Path=".gitattributes" />
<File Path=".gitignore" />
<File Path=".gitmodules" />
<File Path="Directory.Build.props" />
<File Path="LICENSE.txt" />
<File Path="README.md" />
</Folder>
<Project Path="Ukiyoe/Ukiyoe.csproj">
<Platform Solution="*|x64" Project="x64" />
<BuildDependency Project="Ukiyoe.Shader/Ukiyoe.Shader.vcxproj" />
</Project>
<Project Path="Ukiyoe.Tests/Ukiyoe.Tests.csproj" />
<Project Path="Ukiyoe.Harness/Ukiyoe.Harness.csproj" />
<Project Path="Ukiyoe.Shader/Ukiyoe.Shader.vcxproj">
<BuildType Solution="*|*" Project="Release" />
<Platform Solution="*|*" Project="Win32" />
</Project>
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
</Solution>
+1 -1
ファイルの表示
@@ -2,5 +2,5 @@ namespace Ukiyoe;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/Ukiyoe;component/Shaders/{shaderName}.cso", UriKind.Absolute);
public static Uri Get(string shaderName) => new($"pack://application:,,,/Ukiyoe;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
}
+4 -6
ファイルの表示
@@ -1,10 +1,8 @@
using YukkuriMovieMaker.Generator;
namespace Ukiyoe
{
[AutoGenLocalizer]
partial class Texts
{
namespace Ukiyoe;
}
[AutoGenLocalizer]
partial class Texts
{
}
+6 -22
ファイルの表示
@@ -5,32 +5,18 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.1.1</Version>
<Version>1.2.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<ShaderDirPath>..\Release\</ShaderDirPath>
</PropertyGroup>
<ItemGroup>
<HlslShader Include="Shaders\**\*.hlsl" />
<Resource Include="@(HlslShader->'%(RelativeDir)%(Filename).cso')" />
<Resource Include="$(ShaderDirPath)Ukiyoe.cso" Link="Resources\Shader\Ukiyoe.cso" />
</ItemGroup>
<ItemDefinitionGroup>
<HlslShader>
<ShaderType>ps_5_0</ShaderType>
<EntryPoint>main</EntryPoint>
<ObjectFileOutput>%(RelativeDir)%(Filename).cso</ObjectFileOutput>
</HlslShader>
</ItemDefinitionGroup>
<Target Name="CompileHLSLShaders" BeforeTargets="BeforeBuild" Inputs="@(HlslShader)" Outputs="@(HlslShader->'%(ObjectFileOutput)')">
<Message Text="Compiling HLSL Shader: %(HlslShader.Identity) [Type: %(HlslShader.ShaderType), Entry: %(HlslShader.EntryPoint)]" Importance="high" />
<Error Text="fxc.exe not found at path: $(FxcPath)" Condition="!Exists('$(FxcPath)') AND '$(FxcPath)' != 'fxc.exe'" />
<Exec Command="&quot;$(FxcPath)&quot; /nologo /T %(HlslShader.ShaderType) /E %(HlslShader.EntryPoint) /Fo &quot;%(HlslShader.ObjectFileOutput)&quot; &quot;%(HlslShader.FullPath)&quot;" Condition="Exists('%(HlslShader.FullPath)')" />
</Target>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
@@ -82,8 +68,10 @@
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
</ItemGroup>
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
<ItemGroup>
<PackageReference Include="ComputeWeave" Version="1.4.1" />
<PackageReference Include="ComputeWeave" Version="2.6.0" />
<PackageReference Include="ILRepack" Version="2.0.46" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.142" />
</ItemGroup>
@@ -102,10 +90,6 @@
<AdditionalFiles Include="**/*.csv" />
</ItemGroup>
<ItemGroup>
<Folder Include="Shaders\" />
</ItemGroup>
<Target Name="MergePluginAssembly" AfterTargets="PostBuildEvent" Inputs="$(TargetPath);$(TargetDir)ComputeWeave.dll;$(TargetDir)ComputeWeave.Core.dll" Outputs="$(TargetDir)plugin\$(TargetFileName)">
<MakeDir Directories="$(TargetDir)plugin" />
<Exec Command="&quot;$(PkgILRepack)\tools\ILRepack.exe&quot; /out:&quot;$(TargetDir)plugin\$(TargetFileName)&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))&quot; /internalize &quot;$(TargetPath)&quot; &quot;$(TargetDir)ComputeWeave.dll&quot; &quot;$(TargetDir)ComputeWeave.Core.dll&quot;" />
+12 -1
ファイルの表示
@@ -33,7 +33,18 @@ internal sealed class UkiyoeCustomEffect(IGraphicsDevicesAndContext devices)
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(_cb);
if (drawInformation is null)
return;
try
{
drawInformation.SetPixelShaderConstantBuffer(_cb);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
public override void MapInputRectsToOutputRect(
+12 -1
ファイルの表示
@@ -16,6 +16,7 @@ public sealed class UkiyoeEffect : VideoEffectBase
public UkiyoeEffect()
{
UkiyoeTelemetry.EnsureStartedOnce();
UkiyoeUpdateNotifier.EnsureCheckedOnce();
}
@@ -96,7 +97,17 @@ public sealed class UkiyoeEffect : VideoEffectBase
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new UkiyoeEffectProcessor(devices, this);
{
try
{
return new UkiyoeEffectProcessor(devices, this);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, LineWidth, Coherence, LineDetail, LineStrength, Flatten, Misregistration, Baren, Paper];
+56 -22
ファイルの表示
@@ -1,3 +1,4 @@
using System.ComponentModel;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
@@ -12,12 +13,11 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly UkiyoeEffect _item;
private ComputeExternalQueueScheduler? _scheduler;
private UkiyoeInteropProvider? _interopProvider;
private ComputeInteropDomain? _interopDomain;
private UkiyoeResourceSet? _resourceSet;
private ExternalTextureLease<UkiyoeExternalView>? _outputLease;
private int _sourceWidth;
private int _sourceHeight;
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
private UkiyoePipeline? _pipeline;
private UkiyoeCustomEffect? _effect;
private Crop? _outputCrop;
@@ -42,6 +42,19 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
}
public override DrawDescription Update(EffectDescription effectDescription)
{
try
{
return UpdateCore(effectDescription);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
private DrawDescription UpdateCore(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null)
return effectDescription.DrawDescription;
@@ -92,9 +105,9 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
var quality = UkiyoeSettings.GetQuality(parameters.Quality);
var cellEstimate = (float)Math.Max((longSide + 128d) / quality.GridResolution, 1d);
var margin = UkiyoeSettings.GetMargin(
UkiyoeSettings.GetShiftPixels(Math.Clamp(parameters.Misregistration, 0f, 1f)),
UkiyoeSettings.GetLineSigmaPixels(Math.Clamp(parameters.LineWidth, 0f, 1f)),
UkiyoeSettings.GetFlowSigma(Math.Clamp(parameters.Coherence, 0f, 1f)),
UkiyoeSettings.MaximumShiftPixels,
UkiyoeSettings.MaximumLineSigmaPixels,
UkiyoeSettings.MaximumFlowSigma,
cellEstimate);
if (marginLimit < margin)
{
@@ -197,7 +210,8 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
if (outputChanged || !_hasOutput)
{
_outputCrop.SetInput(0, _outputLease.DangerousGetView().Bitmap, true);
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
_outputCrop.SetInput(0, outputBitmap, true);
_effect.SetInput(1, _outputTransformOutput, true);
}
var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height);
@@ -222,17 +236,7 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
private bool EnsureSource(int width, int height)
{
if (_sourceWidth == width && _sourceHeight == height)
return true;
_sourceWidth = 0;
_sourceHeight = 0;
if (!_resourceSet!.TryEnsureSource(width, height, out _))
return false;
_sourceWidth = width;
_sourceHeight = height;
return true;
return _resourceSet!.TryEnsureSource(width, height, out _);
}
private bool OutputCovers(int width, int height)
@@ -256,7 +260,8 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
var renderContext = _interopProvider!.RenderContext;
using var borrow = _resourceSet!.BeginSourceExternalOperation();
var previousTarget = renderContext.Target;
renderContext.Target = borrow.DangerousGetView().Bitmap;
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
renderContext.Target = sourceBitmap;
renderContext.BeginDraw();
renderContext.Clear(null);
renderContext.DrawImage(
@@ -283,15 +288,21 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
_interopDomain = null;
_interopProvider?.Dispose();
_interopProvider = null;
_sourceWidth = 0;
_sourceHeight = 0;
_scheduler?.Dispose();
_scheduler = null;
}
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
var interopProvider = UkiyoeInteropProvider.TryCreate(devices, out var interopDevice);
var scheduler = ComputeExternalQueueScheduler.Create();
var interopProvider = UkiyoeInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
if (interopProvider is null || interopDevice is null)
{
scheduler.Dispose();
return null;
}
_scheduler = scheduler;
try
{
@@ -300,6 +311,11 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
_resourceSet = UkiyoeResourceSet.Create(interopDevice, _interopDomain);
_pipeline = UkiyoePipeline.TryCreate(interopDevice);
}
catch (Win32Exception)
{
ReleaseInterop();
return null;
}
catch
{
ReleaseInterop();
@@ -363,6 +379,19 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
}
protected override void setInput(ID2D1Image? inputImage)
{
try
{
SetInputCore(inputImage);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
private void SetInputCore(ID2D1Image? inputImage)
{
_effect?.SetInput(0, inputImage, true);
if (!_hasOutput)
@@ -391,6 +420,11 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
ReleaseInterop();
}
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
finally
{
base.Dispose(disposing);
+49 -171
ファイルの表示
@@ -1,190 +1,68 @@
using System.Threading;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct3D11;
using Vortice.DXGI;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
namespace Ukiyoe;
internal sealed class UkiyoeQueueScheduler : ComputeExternalQueueScheduler
internal sealed class UkiyoeInteropProvider : ComputeExternalDirect3D11Provider
{
private int _entered;
private readonly ID2D1DeviceContext6 _renderContext;
protected override void EnterCore()
private UkiyoeInteropProvider(
ID3D11Device1 device,
ID3D11DeviceContext4 context,
ID2D1DeviceContext6 renderContext,
ComputeExternalQueueScheduler scheduler)
: base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler)
{
if (Interlocked.CompareExchange(ref _entered, 1, 0) != 0)
throw new InvalidOperationException();
_renderContext = renderContext;
}
protected override void ExitCore()
public ID2D1DeviceContext6 RenderContext => _renderContext;
public static UkiyoeInteropProvider? TryCreate(
IGraphicsDevicesAndContext devices,
ComputeExternalQueueScheduler scheduler,
out GraphicsDevice? graphicsDevice)
{
if (Interlocked.Exchange(ref _entered, 0) != 1)
throw new InvalidOperationException();
ArgumentNullException.ThrowIfNull(scheduler);
graphicsDevice = null;
ID3D11Device1? device = null;
ID3D11DeviceContext4? context = null;
ID2D1DeviceContext6? renderContext = null;
try
{
if (!GraphicsDevice.TryGetDevice(new ExternalAdapterIdentity(devices.DXGI.Adapter.Description.Luid), out graphicsDevice))
return null;
device = devices.D3D.Device.QueryInterface<ID3D11Device1>();
context = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
var provider = new UkiyoeInteropProvider(device, context, renderContext, scheduler);
renderContext = null;
return provider;
}
catch
{
graphicsDevice = null;
return null;
}
finally
{
// 基底は自身の参照を取得済みなので、ここで取得した参照は返す。
// renderContext は成功時に provider が引き取るため null にしてある。
renderContext?.Dispose();
context?.Dispose();
device?.Dispose();
}
}
protected override void DisposeCore()
{
}
}
internal sealed class UkiyoeExternalView(ID3D11Texture2D texture, ID2D1Bitmap1 bitmap) : IDisposable
{
private readonly ID3D11Texture2D _texture = texture;
private readonly ID2D1Bitmap1 _bitmap = bitmap;
public ID2D1Bitmap1 Bitmap => _bitmap;
public void Dispose()
{
_bitmap.Dispose();
_texture.Dispose();
}
}
internal sealed class UkiyoeInteropProvider : IComputeExternalInteropProvider<UkiyoeExternalView>
{
private readonly ID3D11Device1 _device;
private readonly ID3D11Device5 _device5;
private readonly ID3D11DeviceContext4 _context;
private readonly ID2D1DeviceContext6 _renderContext;
private readonly UkiyoeQueueScheduler _scheduler;
private readonly long _adapterLuid;
private ID3D11Fence? _fence;
private bool _disposed;
private UkiyoeInteropProvider(
ID3D11Device1 device,
ID3D11Device5 device5,
ID3D11DeviceContext4 context,
ID2D1DeviceContext6 renderContext,
UkiyoeQueueScheduler scheduler,
long adapterLuid)
{
_device = device;
_device5 = device5;
_context = context;
_renderContext = renderContext;
_scheduler = scheduler;
_adapterLuid = adapterLuid;
}
public ExternalAdapterIdentity AdapterIdentity => new(_adapterLuid);
public ComputeExternalQueueScheduler Scheduler => _scheduler;
public ExternalInteropCapabilities Capabilities =>
ExternalInteropCapabilities.SharedFence |
ExternalInteropCapabilities.SharedTexture2D |
ExternalInteropCapabilities.SingleImmediateContextOrdering |
ExternalInteropCapabilities.PersistentExternalViewOrdering;
public ID2D1DeviceContext6 RenderContext => _renderContext;
public static UkiyoeInteropProvider? TryCreate(IGraphicsDevicesAndContext devices, out GraphicsDevice? graphicsDevice)
{
graphicsDevice = null;
ID3D11Device1? device = null;
ID3D11Device5? device5 = null;
ID3D11DeviceContext4? context = null;
ID2D1DeviceContext6? renderContext = null;
UkiyoeQueueScheduler? scheduler = null;
try
{
var adapterLuidText = devices.DXGI.Adapter.Description.Luid.ToString();
using var enumerator = GraphicsDevice
.QueryDevices(candidate => string.Equals(candidate.Luid.ToString(), adapterLuidText, StringComparison.Ordinal))
.GetEnumerator();
if (!enumerator.MoveNext())
return null;
graphicsDevice = enumerator.Current;
device = devices.D3D.Device.QueryInterface<ID3D11Device1>();
device5 = devices.D3D.Device.QueryInterface<ID3D11Device5>();
context = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
renderContext = devices.D2D.Device
.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations)
.QueryInterface<ID2D1DeviceContext6>();
scheduler = new UkiyoeQueueScheduler();
return new UkiyoeInteropProvider(device, device5, context, renderContext, scheduler, graphicsDevice.Luid.ToInt64());
}
catch
{
scheduler?.Dispose();
renderContext?.Dispose();
context?.Dispose();
device5?.Dispose();
device?.Dispose();
graphicsDevice = null;
return null;
}
}
public void Initialize(in ExternalTimelineInitialization initialization)
{
_fence = _device5.OpenSharedFence<ID3D11Fence>(initialization.SharedFenceHandle.DangerousGetHandle());
}
public void EnqueueSignal(ulong value)
{
_context.Signal(_fence!, value);
}
public void FlushAfterSignal()
{
_context.Flush();
}
public void EnqueueWait(ulong value)
{
_context.Wait(_fence!, value);
}
public UkiyoeExternalView OpenSharedTexture(BorrowedSharedHandle resourceHandle, in ExternalTextureDescriptor descriptor)
{
ID3D11Texture2D? texture = null;
ID2D1Bitmap1? bitmap = null;
try
{
texture = _device.OpenSharedResource1<ID3D11Texture2D>(resourceHandle.DangerousGetHandle());
using var surface = texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
var options = descriptor.ExternalUsage is ExternalTextureUsage.RenderTarget
? BitmapOptions.Target
: BitmapOptions.None;
bitmap = _renderContext.CreateBitmapFromDxgiSurface(
surface,
new BitmapProperties1(pixelFormat, 96f, 96f, options));
var view = new UkiyoeExternalView(texture, bitmap);
texture = null;
bitmap = null;
return view;
}
finally
{
bitmap?.Dispose();
texture?.Dispose();
}
}
public void OnDeviceTerminal(Exception reason)
{
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_fence?.Dispose();
_renderContext.Dispose();
_context.Dispose();
_device5.Dispose();
_device.Dispose();
_scheduler.Dispose();
}
}
@@ -199,7 +77,7 @@ internal sealed partial class UkiyoeResourceSet
ComputeAlphaMode.Premultiplied,
ComputeSharedTextureInitialOwner.External,
ComputeResourceRecovery.RecreateFromHost)]
private readonly SharedTextureSlot<Bgra32, Float4, UkiyoeExternalView> _source;
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _source;
[ComputeSharedTexture(
ComputeResourceResizePolicy.GrowOnly,
@@ -209,5 +87,5 @@ internal sealed partial class UkiyoeResourceSet
ComputeAlphaMode.Premultiplied,
ComputeSharedTextureInitialOwner.Compute,
ComputeResourceRecovery.Recompute)]
private readonly SharedTextureSlot<Bgra32, Float4, UkiyoeExternalView> _output;
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _output;
}
+2 -1
ファイルの表示
@@ -1,4 +1,5 @@
using ComputeWeave;
// Stryker disable all
using ComputeWeave;
namespace Ukiyoe;
+59 -24
ファイルの表示
@@ -1,3 +1,4 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using ComputeWeave;
@@ -9,7 +10,9 @@ internal sealed class UkiyoePipeline : IDisposable
private readonly UkiyoePipelineHost _host;
private readonly ReadWriteBuffer<int> _scratch;
private readonly ReadBackBuffer<int> _scratchReadBack;
private StructureKey? _structureKey;
private PrefixKey? _prefixKey;
private FlattenKey? _flattenKey;
private LinesKey? _linesKey;
private int _cachedLitCount;
private int _cachedBoundsMinX;
private int _cachedBoundsMinY;
@@ -48,13 +51,18 @@ internal sealed class UkiyoePipeline : IDisposable
try
{
host = UkiyoePipelineHost.Create(device, UkiyoeSettings.MaximumPendingSubmissions);
return new UkiyoePipeline(device, host);
var pipeline = new UkiyoePipeline(device, host);
host = null;
return pipeline;
}
catch
catch (Win32Exception)
{
return null;
}
finally
{
host?.Dispose();
host?.WaitForDisposal();
return null;
}
}
@@ -144,21 +152,36 @@ internal sealed class UkiyoePipeline : IDisposable
_cachedBoundsMinY = hashed[UkiyoeSettings.ScratchBoundsMinY];
_cachedBoundsMaxX = hashed[UkiyoeSettings.ScratchBoundsMaxX];
_cachedBoundsMaxY = hashed[UkiyoeSettings.ScratchBoundsMaxY];
var key = new StructureKey(
var prefixKey = new PrefixKey(
hashed[UkiyoeSettings.ScratchMaskHashSum],
hashed[UkiyoeSettings.ScratchMaskHashMix],
canvasWidth,
canvasHeight,
parameters.Quality,
parameters.LineWidth,
parameters.Coherence,
parameters.LineDetail,
parameters.Flatten);
if (_structureKey == key)
parameters.Quality);
var flattenKey = new FlattenKey(prefixKey, parameters.Flatten);
var linesKey = new LinesKey(prefixKey, parameters.LineWidth, parameters.Coherence, parameters.LineDetail);
if (_prefixKey == prefixKey && _flattenKey == flattenKey && _linesKey == linesKey)
return false;
_host.RecordStructure(_scratch, _gridWidth, _gridHeight, in derived).Wait();
_structureKey = key;
if (_prefixKey != prefixKey)
{
_host.RecordStructurePrefix(_scratch, _gridWidth, _gridHeight, in derived).Wait();
_prefixKey = prefixKey;
}
if (_flattenKey != flattenKey)
{
_host.RecordFlatten(_scratch, _gridWidth, _gridHeight, in derived).Wait();
_flattenKey = flattenKey;
}
if (_linesKey != linesKey)
{
_host.RecordLines(_gridWidth, _gridHeight, in derived).Wait();
_linesKey = linesKey;
}
return true;
}
@@ -213,7 +236,9 @@ internal sealed class UkiyoePipeline : IDisposable
int height,
in Parameters parameters)
{
_structureKey = null;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
var derived = Derive(width, height, in parameters);
return _host.RecordFullPipeline(source, output, _scratch, width, height, _gridWidth, _gridHeight, in derived, in parameters);
}
@@ -249,22 +274,24 @@ internal sealed class UkiyoePipeline : IDisposable
private void EnsureGrid(int gridWidth, int gridHeight)
{
if (_gridWidth == gridWidth && _gridHeight == gridHeight)
return;
var gridLength = gridWidth * gridHeight;
if (!_host.TryEnsureGrid(
new UkiyoeGridResources.Plan(
gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength),
out _))
out var changed))
throw new InvalidOperationException();
if (!changed && _gridWidth == gridWidth && _gridHeight == gridHeight)
return;
_cachedLitCount = 0;
_cachedBoundsMinX = int.MaxValue;
_cachedBoundsMinY = int.MaxValue;
_cachedBoundsMaxX = int.MinValue;
_cachedBoundsMaxY = int.MinValue;
_structureKey = null;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
_gridWidth = gridWidth;
_gridHeight = gridHeight;
}
@@ -292,7 +319,9 @@ internal sealed class UkiyoePipeline : IDisposable
_packedOutput = null;
_packedWidth = 0;
_packedHeight = 0;
_structureKey = null;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
_gridWidth = 0;
_gridHeight = 0;
_scratchReadBack.Dispose();
@@ -301,16 +330,22 @@ internal sealed class UkiyoePipeline : IDisposable
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
private readonly record struct StructureKey(
private readonly record struct PrefixKey(
int MaskHashSum,
int MaskHashMix,
int CanvasWidth,
int CanvasHeight,
UkiyoeQuality Quality,
UkiyoeQuality Quality);
private readonly record struct FlattenKey(
PrefixKey Prefix,
float Flatten);
private readonly record struct LinesKey(
PrefixKey Prefix,
float LineWidth,
float Coherence,
float LineDetail,
float Flatten);
float LineDetail);
internal readonly record struct DerivedValues(
float CellSize,
+79 -3
ファイルの表示
@@ -134,6 +134,47 @@ internal sealed partial class UkiyoePipelineHost
RecordStructureStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordStructurePrefix(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordStructurePrefixStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordFlatten(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordFlattenStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordLines(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordLinesStage(in context, grid, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordRender(
in ComputeContext context,
@@ -188,6 +229,24 @@ internal sealed partial class UkiyoePipelineHost
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
RecordStructurePrefixStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
RecordFlattenStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
RecordLinesStage(in context, grid, gridWidth, gridHeight, in derived);
}
private static ReadWriteBuffer<Float2> GetTangent(UkiyoeGridResources grid, in UkiyoePipeline.DerivedValues derived)
{
return (derived.EtfIterations & 1) == 0 ? grid.TangentA : grid.TangentB;
}
private static void RecordStructurePrefixStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
context.For(1, new InitScratchShader(scratch));
context.Barrier(scratch);
@@ -204,12 +263,20 @@ internal sealed partial class UkiyoePipelineHost
context.Barrier(tangentOut);
(tangentIn, tangentOut) = (tangentOut, tangentIn);
}
var tangent = tangentIn;
}
private static void RecordFlattenStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
context.For(gridWidth, gridHeight, new CopyColorShader(grid.ColorIn, grid.ColorA, gridWidth, gridHeight));
context.Barrier(grid.ColorA);
var flattenDispatchWidth = (gridWidth + UkiyoeSettings.FlattenGroupDim - 1) & ~(UkiyoeSettings.FlattenGroupDim - 1);
var flattenDispatchHeight = (gridHeight + UkiyoeSettings.FlattenGroupDim - 1) & ~(UkiyoeSettings.FlattenGroupDim - 1);
var flattenDispatchWidth = ThreadGroupAlignment.AlignX<FlattenShader>(gridWidth);
var flattenDispatchHeight = ThreadGroupAlignment.AlignY<FlattenShader>(gridHeight);
var iterateIn = grid.ColorA;
var iterateOut = grid.ColorB;
for (var iteration = 0; iteration < derived.FlattenIterations; iteration++)
@@ -219,7 +286,16 @@ internal sealed partial class UkiyoePipelineHost
context.Barrier(iterateOut);
(iterateIn, iterateOut) = (iterateOut, iterateIn);
}
}
private static void RecordLinesStage(
in ComputeContext context,
UkiyoeGridResources grid,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
var tangent = GetTangent(grid, in derived);
for (var iteration = 0; iteration < derived.FdogIterations; iteration++)
{
context.For(gridWidth, gridHeight, new DogShader(
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace Ukiyoe;
internal static class UkiyoeTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(UkiyoeTelemetry).Assembly;
private static int _started;
public static void EnsureStartedOnce()
{
var application = Application.Current;
if (application is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
application.DispatcherUnhandledException += OnDispatcherUnhandledException;
TelemetryReporter.Start();
}
public static void Report(Exception exception)
{
if (Volatile.Read(ref _started) != 0)
TelemetryReporter.Report(exception);
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
=> ReportOwn(e.ExceptionObject as Exception);
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void ReportOwn(Exception? exception)
{
if (exception is not null && IsOwn(exception))
TelemetryReporter.Report(exception);
}
private static bool IsOwn(Exception exception)
{
var current = exception;
for (var depth = 0; current is not null && depth < MaxChainLength; depth++)
{
if (HasOwnFrame(current))
return true;
current = current is AggregateException aggregate && aggregate.InnerExceptions.Count > 0
? aggregate.InnerExceptions[0]
: current.InnerException;
}
return false;
}
private static bool HasOwnFrame(Exception exception)
{
StackFrame[]? frames;
try
{
frames = new StackTrace(exception, false).GetFrames();
}
catch (Exception)
{
return false;
}
if (frames is null)
return false;
for (var index = 0; index < Math.Min(frames.Length, MaxFrames); index++)
{
MethodBase? method;
try
{
method = frames[index].GetMethod();
}
catch (Exception)
{
continue;
}
if (method?.DeclaringType is { } declaringType && ReferenceEquals(declaringType.Assembly, Own))
return true;
}
return false;
}
}
+4 -2
ファイルの表示
@@ -13,7 +13,7 @@ internal static class UkiyoeUpdateNotifier
public static void EnsureCheckedOnce()
{
if (Interlocked.Exchange(ref _started, 1) != 0)
if (Application.Current is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
_ = RunAsync();
}
@@ -31,8 +31,10 @@ internal static class UkiyoeUpdateNotifier
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
catch (Exception exception)
{
if (exception is not UpdateCheckException)
UkiyoeTelemetry.Report(exception);
}
}
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更前

幅:  |  高さ:  |  サイズ: 1.3 MiB

変更後

幅:  |  高さ:  |  サイズ: 1.4 MiB

+5
ファイルの表示
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}