コミットを比較
50
コミット
pre-squash3
...
main
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
3f14a41cf2
|
||
|
|
d2636381b5
|
||
|
|
936504dfd4
|
||
|
|
fc5b3f82ea
|
||
|
|
7d643608b1
|
||
|
|
1c12670944
|
||
|
|
4c9b2e616d
|
||
|
|
9f321268df
|
||
|
|
a1a5cbb16f
|
||
|
|
aa92ea1214
|
||
|
|
3ff3a0a70d
|
||
|
|
58b53388d5
|
||
|
|
5929a3d6bf
|
||
|
|
d8e3b15b86
|
||
|
|
2d1365fbda
|
||
|
|
dca07250d1
|
||
|
|
503ade7091
|
||
|
|
c039c9cb4a
|
||
|
|
0307d7d5f1
|
||
|
|
dd4fe53e64
|
||
|
|
cde72340a8
|
||
|
|
581da7d70d
|
||
|
|
375f587c0e
|
||
|
|
51d2a164a2
|
||
|
|
139c353631
|
||
|
|
58afdfd29c
|
||
|
|
bc7c5b7670
|
||
|
|
72e20fc473
|
||
|
|
0815cddc09
|
||
|
|
69ca5a1c26
|
||
|
|
c195191fe7
|
||
|
|
1adff6ba63
|
||
|
|
f4fbee37c5
|
||
|
|
2b8c593a19
|
||
|
|
5944629ef6
|
||
|
|
76e8d965c7
|
||
|
|
6e5172889e
|
||
|
|
b71f075ba0
|
||
|
|
3a48c29c4d
|
||
|
|
b21b2de4ff
|
||
|
|
d6dfb0472d
|
||
|
|
c5d2c47661
|
||
|
|
cf2e2236ec
|
||
|
|
67f993ac7f
|
||
|
|
edd4369e1b
|
||
|
|
fc150acbf0
|
||
|
|
644ffe07c7
|
||
|
|
b517e8111f
|
||
|
|
767bc86a1a
|
||
|
|
2de9681dc6
|
検索条件に一致するファイルはありません
@@ -0,0 +1,517 @@
|
||||
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" = "VolumetricLight-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 = "VolumetricLight/VolumetricLight.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 VolumetricLight.Shader/VolumetricLight.Shader.vcxproj `
|
||||
/p:Configuration=Release `
|
||||
/p:Platform=Win32 `
|
||||
/nologo
|
||||
|
||||
- name: プロジェクトのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
$proj = "VolumetricLight/VolumetricLight.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: パッケージの作成
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "VolumetricLight/bin/Release/net10.0-windows10.0.19041.0"
|
||||
$stageRoot = "stage/VolumetricLight"
|
||||
$pkgName = "VolumetricLight_$version.ymme"
|
||||
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||
|
||||
$dll = "$outDir/VolumetricLight.dll"
|
||||
if (-not (Test-Path $dll)) {
|
||||
Write-Error "ビルド結果に VolumetricLight.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)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
VolumetricLight
|
||||
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 routersys
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,148 @@
|
||||
========================================
|
||||
体積光 for YMM4 v1.0.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材の明るい部分を光源とみなし、
|
||||
アイテムの3Dの位置と向きに沿って、
|
||||
画像の面から手前や奥へ伸びる光の筋を描いて元の映像に重ねる
|
||||
映像エフェクトプラグインです。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
結果は設定と素材の画素とフレームの位置から決まり、乱数は使いません。
|
||||
同じ設定では、同じフレームは何度描いても同じ絵になります。
|
||||
向き、手前への角度、拡がり、長さ、強さ、しきい値、減衰、光源の大きさ、
|
||||
前方散乱、濃淡、大きさ、流れの速さ、流れの向きの13項目は
|
||||
アニメーションに対応しています。
|
||||
エフェクトの種類一覧では「体積光」と「体積光の遮光」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
--------------------------------------------------------------------------------
|
||||
- OS : Windows 10 バージョン2004(ビルド19041)以降、または
|
||||
64ビット版のWindows 11
|
||||
- YMM4 : YukkuriMovieMaker4の最新版を推奨します
|
||||
- ランタイム : .NET 10.0
|
||||
--------------------------------------------------------------------------------
|
||||
■ 注意事項
|
||||
--------------------------------------------------------------------------------
|
||||
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
|
||||
|
||||
- 効果をかけないとき: Direct2Dのカスタムエフェクトを作成できない場合は、
|
||||
エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 処理対象: 光源には、現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
|
||||
- 素材の大きさ: 素材の幅か高さが4096画素を超えるときは、
|
||||
エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 描く範囲: 光の筋は、画面に入る範囲だけを計算します。
|
||||
|
||||
- アイテムの位置と回転: アイテムの位置、回転、拡大率、反転と、
|
||||
カメラの設定を読んで、光の柱を3Dの空間に置きます。
|
||||
このエフェクトはそれらの設定を映像に反映したあと、初期の値に戻して
|
||||
後ろのエフェクトへ渡します。
|
||||
|
||||
- 前後の順: 光の筋は、このエフェクトを付けたアイテムのレイヤーに、
|
||||
1枚の映像として描きます。奥行きの違うほかのアイテムとの前後は、
|
||||
レイヤーの順で決まります。
|
||||
|
||||
- 影: 前景のアイテムに「体積光の遮光」を付け、「体積光」の
|
||||
「遮光の番号」と同じ番号を選ぶと、光の筋に影を落とせます。
|
||||
影を落とすアイテムは、「体積光」を付けたアイテムより上のレイヤーに
|
||||
置いてください。番号は1から8までで、同じシーンの同じ番号に付けられる
|
||||
のは4つまでです。別のシーンのアイテムには、番号が同じでも影を落とし
|
||||
ません。
|
||||
|
||||
- 影の範囲: 影を落とすアイテムが影を落とすのは、光源の画像と光の筋の間に
|
||||
あるときだけです。影の縁は影を落とすアイテムの画像の縁のままで、
|
||||
ぼかしません。「体積光」と「体積光の遮光」を同じアイテムに付けても、
|
||||
そのアイテム自身の影は落ちません。
|
||||
|
||||
- 影の位置: 「体積光の遮光」はそのエフェクトを付けた位置までの設定で
|
||||
決まる位置と画像を使います。後ろに付けたエフェクトが位置や画像を
|
||||
変えても、影には反映されません。アイテムのエフェクトの最後に
|
||||
付けてください。「体積光」と「体積光の遮光」は、同じカメラの設定を
|
||||
使うアイテムの間でだけ、位置が合います。
|
||||
|
||||
- 光の筋を描かないとき: 「長さ」が0のときは、映像をそのまま通します。
|
||||
「強さ」が0のときと、光の筋が画面に入らないときは、光の筋の計算を
|
||||
行わず、元の画像だけを表示します。「元の画像を表示」がOFFのときは、
|
||||
透明な映像になります。
|
||||
|
||||
- 処理負荷: 光の筋を調べる回数は、「品質」、「長さ」、画面に占める
|
||||
光の筋の面積、素材の大きさで決まります。「品質」を上げるか
|
||||
「長さ」を伸ばすと、重くなります。「濃淡」を0%より大きくすると、
|
||||
さらに重くなります。
|
||||
|
||||
- 再現性: 結果は設定と素材の画素とフレームの位置から決まります。
|
||||
乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||
|
||||
- 更新通知: エフェクトを最初に生成したときに、
|
||||
YMM4の実行中に一度だけ新しい正式版を確認します。
|
||||
更新情報を取得できない場合は通知せず、そのまま動作します。
|
||||
プレリリースは通知の対象に含めません。
|
||||
|
||||
- 本プラグインを使用する前に、
|
||||
YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||
送信します。同意は求めません。止める設定もありません。
|
||||
|
||||
送信する数には上限があります。YMM4の1回の起動で送る報告は、
|
||||
YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。
|
||||
例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、
|
||||
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号、
|
||||
プラグイン自身のコードかどうか
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
時刻 : 報告を作った時刻(UTC)
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
|
||||
作るとき、フレームごとに更新するとき、破棄するときと、Direct2Dが
|
||||
シェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へ
|
||||
そのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
|
||||
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
|
||||
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
|
||||
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
|
||||
本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
効果をかけないだけで済ませるもの : Direct2Dのカスタムエフェクトを
|
||||
作成できないときに、エフェクトを適用せず
|
||||
入力映像を表示したとき
|
||||
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
|
||||
接続できない
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
|
||||
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
|
||||
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
|
||||
退避した報告を1回の起動で10件まで送り直します。
|
||||
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
|
||||
ありません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、
|
||||
商品性、特定目的への適合性、および権利非侵害に関する保証を含む、
|
||||
いかなる種類の保証も行いません。
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、
|
||||
一切の責任を負いません。
|
||||
ご利用は自己責任でお願いします。
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
MIT License
|
||||
https://github.com/routersys/YMM4-VolumetricLight
|
||||
========================================
|
||||
@@ -0,0 +1,392 @@
|
||||
name: リリース
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: ソースコードのチェックアウト
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: .NET SDK のセットアップ
|
||||
uses: actions/setup-dotnet@v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: MSBuild のセットアップ
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: YMM4 最新リリースの取得と解凍
|
||||
id: ymm4
|
||||
shell: pwsh
|
||||
run: |
|
||||
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases/latest" `
|
||||
-Headers @{ "User-Agent" = "VolumetricLight-CI" }
|
||||
$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)"
|
||||
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
|
||||
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
|
||||
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: タグ名からバージョンを取得
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$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 = "VolumetricLight/VolumetricLight.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 VolumetricLight.Shader/VolumetricLight.Shader.vcxproj `
|
||||
/p:Configuration=Release `
|
||||
/p:Platform=Win32 `
|
||||
/nologo
|
||||
|
||||
- name: プロジェクトのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
$proj = "VolumetricLight/VolumetricLight.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: パッケージの作成
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "VolumetricLight/bin/Release/net10.0-windows10.0.19041.0"
|
||||
$stageRoot = "stage/VolumetricLight"
|
||||
$pkgName = "VolumetricLight_$version.ymme"
|
||||
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||
|
||||
$dll = "$outDir/VolumetricLight.dll"
|
||||
if (-not (Test-Path $dll)) {
|
||||
Write-Error "ビルド結果に VolumetricLight.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:
|
||||
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: release-body.md
|
||||
files: ${{ steps.package.outputs.PKG_NAME }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
[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://github.com/routersys/YMM4-Telemetry.git
|
||||
url = https://git.routersys.com/routersys/YMM4-Telemetry.git
|
||||
@@ -1 +1,298 @@
|
||||
# VolumetricLight
|
||||
# 体積光 for YMM4
|
||||
|
||||
[](#)
|
||||
[](#)
|
||||
[](https://github.com/routersys/YMM4-VolumetricLight/releases)
|
||||
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材の明るい部分を光源とみなし、画像の面から手前や奥へ伸びる光の筋を、アイテムの3Dの位置と向きに沿って描き、元の映像に重ねる映像エフェクトプラグインです。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
結果は設定と素材の画素とフレームの位置から決まり、乱数は使いません。同じ設定では、同じフレームは何度描いても同じ絵になります。
|
||||
向き、手前への角度、拡がり、長さ、強さ、しきい値、減衰、光源の大きさ、前方散乱、濃淡、大きさ、流れの速さ、流れの向きの13項目はアニメーションに対応しています。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
|
||||
1. [概要](#概要)
|
||||
2. [動作要件](#動作要件)
|
||||
3. [インストール方法](#インストール方法)
|
||||
4. [主な機能](#主な機能)
|
||||
- [1. 光源にする部分](#1-光源にする部分)
|
||||
- [2. 光の向きと広がり](#2-光の向きと広がり)
|
||||
- [3. 光の筋の見え方](#3-光の筋の見え方)
|
||||
- [4. 塵による濃淡](#4-塵による濃淡)
|
||||
- [5. アイテムの位置と回転](#5-アイテムの位置と回転)
|
||||
- [6. 元の画像の表示と品質](#6-元の画像の表示と品質)
|
||||
- [7. 影を落とす](#7-影を落とす)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [光の向きグループ](#光の向きグループ)
|
||||
- [光グループ](#光グループ)
|
||||
- [光の筋グループ](#光の筋グループ)
|
||||
- [塵グループ](#塵グループ)
|
||||
- [表示グループ](#表示グループ)
|
||||
- [遮光グループ(体積光)](#遮光グループ体積光)
|
||||
- [遮光グループ(体積光の遮光)](#遮光グループ体積光の遮光)
|
||||
6. [制限事項](#制限事項)
|
||||
7. [注意事項](#注意事項)
|
||||
8. [不具合の報告](#不具合の報告)
|
||||
9. [免責事項](#免責事項)
|
||||
10. [ライセンス](#ライセンス)
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「体積光」と「体積光の遮光」として表示されます。カテゴリは装飾です。
|
||||
|
||||
体積光は、空気中の霧や塵に当たった光が散乱して、光の通り道が筋のように見える現象です。3DCGではボリュームライトとも呼ばれます。「体積光」は、この現象を映像として描きます。素材の画像を、光を通す窓のように扱います。画像の面から、「向き」と「手前への角度」で決めた向きへ、画像の矩形を断面とする光の柱が伸びていると考え、画面の各画素から視線に沿って柱の中をたどって、光の筋の明るさを求めます。光の筋の色は素材の画素の色に「色」を掛けたものです。
|
||||
|
||||
光の筋は次の順で作ります。
|
||||
|
||||
1. 素材の明るさが「しきい値」を超えた分だけを光にします。色合いは変えません。
|
||||
2. アイテムの位置、回転、拡大率、カメラの設定に従って、光の柱を3Dの空間に置きます。
|
||||
3. 画面の各画素から視線をたどり、視線が柱を通る区間を細かく区切ります。
|
||||
4. 区間ごとに、光源の画像の対応する点の光に、「減衰」「前方散乱」「濃淡」と影を掛けて足し合わせます。「光源の大きさ」が大きいほど、遠い区間では光源の画像をぼかして読みます。
|
||||
5. 「強さ」と「色」を掛け、元の画像に加算で重ねます。
|
||||
|
||||
「前方散乱」の見る向きによる明るさの違いには、HenyeyとGreensteinの位相関数を使います。この関数は、Henyey and Greensteinの論文「Diffuse radiation in the Galaxy」(The Astrophysical Journal 93巻、1941年)に基づきます。
|
||||
|
||||
「体積光の遮光」は人物などの前景のアイテムに付けるエフェクトです。同じ番号の「体積光」の光の筋を、アイテムの不透明な部分で遮り、光の筋の中に影を落とします。
|
||||
|
||||
結果は設定と素材の画素とフレームの位置から決まります。乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||
|
||||
処理はDirect2Dのカスタムピクセルシェーダーと標準のエフェクトが行います。CPUへの画素の読み戻しは行いません。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
---
|
||||
|
||||
## 動作要件
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| OS | Windows 10 バージョン2004(ビルド19041)以降 / Windows 11(64bit) |
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
|
||||
---
|
||||
|
||||
## インストール方法
|
||||
|
||||
1. [Releases](https://github.com/routersys/YMM4-VolumetricLight/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
||||
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
|
||||
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||
4. 映像エフェクトの種類として「体積光」を選択してください。影を落とすときは、前景のアイテムに「体積光の遮光」を追加し、「体積光」と同じ番号を選びます。
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. 光源にする部分
|
||||
|
||||
「しきい値」は光源にする明るさの下限です。素材の画素の明るさから「しきい値」を引いた分が光になり、色合いは変わりません。上げると明るい部分だけが光源になり、下げると暗い部分も光源になります。0%では素材の全体が光源です。透明な画素は光りません。
|
||||
|
||||
「色」は光に掛ける色です。白では素材の画素の色のままになります。
|
||||
|
||||
次の画像は、ステンドグラスの窓の写真に適用した例です。「向き」は-60°、「手前への角度」は45°、「強さ」は700%、「しきい値」は30%で、ほかの項目は既定値です。上が入力、下が出力で、しきい値を超える明るいガラスの部分だけが光源になり、窓から右下へ光の筋が伸びます。元の写真は、Wikimedia CommonsにCC0で公開されているWmpearl氏の「[Stained glass window, Hammerfest Church](https://commons.wikimedia.org/wiki/File:Stained_glass_window,_Hammerfest_Church.JPG)」です。
|
||||
|
||||

|
||||
|
||||
### 2. 光の向きと広がり
|
||||
|
||||
「向き」は、光が進む向きを、画像の面に沿った角度で決めます。0°が右、90°が上、-90°が下です。
|
||||
|
||||
「手前への角度」は、光が進む向きの、画像の面からカメラの側への傾きです。正の値で光はカメラの側へ進み、負の値で奥へ進みます。0°に近いほど画像の面に沿って流れ、90°に近いほど画像の面にまっすぐ立ち上がります。絶対値が1°より小さい値は絶対値1°と同じで、89°より大きい値は89°と同じです。
|
||||
|
||||
「拡がり」は光の筋の広がり方です。0°では光の筋が平行に進みます。正の値では外へ広がり、負の値では光源より先の一点へ向かって絞られます。絶対値が0.01°より小さい値は0°です。
|
||||
|
||||
「長さ」は光の筋の長さです。画像の面から、光が進む向きに沿って測ります。0pxでは光の筋を描かず、映像をそのまま通します。
|
||||
|
||||
### 3. 光の筋の見え方
|
||||
|
||||
「強さ」は光の筋の明るさです。0%では光の筋を描きません。
|
||||
|
||||
「減衰」は光の筋が先端へ向かって弱まる形です。どの値でも、光の筋は先端で消えます。0%では先端へ向かって直線的に弱まり、100%に近いほど光源の近くで急に弱まります。99%より大きい値は99%と同じです。
|
||||
|
||||
「光源の大きさ」は光源の見かけの大きさを角度で表した値です。大きいほど、光の筋の縁が先へ向かってぼやけます。
|
||||
|
||||
「前方散乱」は光が進む向きへ散乱する強さです。正の値では光源の方を見る向きで光の筋が明るくなり、負の値では光源を背にする向きで明るくなります。0%では見る向きによる明るさの差がありません。
|
||||
|
||||
### 4. 塵による濃淡
|
||||
|
||||
「濃淡」は光の筋の中を漂う塵のように、光の筋に濃い所と薄い所を付けます。0%では濃淡が付かず、光の筋は一様です。100%ではいちばん薄い所で光がなくなり、いちばん濃い所で明るさが2倍になります。
|
||||
|
||||
濃淡は光の筋の中の位置から決まり、奥行きの方向にも変わります。「大きさ」は濃淡のむらの大きさ、「流れの速さ」と「流れの向き」は、むらが画像の面に沿って動く速さと向きです。「流れの速さ」が0px/sのときは、むらは動きません。
|
||||
|
||||
「シード値」はむらの形を決める値です。「濃淡」が0%のときは、「シード値」を変えても結果は変わりません。
|
||||
|
||||
### 5. アイテムの位置と回転
|
||||
|
||||
「体積光」はアイテムの位置、回転、拡大率、反転と、カメラの設定を読んで、光の柱を3Dの空間に置きます。アイテムのX・Y・Zの位置、回転、カメラを変えると、光の筋の見える向きと遠近も一緒に変わります。
|
||||
|
||||
このエフェクトはそれらの設定を映像に反映したあと、初期の値に戻して後ろのエフェクトへ渡します。
|
||||
|
||||
### 6. 元の画像の表示と品質
|
||||
|
||||
「元の画像を表示」がONのときは、光源にした画像も光の筋と一緒に表示します。OFFにすると、光の筋だけを描きます。
|
||||
|
||||
「品質」は光の筋を調べる細かさです。「標準」と「高」は、光の筋を縦横それぞれ半分の大きさで計算してから拡大します。「高」は「標準」より細かい間隔で調べ、「最高」は等倍で計算して「高」よりさらに細かい間隔で調べる設定です。高くするほど塵のむらや縁が滑らかになりますが、処理は重くなります。
|
||||
|
||||
### 7. 影を落とす
|
||||
|
||||
前景のアイテムが光源と光の筋の間にあるとき、その影を光の筋に落とせます。
|
||||
|
||||
1. 光源にするアイテムに「体積光」を付け、「遮光」グループの「遮光の番号」を1から8のどれかにします。
|
||||
2. 影を落とすアイテムに「体積光の遮光」を付け、「番号」を同じ値にします。
|
||||
3. 影を落とすアイテムは「体積光」を付けたアイテムより上のレイヤーに置きます。
|
||||
|
||||
影を落とすアイテムは位置と回転と拡大率を持つ平らな画像として扱い、画像の不透明な部分が光を遮ります。光源の画像の各点から出た光の線が、影を落とすアイテムの不透明な部分を通ると、その線の先の光の筋が弱まって影になります。影を落とすアイテムが影を落とすのは、光源の画像と光の筋の間にあるときだけです。
|
||||
|
||||
次の画像は、窓の写真の手前にキャラクターを置いた例です。窓の写真には前の画像と同じ設定の「体積光」を付け、「遮光の番号」を1にしました。キャラクターには「体積光の遮光」を付け、「番号」を上は2、下は1にしました。上は番号が違うので影が落ちません。下は番号が同じなので、キャラクターが遮った分だけ、右と下の光の筋が弱まります。
|
||||
|
||||

|
||||
|
||||
「遮る強さ」は、影を落とすアイテムの不透明な部分が、光をどれだけ遮るかです。アイテムの不透明度も掛かります。100%で光を通さず、0%で遮りません。
|
||||
|
||||
同じシーンの同じ番号に付けられる「体積光の遮光」は4つまでです。5つ目以降は影を落としません。別のシーンのアイテムには、番号が同じでも影を落としません。
|
||||
|
||||
---
|
||||
|
||||
## パラメータ一覧
|
||||
|
||||
### 光の向きグループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 向き | 数値 | -90° | -180〜180° | 対応 | 光が進む向きを、画像の面に沿った角度で指定します。0°が右、90°が上、-90°が下です。直接入力では-360〜360°まで指定できます。 |
|
||||
| 手前への角度 | 数値 | 55° | -89〜89° | 対応 | 光が進む向きの、画像の面から手前への傾きです。正の値でカメラの側へ、負の値で奥へ進みます。絶対値が1°より小さい値は絶対値1°と同じです。 |
|
||||
| 拡がり | 数値 | 10° | -60〜60° | 対応 | 光の筋の広がり方です。0°で平行、正の値で外へ広がり、負の値で一点へ向かって絞られます。絶対値が0.01°より小さい値は0°です。直接入力では-85〜85°まで指定できます。 |
|
||||
| 長さ | 数値 | 1200px | 0〜4000px | 対応 | 光の筋の長さを、画像の面から光が進む向きに沿って測った値です。0pxでは光の筋を描かず、映像をそのまま通します。直接入力では0〜100000pxまで指定できます。 |
|
||||
|
||||
### 光グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 強さ | 数値 | 150% | 0〜300% | 対応 | 光の筋の明るさです。0%では光の筋を描きません。直接入力では0〜1000%まで指定できます。 |
|
||||
| しきい値 | 数値 | 8% | 0〜100% | 対応 | 素材の明るさがこの値を超えた分だけが光になります。大きいほど、明るい部分だけが光源になります。 |
|
||||
| 色 | 色 | 白 | — | 非対応 | 光に掛ける色です。白では素材の画素の色のままになります。 |
|
||||
|
||||
### 光の筋グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 減衰 | 数値 | 60% | 0〜100% | 対応 | 光の筋が先端へ向かって弱まる形です。0%では直線的に弱まり、100%に近いほど光源の近くで急に弱まります。どの値でも先端では消えます。99%より大きい値は99%と同じです。 |
|
||||
| 光源の大きさ | 数値 | 1.5° | 0〜10° | 対応 | 光源の見かけの大きさを表す角度です。大きいほど、光の筋の縁が先へ向かってぼやけます。直接入力では0〜30°まで指定できます。 |
|
||||
| 前方散乱 | 数値 | 30% | -90〜90% | 対応 | 光が進む向きへ散乱する強さです。正の値では光源の方を見るときに明るくなり、負の値では光源を背にして見るときに明るくなります。直接入力では-95〜95%まで指定できます。 |
|
||||
|
||||
### 塵グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 濃淡 | 数値 | 0% | 0〜100% | 対応 | 光の筋の中を漂う塵による濃淡の量です。0%では光の筋が一様になります。 |
|
||||
| 大きさ | 数値 | 220px | 20〜1000px | 対応 | 塵のむらの大きさです。直接入力では8〜4000pxまで指定できます。 |
|
||||
| 流れの速さ | 数値 | 40px/s | -500〜500px/s | 対応 | 塵が流れる速さです。単位は1秒あたりのpxです。直接入力では-5000〜5000px/sまで指定できます。 |
|
||||
| 流れの向き | 数値 | -90° | -180〜180° | 対応 | 塵が流れる向きを、画像の面に沿った角度で指定します。0°が右、90°が上です。直接入力では-360〜360°まで指定できます。 |
|
||||
| シード値 | 整数 | 0 | -1000〜1000 | 非対応 | 塵のむらの形を決める値です。 |
|
||||
|
||||
### 表示グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 元の画像を表示 | ON/OFF | ON | — | 非対応 | 光源にした画像そのものも表示します。OFFでは光の筋だけを描きます。 |
|
||||
| 品質 | 列挙 | 標準 | 標準 / 高 / 最高 | 非対応 | 光の筋を調べる細かさです。高いほど滑らかになりますが、処理は重くなります。 |
|
||||
|
||||
### 遮光グループ(体積光)
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 遮光の番号 | 整数 | 0 | 0〜8 | 非対応 | 同じ番号を選んだ「体積光の遮光」のアイテムが、光の筋を遮って影を落とします。0のときは何も遮りません。 |
|
||||
|
||||
### 遮光グループ(体積光の遮光)
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 番号 | 整数 | 1 | 1〜8 | 非対応 | 同じ番号を選んだ「体積光」の光の筋を、このアイテムが遮ります。シーンと番号ごとに遮れるアイテムは4つまでです。 |
|
||||
| 遮る強さ | 数値 | 100% | 0〜100% | 対応 | アイテムの不透明な部分が光をどれだけ遮るかです。アイテムの不透明度も掛かります。100%で光を通さず、0%で遮りません。 |
|
||||
|
||||
---
|
||||
|
||||
## 制限事項
|
||||
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- Direct2Dのカスタムエフェクトを作成できない場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 光源には現在のフレームの色と不透明度だけを使います。履歴フレーム、外部画像、学習済みモデルも使いません。
|
||||
- 素材の幅か高さが4096pxを超えるときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 光の筋は画面に入る範囲だけを計算します。
|
||||
- 光の筋はこのエフェクトを付けたアイテムのレイヤーに1枚の映像として描きます。奥行きの違うほかのアイテムとの前後は、レイヤーの順で決まります。
|
||||
- 「体積光の遮光」は、シーンと番号ごとに4つまで付けられます。番号は1から8までです。
|
||||
- 影の縁は影を落とすアイテムの画像の縁のままで、ぼかしません。
|
||||
- 「体積光」と「体積光の遮光」を同じアイテムに付けても、そのアイテム自身の影は落ちません。
|
||||
- 「体積光の遮光」はそのエフェクトを付けた位置までの設定で決まる位置と画像を使います。後ろに付けたエフェクトが位置や画像を変えても、影には反映されません。アイテムのエフェクトの最後に付けてください。
|
||||
- 「体積光」と「体積光の遮光」は、同じカメラの設定を使うアイテムの間でだけ、位置が合います。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 光の筋を調べる回数は「品質」、「長さ」、画面に占める光の筋の面積、素材の大きさで決まります。「品質」を上げるか「長さ」を伸ばすと、重くなります。「濃淡」を0%より大きくすると、さらに重くなります。
|
||||
- 光の筋を描かないとき: 「長さ」が0のときは、映像をそのまま通します。「強さ」が0のときと、光の筋が画面に入らないときは、光の筋の計算を行わず、元の画像だけを表示します。「元の画像を表示」がOFFのときは、透明な映像になります。
|
||||
- 再現性: 結果は設定と素材の画素とフレームの位置から決まります。乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めません。止める設定もありません。
|
||||
|
||||
送信する数には上限があります。YMM4の1回の起動で送る報告は、YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
| 種類 | 内容 |
|
||||
|---|---|
|
||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号、プラグイン自身のコードかどうか |
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
| 時刻 | 報告を作った時刻(UTC) |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 効果をかけないだけで済ませるもの | Direct2Dのカスタムエフェクトを作成できないときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
|
||||
|
||||
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
|
||||
|
||||
---
|
||||
|
||||
## 免責事項
|
||||
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。
|
||||
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。ご利用は自己責任でお願いします。
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
[MIT License](LICENSE.txt)
|
||||
@@ -12,22 +12,23 @@ internal enum HarnessMode
|
||||
Benchmark,
|
||||
}
|
||||
|
||||
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After)
|
||||
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After, string? Case = null)
|
||||
{
|
||||
public const string Usage = """
|
||||
使い方:
|
||||
[<出力先>] [--input <画像>] ケースを描き、PNG とハッシュを出します
|
||||
[<出力先>] [--input <画像>] [--case <名前>] ケースを描き、PNG とハッシュを出します。--case は名前に含まれるケースだけを描きます
|
||||
--golden [--input <画像>] 基準値を golden.json に書きます
|
||||
--verify [--input <画像>] 基準値と照合します
|
||||
--transition [<出力先>] [--input <画像>] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
|
||||
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
|
||||
--benchmark [--input <画像>] 描画を計測します
|
||||
--benchmark [--input <画像>] [--case <名前>] 描画を計測します
|
||||
""";
|
||||
|
||||
public static HarnessArguments Parse(string[] arguments)
|
||||
{
|
||||
HarnessMode? mode = null;
|
||||
string? input = null;
|
||||
string? caseFilter = null;
|
||||
var positionals = new List<string>();
|
||||
for (var index = 0; index < arguments.Length; index++)
|
||||
{
|
||||
@@ -49,6 +50,11 @@ internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string?
|
||||
case "--benchmark":
|
||||
mode = Select(mode, HarnessMode.Benchmark);
|
||||
break;
|
||||
case "--case":
|
||||
if (index + 1 >= arguments.Length)
|
||||
throw new HarnessException("--case には名前を続けてください。");
|
||||
caseFilter = arguments[++index];
|
||||
break;
|
||||
case "--input":
|
||||
if (index + 1 >= arguments.Length)
|
||||
throw new HarnessException("--input には画像のパスを続けてください。");
|
||||
@@ -75,10 +81,16 @@ internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string?
|
||||
case HarnessMode.Transition:
|
||||
if (positionals.Count > 1)
|
||||
throw new HarnessException($"余分な引数です。{positionals[1]}");
|
||||
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null);
|
||||
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null, caseFilter);
|
||||
case HarnessMode.Benchmark:
|
||||
if (positionals.Count > 0)
|
||||
throw new HarnessException($"余分な引数です。{positionals[0]}");
|
||||
return new HarnessArguments(selected, input, null, null, null, caseFilter);
|
||||
default:
|
||||
if (positionals.Count > 0)
|
||||
throw new HarnessException($"余分な引数です。{positionals[0]}");
|
||||
if (caseFilter is not null)
|
||||
throw new HarnessException("--case は、ケースを描く場合と --benchmark でだけ使えます。");
|
||||
return new HarnessArguments(selected, input, null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,141 @@
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
|
||||
namespace VolumetricLight.Harness;
|
||||
|
||||
internal static class HarnessCases
|
||||
{
|
||||
public static IEnumerable<(string Name, IVideoEffect Effect, IReadOnlyList<int> Frames)> All()
|
||||
static readonly HarnessPose RotatedY = HarnessPose.Flat with { Rotation = new Vector3(0f, 35f, 0f) };
|
||||
static readonly HarnessPose RotatedX = HarnessPose.Flat with { Rotation = new Vector3(25f, 0f, 0f) };
|
||||
static readonly HarnessPose RotatedZ = HarnessPose.Flat with { Rotation = new Vector3(0f, 0f, 20f) };
|
||||
static readonly HarnessPose Shrunk = HarnessPose.Flat with { Zoom = new Vector2(0.6f, 0.6f) };
|
||||
static readonly HarnessPose Offset = HarnessPose.Flat with { Draw = new Vector3(-180f, 60f, 0f) };
|
||||
static readonly HarnessPose Near = HarnessPose.Flat with { Draw = new Vector3(0f, 0f, 300f) };
|
||||
static readonly HarnessPose Mirrored = HarnessPose.Flat with { Invert = true };
|
||||
static readonly HarnessPose Orbit = HarnessPose.Flat with { Camera = HarnessPose.CameraAt(new Vector3(220f, 0f, 300f), new Vector3(0f, -15f, 0f)) };
|
||||
static readonly HarnessPose Telephoto = HarnessPose.Flat with { PerspectiveDistance = 3000f };
|
||||
|
||||
public static IEnumerable<(string Name, VolumetricLightEffect Effect, IReadOnlyList<int> Frames, HarnessPose Pose)> All()
|
||||
{
|
||||
yield break;
|
||||
yield return ("default", Create(), [0], HarnessPose.Flat);
|
||||
yield return ("direction-animated-frames", Create(effect => effect.Direction.CopyFrom(Linear(-150d, -30d))), [0, 100, 200, 299], HarnessPose.Flat);
|
||||
yield return ("direction-0", Create(effect => effect.Direction.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("direction-180", Create(effect => effect.Direction.Values[0].Value = 180), [0], HarnessPose.Flat);
|
||||
yield return ("elevation-15", Create(effect => effect.Elevation.Values[0].Value = 15), [0], HarnessPose.Flat);
|
||||
yield return ("elevation-70", Create(effect => effect.Elevation.Values[0].Value = 70), [0], HarnessPose.Flat);
|
||||
yield return ("elevation-minus-35", Create(effect => effect.Elevation.Values[0].Value = -35), [0], HarnessPose.Flat);
|
||||
yield return ("spread-0", Create(effect => effect.Spread.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("spread-35", Create(effect => effect.Spread.Values[0].Value = 35), [0], HarnessPose.Flat);
|
||||
yield return ("spread-minus-25", Create(effect => effect.Spread.Values[0].Value = -25), [0], HarnessPose.Flat);
|
||||
yield return ("length-400", Create(effect => effect.Length.Values[0].Value = 400), [0], HarnessPose.Flat);
|
||||
yield return ("length-2800", Create(effect => effect.Length.Values[0].Value = 2800), [0], HarnessPose.Flat);
|
||||
yield return ("length-0", Create(effect => effect.Length.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("intensity-40", Create(effect => effect.Intensity.Values[0].Value = 40), [0], HarnessPose.Flat);
|
||||
yield return ("intensity-250", Create(effect => effect.Intensity.Values[0].Value = 250), [0], HarnessPose.Flat);
|
||||
yield return ("threshold-0", Create(effect => effect.Threshold.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("threshold-60", Create(effect => effect.Threshold.Values[0].Value = 60), [0], HarnessPose.Flat);
|
||||
yield return ("tint-amber", Create(effect => effect.Tint = System.Windows.Media.Color.FromRgb(255, 190, 90)), [0], HarnessPose.Flat);
|
||||
yield return ("falloff-0", Create(effect => effect.Falloff.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("falloff-95", Create(effect => effect.Falloff.Values[0].Value = 95), [0], HarnessPose.Flat);
|
||||
yield return ("lamp-size-0", Create(effect => effect.LampSize.Values[0].Value = 0), [0], HarnessPose.Flat);
|
||||
yield return ("lamp-size-6", Create(effect => effect.LampSize.Values[0].Value = 6), [0], HarnessPose.Flat);
|
||||
yield return ("scattering-minus-60", Create(effect => effect.Scattering.Values[0].Value = -60), [0], HarnessPose.Flat);
|
||||
yield return ("scattering-85", Create(effect => effect.Scattering.Values[0].Value = 85), [0], HarnessPose.Flat);
|
||||
yield return ("source-hidden", Create(effect => effect.ShowSource = false), [0], HarnessPose.Flat);
|
||||
yield return ("dust-60", Create(effect => effect.DustAmount.Values[0].Value = 60), [0], HarnessPose.Flat);
|
||||
yield return ("dust-60-animated-frames", Create(effect => effect.DustAmount.Values[0].Value = 60), [0, 90, 180], HarnessPose.Flat);
|
||||
yield return ("dust-seed-7", Create(effect => { effect.DustAmount.Values[0].Value = 60; effect.Seed = 7; }), [0], HarnessPose.Flat);
|
||||
yield return ("quality-high", Create(effect => effect.Quality = VolumetricLightQuality.High), [0], HarnessPose.Flat);
|
||||
yield return ("quality-ultra", Create(effect => effect.Quality = VolumetricLightQuality.Ultra), [0], HarnessPose.Flat);
|
||||
yield return ("pose-rotated-y", Create(), [0], RotatedY);
|
||||
yield return ("pose-rotated-x", Create(), [0], RotatedX);
|
||||
yield return ("pose-rotated-z", Create(), [0], RotatedZ);
|
||||
yield return ("pose-shrunk", Create(), [0], Shrunk);
|
||||
yield return ("pose-offset", Create(), [0], Offset);
|
||||
yield return ("pose-near", Create(), [0], Near);
|
||||
yield return ("pose-mirrored", Create(), [0], Mirrored);
|
||||
yield return ("pose-orbit", Create(), [0], Orbit);
|
||||
yield return ("pose-telephoto", Create(), [0], Telephoto);
|
||||
yield return ("pose-rotated-y-converging", Create(effect => effect.Spread.Values[0].Value = -25), [0], RotatedY);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<IVideoEffect> Create, Action<IVideoEffect> Change, int Frame)> Transitions()
|
||||
static readonly HarnessImage FigureImage = HarnessImage.Silhouette(360, 540);
|
||||
|
||||
static HarnessOccluder Figure(Vector3 draw, Vector3? rotation = null, Action<VolumetricLightOccluderEffect>? configure = null)
|
||||
{
|
||||
yield break;
|
||||
var effect = new VolumetricLightOccluderEffect();
|
||||
configure?.Invoke(effect);
|
||||
return new HarnessOccluder(effect, HarnessPose.Flat with { Draw = draw, Rotation = rotation ?? Vector3.Zero }, FigureImage);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, IVideoEffect Effect)> Benchmarks()
|
||||
static VolumetricLightEffect Shadowed(Action<VolumetricLightEffect>? configure = null)
|
||||
=> Create(effect =>
|
||||
{
|
||||
effect.OcclusionChannel = 1;
|
||||
effect.Intensity.Values[0].Value = 250;
|
||||
configure?.Invoke(effect);
|
||||
});
|
||||
|
||||
public static IEnumerable<(string Name, VolumetricLightEffect Effect, IReadOnlyList<int> Frames, HarnessPose Pose, IReadOnlyList<HarnessOccluder> Occluders)> Everything()
|
||||
{
|
||||
yield break;
|
||||
foreach (var (name, effect, frames, pose) in All())
|
||||
yield return (name, effect, frames, pose, []);
|
||||
foreach (var item in Shadows())
|
||||
yield return item;
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, VolumetricLightEffect Effect, IReadOnlyList<int> Frames, HarnessPose Pose, IReadOnlyList<HarnessOccluder> Occluders)> Shadows()
|
||||
{
|
||||
yield return ("shadow-figure", Shadowed(effect => { effect.Direction.Values[0].Value = -60; effect.Elevation.Values[0].Value = 45; }), [0], HarnessPose.Flat, [Figure(new Vector3(-120f, 110f, 240f))]);
|
||||
yield return ("shadow-figure-default-light", Shadowed(), [0], HarnessPose.Flat, [Figure(new Vector3(0f, 120f, 200f))]);
|
||||
yield return ("shadow-figure-point-light", Shadowed(effect => effect.Spread.Values[0].Value = 25), [0], HarnessPose.Flat, [Figure(new Vector3(60f, 110f, 220f))]);
|
||||
yield return ("shadow-two-figures", Shadowed(effect => effect.Direction.Values[0].Value = -70), [0], HarnessPose.Flat, [Figure(new Vector3(-220f, 130f, 160f)), Figure(new Vector3(200f, 110f, 300f), new Vector3(0f, -15f, 0f))]);
|
||||
yield return ("shadow-figure-half-strength", Shadowed(effect => effect.Direction.Values[0].Value = -60), [0], HarnessPose.Flat, [Figure(new Vector3(-120f, 110f, 240f), configure: effect => effect.Strength.Values[0].Value = 50)]);
|
||||
yield return ("shadow-figure-strength-animated-frames", Shadowed(effect => effect.Direction.Values[0].Value = -60), [0, 150, 299], HarnessPose.Flat, [Figure(new Vector3(-120f, 110f, 240f), configure: effect => effect.Strength.CopyFrom(Linear(100d, 10d)))]);
|
||||
yield return ("shadow-figure-rotated-light", Shadowed(), [0], RotatedY, [Figure(new Vector3(0f, 120f, 200f))]);
|
||||
yield return ("shadow-figure-other-scene", Shadowed(effect => { effect.Direction.Values[0].Value = -60; effect.Elevation.Values[0].Value = 45; }), [0], HarnessPose.Flat, [Figure(new Vector3(40f, 120f, 220f)) with { Scene = new Guid("5b0a8d3e-2c1f-4e7a-9a52-7d4f1c6b8e90") }]);
|
||||
yield return ("shadow-figure-other-frame", Shadowed(effect => { effect.Direction.Values[0].Value = -60; effect.Elevation.Values[0].Value = 45; }), [0], HarnessPose.Flat, [Figure(new Vector3(-220f, 130f, 160f)) with { FrameOffset = 7 }]);
|
||||
yield return ("shadow-figure-other-number", Shadowed(effect => { effect.Direction.Values[0].Value = -60; effect.Elevation.Values[0].Value = 45; }), [0], HarnessPose.Flat, [Figure(new Vector3(-120f, 110f, 240f), configure: effect => effect.Channel = 2)]);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<VolumetricLightEffect> Create, Action<VolumetricLightEffect> Change, int Frame, HarnessPose Pose)> Transitions()
|
||||
{
|
||||
yield return ("direction-minus-90-to-0", () => Create(), effect => effect.Direction.Values[0].Value = 0, 0, HarnessPose.Flat);
|
||||
yield return ("elevation-35-to-60", () => Create(), effect => effect.Elevation.Values[0].Value = 60, 0, HarnessPose.Flat);
|
||||
yield return ("spread-12-to-minus-20", () => Create(), effect => effect.Spread.Values[0].Value = -20, 0, HarnessPose.Flat);
|
||||
yield return ("length-1200-to-500", () => Create(), effect => effect.Length.Values[0].Value = 500, 0, HarnessPose.Flat);
|
||||
yield return ("intensity-150-to-30", () => Create(), effect => effect.Intensity.Values[0].Value = 30, 0, HarnessPose.Flat);
|
||||
yield return ("threshold-25-to-70", () => Create(), effect => effect.Threshold.Values[0].Value = 70, 0, HarnessPose.Flat);
|
||||
yield return ("threshold-70-to-10", () => Create(effect => effect.Threshold.Values[0].Value = 70), effect => effect.Threshold.Values[0].Value = 10, 0, HarnessPose.Flat);
|
||||
yield return ("tint-white-to-blue", () => Create(), effect => effect.Tint = System.Windows.Media.Color.FromRgb(90, 140, 255), 0, HarnessPose.Flat);
|
||||
yield return ("show-source-on-to-off", () => Create(), effect => effect.ShowSource = false, 0, HarnessPose.Flat);
|
||||
yield return ("show-source-off-to-on", () => Create(effect => effect.ShowSource = false), effect => effect.ShowSource = true, 0, HarnessPose.Flat);
|
||||
yield return ("dust-0-to-60", () => Create(), effect => effect.DustAmount.Values[0].Value = 60, 90, HarnessPose.Flat);
|
||||
yield return ("quality-standard-to-ultra", () => Create(), effect => effect.Quality = VolumetricLightQuality.Ultra, 0, HarnessPose.Flat);
|
||||
yield return ("falloff-60-to-0", () => Create(), effect => effect.Falloff.Values[0].Value = 0, 0, HarnessPose.Flat);
|
||||
yield return ("scattering-30-to-minus-50", () => Create(), effect => effect.Scattering.Values[0].Value = -50, 0, HarnessPose.Flat);
|
||||
yield return ("lamp-size-1.5-to-6", () => Create(), effect => effect.LampSize.Values[0].Value = 6, 0, HarnessPose.Flat);
|
||||
yield return ("rotated-y-length-1200-to-500", () => Create(), effect => effect.Length.Values[0].Value = 500, 0, RotatedY);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, VolumetricLightEffect Effect, HarnessPose Pose)> Benchmarks()
|
||||
{
|
||||
yield return ("default", Create(), HarnessPose.Flat);
|
||||
yield return ("quality-ultra", Create(effect => effect.Quality = VolumetricLightQuality.Ultra), HarnessPose.Flat);
|
||||
yield return ("dust-60", Create(effect => effect.DustAmount.Values[0].Value = 60), HarnessPose.Flat);
|
||||
yield return ("pose-rotated-y", Create(), RotatedY);
|
||||
yield return ("direction-animated", Create(effect => effect.Direction.CopyFrom(Linear(-150d, -30d))), HarnessPose.Flat);
|
||||
}
|
||||
|
||||
static Animation Linear(double from, double to)
|
||||
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}""")) ?? throw new HarnessException("アニメーションを読み込めません。");
|
||||
|
||||
public static VolumetricLightEffect Create(Action<VolumetricLightEffect>? configure = null)
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
configure?.Invoke(effect);
|
||||
return effect;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,12 @@ internal sealed record HarnessImage(int Width, int Height, byte[] Pixels, string
|
||||
return new HarnessImage(width, height, pixels, $"synthetic {width}x{height} {Convert.ToHexString(SHA256.HashData(pixels))[..KeyLength]}", null);
|
||||
}
|
||||
|
||||
public static HarnessImage Silhouette(int width, int height)
|
||||
{
|
||||
var pixels = SyntheticImage.CreateSilhouette(width, height);
|
||||
return new HarnessImage(width, height, pixels, $"silhouette {width}x{height} {Convert.ToHexString(SHA256.HashData(pixels))[..KeyLength]}", null);
|
||||
}
|
||||
|
||||
public static HarnessImage Load(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Harness;
|
||||
|
||||
internal sealed record HarnessOccluder(VolumetricLightOccluderEffect Effect, HarnessPose Pose, HarnessImage Image, Guid Scene = default, int FrameOffset = 0);
|
||||
|
||||
internal sealed class HarnessOccluderScene : IDisposable
|
||||
{
|
||||
sealed class Entry(HarnessOccluder occluder, ID2D1Bitmap1 bitmap, AffineTransform2D placement, ID2D1Image centered, IVideoEffectProcessor blocker, IVideoEffectProcessor display) : IDisposable
|
||||
{
|
||||
public HarnessOccluder Occluder { get; } = occluder;
|
||||
|
||||
public IVideoEffectProcessor Blocker { get; } = blocker;
|
||||
|
||||
public IVideoEffectProcessor Display { get; } = display;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Blocker.ClearInput();
|
||||
Display.ClearInput();
|
||||
Blocker.Dispose();
|
||||
Display.Dispose();
|
||||
placement.SetInput(0, null, true);
|
||||
centered.Dispose();
|
||||
placement.Dispose();
|
||||
bitmap.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
readonly List<Entry> entries = [];
|
||||
|
||||
public HarnessOccluderScene(IGraphicsDevicesAndContext context, IReadOnlyList<HarnessOccluder> occluders)
|
||||
{
|
||||
foreach (var occluder in occluders)
|
||||
{
|
||||
var bitmap = HarnessRenderer.CreateBitmap(context.DeviceContext, occluder.Image.Width, occluder.Image.Height, Vortice.Direct2D1.BitmapOptions.None);
|
||||
bitmap.CopyFromMemory(occluder.Image.Pixels, occluder.Image.Width * HarnessImage.BytesPerPixel);
|
||||
var placement = new AffineTransform2D(context.DeviceContext)
|
||||
{
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(-occluder.Image.Width * 0.5f, -occluder.Image.Height * 0.5f),
|
||||
};
|
||||
placement.SetInput(0, bitmap, true);
|
||||
var centered = placement.Output;
|
||||
var blocker = occluder.Effect.CreateVideoEffect(context);
|
||||
blocker.SetInput(centered);
|
||||
var displayEffect = new VolumetricLightEffect();
|
||||
displayEffect.Intensity.Values[0].Value = 0d;
|
||||
var display = displayEffect.CreateVideoEffect(context);
|
||||
display.SetInput(centered);
|
||||
entries.Add(new Entry(occluder, bitmap, placement, centered, blocker, display));
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<ID2D1Image> Layers => entries.Select(entry => entry.Display.Output);
|
||||
|
||||
public void Update(Func<int, HarnessPose?, Guid, EffectDescription> describe, int frame)
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var description = describe(frame + entry.Occluder.FrameOffset, entry.Occluder.Pose, entry.Occluder.Scene);
|
||||
entry.Blocker.Update(description);
|
||||
entry.Display.Update(description);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
entry.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace VolumetricLight.Harness;
|
||||
|
||||
internal sealed record HarnessPose(Vector3 Draw, Vector3 Rotation, Vector2 Zoom, Matrix4x4 Camera, bool Invert, float? PerspectiveDistance = null)
|
||||
{
|
||||
const float CameraPivotDepth = 1000f;
|
||||
|
||||
public static HarnessPose Flat { get; } = new(Vector3.Zero, Vector3.Zero, Vector2.One, Matrix4x4.Identity, false);
|
||||
|
||||
public static Matrix4x4 CameraAt(Vector3 position, Vector3 rotationDegrees)
|
||||
{
|
||||
var translation = new Vector3(position.X, position.Y, -position.Z);
|
||||
var pivot = new Vector3(0f, 0f, CameraPivotDepth);
|
||||
return Matrix4x4.CreateTranslation(-translation)
|
||||
* Matrix4x4.CreateRotationY(MathF.PI * rotationDegrees.Y / 180f, pivot)
|
||||
* Matrix4x4.CreateRotationX(MathF.PI * rotationDegrees.X / 180f, pivot)
|
||||
* Matrix4x4.CreateRotationZ(MathF.PI * rotationDegrees.Z / 180f, pivot);
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,12 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
{
|
||||
const int Fps = 30;
|
||||
const int Length = 300;
|
||||
const int WarmupUpdates = 2000;
|
||||
const int UpdateRepeats = 20;
|
||||
const int WarmupUpdates = 100;
|
||||
const int UpdateRepeats = 5;
|
||||
const float Dpi = 96f;
|
||||
|
||||
static readonly Color4 Backdrop = new(0f, 0f, 0f, 1f);
|
||||
|
||||
static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
|
||||
readonly GraphicsDevices devices;
|
||||
@@ -67,11 +69,12 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
|
||||
public string Driver { get; }
|
||||
|
||||
public byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames)
|
||||
public byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames, HarnessPose? pose = null, IReadOnlyList<HarnessOccluder>? occluders = null)
|
||||
{
|
||||
if (frames.Count == 0)
|
||||
throw new ArgumentException("フレームを 1 つ以上指定してください。", nameof(frames));
|
||||
|
||||
using var scene = new HarnessOccluderScene(context, occluders ?? []);
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
@@ -79,8 +82,9 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
var rendered = new byte[frames.Count][];
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
processor.Update(Describe(frames[index]));
|
||||
rendered[index] = Capture(processor.Output);
|
||||
scene.Update(Describe, frames[index]);
|
||||
processor.Update(Describe(frames[index], pose));
|
||||
rendered[index] = Capture(processor.Output, scene.Layers);
|
||||
}
|
||||
|
||||
return rendered;
|
||||
@@ -91,22 +95,22 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public (byte[] Direct, byte[] Transitioned) RenderTransition<TEffect>(Func<TEffect> create, Action<TEffect> change, int frame)
|
||||
public (byte[] Direct, byte[] Transitioned) RenderTransition<TEffect>(Func<TEffect> create, Action<TEffect> change, int frame, HarnessPose? pose = null)
|
||||
where TEffect : IVideoEffect
|
||||
{
|
||||
var settled = create();
|
||||
change(settled);
|
||||
var direct = Render(settled, [frame])[0];
|
||||
var direct = Render(settled, [frame], pose)[0];
|
||||
|
||||
var live = create();
|
||||
using var processor = live.CreateVideoEffect(context);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
{
|
||||
processor.Update(Describe(frame));
|
||||
processor.Update(Describe(frame, pose));
|
||||
_ = Capture(processor.Output);
|
||||
change(live);
|
||||
processor.Update(Describe(frame));
|
||||
processor.Update(Describe(frame, pose));
|
||||
return (direct, Capture(processor.Output));
|
||||
}
|
||||
finally
|
||||
@@ -115,11 +119,11 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public Measurement Measure(IVideoEffect effect, int frames, bool moving)
|
||||
public Measurement Measure(IVideoEffect effect, int frames, bool moving, HarnessPose? pose = null)
|
||||
{
|
||||
var descriptions = new EffectDescription[frames];
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
descriptions[frame] = Describe(moving ? frame : 0);
|
||||
descriptions[frame] = Describe(moving ? frame : 0, pose);
|
||||
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(centered);
|
||||
@@ -182,9 +186,9 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
byte[] Capture(ID2D1Image output)
|
||||
byte[] Capture(ID2D1Image output, IEnumerable<ID2D1Image>? overlays = null)
|
||||
{
|
||||
Submit(output);
|
||||
Submit(output, overlays);
|
||||
readback.CopyFromBitmap(target);
|
||||
|
||||
var stride = CanvasWidth * HarnessImage.BytesPerPixel;
|
||||
@@ -203,13 +207,16 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
return pixels;
|
||||
}
|
||||
|
||||
void Submit(ID2D1Image output)
|
||||
void Submit(ID2D1Image output, IEnumerable<ID2D1Image>? overlays = null)
|
||||
{
|
||||
var deviceContext = context.DeviceContext;
|
||||
var origin = new Vector2(CanvasWidth * 0.5f, CanvasHeight * 0.5f);
|
||||
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.Clear(Backdrop);
|
||||
deviceContext.DrawImage(output, origin, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceOver);
|
||||
foreach (var overlay in overlays ?? [])
|
||||
deviceContext.DrawImage(overlay, origin, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceOver);
|
||||
deviceContext.EndDraw();
|
||||
deviceContext.Target = null;
|
||||
}
|
||||
@@ -221,7 +228,7 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
sync.Unmap();
|
||||
}
|
||||
|
||||
EffectDescription Describe(int frame)
|
||||
internal EffectDescription Describe(int frame, HarnessPose? pose, Guid scene = default)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
new System.Drawing.Size(CanvasWidth, CanvasHeight),
|
||||
@@ -229,14 +236,18 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
new YukkuriMovieMaker.Player.Video.FrameTime(Length, Fps),
|
||||
Fps,
|
||||
TimelineSourceUsage.Playing,
|
||||
Guid.Empty,
|
||||
scene,
|
||||
[]);
|
||||
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, []);
|
||||
var placement = pose ?? HarnessPose.Flat;
|
||||
var draw = new DrawDescription(placement.Draw, Vector2.Zero, placement.Zoom, placement.Rotation, placement.Camera, InterpolationMode.Linear, 1d, placement.Invert, [])
|
||||
{
|
||||
PerspectiveDistance = placement.PerspectiveDistance,
|
||||
};
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
|
||||
static ID2D1Bitmap1 CreateBitmap(ID2D1DeviceContext6 deviceContext, int width, int height, BitmapOptions options)
|
||||
internal 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));
|
||||
|
||||
@@ -6,8 +6,8 @@ using SharpGen.Runtime;
|
||||
|
||||
const int CanvasWidth = 1280;
|
||||
const int CanvasHeight = 720;
|
||||
const int ImageWidth = 640;
|
||||
const int ImageHeight = 480;
|
||||
const int ImageWidth = 960;
|
||||
const int ImageHeight = 540;
|
||||
const int FullHdWidth = 1920;
|
||||
const int FullHdHeight = 1080;
|
||||
|
||||
@@ -35,12 +35,12 @@ try
|
||||
{
|
||||
if (arguments.Input is { } benchmarkInput)
|
||||
{
|
||||
Benchmark(HarnessImage.Load(benchmarkInput));
|
||||
Benchmark(HarnessImage.Load(benchmarkInput), arguments.Case);
|
||||
}
|
||||
else
|
||||
{
|
||||
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
|
||||
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
|
||||
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight), arguments.Case);
|
||||
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight), arguments.Case);
|
||||
}
|
||||
|
||||
return 0;
|
||||
@@ -53,7 +53,7 @@ try
|
||||
HarnessMode.Golden => WriteGolden(renderer, image),
|
||||
HarnessMode.Verify => Verify(renderer, image),
|
||||
HarnessMode.Transition => Transition(renderer, outputDirectory),
|
||||
_ => Render(renderer, outputDirectory),
|
||||
_ => Render(renderer, outputDirectory, arguments.Case),
|
||||
};
|
||||
}
|
||||
catch (Exception exception) when (exception is HarnessException or SharpGenException)
|
||||
@@ -62,21 +62,21 @@ catch (Exception exception) when (exception is HarnessException or SharpGenExcep
|
||||
return 2;
|
||||
}
|
||||
|
||||
static int Render(HarnessRenderer renderer, string outputDirectory)
|
||||
static int Render(HarnessRenderer renderer, string outputDirectory, string? caseFilter)
|
||||
{
|
||||
Directory.CreateDirectory(outputDirectory);
|
||||
var failures = 0;
|
||||
var cases = Evaluate(renderer, (golden, files, frames) =>
|
||||
var cases = Evaluate(renderer, caseFilter, (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)
|
||||
var lit = CountLit(frames[index]);
|
||||
Console.WriteLine($" {files[index]} lit={lit}");
|
||||
if (lit == 0)
|
||||
{
|
||||
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
|
||||
Console.Error.WriteLine($"{files[index]}: 出力が真っ黒です。");
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ static int Render(HarnessRenderer renderer, string outputDirectory)
|
||||
|
||||
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
|
||||
{
|
||||
var cases = Evaluate(renderer, null);
|
||||
var cases = Evaluate(renderer, null, null);
|
||||
if (CountDuplicates(cases) != 0)
|
||||
return 1;
|
||||
if (cases.Count == 0)
|
||||
@@ -118,7 +118,7 @@ static int Verify(HarnessRenderer renderer, HarnessImage image)
|
||||
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);
|
||||
var current = Evaluate(renderer, null, 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)
|
||||
@@ -156,9 +156,9 @@ static int Verify(HarnessRenderer renderer, HarnessImage image)
|
||||
static int Transition(HarnessRenderer renderer, string outputDirectory)
|
||||
{
|
||||
var failures = 0;
|
||||
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
|
||||
foreach (var (name, create, change, frame, pose) in HarnessCases.Transitions())
|
||||
{
|
||||
var (direct, transitioned) = renderer.RenderTransition(create, change, frame);
|
||||
var (direct, transitioned) = renderer.RenderTransition(create, change, frame, pose);
|
||||
var difference = ImageComparison.Of(direct, transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
if (difference.IsEmpty)
|
||||
{
|
||||
@@ -173,18 +173,18 @@ static int Transition(HarnessRenderer renderer, string outputDirectory)
|
||||
Console.Error.WriteLine($"{name}: {difference}。設定を変えた後の描画が作り直した場合と違います。-> {outputDirectory}");
|
||||
}
|
||||
|
||||
if (!HarnessCases.Transitions().Any() && !HarnessCases.All().Any(item => item.Frames.Count > 1))
|
||||
if (!HarnessCases.Transitions().Any() && !HarnessCases.Everything().Any(item => item.Frames.Count > 1))
|
||||
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
|
||||
|
||||
foreach (var (name, effect, frames) in HarnessCases.All())
|
||||
foreach (var (name, effect, frames, pose, occluders) in HarnessCases.Everything())
|
||||
{
|
||||
if (frames.Count < 2)
|
||||
continue;
|
||||
|
||||
var sequential = renderer.Render(effect, frames);
|
||||
var sequential = renderer.Render(effect, frames, pose, occluders);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
var fresh = renderer.Render(effect, [frames[index]])[0];
|
||||
var fresh = renderer.Render(effect, [frames[index]], pose, occluders)[0];
|
||||
var difference = ImageComparison.Of(fresh, sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
var label = $"{name}-f{frames[index]:D3}";
|
||||
if (difference.IsEmpty)
|
||||
@@ -248,37 +248,42 @@ static int Compare(string beforeDirectory, string afterDirectory)
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static void Benchmark(HarnessImage image)
|
||||
static void Benchmark(HarnessImage image, string? caseFilter)
|
||||
{
|
||||
const int Frames = 60;
|
||||
const int Frames = 12;
|
||||
|
||||
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())
|
||||
foreach (var (name, effect, pose) in HarnessCases.Benchmarks())
|
||||
{
|
||||
Report(image, name, "still", renderer.Measure(effect, Frames, moving: false));
|
||||
Report(image, name, "moving", renderer.Measure(effect, Frames, moving: true));
|
||||
if (caseFilter is not null && !name.Contains(caseFilter, StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
Report(image, name, "still", renderer.Measure(effect, Frames, moving: false, pose));
|
||||
Report(image, name, "moving", renderer.Measure(effect, Frames, moving: true, pose));
|
||||
}
|
||||
}
|
||||
|
||||
static void Report(HarnessImage image, string name, string motion, HarnessRenderer.Measurement measurement)
|
||||
=> Console.WriteLine(
|
||||
$"{image.Width}x{image.Height} {name,-15} {motion,-6} " +
|
||||
$"{image.Width}x{image.Height} {name,-22} {motion,-6} " +
|
||||
$"gpu={(measurement.Gpu is { } gpu ? gpu.TotalMilliseconds.ToString("F3") : "n/a"),7} " +
|
||||
$"cpu={measurement.Cpu.TotalMilliseconds,7:F3} " +
|
||||
$"update={measurement.Update.TotalMilliseconds,6:F3} " +
|
||||
$"alloc={measurement.Allocated,6} gen0={measurement.Gen0}");
|
||||
|
||||
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
|
||||
static List<GoldenCase> Evaluate(HarnessRenderer renderer, string? caseFilter, Action<GoldenCase, string[], byte[][]>? report)
|
||||
{
|
||||
var cases = new List<GoldenCase>();
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var (name, effect, frames) in HarnessCases.All())
|
||||
foreach (var (name, effect, frames, pose, occluders) in HarnessCases.Everything())
|
||||
{
|
||||
if (!names.Add(name))
|
||||
throw new HarnessException($"ケース名が重複しています。{name}");
|
||||
if (caseFilter is not null && !name.Contains(caseFilter, StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
var rendered = renderer.Render(effect, frames);
|
||||
var rendered = renderer.Render(effect, frames, pose, occluders);
|
||||
var files = new string[frames.Count];
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
@@ -315,12 +320,12 @@ static int CountDuplicates(IReadOnlyList<GoldenCase> cases)
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
static int CountOpaque(byte[] pixels)
|
||||
static int CountLit(byte[] pixels)
|
||||
{
|
||||
var count = 0;
|
||||
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
|
||||
for (var offset = 0; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
|
||||
{
|
||||
if (pixels[offset] != 0)
|
||||
if (pixels[offset] != 0 || pixels[offset + 1] != 0 || pixels[offset + 2] != 0)
|
||||
count++;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,44 +2,99 @@ namespace VolumetricLight.Harness;
|
||||
|
||||
internal static class SyntheticImage
|
||||
{
|
||||
const int GridPitch = 32;
|
||||
const int Samples = 4;
|
||||
const float LeadWidthFraction = 0.006f;
|
||||
const float StoneLevel = 0.03f;
|
||||
const float LeadLevel = 0.02f;
|
||||
const int ColumnsPerWindow = 3;
|
||||
const float RowHeightFraction = 0.095f;
|
||||
|
||||
static readonly (float Red, float Green, float Blue)[] Palette =
|
||||
[
|
||||
(0.10f, 0.22f, 0.95f),
|
||||
(0.95f, 0.10f, 0.16f),
|
||||
(1.00f, 0.62f, 0.10f),
|
||||
(0.10f, 0.72f, 0.32f),
|
||||
(0.62f, 0.20f, 0.85f),
|
||||
(0.10f, 0.72f, 0.92f),
|
||||
(0.97f, 0.32f, 0.62f),
|
||||
(1.00f, 0.92f, 0.24f),
|
||||
];
|
||||
|
||||
static readonly (float Center, float HalfWidth, float Top)[] Windows =
|
||||
[
|
||||
(0.20f, 0.105f, 0.30f),
|
||||
(0.50f, 0.130f, 0.10f),
|
||||
(0.80f, 0.105f, 0.30f),
|
||||
];
|
||||
|
||||
const float WindowBottom = 0.93f;
|
||||
|
||||
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;
|
||||
|
||||
var lead = LeadWidthFraction * width;
|
||||
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 red = 0f;
|
||||
var green = 0f;
|
||||
var blue = 0f;
|
||||
for (var sy = 0; sy < Samples; sy++)
|
||||
{
|
||||
for (var sx = 0; sx < Samples; sx++)
|
||||
{
|
||||
var (r, g, b) = Shade(x + (sx + 0.5f) / Samples, y + (sy + 0.5f) / Samples, width, height, lead);
|
||||
red += r;
|
||||
green += g;
|
||||
blue += b;
|
||||
}
|
||||
}
|
||||
|
||||
var scale = 1f / (Samples * Samples);
|
||||
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
|
||||
pixels[offset] = ToByte(blue);
|
||||
pixels[offset + 1] = ToByte(green);
|
||||
pixels[offset + 2] = ToByte(red);
|
||||
pixels[offset] = ToByte(blue * scale);
|
||||
pixels[offset + 1] = ToByte(green * scale);
|
||||
pixels[offset + 2] = ToByte(red * scale);
|
||||
pixels[offset + 3] = byte.MaxValue;
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
const float SilhouetteLevel = 0.02f;
|
||||
const float HeadRadiusFraction = 0.13f;
|
||||
const float HeadCenterFraction = 0.2f;
|
||||
const float NeckHalfWidthFraction = 0.09f;
|
||||
const float ShoulderTopFraction = 0.36f;
|
||||
const float ShoulderHalfWidthFraction = 0.46f;
|
||||
const float BodyHalfWidthFraction = 0.34f;
|
||||
const float ShoulderRoundFraction = 0.12f;
|
||||
|
||||
public static byte[] CreateSilhouette(int width, int height)
|
||||
{
|
||||
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var covered = 0;
|
||||
for (var sy = 0; sy < Samples; sy++)
|
||||
{
|
||||
for (var sx = 0; sx < Samples; sx++)
|
||||
{
|
||||
if (InsideSilhouette((x + (sx + 0.5f) / Samples) / width, (y + (sy + 0.5f) / Samples) / height, height / (float)width))
|
||||
covered++;
|
||||
}
|
||||
}
|
||||
|
||||
var alpha = covered / (float)(Samples * Samples);
|
||||
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
|
||||
pixels[offset] = ToByte(SilhouetteLevel * alpha);
|
||||
pixels[offset + 1] = ToByte(SilhouetteLevel * alpha);
|
||||
pixels[offset + 2] = ToByte(SilhouetteLevel * alpha);
|
||||
pixels[offset + 3] = ToByte(alpha);
|
||||
}
|
||||
}
|
||||
@@ -47,5 +102,96 @@ internal static class SyntheticImage
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static bool InsideSilhouette(float u, float v, float aspect)
|
||||
{
|
||||
var dx = u - 0.5f;
|
||||
var headDy = (v - HeadCenterFraction) * aspect;
|
||||
if (dx * dx + headDy * headDy < HeadRadiusFraction * HeadRadiusFraction)
|
||||
return true;
|
||||
|
||||
if (v > HeadCenterFraction && v < ShoulderTopFraction && MathF.Abs(dx) < NeckHalfWidthFraction)
|
||||
return true;
|
||||
|
||||
if (v < ShoulderTopFraction)
|
||||
return false;
|
||||
|
||||
var halfWidth = v < ShoulderTopFraction + ShoulderRoundFraction
|
||||
? NeckHalfWidthFraction + (ShoulderHalfWidthFraction - NeckHalfWidthFraction) * MathF.Sqrt(1f - MathF.Pow(1f - (v - ShoulderTopFraction) / ShoulderRoundFraction, 2f))
|
||||
: BodyHalfWidthFraction + (ShoulderHalfWidthFraction - BodyHalfWidthFraction) * Math.Max(0f, 1f - (v - ShoulderTopFraction - ShoulderRoundFraction) * 6f);
|
||||
return MathF.Abs(dx) < halfWidth;
|
||||
}
|
||||
|
||||
static (float Red, float Green, float Blue) Shade(float x, float y, int width, int height, float lead)
|
||||
{
|
||||
for (var index = 0; index < Windows.Length; index++)
|
||||
{
|
||||
var (centerFraction, halfFraction, topFraction) = Windows[index];
|
||||
var centerX = centerFraction * width;
|
||||
var halfWidth = halfFraction * width;
|
||||
var top = topFraction * height;
|
||||
var bottom = WindowBottom * height;
|
||||
var arcCenterY = top + halfWidth;
|
||||
if (!Inside(x, y, centerX, halfWidth, arcCenterY, bottom, out var edge))
|
||||
continue;
|
||||
|
||||
if (edge < lead)
|
||||
return (LeadLevel, LeadLevel, LeadLevel);
|
||||
|
||||
var cellWidth = 2f * halfWidth / ColumnsPerWindow;
|
||||
var cellHeight = RowHeightFraction * height;
|
||||
var localX = x - (centerX - halfWidth);
|
||||
var localY = y - top;
|
||||
var column = (int)MathF.Floor(localX / cellWidth);
|
||||
var row = (int)MathF.Floor(localY / cellHeight);
|
||||
var gridX = MathF.Abs(localX - MathF.Round(localX / cellWidth) * cellWidth);
|
||||
var gridY = MathF.Abs(localY - MathF.Round(localY / cellHeight) * cellHeight);
|
||||
if (MathF.Min(gridX, gridY) < lead * 0.5f)
|
||||
return (LeadLevel, LeadLevel, LeadLevel);
|
||||
|
||||
var entry = Palette[(int)(Hash(column + 7 * row + 31 * index) % (uint)Palette.Length)];
|
||||
var shade = 1f - 0.35f * (y - top) / (bottom - top);
|
||||
return (entry.Red * shade, entry.Green * shade, entry.Blue * shade);
|
||||
}
|
||||
|
||||
return (StoneLevel, StoneLevel, StoneLevel);
|
||||
}
|
||||
|
||||
static bool Inside(float x, float y, float centerX, float halfWidth, float arcCenterY, float bottom, out float edge)
|
||||
{
|
||||
edge = 0f;
|
||||
if (y > bottom)
|
||||
return false;
|
||||
|
||||
if (y >= arcCenterY)
|
||||
{
|
||||
var side = halfWidth - MathF.Abs(x - centerX);
|
||||
if (side < 0f)
|
||||
return false;
|
||||
|
||||
edge = MathF.Min(side, bottom - y);
|
||||
return true;
|
||||
}
|
||||
|
||||
var dx = x - centerX;
|
||||
var dy = y - arcCenterY;
|
||||
var distance = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (distance > halfWidth)
|
||||
return false;
|
||||
|
||||
edge = halfWidth - distance;
|
||||
return true;
|
||||
}
|
||||
|
||||
static uint Hash(int value)
|
||||
{
|
||||
var hash = (uint)value;
|
||||
hash ^= hash >> 16;
|
||||
hash *= 0x85EBCA6Bu;
|
||||
hash ^= hash >> 13;
|
||||
hash *= 0xC2B2AE35u;
|
||||
hash ^= hash >> 16;
|
||||
return hash;
|
||||
}
|
||||
|
||||
static byte ToByte(float premultiplied) => (byte)MathF.Round(Math.Clamp(premultiplied, 0f, 1f) * byte.MaxValue);
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
{
|
||||
"adapter": "Intel(R) Iris(R) Xe Graphics",
|
||||
"driver": "32.0.101.7085",
|
||||
"input": "synthetic 960x540 6A51E0BB2329D7D8",
|
||||
"canvas": "1280x720",
|
||||
"cases": [
|
||||
{
|
||||
"name": "default",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8C7594D4CD2E86E488691FE5A613DF9CAA80DEDFD2C27587209E15E70A095B99"
|
||||
},
|
||||
{
|
||||
"name": "direction-animated-frames",
|
||||
"frames": [
|
||||
0,
|
||||
100,
|
||||
200,
|
||||
299
|
||||
],
|
||||
"hash": "77221A367FB617685BA7B685C316D8C5099C3EB7A779488ABD2354782BB0BD51"
|
||||
},
|
||||
{
|
||||
"name": "direction-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9FFC30E5745BC3D15638067AC14CAC801433D45F498927C0802A238D3D7B2FA6"
|
||||
},
|
||||
{
|
||||
"name": "direction-180",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "CDE0A57368699F9FFF33D6DCBAA47050FFDD4E699DC67C810980B4592A6587A2"
|
||||
},
|
||||
{
|
||||
"name": "elevation-15",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8A7D3E7AFD8CA0527F5A6BCF5361695CC262DFC72B7BDA9B6C56BBFA9AF374D2"
|
||||
},
|
||||
{
|
||||
"name": "elevation-70",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "41A69C802D7EC73FF611299B0CA84961B4368805B2975DB7A7DCF414C282A200"
|
||||
},
|
||||
{
|
||||
"name": "elevation-minus-35",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E0032A1E1185C048444D87CDD63FC46E99B7B143EB3E025DF625710716BC3AA1"
|
||||
},
|
||||
{
|
||||
"name": "spread-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "19418CF8B1A86E5B77BEB3B44ADBE2130B04FEC6C1B54E283C97CF3755991320"
|
||||
},
|
||||
{
|
||||
"name": "spread-35",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B43ED039FEC53DF05E14E4CA6B59759C1639633B7EEDE3217E15472E6735F151"
|
||||
},
|
||||
{
|
||||
"name": "spread-minus-25",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9D06FB5C6E86CED02E97305545D7DDD7037D4F86552FAB31B7E0E217BFF0D9A0"
|
||||
},
|
||||
{
|
||||
"name": "length-400",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "30693587F5870AC63B2EDF7A379A29C00906EF6D983B36989FBAC24C10676F49"
|
||||
},
|
||||
{
|
||||
"name": "length-2800",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4EA4F0FCF705DBB9BBA3732897F14EF4058B97BEF48C22AA839EAE6E600055AE"
|
||||
},
|
||||
{
|
||||
"name": "length-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1235FE946041792635D34CED5FEF36B0988A14088518D99397D71C92C9241403"
|
||||
},
|
||||
{
|
||||
"name": "intensity-40",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7CAF9B0FC93C6F3C2B83A3403E4B266E98E50A1146DAE4C2CF7A533F9830ABB5"
|
||||
},
|
||||
{
|
||||
"name": "intensity-250",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6156067CB7C72567462B9352B2A0FCFD0DF6C8D0E11804261170DC90A4DA3F9D"
|
||||
},
|
||||
{
|
||||
"name": "threshold-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4558510EDA9233BF273E5F52A535E4F041A091105733AA6A679BC928D1A95349"
|
||||
},
|
||||
{
|
||||
"name": "threshold-60",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3FEB56A665A4A853CEC4BD049E4BA44552FE1411CE3F190D922F523EB21BEF63"
|
||||
},
|
||||
{
|
||||
"name": "tint-amber",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8E58F973B08F627AFF6DA964653334FC72079CDABB2B02BC4FEBD3532EDDF24D"
|
||||
},
|
||||
{
|
||||
"name": "falloff-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D76415C45548F3770C1C7CCD1E7FA7A93B94FBC14293296A0726FFD534A46C97"
|
||||
},
|
||||
{
|
||||
"name": "falloff-95",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "202E82C3210B3FAD7786F5B8CA98762E341316CECE0A68C02F2D439877591EB1"
|
||||
},
|
||||
{
|
||||
"name": "lamp-size-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AB24D7F3B6DB47A078B7E4E04B30BCCA1AC7C7826B0543C05B5DFCFF91446ECD"
|
||||
},
|
||||
{
|
||||
"name": "lamp-size-6",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "BE08D97F9FED059B2EB09321A87AA6BA22514121914A3ABD9B40A537965420E8"
|
||||
},
|
||||
{
|
||||
"name": "scattering-minus-60",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7B1E6C7307D93EDD776198D84A8021439BB46D81AAE99B19D21E76B5A20AA3A3"
|
||||
},
|
||||
{
|
||||
"name": "scattering-85",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1EC65D8E4BFC30D55A52B03070274D57C31B3D6E90988F7F603AB1FDBD26F4DC"
|
||||
},
|
||||
{
|
||||
"name": "source-hidden",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "ACB0D0AE498CDC2B5D49C0F2087FB5F1ECDCB36E79A1DC34C1AC2F338D9161C9"
|
||||
},
|
||||
{
|
||||
"name": "dust-60",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "73067DEB8B7BDDB9EC8D69B8CF5060C2DE8F109CD1E13AF1974F02DA6B04C196"
|
||||
},
|
||||
{
|
||||
"name": "dust-60-animated-frames",
|
||||
"frames": [
|
||||
0,
|
||||
90,
|
||||
180
|
||||
],
|
||||
"hash": "CC0CBA43D0F8060B2B09741F8EA9681C3299C5FF9AA992BC4C6E9DDC137CE84F"
|
||||
},
|
||||
{
|
||||
"name": "dust-seed-7",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8D721AB792A0D2048F73C86013960D234697FE5C6141F663A98958870AAA5A5B"
|
||||
},
|
||||
{
|
||||
"name": "quality-high",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "322333481D79A16D0599E1316261B6EC41668AB6CF8E6D870889497B51BC1B58"
|
||||
},
|
||||
{
|
||||
"name": "quality-ultra",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "338B953EACEB00CDB803327228060756CA5ECE48EEB40EA650974425493939CC"
|
||||
},
|
||||
{
|
||||
"name": "pose-rotated-y",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "CB75312042B9C442148870DBC62E66EDCA9B6BB674706A6F343DA49E690E9E18"
|
||||
},
|
||||
{
|
||||
"name": "pose-rotated-x",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "06FF1E795A6984C57BB6C44A9F10269C621E901092D66674677BBFF6EDF9280F"
|
||||
},
|
||||
{
|
||||
"name": "pose-rotated-z",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5FCAB8B93ED45E96731C28A16C8C51ABBE1EF428F2C9C0860FE675B36E71F9C6"
|
||||
},
|
||||
{
|
||||
"name": "pose-shrunk",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "F79342FCE10B0494D8EECB8DFC234C74F219C581434965FC6CB39AF568996493"
|
||||
},
|
||||
{
|
||||
"name": "pose-offset",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D49A0B11B01C8C4FB35D1C8604EB231248D821E36CE833E08BB617EC0567ED1C"
|
||||
},
|
||||
{
|
||||
"name": "pose-near",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9F41B6C7BB5D9FD9245CD5CB0E06A502E7613E1E249B8A28CC86FBBED1738637"
|
||||
},
|
||||
{
|
||||
"name": "pose-mirrored",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DC258106CA130AF7D9D3F937E24CA5B35F7AE752A6F46385BDD9D05B11BBD748"
|
||||
},
|
||||
{
|
||||
"name": "pose-orbit",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3813DBE687FC6CA379CBA5885AFFCB3E1E90ABDE646FDE8E51AB36E744401CEA"
|
||||
},
|
||||
{
|
||||
"name": "pose-telephoto",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "17CD7C9969DCD10E85A0FFC50C79D69DEF33CDA36FFCFFCA023708E8CD360211"
|
||||
},
|
||||
{
|
||||
"name": "pose-rotated-y-converging",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FCDA7898A1348764430DFEDFCB1881788BC49E2422E1E41636FA676A0C98920E"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "85AA906B4218F1ED6BED71C94BC973A64F9FCE1FC79CB986964613F5689C2E62"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-default-light",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1A4F09029ABB1D29F8CAE9BE65E3FF3CA6D2F97FE1580CF2AECB45BD9CC85C8B"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-point-light",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E9C02F93C4A29C6CF11DF205D09364594F06E69863928E80898C2A716F785206"
|
||||
},
|
||||
{
|
||||
"name": "shadow-two-figures",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "99070A5A660094BAB227022FCE8CB0A7C6B66B79AEBA4C4DE85E0C26AF40A471"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-half-strength",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "45F8CC71613C9A2DEDB095247AF962C8D8105042D4E30D5152AA13B7EBAD4398"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-strength-animated-frames",
|
||||
"frames": [
|
||||
0,
|
||||
150,
|
||||
299
|
||||
],
|
||||
"hash": "B448BCCDFAFFB5E90BC6D8D934CF8FA81C49DC0D1D35444A898F8871A7AC027F"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-rotated-light",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6885C2736451491A0EC78156B9813B642238350992D3F33BF52435E1ADC9DE83"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-other-scene",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "44996CD0E824BAE692A7BFF8063E42BFEA76A8E1997B93A86584B92956835454"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-other-frame",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "91CC1D8F8948BE95E71C93CFE47816849FDF2A03D1DA5E7752059F401CB0774F"
|
||||
},
|
||||
{
|
||||
"name": "shadow-figure-other-number",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1A51B17D1AED60E09859C11096786A0D26CF07D15308896E28B3596A063A5CA8"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -4,12 +4,20 @@ Texture2D Level2 : register(t2);
|
||||
Texture2D Level3 : register(t3);
|
||||
Texture2D Level4 : register(t4);
|
||||
Texture2D Level5 : register(t5);
|
||||
Texture2D Occluder0 : register(t6);
|
||||
Texture2D Occluder1 : register(t7);
|
||||
Texture2D Occluder2 : register(t8);
|
||||
Texture2D Occluder3 : register(t9);
|
||||
SamplerState Sampler0 : register(s0);
|
||||
SamplerState Sampler1 : register(s1);
|
||||
SamplerState Sampler2 : register(s2);
|
||||
SamplerState Sampler3 : register(s3);
|
||||
SamplerState Sampler4 : register(s4);
|
||||
SamplerState Sampler5 : register(s5);
|
||||
SamplerState Sampler6 : register(s6);
|
||||
SamplerState Sampler7 : register(s7);
|
||||
SamplerState Sampler8 : register(s8);
|
||||
SamplerState Sampler9 : register(s9);
|
||||
|
||||
cbuffer Constants : register(b0)
|
||||
{
|
||||
@@ -26,6 +34,10 @@ cbuffer Constants : register(b0)
|
||||
float4 wind : packoffset(c18);
|
||||
float4 mode : packoffset(c19);
|
||||
float4 fade : packoffset(c20);
|
||||
float4 occluderPlanes[4] : packoffset(c21);
|
||||
float4 occluderImageX[4] : packoffset(c25);
|
||||
float4 occluderImageY[4] : packoffset(c29);
|
||||
float4 occluderStrength : packoffset(c33);
|
||||
};
|
||||
|
||||
static const int MaximumLevel = 5;
|
||||
@@ -38,6 +50,7 @@ static const float DustSecondWeight = 0.5;
|
||||
static const float LinearFalloffLevel = 0.9999;
|
||||
|
||||
static float4 SceneUv[6];
|
||||
static float4 OccluderUv[4];
|
||||
static float2 ScenePoint;
|
||||
|
||||
uint Mix(uint value)
|
||||
@@ -106,6 +119,50 @@ float4 ReadLevel(int level, float2 imagePosition)
|
||||
return Level5.SampleLevel(Sampler5, uv, 0);
|
||||
}
|
||||
|
||||
float OccluderAlpha(int index, float2 imagePosition)
|
||||
{
|
||||
float4 uvs = OccluderUv[index];
|
||||
float2 uv = uvs.xy + (imagePosition - ScenePoint) * uvs.zw;
|
||||
if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)
|
||||
return 0.0;
|
||||
|
||||
if (index == 0)
|
||||
return Occluder0.SampleLevel(Sampler6, uv, 0).a;
|
||||
if (index == 1)
|
||||
return Occluder1.SampleLevel(Sampler7, uv, 0).a;
|
||||
if (index == 2)
|
||||
return Occluder2.SampleLevel(Sampler8, uv, 0).a;
|
||||
return Occluder3.SampleLevel(Sampler9, uv, 0).a;
|
||||
}
|
||||
|
||||
float GetTransmission(float3 volumePoint, float3 sourcePoint)
|
||||
{
|
||||
float transmission = 1.0;
|
||||
[unroll]
|
||||
for (int index = 0; index < 4; ++index)
|
||||
{
|
||||
float strength = occluderStrength[index];
|
||||
if (strength > 0.0)
|
||||
{
|
||||
float4 plane = occluderPlanes[index];
|
||||
float near = dot(plane.xyz, volumePoint) + plane.w;
|
||||
float span = dot(plane.xyz, sourcePoint) + plane.w - near;
|
||||
if (abs(span) > RateEpsilon)
|
||||
{
|
||||
float ratio = -near / span;
|
||||
if (ratio > 0.0 && ratio < 1.0)
|
||||
{
|
||||
float4 crossing = float4(volumePoint + (sourcePoint - volumePoint) * ratio, 1.0);
|
||||
float2 imagePosition = float2(dot(occluderImageX[index], crossing), dot(occluderImageY[index], crossing));
|
||||
transmission *= 1.0 - strength * OccluderAlpha(index, imagePosition);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return transmission;
|
||||
}
|
||||
|
||||
float4 SampleGobo(float2 imagePosition, float lod)
|
||||
{
|
||||
float clamped = clamp(lod, 0.0, (float)MaximumLevel);
|
||||
@@ -170,7 +227,11 @@ float4 main(
|
||||
float4 uv2 : TEXCOORD2,
|
||||
float4 uv3 : TEXCOORD3,
|
||||
float4 uv4 : TEXCOORD4,
|
||||
float4 uv5 : TEXCOORD5
|
||||
float4 uv5 : TEXCOORD5,
|
||||
float4 uv6 : TEXCOORD6,
|
||||
float4 uv7 : TEXCOORD7,
|
||||
float4 uv8 : TEXCOORD8,
|
||||
float4 uv9 : TEXCOORD9
|
||||
) : SV_TARGET
|
||||
{
|
||||
SceneUv[0] = uv0;
|
||||
@@ -179,6 +240,10 @@ float4 main(
|
||||
SceneUv[3] = uv3;
|
||||
SceneUv[4] = uv4;
|
||||
SceneUv[5] = uv5;
|
||||
OccluderUv[0] = uv6;
|
||||
OccluderUv[1] = uv7;
|
||||
OccluderUv[2] = uv8;
|
||||
OccluderUv[3] = uv9;
|
||||
ScenePoint = scenePosition.xy;
|
||||
|
||||
float footprint = mode.z;
|
||||
@@ -256,7 +321,8 @@ float4 main(
|
||||
if (dust.x > 0.0)
|
||||
density = max(1.0 + dust.x * (2.0 * Dust((volumePoint + wind.xyz) * dust.y, seed) - 1.0), 0.0);
|
||||
|
||||
sum += emission * (GetFalloff(travel) * phase * density);
|
||||
float transmission = occluderStrength.x + occluderStrength.y + occluderStrength.z + occluderStrength.w > 0.0 ? GetTransmission(volumePoint, sourcePoint) : 1.0;
|
||||
sum += emission * (GetFalloff(travel) * phase * density * transmission);
|
||||
}
|
||||
|
||||
return float4(sum * stepWeight * tint.rgb, 0.0);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace VolumetricLight.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);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Drawing;
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
internal static class EffectDescriptions
|
||||
{
|
||||
public const int Fps = 30;
|
||||
public const int ScreenWidth = 1920;
|
||||
public const int ScreenHeight = 1080;
|
||||
|
||||
static readonly Size ScreenSize = new(ScreenWidth, ScreenHeight);
|
||||
|
||||
public static DrawDescription Flat { get; } = new(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
|
||||
public static EffectDescription At(int frame, int length) => At(frame, length, Flat);
|
||||
|
||||
public static EffectDescription At(int frame, int length, DrawDescription draw) => At(frame, length, draw, ScreenSize);
|
||||
|
||||
public static EffectDescription At(int frame, int length, DrawDescription draw, Size screenSize, Guid scene = default)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
screenSize,
|
||||
new FrameTime(frame, Fps),
|
||||
new FrameTime(length, Fps),
|
||||
Fps,
|
||||
TimelineSourceUsage.Playing,
|
||||
scene,
|
||||
[]);
|
||||
var item = new TimelineItemSourceDescription(timeline, frame, length, 0);
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Numerics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using static VolumetricLight.EmissionCustomEffect;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class EmissionCustomEffectTests
|
||||
{
|
||||
const int Width = 64;
|
||||
const int Height = 48;
|
||||
const float Relative = 0.01f;
|
||||
const float Absolute = 0.003f;
|
||||
const float MaximumChannel = 255f;
|
||||
const float MinimumLuma = 1e-6f;
|
||||
|
||||
static readonly Vector3 LumaWeights = new(0.2126f, 0.7152f, 0.0722f);
|
||||
|
||||
static Bgra Pattern(int x, int y)
|
||||
{
|
||||
if (x < 8)
|
||||
return Bgra.Transparent;
|
||||
|
||||
var alpha = (byte)(y < Height / 2 ? byte.MaxValue : 40 + x * 3);
|
||||
return new Bgra((byte)(y * 5), (byte)(x * 4), (byte)(255 - y * 5), alpha);
|
||||
}
|
||||
|
||||
static float Read(EmissionCustomEffect effect) => effect.GetFloatValue((int)PropertyIndex.Threshold);
|
||||
|
||||
static FloatRendering Render(IGraphicsDevicesAndContext devices, SourceImage source, float threshold)
|
||||
{
|
||||
using var effect = new EmissionCustomEffect(devices);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
effect.Threshold = threshold;
|
||||
using var output = effect.Output;
|
||||
|
||||
return FloatRendering.Capture(devices, output);
|
||||
}
|
||||
|
||||
static Vector4 Expected(SourceImage source, int x, int y, float threshold)
|
||||
{
|
||||
var pixel = source[x, y];
|
||||
var color = new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / MaximumChannel;
|
||||
if (color.W <= 0f)
|
||||
return Vector4.Zero;
|
||||
|
||||
var luma = Vector3.Dot(new Vector3(color.X, color.Y, color.Z) / color.W, LumaWeights);
|
||||
return color * (MathF.Max(luma - threshold, 0f) / MathF.Max(luma, MinimumLuma));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsEnabledOnceCreated()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new EmissionCustomEffect(context);
|
||||
|
||||
Assert.True(effect.IsEnabled);
|
||||
Assert.Equal(0f, Read(effect));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.25f, 0.25f)]
|
||||
[InlineData(1f, 1f)]
|
||||
[InlineData(-0.5f, 0f)]
|
||||
[InlineData(3f, 1f)]
|
||||
[InlineData(float.NaN, 0f)]
|
||||
public void TheThresholdIsKeptWithinZeroAndOne(float value, float expected)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new EmissionCustomEffect(context);
|
||||
|
||||
effect.Threshold = value;
|
||||
|
||||
Assert.Equal(expected, Read(effect));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(0.08f)]
|
||||
[InlineData(0.4f)]
|
||||
[InlineData(0.75f)]
|
||||
public void EveryPixelKeepsItsHueAndLosesOnlyTheLumaUnderTheThreshold(float threshold)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Pattern);
|
||||
|
||||
var rendering = Render(context, source, threshold);
|
||||
|
||||
var close = 0;
|
||||
var bright = 0;
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
var expected = Expected(source, x, y, threshold);
|
||||
var actual = rendering[x, y];
|
||||
var error = Vector4.Abs(expected - actual);
|
||||
var scale = MathF.Max(MathF.Max(expected.X, expected.Y), MathF.Max(expected.Z, expected.W));
|
||||
if (scale > Absolute)
|
||||
bright++;
|
||||
if (MathF.Max(MathF.Max(error.X, error.Y), MathF.Max(error.Z, error.W)) <= Relative * scale + Absolute)
|
||||
close++;
|
||||
}
|
||||
|
||||
Assert.Equal(Width * Height, close);
|
||||
Assert.True(threshold >= 0.75f || bright > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroThresholdPassesTheImageThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Pattern);
|
||||
|
||||
var rendering = Render(context, source, 0f);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point =>
|
||||
{
|
||||
var pixel = source[point.X, point.Y];
|
||||
var actual = rendering[point.X, point.Y];
|
||||
Assert.True(MathF.Abs(actual.X - pixel.Red / MaximumChannel) <= Absolute, $"{point} red");
|
||||
Assert.True(MathF.Abs(actual.Y - pixel.Green / MaximumChannel) <= Absolute, $"{point} green");
|
||||
Assert.True(MathF.Abs(actual.Z - pixel.Blue / MaximumChannel) <= Absolute, $"{point} blue");
|
||||
Assert.True(MathF.Abs(actual.W - pixel.Alpha / MaximumChannel) <= Absolute, $"{point} alpha");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AThresholdOfOneRemovesEverything()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Pattern);
|
||||
|
||||
var rendering = Render(context, source, 1f);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(Vector4.Zero, rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransparentPixelsStayEmpty()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Pattern);
|
||||
|
||||
var rendering = Render(context, source, 0.1f);
|
||||
|
||||
Assert.All(rendering.Coordinates().Where(point => point.X < 8), point => Assert.Equal(Vector4.Zero, rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOutputCoversTheInput()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Pattern);
|
||||
|
||||
var rendering = Render(context, source, 0.2f);
|
||||
|
||||
Assert.Equal((0, 0, Width, Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
internal sealed class FloatRendering
|
||||
{
|
||||
public const int Channels = 4;
|
||||
|
||||
static readonly PixelFormat PixelFormat = new(Format.R32G32B32A32_Float, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
|
||||
readonly float[] pixels;
|
||||
|
||||
public int Left { get; }
|
||||
|
||||
public int Top { get; }
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
FloatRendering(int left, int top, int width, int height, float[] pixels)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
Width = width;
|
||||
Height = height;
|
||||
this.pixels = pixels;
|
||||
}
|
||||
|
||||
public static FloatRendering 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 * Channels * sizeof(float);
|
||||
var size = new SizeI(width, height);
|
||||
|
||||
using var target = context.CreateBitmap(size, nint.Zero, stride, new BitmapProperties1(PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.Target));
|
||||
using var readback = context.CreateBitmap(size, nint.Zero, stride, new BitmapProperties1(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 values = new float[width * height * Channels];
|
||||
var mapped = readback.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, values, y * width * Channels, width * Channels);
|
||||
}
|
||||
finally
|
||||
{
|
||||
readback.Unmap();
|
||||
}
|
||||
|
||||
return new FloatRendering(left, top, width, height, values);
|
||||
}
|
||||
|
||||
public Vector4 this[int x, int y]
|
||||
{
|
||||
get
|
||||
{
|
||||
var offset = ((y - Top) * Width + (x - Left)) * Channels;
|
||||
return new Vector4(pixels[offset], pixels[offset + 1], pixels[offset + 2], pixels[offset + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<(int X, int Y)> Coordinates()
|
||||
{
|
||||
for (var y = Top; y < Top + Height; y++)
|
||||
{
|
||||
for (var x = Left; x < Left + Width; x++)
|
||||
yield return (x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Windows;
|
||||
using Telemetry;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class HostIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
VolumetricLightTelemetry.EnsureStartedOnce();
|
||||
VolumetricLightTelemetry.Report(new InvalidOperationException());
|
||||
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
Assert.Null(ProcessState.Read("SentCount"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
Assert.Equal(Texts.VolumetricLight, effect.Label);
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class LightVolumeTests
|
||||
{
|
||||
const float Tolerance = 5e-3f;
|
||||
const float TexelSize = 1f;
|
||||
|
||||
static readonly PlaneRect Rect = new(-200f, -100f, 200f, 100f);
|
||||
|
||||
static LightVolume Create(double azimuth, double elevation, double spread, double length = 1000d, PlaneRect? rect = null)
|
||||
{
|
||||
var axis = VolumetricLightSettings.GetAxis(azimuth, elevation);
|
||||
Assert.True(LightVolume.TryCreate(rect ?? Rect, axis, spread, length, TexelSize, out var volume));
|
||||
return volume;
|
||||
}
|
||||
|
||||
static bool IsInside(LightVolume volume, Vector3 point, float margin = 0f)
|
||||
{
|
||||
for (var index = 0; index < VolumetricLightSettings.PlaneCount; index++)
|
||||
{
|
||||
var plane = volume.Planes[index];
|
||||
if (Vector3.Dot(new Vector3(plane.X, plane.Y, plane.Z), point) - plane.W < -margin)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static TheoryData<double, double, double> Shapes => new()
|
||||
{
|
||||
{ -90d, 55d, 0d },
|
||||
{ 30d, 40d, 0d },
|
||||
{ 200d, -35d, 0d },
|
||||
{ -90d, 55d, 12d },
|
||||
{ 45d, 20d, 30d },
|
||||
{ 160d, -50d, 25d },
|
||||
{ -90d, 55d, -15d },
|
||||
{ 10d, 70d, -30d },
|
||||
{ 0d, -45d, -20d },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Shapes))]
|
||||
public void EveryRayLeavingTheRectangleStaysInsideTheVolumeUntilItsEnd(double azimuth, double elevation, double spread)
|
||||
{
|
||||
var volume = Create(azimuth, elevation, spread);
|
||||
var random = new Random(3);
|
||||
for (var index = 0; index < 500; index++)
|
||||
{
|
||||
var source = new Vector3(Rect.Left + (float)random.NextDouble() * Rect.Width, Rect.Top + (float)random.NextDouble() * Rect.Height, 0f);
|
||||
var direction = volume.GetDirection(source);
|
||||
var reach = volume.DepthSign * volume.FarDepth * (float)random.NextDouble() / direction.Z;
|
||||
var point = source + direction * reach;
|
||||
|
||||
Assert.True(IsInside(volume, point, 1e-2f), $"{index} {point}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Shapes))]
|
||||
public void PointsOutsideTheRectangleOrBeyondTheEndAreOutsideTheVolume(double azimuth, double elevation, double spread)
|
||||
{
|
||||
var volume = Create(azimuth, elevation, spread);
|
||||
var direction = volume.GetDirection(Vector3.Zero);
|
||||
var inside = direction * (volume.DepthSign * volume.FarDepth * 0.5f / direction.Z);
|
||||
Assert.True(IsInside(volume, inside));
|
||||
|
||||
Assert.False(IsInside(volume, inside + direction * (volume.DepthSign * volume.FarDepth / direction.Z)));
|
||||
Assert.False(IsInside(volume, inside with { Z = -volume.DepthSign * 5f }));
|
||||
Assert.False(IsInside(volume, inside + new Vector3(5000f, 0f, 0f)));
|
||||
Assert.False(IsInside(volume, inside + new Vector3(0f, -5000f, 0f)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Shapes))]
|
||||
public void TheSourceAndTheTravelOfAVolumePointAreTheOnesItWasBuiltFrom(double azimuth, double elevation, double spread)
|
||||
{
|
||||
var volume = Create(azimuth, elevation, spread);
|
||||
var random = new Random(11);
|
||||
for (var index = 0; index < 300; index++)
|
||||
{
|
||||
var source = new Vector3(Rect.Left + (float)random.NextDouble() * Rect.Width, Rect.Top + (float)random.NextDouble() * Rect.Height, 0f);
|
||||
var direction = volume.GetDirection(source);
|
||||
var travel = (float)random.NextDouble() * volume.FarDepth / MathF.Abs(direction.Z);
|
||||
var point = source + direction * travel;
|
||||
|
||||
Assert.True(volume.TryGetSource(point, out var found, out var distance));
|
||||
|
||||
Assert.True(Vector3.Distance(source, found) < Tolerance * (1f + travel * 0.01f), $"{index} {source} {found}");
|
||||
Assert.True(MathF.Abs(travel - distance) < Tolerance * (1f + travel * 0.01f), $"{index} {travel} {distance}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AParallelVolumeKeepsItsDirectionEverywhere()
|
||||
{
|
||||
var volume = Create(-90d, 55d, 0d);
|
||||
|
||||
Assert.False(volume.IsPoint);
|
||||
Assert.Equal(volume.Axis, volume.GetDirection(new Vector3(120f, -40f, 300f)));
|
||||
Assert.Equal(volume.Axis, volume.GetDirection(Vector3.Zero));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADivergingVolumeFansOutFromAFocusBehindThePlane()
|
||||
{
|
||||
var volume = Create(-90d, 55d, 20d);
|
||||
|
||||
Assert.True(volume.IsPoint);
|
||||
Assert.Equal(1f, volume.Sign);
|
||||
Assert.True(volume.Focus.Z < 0f);
|
||||
var left = volume.GetDirection(new Vector3(-200f, 0f, 0f));
|
||||
var right = volume.GetDirection(new Vector3(200f, 0f, 0f));
|
||||
Assert.True(left.X < right.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConvergingVolumeAimsAtAFocusInFrontOfThePlane()
|
||||
{
|
||||
var volume = Create(-90d, 55d, -20d);
|
||||
|
||||
Assert.True(volume.IsPoint);
|
||||
Assert.Equal(-1f, volume.Sign);
|
||||
Assert.True(volume.Focus.Z > 0f);
|
||||
var left = volume.GetDirection(new Vector3(-200f, 0f, 0f));
|
||||
var right = volume.GetDirection(new Vector3(200f, 0f, 0f));
|
||||
Assert.True(left.X > right.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConvergingVolumeEndsBeforeItsFocus()
|
||||
{
|
||||
var volume = Create(-90d, 55d, -20d, 1_000_000d);
|
||||
|
||||
Assert.True(volume.FarDepth < MathF.Abs(volume.Focus.Z));
|
||||
Assert.True(volume.FarDepth > 0.99f * MathF.Abs(volume.Focus.Z));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLengthIsMeasuredAlongTheAxisAndLimitsTheDepth()
|
||||
{
|
||||
var volume = Create(0d, 30d, 0d, 800d);
|
||||
|
||||
Assert.Equal(800f * MathF.Sin(MathF.PI / 6f), volume.FarDepth, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABeamPointingAwayFromTheCameraLiesBehindThePlane()
|
||||
{
|
||||
var volume = Create(0d, -40d, 0d);
|
||||
var corners = new Vector3[8];
|
||||
|
||||
volume.GetCorners(corners);
|
||||
|
||||
Assert.Equal(-1f, volume.DepthSign);
|
||||
Assert.All(corners[4..], corner => Assert.Equal(-volume.FarDepth, corner.Z, Tolerance));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCornersAreTheRectangleAndItsProjectionAtTheEnd()
|
||||
{
|
||||
var volume = Create(-90d, 55d, 0d);
|
||||
var corners = new Vector3[8];
|
||||
|
||||
volume.GetCorners(corners);
|
||||
|
||||
Assert.Equal(new Vector3(Rect.Left, Rect.Top, 0f), corners[0]);
|
||||
Assert.Equal(new Vector3(Rect.Right, Rect.Top, 0f), corners[1]);
|
||||
Assert.Equal(new Vector3(Rect.Right, Rect.Bottom, 0f), corners[2]);
|
||||
Assert.Equal(new Vector3(Rect.Left, Rect.Bottom, 0f), corners[3]);
|
||||
for (var index = 0; index < 4; index++)
|
||||
{
|
||||
Assert.Equal(volume.FarDepth, corners[4 + index].Z, Tolerance);
|
||||
Assert.True(Vector3.Distance(corners[4 + index] - corners[index], volume.Axis * (volume.FarDepth / volume.Axis.Z)) < Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyRectangleHasNoVolume()
|
||||
{
|
||||
Assert.False(LightVolume.TryCreate(new PlaneRect(0f, 0f, 1000f, 0f), VolumetricLightSettings.GetAxis(0d, 45d), 0d, 1000d, TexelSize, out _));
|
||||
Assert.False(LightVolume.TryCreate(new PlaneRect(0f, 0f, 0f, 1000f), VolumetricLightSettings.GetAxis(0d, 45d), 0d, 1000d, TexelSize, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALengthOfZeroHasNoVolume()
|
||||
{
|
||||
Assert.False(LightVolume.TryCreate(Rect, VolumetricLightSettings.GetAxis(0d, 45d), 0d, 0d, TexelSize, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAxisLyingInThePlaneHasNoVolume()
|
||||
{
|
||||
Assert.False(LightVolume.TryCreate(Rect, new Vector3(1f, 0f, 0f), 0d, 1000d, TexelSize, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFocusSoCloseThatNothingRemainsHasNoVolume()
|
||||
{
|
||||
var tiny = new PlaneRect(-0.4f, -0.4f, 0.4f, 0.4f);
|
||||
|
||||
Assert.False(LightVolume.TryCreate(tiny, VolumetricLightSettings.GetAxis(0d, 45d), -30d, 1000d, 2f, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRectangleMapsThroughTheZoomAndTheFlip()
|
||||
{
|
||||
var plain = PlaneRect.Create(-100f, -50f, 100f, 50f, new Vector2(2f, 3f), false, Vector2.Zero);
|
||||
var mirrored = PlaneRect.Create(-100f, -50f, 100f, 50f, new Vector2(2f, 3f), true, new Vector2(10f, 0f));
|
||||
var negative = PlaneRect.Create(-100f, -50f, 100f, 50f, new Vector2(-1f, -1f), false, Vector2.Zero);
|
||||
|
||||
Assert.Equal(new PlaneRect(-200f, -150f, 200f, 150f), plain);
|
||||
Assert.Equal(new PlaneRect(-160f, -150f, 240f, 150f), mirrored);
|
||||
Assert.Equal(new PlaneRect(-100f, -50f, 100f, 50f), negative);
|
||||
Assert.Equal(250f, plain.HalfDiagonal, 1e-3f);
|
||||
Assert.Equal(new Vector3(0f, 0f, 0f), plain.Center);
|
||||
Assert.True(plain.IsValid);
|
||||
Assert.False(new PlaneRect(0f, 0f, float.PositiveInfinity, 10f).IsValid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f, false, 0f)]
|
||||
[InlineData(2f, false, 0f)]
|
||||
[InlineData(2f, true, 10f)]
|
||||
[InlineData(-1.5f, true, -7f)]
|
||||
public void TheGoboMappingUndoesTheZoomAndTheFlip(float zoom, bool invert, float center)
|
||||
{
|
||||
var mapping = GoboMapping.Create(new Vector2(zoom, zoom), invert, new Vector2(center, 0f));
|
||||
var rect = PlaneRect.Create(-30f, -20f, 70f, 40f, new Vector2(zoom, zoom), invert, new Vector2(center, 0f));
|
||||
var corners = new[]
|
||||
{
|
||||
(rect.Left, rect.Top),
|
||||
(rect.Right, rect.Top),
|
||||
(rect.Right, rect.Bottom),
|
||||
(rect.Left, rect.Bottom),
|
||||
};
|
||||
|
||||
var images = corners.Select(corner => mapping.ToImage(corner.Item1, corner.Item2)).ToArray();
|
||||
|
||||
Assert.Equal(-30f, images.Min(image => image.X), Tolerance);
|
||||
Assert.Equal(70f, images.Max(image => image.X), Tolerance);
|
||||
Assert.Equal(-20f, images.Min(image => image.Y), Tolerance);
|
||||
Assert.Equal(40f, images.Max(image => image.Y), Tolerance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class OccluderRegistryTests
|
||||
{
|
||||
const int Width = 8;
|
||||
const int Height = 4;
|
||||
|
||||
static Bgra Marker(int x, int y) => Bgra.Opaque((byte)(x * 20), (byte)(y * 40), 200);
|
||||
|
||||
static Occluder Sample(float strength = 1f)
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(EffectDescriptions.Flat, out var view));
|
||||
return new Occluder(view, GoboMapping.Create(Vector2.One, false, Vector2.Zero), strength);
|
||||
}
|
||||
|
||||
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image image) => Rendering.Capture(devices, image);
|
||||
|
||||
[Fact]
|
||||
public void TheSameChannelOnTheSameDeviceSharesOneGroup()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var first = devices.CreateContext();
|
||||
using var second = devices.CreateContext();
|
||||
|
||||
using var a = OccluderRegistry.Acquire(first, Guid.Empty, 1);
|
||||
using var b = OccluderRegistry.Acquire(second, Guid.Empty, 1);
|
||||
using var c = OccluderRegistry.Acquire(first, Guid.Empty, 2);
|
||||
|
||||
Assert.Same(a.Group, b.Group);
|
||||
Assert.NotSame(a.Group, c.Group);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameNumberInAnotherSceneHasItsOwnGroup()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var home = Guid.NewGuid();
|
||||
|
||||
using var a = OccluderRegistry.Acquire(context, home, 1);
|
||||
using var b = OccluderRegistry.Acquire(context, home, 1);
|
||||
using var c = OccluderRegistry.Acquire(context, Guid.NewGuid(), 1);
|
||||
|
||||
Assert.Same(a.Group, b.Group);
|
||||
Assert.NotSame(a.Group, c.Group);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASnapshotKeepsOnlyTheOccludersPublishedForItsOwnFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
using var now = lease.Group.Claim()!;
|
||||
using var later = lease.Group.Claim()!;
|
||||
now.Publish(source.Bitmap, Sample(0.25f), 4);
|
||||
later.Publish(source.Bitmap, Sample(0.75f), 9);
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
|
||||
lease.Group.Snapshot(snapshot, 4);
|
||||
Assert.Equal(0.25f, snapshot[0].Strength);
|
||||
Assert.Equal(0f, snapshot[1].Strength);
|
||||
|
||||
lease.Group.Snapshot(snapshot, 9);
|
||||
Assert.Equal(0f, snapshot[0].Strength);
|
||||
Assert.Equal(0.75f, snapshot[1].Strength);
|
||||
|
||||
lease.Group.Snapshot(snapshot, 5);
|
||||
Assert.All(snapshot, occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentDevicesNeverShareAGroup()
|
||||
{
|
||||
using var firstDevices = new GraphicsDevices();
|
||||
using var secondDevices = new GraphicsDevices();
|
||||
using var first = firstDevices.CreateContext();
|
||||
using var second = secondDevices.CreateContext();
|
||||
|
||||
using var a = OccluderRegistry.Acquire(first, Guid.Empty, 1);
|
||||
using var b = OccluderRegistry.Acquire(second, Guid.Empty, 1);
|
||||
|
||||
Assert.NotSame(a.Group, b.Group);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGroupLivesUntilTheLastLeaseIsReleasedAndThenStartsOver()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var a = OccluderRegistry.Acquire(context, Guid.Empty, 3);
|
||||
var b = OccluderRegistry.Acquire(context, Guid.Empty, 3);
|
||||
var group = a.Group;
|
||||
var slot = group.Claim()!;
|
||||
|
||||
a.Dispose();
|
||||
a.Dispose();
|
||||
Assert.NotNull(group.Claim());
|
||||
b.Dispose();
|
||||
using var again = OccluderRegistry.Acquire(context, Guid.Empty, 3);
|
||||
|
||||
Assert.NotSame(group, again.Group);
|
||||
Assert.Null(group.Claim());
|
||||
slot.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyFourOccludersFitAndARetiredSlotCanBeClaimedAgain()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var slots = Enumerable.Range(0, VolumetricLightSettings.OccluderCapacity).Select(_ => lease.Group.Claim()).ToArray();
|
||||
|
||||
Assert.All(slots, Assert.NotNull);
|
||||
Assert.Null(lease.Group.Claim());
|
||||
slots[1]!.Dispose();
|
||||
slots[1]!.Dispose();
|
||||
var reclaimed = lease.Group.Claim();
|
||||
Assert.NotNull(reclaimed);
|
||||
Assert.Null(lease.Group.Claim());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGroupIsOccupiedWhileAnySlotIsClaimed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
Assert.False(lease.Group.IsOccupied);
|
||||
|
||||
var first = lease.Group.Claim()!;
|
||||
var second = lease.Group.Claim()!;
|
||||
Assert.True(lease.Group.IsOccupied);
|
||||
first.Dispose();
|
||||
Assert.True(lease.Group.IsOccupied);
|
||||
second.Dispose();
|
||||
Assert.False(lease.Group.IsOccupied);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePublishedOccluderAppearsInTheSnapshotUntilItsSlotIsDisposed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
using var first = lease.Group.Claim()!;
|
||||
var second = lease.Group.Claim()!;
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
|
||||
first.Publish(source.Bitmap, Sample(0.25f), 0);
|
||||
second.Publish(source.Bitmap, Sample(0.75f), 0);
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
Assert.Equal([0.25f, 0.75f, 0f, 0f], snapshot.Select(occluder => occluder.Strength));
|
||||
|
||||
second.Dispose();
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
Assert.Equal([0.25f, 0f, 0f, 0f], snapshot.Select(occluder => occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnclaimedSlotIgnoresPublishing()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var slot = lease.Group.Claim()!;
|
||||
slot.Dispose();
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
|
||||
slot.Publish(source.Bitmap, Sample(), 0);
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
|
||||
Assert.All(snapshot, occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRelayShowsThePublishedImageAndGoesEmptyAgainAfterwards()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var slot = lease.Group.Claim()!;
|
||||
var relay = lease.Group.GetOutput(0);
|
||||
|
||||
var empty = context.DeviceContext.GetImageLocalBounds(relay);
|
||||
slot.Publish(source.Bitmap, Sample(), 0);
|
||||
var shown = Render(context, relay);
|
||||
slot.Dispose();
|
||||
var gone = context.DeviceContext.GetImageLocalBounds(relay);
|
||||
|
||||
Assert.Equal((0f, 0f, 0f, 0f), (empty.Left, empty.Top, empty.Right, empty.Bottom));
|
||||
Assert.Equal((0, 0, Width, Height), (shown.Left, shown.Top, shown.Width, shown.Height));
|
||||
Assert.All(shown.Coordinates(), point => Assert.Equal(source[point.X, point.Y], shown[point.X, point.Y]));
|
||||
Assert.Equal((0f, 0f, 0f, 0f), (gone.Left, gone.Top, gone.Right, gone.Bottom));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOtherContextOfTheSameDeviceCanPublishAndAnotherCanRead()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var reader = devices.CreateContext();
|
||||
using var writer = devices.CreateContext();
|
||||
using var source = new SourceImage(writer, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(reader, Guid.Empty, 1);
|
||||
using var slot = lease.Group.Claim()!;
|
||||
|
||||
slot.Publish(source.Bitmap, Sample(), 0);
|
||||
var shown = Render(reader, lease.Group.GetOutput(0));
|
||||
|
||||
Assert.Equal(source[3, 2], shown[3, 2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARelayStaysValidAfterTheContextThatCreatedItIsDisposed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var reader = devices.CreateContext();
|
||||
var creator = devices.CreateContext();
|
||||
using var source = new SourceImage(reader, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(creator, Guid.Empty, 1);
|
||||
using var slot = lease.Group.Claim()!;
|
||||
creator.Dispose();
|
||||
|
||||
slot.Publish(source.Bitmap, Sample(), 0);
|
||||
var shown = Render(reader, lease.Group.GetOutput(0));
|
||||
|
||||
Assert.Equal(source[5, 1], shown[5, 1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClaimingAndPublishingFromManyThreadsKeepsEverySlotConsistent()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var claimed = 0;
|
||||
|
||||
Parallel.For(0, 64, index =>
|
||||
{
|
||||
var slot = lease.Group.Claim();
|
||||
if (slot is null)
|
||||
return;
|
||||
|
||||
Interlocked.Increment(ref claimed);
|
||||
slot.Publish(source.Bitmap, Sample((index + 1) / 100f), 0);
|
||||
});
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
|
||||
Assert.Equal(VolumetricLightSettings.OccluderCapacity, claimed);
|
||||
Assert.All(snapshot, occluder => Assert.True(occluder.Strength > 0f));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnImageThatDependsOnAConsumerIsKeptOutUntilTheConsumerLeaves()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
using var slot = lease.Group.Claim()!;
|
||||
using var blur = new Vortice.Direct2D1.Effects.GaussianBlur(context.DeviceContext);
|
||||
blur.SetInput(0, source.Bitmap, true);
|
||||
using var downstream = new Vortice.Direct2D1.Effects.Crop(context.DeviceContext) { Rectangle = new Vector4(0f, 0f, Width, Height) };
|
||||
using var blurOutput = blur.Output;
|
||||
downstream.SetInput(0, blurOutput, true);
|
||||
using var image = downstream.Output;
|
||||
var blocked = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
var freed = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
|
||||
lease.Group.AddConsumer(blur.NativePointer);
|
||||
slot.Publish(image, Sample(), 0);
|
||||
lease.Group.Snapshot(blocked, 0);
|
||||
var kept = context.DeviceContext.GetImageLocalBounds(lease.Group.GetOutput(0));
|
||||
lease.Group.RemoveConsumer(blur.NativePointer);
|
||||
slot.Publish(image, Sample(), 0);
|
||||
lease.Group.Snapshot(freed, 0);
|
||||
var relayed = context.DeviceContext.GetImageLocalBounds(lease.Group.GetOutput(0));
|
||||
|
||||
Assert.Equal(0f, blocked[0].Strength);
|
||||
Assert.Equal((0f, 0f, 0f, 0f), (kept.Left, kept.Top, kept.Right, kept.Bottom));
|
||||
Assert.Equal(1f, freed[0].Strength);
|
||||
Assert.True(relayed.Right > relayed.Left);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConsumerThatArrivesAfterThePublishingStillBlocksAnImageItDependsOn()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Marker);
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
using var slot = lease.Group.Claim()!;
|
||||
using var blur = new Vortice.Direct2D1.Effects.GaussianBlur(context.DeviceContext);
|
||||
blur.SetInput(0, source.Bitmap, true);
|
||||
using var image = blur.Output;
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
slot.Publish(image, Sample(), 0);
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
Assert.Equal(1f, snapshot[0].Strength);
|
||||
|
||||
lease.Group.AddConsumer(blur.NativePointer);
|
||||
lease.Group.Snapshot(snapshot, 0);
|
||||
|
||||
Assert.Equal(0f, snapshot[0].Strength);
|
||||
Assert.Equal((0f, 0f, 0f, 0f), (context.DeviceContext.GetImageLocalBounds(lease.Group.GetOutput(0)) is var bounds ? (bounds.Left, bounds.Top, bounds.Right, bounds.Bottom) : default));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALinkHandsBackItsGroupByIdUntilItIsUnregistered()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var lease = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var link = new OccluderLink { Group = lease.Group, Frame = 0 };
|
||||
|
||||
var id = OccluderLinks.Register(link);
|
||||
|
||||
Assert.True(OccluderLinks.TryGet(id, out var found));
|
||||
Assert.Same(link, found);
|
||||
Assert.Same(lease.Group, found.Group);
|
||||
OccluderLinks.Unregister(id);
|
||||
Assert.False(OccluderLinks.TryGet(id, out _));
|
||||
Assert.NotEqual(id, OccluderLinks.Register(new OccluderLink()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class OcclusionTests
|
||||
{
|
||||
const float Tolerance = 2e-3f;
|
||||
|
||||
static float Next(Random random, float range) => (float)(random.NextDouble() * 2.0 - 1.0) * range;
|
||||
|
||||
static Matrix4x4 Camera(Random random)
|
||||
=> Matrix4x4.CreateTranslation(-new Vector3(Next(random, 300f), Next(random, 300f), Next(random, 400f)))
|
||||
* Matrix4x4.CreateRotationY(MathF.PI * Next(random, 25f) / 180f, new Vector3(0f, 0f, 1000f))
|
||||
* Matrix4x4.CreateRotationX(MathF.PI * Next(random, 20f) / 180f, new Vector3(0f, 0f, 1000f));
|
||||
|
||||
static ViewTransform View(DrawDescription draw)
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
return view;
|
||||
}
|
||||
|
||||
static DrawDescription Describe(Vector3 draw, Vector3 rotation, Matrix4x4 camera, Vector2 zoom, bool invert, Vector2 center)
|
||||
=> new(draw, center, zoom, rotation, camera, InterpolationMode.Linear, 1d, invert, []);
|
||||
|
||||
static Occluder Create(DrawDescription draw, float strength = 1f)
|
||||
=> new(View(draw), GoboMapping.Create(draw.Zoom, draw.Invert, draw.CenterPoint), strength);
|
||||
|
||||
static float Dot(Vector4 row, Vector3 point) => row.X * point.X + row.Y * point.Y + row.Z * point.Z + row.W;
|
||||
|
||||
[Fact]
|
||||
public void ThePlaneIsZeroOnTheOccluderAndGrowsWithTheDistanceFromIt()
|
||||
{
|
||||
var random = new Random(11);
|
||||
for (var index = 0; index < 40; index++)
|
||||
{
|
||||
var lightDraw = Describe(new Vector3(Next(random, 200f), Next(random, 200f), Next(random, 200f)), new Vector3(Next(random, 40f), Next(random, 40f), Next(random, 40f)), Camera(random), Vector2.One, false, Vector2.Zero);
|
||||
var occluderDraw = Describe(new Vector3(Next(random, 200f), Next(random, 200f), Next(random, 300f)), new Vector3(Next(random, 40f), Next(random, 40f), Next(random, 40f)), lightDraw.Camera, Vector2.One, false, Vector2.Zero);
|
||||
var light = View(lightDraw);
|
||||
var occluder = Create(occluderDraw);
|
||||
var plane = OccluderPlane.Create(light.CameraFromLocal, occluder);
|
||||
var onPlane = new Vector3(Next(random, 150f), Next(random, 150f), 0f);
|
||||
var offPlane = onPlane + new Vector3(0f, 0f, Next(random, 80f));
|
||||
|
||||
var lightPointOnPlane = Vector3.Transform(Vector3.Transform(onPlane, occluder.View.CameraFromLocal), light.LocalFromCamera);
|
||||
var lightPointOffPlane = Vector3.Transform(Vector3.Transform(offPlane, occluder.View.CameraFromLocal), light.LocalFromCamera);
|
||||
|
||||
Assert.True(MathF.Abs(Dot(plane.Plane, lightPointOnPlane)) < Tolerance * 10f, $"{index} on");
|
||||
Assert.True(MathF.Abs(Dot(plane.Plane, lightPointOffPlane) - offPlane.Z) < Tolerance * 10f, $"{index} off");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f, 1f, false)]
|
||||
[InlineData(1.6f, 0.7f, false)]
|
||||
[InlineData(1.6f, 0.7f, true)]
|
||||
[InlineData(0.5f, 2f, true)]
|
||||
public void TheImagePositionIsWhereTheOccluderPixelIs(float zoomX, float zoomY, bool invert)
|
||||
{
|
||||
var random = new Random(5);
|
||||
var center = new Vector2(30f, -12f);
|
||||
for (var index = 0; index < 20; index++)
|
||||
{
|
||||
var lightDraw = Describe(new Vector3(Next(random, 100f), Next(random, 100f), 0f), new Vector3(Next(random, 30f), Next(random, 30f), 0f), Camera(random), Vector2.One, false, Vector2.Zero);
|
||||
var occluderDraw = Describe(new Vector3(Next(random, 100f), Next(random, 100f), Next(random, 100f)), new Vector3(Next(random, 30f), Next(random, 30f), Next(random, 30f)), lightDraw.Camera, new Vector2(zoomX, zoomY), invert, center);
|
||||
var light = View(lightDraw);
|
||||
var occluder = Create(occluderDraw);
|
||||
var plane = OccluderPlane.Create(light.CameraFromLocal, occluder);
|
||||
var local = new Vector3(Next(random, 120f), Next(random, 120f), 0f);
|
||||
var lightPoint = Vector3.Transform(Vector3.Transform(local, occluder.View.CameraFromLocal), light.LocalFromCamera);
|
||||
|
||||
var expected = occluder.Gobo.ToImage(local.X, local.Y);
|
||||
|
||||
Assert.True(MathF.Abs(Dot(plane.ImageX, lightPoint) - expected.X) < Tolerance * 10f, $"{index} x");
|
||||
Assert.True(MathF.Abs(Dot(plane.ImageY, lightPoint) - expected.Y) < Tolerance * 10f, $"{index} y");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderSittingOnTheLightPlaneHasThePlaneEquationOfThatPlane()
|
||||
{
|
||||
var draw = Describe(new Vector3(20f, -10f, 0f), new Vector3(10f, 20f, 5f), Matrix4x4.Identity, Vector2.One, false, Vector2.Zero);
|
||||
var light = View(draw);
|
||||
|
||||
var plane = OccluderPlane.Create(light.CameraFromLocal, Create(draw));
|
||||
|
||||
Assert.True(MathF.Abs(Dot(plane.Plane, new Vector3(30f, 40f, 0f))) < Tolerance);
|
||||
Assert.True(MathF.Abs(Dot(plane.Plane, new Vector3(30f, 40f, 25f)) - 25f) < Tolerance);
|
||||
Assert.True(MathF.Abs(Dot(plane.ImageX, new Vector3(30f, 40f, 0f)) - 30f) < Tolerance);
|
||||
Assert.True(MathF.Abs(Dot(plane.ImageY, new Vector3(30f, 40f, 0f)) - 40f) < Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(-1f)]
|
||||
[InlineData(float.NaN)]
|
||||
public void AnOccluderWithoutStrengthLeavesNoPlane(float strength)
|
||||
{
|
||||
var draw = Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity, Vector2.One, false, Vector2.Zero);
|
||||
|
||||
Assert.Equal(default, OccluderPlane.Create(View(draw).CameraFromLocal, Create(draw, strength)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnInfiniteImageMappingLeavesNoPlane()
|
||||
{
|
||||
var draw = Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity, Vector2.Zero, false, Vector2.Zero);
|
||||
|
||||
Assert.Equal(default, OccluderPlane.Create(View(draw).CameraFromLocal, Create(draw)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100d, 1d, 1f)]
|
||||
[InlineData(50d, 1d, 0.5f)]
|
||||
[InlineData(100d, 0.25d, 0.25f)]
|
||||
[InlineData(50d, 0.5d, 0.25f)]
|
||||
[InlineData(250d, 1d, 1f)]
|
||||
[InlineData(-10d, 1d, 0f)]
|
||||
[InlineData(100d, 3d, 1f)]
|
||||
[InlineData(100d, -1d, 0f)]
|
||||
public void TheStrengthIsThePercentTimesTheOpacityWithinZeroAndOne(double percent, double opacity, float expected)
|
||||
{
|
||||
Assert.Equal(expected, Occluder.GetStrength(percent, opacity), 5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
internal static class PackUriScheme
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Register() => _ = PackUriHelper.UriSchemePack;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace VolumetricLight.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class ScreenBoundsTests
|
||||
{
|
||||
static readonly PlaneRect Rect = new(-200f, -100f, 200f, 100f);
|
||||
|
||||
static ViewTransform View(Vector3 draw, Vector3 rotation, Matrix4x4 camera)
|
||||
{
|
||||
var description = new DrawDescription(draw, Vector2.Zero, Vector2.One, rotation, camera, InterpolationMode.Linear, 1d, false, []);
|
||||
Assert.True(ViewTransform.TryCreate(description, out var view));
|
||||
return view;
|
||||
}
|
||||
|
||||
static LightVolume Volume(double azimuth, double elevation, double spread, double length)
|
||||
{
|
||||
Assert.True(LightVolume.TryCreate(Rect, VolumetricLightSettings.GetAxis(azimuth, elevation), spread, length, 1f, out var volume));
|
||||
return volume;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1280, 720, -640, -360, 640, 360)]
|
||||
[InlineData(1281, 721, -641, -361, 641, 361)]
|
||||
[InlineData(1920, 1080, -960, -540, 960, 540)]
|
||||
public void TheCanvasIsCenteredOnTheOrigin(int width, int height, int left, int top, int right, int bottom)
|
||||
{
|
||||
Assert.Equal(new ScreenRect(left, top, right, bottom), ScreenRect.FromCanvas(width, height));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheIntersectionKeepsOnlyTheSharedArea()
|
||||
{
|
||||
var first = new ScreenRect(-10, -10, 20, 30);
|
||||
var second = new ScreenRect(0, -20, 50, 10);
|
||||
|
||||
Assert.Equal(new ScreenRect(0, -10, 20, 10), first.Intersect(second));
|
||||
Assert.True(first.Intersect(new ScreenRect(30, 0, 40, 10)).IsEmpty);
|
||||
Assert.True(default(ScreenRect).IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ScalingRoundsTheEdgesOutward()
|
||||
{
|
||||
Assert.Equal(new ScreenRect(-6, -6, 7, 9), new ScreenRect(-11, -11, 13, 17).Scale(0.5f));
|
||||
Assert.Equal(new ScreenRect(-5, -6, 7, 9), new ScreenRect(-10, -11, 13, 17).Scale(0.5f));
|
||||
Assert.Equal(new ScreenRect(-10, -11, 13, 17), new ScreenRect(-10, -11, 13, 17).Scale(1f));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRectangleIsTheBoundingBoxOfTheProjectedCorners()
|
||||
{
|
||||
var view = View(new Vector3(30f, -20f, 0f), new Vector3(10f, 20f, 0f), Matrix4x4.Identity);
|
||||
var volume = Volume(-90d, 30d, 10d, 400d);
|
||||
var canvas = ScreenRect.FromCanvas(8192, 8192);
|
||||
var corners = new Vector3[8];
|
||||
volume.GetCorners(corners);
|
||||
var projected = corners.Select(corner =>
|
||||
{
|
||||
Assert.True(view.TryProject(corner, out var screen));
|
||||
return screen;
|
||||
}).ToArray();
|
||||
|
||||
var rect = ScreenBounds.GetVolumeRect(view, volume, canvas);
|
||||
|
||||
Assert.Equal((int)Math.Floor(projected.Min(point => point.X)), rect.Left);
|
||||
Assert.Equal((int)Math.Floor(projected.Min(point => point.Y)), rect.Top);
|
||||
Assert.Equal((int)Math.Ceiling(projected.Max(point => point.X)), rect.Right);
|
||||
Assert.Equal((int)Math.Ceiling(projected.Max(point => point.Y)), rect.Bottom);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRectangleNeverLeavesTheCanvas()
|
||||
{
|
||||
var view = View(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity);
|
||||
var canvas = ScreenRect.FromCanvas(320, 180);
|
||||
|
||||
var rect = ScreenBounds.GetVolumeRect(view, Volume(-90d, 55d, 10d, 1200d), canvas);
|
||||
|
||||
Assert.False(rect.IsEmpty);
|
||||
Assert.True(rect.Left >= canvas.Left && rect.Top >= canvas.Top && rect.Right <= canvas.Right && rect.Bottom <= canvas.Bottom);
|
||||
Assert.Equal(canvas.Bottom, rect.Bottom);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AVolumeEntirelyOffTheCanvasHasNoRectangle()
|
||||
{
|
||||
var view = View(new Vector3(0f, -5000f, 0f), Vector3.Zero, Matrix4x4.Identity);
|
||||
|
||||
var rect = ScreenBounds.GetVolumeRect(view, Volume(90d, 20d, 0d, 100d), ScreenRect.FromCanvas(1280, 720));
|
||||
|
||||
Assert.True(rect.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AVolumeThatReachesBehindTheEyeCoversTheCanvas()
|
||||
{
|
||||
var view = View(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity);
|
||||
var canvas = ScreenRect.FromCanvas(1280, 720);
|
||||
|
||||
var rect = ScreenBounds.GetVolumeRect(view, Volume(-90d, 80d, 0d, 20000d), canvas);
|
||||
|
||||
Assert.Equal(canvas, rect);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
using System.Numerics;
|
||||
using System.Windows.Media;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using static VolumetricLight.ShaftCustomEffect;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ShaftCustomEffectTests(ITestOutputHelper output)
|
||||
{
|
||||
const int GoboSize = 128;
|
||||
const int Canvas = 512;
|
||||
const float Relative = 0.03f;
|
||||
const float Absolute = 0.003f;
|
||||
const double ToleratedFraction = 0.995;
|
||||
|
||||
static VolumetricLightParameters Typical => new(-90d, 55d, 10d, 300d, 100d, Colors.White, 60d, 1.5d, 30d, 0d, 40d, 40d, -90d, 0, VolumetricLightQuality.Ultra);
|
||||
|
||||
static Func<int, int, Vector3> EmissionOf(int size) => (x, y) =>
|
||||
{
|
||||
const int Margin = 12;
|
||||
if (x < Margin || y < Margin || x >= size - Margin || y >= size - Margin)
|
||||
return Vector3.Zero;
|
||||
|
||||
var bars = (x / 6) % 2 == 0 ? 0.9f : 0.2f;
|
||||
var dx = x - size / 2;
|
||||
var dy = y - size / 2;
|
||||
var disc = dx * dx + dy * dy < 24 * 24 ? 1f : 0.25f;
|
||||
return new Vector3(bars, y / (float)size, disc);
|
||||
};
|
||||
|
||||
static Vector3 CenteredAt(int size) => new(-size / 2f, -size / 2f, 0f);
|
||||
|
||||
static readonly Vector3 CenteredDraw = new(-64f, -64f, 0f);
|
||||
|
||||
static DrawDescription Pose(Vector3? draw = null, Vector3? rotation = null, Matrix4x4? camera = null, Vector2? zoom = null, Vector2? center = null, bool invert = false)
|
||||
=> new(draw ?? Vector3.Zero, center ?? Vector2.Zero, zoom ?? Vector2.One, rotation ?? Vector3.Zero, camera ?? Matrix4x4.Identity, InterpolationMode.Linear, 1d, invert, []);
|
||||
|
||||
static Matrix4x4 OrbitCamera(Vector3 position, Vector3 rotationDegrees)
|
||||
{
|
||||
var pivot = new Vector3(0f, 0f, 1000f);
|
||||
return Matrix4x4.CreateTranslation(-new Vector3(position.X, position.Y, -position.Z))
|
||||
* Matrix4x4.CreateRotationY(MathF.PI * rotationDegrees.Y / 180f, pivot)
|
||||
* Matrix4x4.CreateRotationX(MathF.PI * rotationDegrees.X / 180f, pivot)
|
||||
* Matrix4x4.CreateRotationZ(MathF.PI * rotationDegrees.Z / 180f, pivot);
|
||||
}
|
||||
|
||||
sealed class OccluderRig : IDisposable
|
||||
{
|
||||
readonly OccluderLease lease;
|
||||
readonly OccluderSlot[] slots;
|
||||
readonly ID2D1Bitmap1[] bitmaps;
|
||||
readonly OccluderLink link = new() { Frame = 0 };
|
||||
|
||||
public OccluderRig(IGraphicsDevicesAndContext devices, IReadOnlyList<(DrawDescription Draw, GoboPyramid Image, float Strength)> occluders)
|
||||
{
|
||||
lease = OccluderRegistry.Acquire(devices, Guid.Empty, 1);
|
||||
link.Group = lease.Group;
|
||||
LinkId = OccluderLinks.Register(link);
|
||||
slots = new OccluderSlot[occluders.Count];
|
||||
bitmaps = new ID2D1Bitmap1[occluders.Count];
|
||||
for (var index = 0; index < occluders.Count; index++)
|
||||
{
|
||||
var (draw, image, strength) = occluders[index];
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
slots[index] = lease.Group.Claim()!;
|
||||
bitmaps[index] = image.CreateBitmaps(devices)[0];
|
||||
slots[index].Publish(bitmaps[index], new Occluder(view, GoboMapping.Create(draw.Zoom, draw.Invert, draw.CenterPoint), strength), 0);
|
||||
}
|
||||
}
|
||||
|
||||
public int LinkId { get; }
|
||||
|
||||
public ID2D1Image GetOutput(int slot) => lease.Group.GetOutput(slot);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var slot in slots)
|
||||
slot.Dispose();
|
||||
OccluderLinks.Unregister(LinkId);
|
||||
lease.Dispose();
|
||||
foreach (var bitmap in bitmaps)
|
||||
bitmap.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static (FloatRendering Rendering, ShaftShaderModel Model, ShaftScene Scene) Render(IGraphicsDevicesAndContext devices, VolumetricLightParameters parameters, DrawDescription draw, IReadOnlyList<(DrawDescription Draw, GoboPyramid Image, float Strength)>? occluders = null, int size = GoboSize)
|
||||
{
|
||||
var pyramid = new GoboPyramid(size, size, EmissionOf(size));
|
||||
Assert.True(ShaftScene.TryCreate(parameters, draw, new RawRectF(0f, 0f, size, size), Canvas, Canvas, 0, EffectDescriptions.Fps, out var scene));
|
||||
using var rig = new OccluderRig(devices, occluders ?? []);
|
||||
using var effect = new ShaftCustomEffect(devices);
|
||||
var bitmaps = pyramid.CreateBitmaps(devices);
|
||||
try
|
||||
{
|
||||
for (var level = 0; level < bitmaps.Length; level++)
|
||||
effect.SetInput(level, bitmaps[level], true);
|
||||
for (var slot = 0; slot < VolumetricLightSettings.OccluderCapacity; slot++)
|
||||
effect.SetInput(VolumetricLightSettings.GoboLevelCount + slot, rig.GetOutput(slot), true);
|
||||
effect.Link = rig.LinkId;
|
||||
effect.Apply(scene.Constants, default, true);
|
||||
using var image = effect.Output;
|
||||
var rendering = FloatRendering.Capture(devices, image);
|
||||
for (var index = 0; index < VolumetricLightSettings.GoboLevelCount + VolumetricLightSettings.OccluderCapacity; index++)
|
||||
effect.SetInput(index, null, true);
|
||||
var planes = (occluders ?? []).Select(occluder =>
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(occluder.Draw, out var view));
|
||||
return (OccluderPlane.Create(scene.Constants.CameraFromLocal, new Occluder(view, GoboMapping.Create(occluder.Draw.Zoom, occluder.Draw.Invert, occluder.Draw.CenterPoint), occluder.Strength)), occluder.Image);
|
||||
}).ToArray();
|
||||
return (rendering, new ShaftShaderModel(scene.Constants, pyramid, planes), scene);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var bitmap in bitmaps)
|
||||
bitmap.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
void AssertFollowsTheModel(FloatRendering rendering, ShaftShaderModel model, string where)
|
||||
{
|
||||
var total = 0;
|
||||
var close = 0;
|
||||
var lit = 0;
|
||||
var worst = 0f;
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
var actual = rendering[x, y];
|
||||
var expected = model.Shade(x, y);
|
||||
var error = MathF.Max(MathF.Abs(expected.X - actual.X), MathF.Max(MathF.Abs(expected.Y - actual.Y), MathF.Abs(expected.Z - actual.Z)));
|
||||
var scale = MathF.Max(expected.X, MathF.Max(expected.Y, expected.Z));
|
||||
total++;
|
||||
if (scale > Absolute)
|
||||
lit++;
|
||||
if (error <= Relative * scale + Absolute)
|
||||
close++;
|
||||
else
|
||||
worst = MathF.Max(worst, error / (scale + Absolute));
|
||||
Assert.Equal(0f, actual.W);
|
||||
}
|
||||
|
||||
output.WriteLine($"{where}: {close}/{total} close, lit={lit}, worst={worst:F3}");
|
||||
Assert.True(lit > total / 50, $"{where} は光が少なすぎます。{lit}/{total}");
|
||||
Assert.True(close >= total * ToleratedFraction, $"{where} {close}/{total}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsEnabledOnceCreated()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new ShaftCustomEffect(context);
|
||||
|
||||
Assert.True(effect.IsEnabled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-90d, 55d, 0d)]
|
||||
[InlineData(-90d, 55d, 12d)]
|
||||
[InlineData(30d, 40d, 25d)]
|
||||
[InlineData(-90d, 55d, -15d)]
|
||||
[InlineData(200d, -35d, 0d)]
|
||||
[InlineData(-90d, 80d, 0d)]
|
||||
public void TheShaderFollowsTheModel(double azimuth, double elevation, double spread)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (rendering, model, _) = Render(context, Typical with { Direction = azimuth, Elevation = elevation, Spread = spread }, Pose(CenteredDraw));
|
||||
|
||||
AssertFollowsTheModel(rendering, model, $"{azimuth}/{elevation}/{spread}");
|
||||
}
|
||||
|
||||
const int ScreenSize = 64;
|
||||
|
||||
static GoboPyramid Stripes() => new(ScreenSize, ScreenSize, (x, y) => new Vector4(0f, 0f, 0f, (x / 8) % 2 == 0 ? 1f : 0f));
|
||||
|
||||
static GoboPyramid Disc() => new(ScreenSize, ScreenSize, (x, y) =>
|
||||
{
|
||||
var dx = x - ScreenSize / 2;
|
||||
var dy = y - ScreenSize / 2;
|
||||
return new Vector4(0f, 0f, 0f, dx * dx + dy * dy < 24 * 24 ? 0.7f : 0f);
|
||||
});
|
||||
|
||||
static (DrawDescription Draw, GoboPyramid Image, float Strength) Occlude(GoboPyramid image, Vector3 draw, Vector3? rotation = null, float strength = 1f, float zoom = 1f)
|
||||
=> (Pose(draw, rotation, zoom: new Vector2(zoom)), image, strength);
|
||||
|
||||
public static TheoryData<string> Shadows => new()
|
||||
{
|
||||
"stripes",
|
||||
"soft-disc",
|
||||
"two",
|
||||
"four",
|
||||
"tilted",
|
||||
"behind-the-window",
|
||||
};
|
||||
|
||||
static IReadOnlyList<(DrawDescription Draw, GoboPyramid Image, float Strength)> NamedShadow(string name) => name switch
|
||||
{
|
||||
"stripes" => [Occlude(Stripes(), new Vector3(-32f, 20f, 60f))],
|
||||
"soft-disc" => [Occlude(Disc(), new Vector3(-32f, 10f, 70f), strength: 0.6f)],
|
||||
"two" => [Occlude(Stripes(), new Vector3(-32f, 10f, 40f)), Occlude(Disc(), new Vector3(-20f, 40f, 110f), strength: 0.8f)],
|
||||
"four" => [Occlude(Disc(), new Vector3(-60f, 20f, 40f)), Occlude(Disc(), new Vector3(10f, 20f, 60f)), Occlude(Stripes(), new Vector3(-30f, 50f, 90f), strength: 0.5f), Occlude(Disc(), new Vector3(-20f, 60f, 140f), strength: 0.9f)],
|
||||
"tilted" => [Occlude(Stripes(), new Vector3(-32f, 20f, 70f), new Vector3(35f, -25f, 12f))],
|
||||
_ => [Occlude(Stripes(), new Vector3(-64f, -100f, -60f), zoom: 2f)],
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Shadows))]
|
||||
public void TheShaderFollowsTheModelWithOccluders(string name)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var occluders = NamedShadow(name);
|
||||
|
||||
var (shadowed, model, _) = Render(context, Typical, Pose(CenteredDraw), occluders);
|
||||
var (clear, _, _) = Render(context, Typical, Pose(CenteredDraw));
|
||||
|
||||
AssertFollowsTheModel(shadowed, model, name);
|
||||
var darker = shadowed.Coordinates().Count(point => shadowed[point.X, point.Y].X < clear[point.X, point.Y].X * 0.9f - Absolute);
|
||||
output.WriteLine($"{name}: darker={darker}");
|
||||
if (name == "behind-the-window")
|
||||
Assert.Equal(0, darker);
|
||||
else
|
||||
Assert.True(darker > 200, $"{name} {darker}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderFollowsTheModelWhereTheStepCountIsHeldAtItsUpperLimit()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (rendering, model, _) = Render(context, Typical with { Quality = VolumetricLightQuality.Standard, LampSize = 0d, Elevation = 25d, Length = 2500d }, Pose(CenteredAt(512)), size: 512);
|
||||
|
||||
AssertFollowsTheModel(rendering, model, "upper limit");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderFollowsTheModelWhereTheStepCountIsHeldAtItsLowerLimit()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (rendering, model, _) = Render(context, Typical with { Quality = VolumetricLightQuality.Standard, Length = 12d, Elevation = 80d }, Pose(CenteredDraw));
|
||||
|
||||
AssertFollowsTheModel(rendering, model, "lower limit");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderOfNoStrengthOrBeyondTheSourceLeavesTheLightAsItWas()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (clear, _, _) = Render(context, Typical, Pose(CenteredDraw));
|
||||
var (weak, _, _) = Render(context, Typical, Pose(CenteredDraw), [Occlude(Stripes(), new Vector3(-32f, 20f, 60f), strength: 0f)]);
|
||||
var (behind, _, _) = Render(context, Typical, Pose(CenteredDraw), [Occlude(Stripes(), new Vector3(-64f, -100f, -60f), zoom: 2f)]);
|
||||
|
||||
Assert.All(clear.Coordinates(), point =>
|
||||
{
|
||||
Assert.Equal(clear[point.X, point.Y], weak[point.X, point.Y]);
|
||||
Assert.Equal(clear[point.X, point.Y], behind[point.X, point.Y]);
|
||||
});
|
||||
}
|
||||
|
||||
public static TheoryData<string> Poses => new()
|
||||
{
|
||||
"rotated",
|
||||
"orbit",
|
||||
"zoomed",
|
||||
"inverted",
|
||||
"off-center",
|
||||
"close",
|
||||
"orthographic",
|
||||
"orthographic-turned",
|
||||
};
|
||||
|
||||
static DrawDescription NamedPose(string name) => name switch
|
||||
{
|
||||
"rotated" => Pose(CenteredDraw, new Vector3(25f, -35f, 10f)),
|
||||
"orbit" => Pose(CenteredDraw, camera: OrbitCamera(new Vector3(40f, -20f, 120f), new Vector3(3f, 7f, 2f))),
|
||||
"zoomed" => Pose(CenteredDraw, zoom: new Vector2(1.6f, 0.7f)),
|
||||
"inverted" => Pose(CenteredDraw, invert: true),
|
||||
"off-center" => Pose(CenteredDraw, new Vector3(0f, 20f, 0f), center: new Vector2(24f, -16f)),
|
||||
"orthographic" => Pose(new Vector3(-62.4f, -64.3f, 0f)) with { PerspectiveDistance = float.PositiveInfinity },
|
||||
"orthographic-turned" => Pose(CenteredDraw, new Vector3(0f, 0f, 30f)) with { PerspectiveDistance = float.PositiveInfinity },
|
||||
_ => Pose(new Vector3(-64f, -64f, 400f), new Vector3(0f, 0f, 15f)),
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Poses))]
|
||||
public void TheShaderFollowsTheModelUnderEveryPose(string name)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (rendering, model, _) = Render(context, Typical, NamedPose(name));
|
||||
|
||||
AssertFollowsTheModel(rendering, model, name);
|
||||
}
|
||||
|
||||
public static TheoryData<string> Variations => new()
|
||||
{
|
||||
"no-falloff",
|
||||
"strong-falloff",
|
||||
"forward",
|
||||
"backward",
|
||||
"isotropic",
|
||||
"wide-lamp",
|
||||
"sharp-lamp",
|
||||
"dusty",
|
||||
"dusty-wind",
|
||||
"tinted",
|
||||
};
|
||||
|
||||
static VolumetricLightParameters NamedVariation(string name) => name switch
|
||||
{
|
||||
"no-falloff" => Typical with { Falloff = 0d },
|
||||
"strong-falloff" => Typical with { Falloff = 95d },
|
||||
"forward" => Typical with { Scattering = 80d },
|
||||
"backward" => Typical with { Scattering = -60d },
|
||||
"isotropic" => Typical with { Scattering = 0d },
|
||||
"wide-lamp" => Typical with { LampSize = 25d },
|
||||
"sharp-lamp" => Typical with { LampSize = 0d },
|
||||
"dusty" => Typical with { DustAmount = 70d, DustSize = 30d },
|
||||
"dusty-wind" => Typical with { DustAmount = 70d, DustSize = 30d, DustSpeed = 400d, DustDirection = 35d, Seed = 77 },
|
||||
_ => Typical with { Tint = Color.FromRgb(255, 140, 40), Intensity = 250d },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Variations))]
|
||||
public void TheShaderFollowsTheModelForEveryLook(string name)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var (rendering, model, _) = Render(context, NamedVariation(name), Pose(CenteredDraw));
|
||||
|
||||
AssertFollowsTheModel(rendering, model, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
using System.Numerics;
|
||||
using System.Windows.Media;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class ShaftSceneTests
|
||||
{
|
||||
const float Tolerance = 1e-5f;
|
||||
const int Width = 1280;
|
||||
const int Height = 720;
|
||||
const int Fps = 30;
|
||||
|
||||
static readonly RawRectF Bounds = new(-480f, -270f, 480f, 270f);
|
||||
|
||||
static VolumetricLightParameters Typical => new(-90d, 55d, 10d, 1200d, 100d, Colors.White, 60d, 1.5d, 30d, 0d, 220d, 40d, -90d, 0, VolumetricLightQuality.Standard);
|
||||
|
||||
static DrawDescription Draw(Vector3? position = null, Vector2? zoom = null, bool invert = false, double opacity = 1d)
|
||||
=> new(position ?? Vector3.Zero, Vector2.Zero, zoom ?? Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, opacity, invert, []);
|
||||
|
||||
static ShaftScene Create(VolumetricLightParameters parameters, DrawDescription? draw = null, long frame = 0)
|
||||
{
|
||||
Assert.True(ShaftScene.TryCreate(parameters, draw ?? Draw(), Bounds, Width, Height, frame, Fps, out var scene));
|
||||
return scene;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATypicalItemProducesAScene()
|
||||
{
|
||||
var scene = Create(Typical);
|
||||
|
||||
Assert.Equal(0.5f, scene.Scale);
|
||||
Assert.Equal(ScreenRect.FromCanvas(Width, Height), scene.Canvas);
|
||||
Assert.False(scene.Shaft.IsEmpty);
|
||||
Assert.Equal(-0.001f, scene.Constants.View.X);
|
||||
Assert.Equal(1f, scene.Constants.Mode.Z * 0.5f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheVolumeAndTheViewAreCarriedIntoTheConstants()
|
||||
{
|
||||
var scene = Create(Typical);
|
||||
var volume = scene.Volume;
|
||||
|
||||
Assert.Equal(new Vector4(volume.Focus, 1f), scene.Constants.Focus);
|
||||
Assert.Equal(new Vector4(volume.Axis, 1f), scene.Constants.Axis);
|
||||
Assert.Equal(volume.Planes[0], scene.Constants.Plane0);
|
||||
Assert.Equal(volume.Planes[5], scene.Constants.Plane5);
|
||||
Assert.Equal(scene.View.LocalFromCamera, scene.Constants.LocalFromCamera);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AParallelBeamHasNoFocus()
|
||||
{
|
||||
var scene = Create(Typical with { Spread = 0d });
|
||||
|
||||
Assert.Equal(0f, scene.Constants.Focus.W);
|
||||
Assert.Equal(1f, scene.Constants.Axis.W);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConvergingBeamCarriesAMinusSign()
|
||||
{
|
||||
var scene = Create(Typical with { Spread = -20d });
|
||||
|
||||
Assert.Equal(1f, scene.Constants.Focus.W);
|
||||
Assert.Equal(-1f, scene.Constants.Axis.W);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBeamConstantsAreTheSettingsDerivations()
|
||||
{
|
||||
var scene = Create(Typical);
|
||||
var volume = scene.Volume;
|
||||
|
||||
Assert.Equal(VolumetricLightSettings.GetFalloffExponent(60d, 1200d), scene.Constants.Beam.X);
|
||||
Assert.Equal(VolumetricLightSettings.GetPenumbraSlope(1.5d), scene.Constants.Beam.Y);
|
||||
Assert.Equal(VolumetricLightSettings.GetAnisotropy(30d), scene.Constants.Beam.Z);
|
||||
Assert.Equal(VolumetricLightSettings.GetGain(100d, volume.HalfDiagonal), scene.Constants.Beam.W);
|
||||
Assert.Equal(VolumetricLightSettings.GetFade(60d, 1200d), scene.Constants.Fade);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMarchStepsFollowTheQualityAndTheEyeLimit()
|
||||
{
|
||||
var standard = Create(Typical).Constants.March;
|
||||
var ultra = Create(Typical with { Quality = VolumetricLightQuality.Ultra }).Constants.March;
|
||||
|
||||
Assert.Equal(3f, standard.X);
|
||||
Assert.Equal(64f, standard.Y);
|
||||
Assert.Equal(1f, standard.Z);
|
||||
Assert.Equal(1f, ultra.X);
|
||||
Assert.Equal(192f, ultra.Y);
|
||||
Assert.Equal((1f / 8192f - 1f) / -0.001f, standard.W, 1f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePhysicalResolutionIsHalfAtStandardAndFullAtUltra()
|
||||
{
|
||||
var standard = Create(Typical);
|
||||
var ultra = Create(Typical with { Quality = VolumetricLightQuality.Ultra });
|
||||
|
||||
Assert.Equal(0.5f, standard.Scale);
|
||||
Assert.Equal(2f, standard.Constants.Mode.Z);
|
||||
Assert.Equal(1f, ultra.Scale);
|
||||
Assert.Equal(1f, ultra.Constants.Mode.Z);
|
||||
Assert.True(ultra.Shaft.Right - ultra.Shaft.Left >= 2 * (standard.Shaft.Right - standard.Shaft.Left) - 2);
|
||||
Assert.Equal(VolumetricLightSettings.MinimumSteps, standard.Constants.Mode.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTintIsPassedAsAFractionOfEachChannel()
|
||||
{
|
||||
var scene = Create(Typical with { Tint = Color.FromRgb(255, 128, 0) });
|
||||
|
||||
Assert.Equal(1f, scene.Constants.Tint.X);
|
||||
Assert.Equal(128f / 255f, scene.Constants.Tint.Y, Tolerance);
|
||||
Assert.Equal(0f, scene.Constants.Tint.Z);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, 30L, 100d, 100f, 0f)]
|
||||
[InlineData(90d, 30L, 100d, 0f, -100f)]
|
||||
[InlineData(180d, 60L, 50d, -100f, 0f)]
|
||||
[InlineData(0d, 0L, 100d, 0f, 0f)]
|
||||
[InlineData(0d, 30L, 1e9d, 5000f, 0f)]
|
||||
public void TheDustDriftsAlongItsDirectionAtItsSpeed(double direction, long frame, double speed, float expectedX, float expectedY)
|
||||
{
|
||||
var scene = Create(Typical with { DustDirection = direction, DustSpeed = speed }, frame: frame);
|
||||
|
||||
Assert.Equal(expectedX, scene.Constants.Wind.X, 1e-3f);
|
||||
Assert.Equal(expectedY, scene.Constants.Wind.Y, 1e-3f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDustSeedAndAmountAreClamped()
|
||||
{
|
||||
var scene = Create(Typical with { DustAmount = 250d, Seed = 7, DustSize = 100d });
|
||||
|
||||
Assert.Equal(1f, scene.Constants.Dust.X);
|
||||
Assert.Equal(0.01f, scene.Constants.Dust.Y, Tolerance);
|
||||
Assert.Equal(7f, scene.Constants.Dust.Z);
|
||||
Assert.Equal(0f, Create(Typical with { DustAmount = -5d }).Constants.Dust.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGoboMappingUsesTheZoomAndTheFlip()
|
||||
{
|
||||
var scene = Create(Typical, Draw(zoom: new Vector2(2f, 4f), invert: true));
|
||||
|
||||
Assert.Equal(-0.5f, scene.Constants.Gobo.X);
|
||||
Assert.Equal(0f, scene.Constants.Gobo.Y);
|
||||
Assert.Equal(0.25f, scene.Constants.Gobo.Z);
|
||||
Assert.Equal(0f, scene.Constants.Gobo.W);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePositionMovesTheVolumeOnTheScreen()
|
||||
{
|
||||
var centered = Create(Typical);
|
||||
var shifted = Create(Typical, Draw(new Vector3(100f, 0f, 0f)));
|
||||
|
||||
Assert.Equal(centered.Constants.March.Z, shifted.Constants.March.Z);
|
||||
Assert.NotEqual(centered.Constants.LocalFromCamera, shifted.Constants.LocalFromCamera);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0f, 1.0f, 1d)]
|
||||
[InlineData(1.0f, 0.0f, 1d)]
|
||||
[InlineData(1.0f, 1.0f, 0d)]
|
||||
public void AnInvisibleItemHasNoScene(float zoomX, float zoomY, double opacity)
|
||||
{
|
||||
Assert.False(ShaftScene.TryCreate(Typical, Draw(zoom: new Vector2(zoomX, zoomY), opacity: opacity), Bounds, Width, Height, 0, Fps, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyOrOversizedSourceHasNoScene()
|
||||
{
|
||||
Assert.False(ShaftScene.TryCreate(Typical, Draw(), new RawRectF(0f, 0f, 0f, 100f), Width, Height, 0, Fps, out _));
|
||||
Assert.False(ShaftScene.TryCreate(Typical, Draw(), new RawRectF(0f, 0f, 100f, -5f), Width, Height, 0, Fps, out _));
|
||||
Assert.False(ShaftScene.TryCreate(Typical, Draw(), new RawRectF(-3000f, 0f, 3000f, 100f), Width, Height, 0, Fps, out _));
|
||||
Assert.False(ShaftScene.TryCreate(Typical, Draw(), new RawRectF(float.MinValue, float.MinValue, float.MaxValue, float.MaxValue), Width, Height, 0, Fps, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABeamOfNoLengthHasNoScene()
|
||||
{
|
||||
Assert.False(ShaftScene.TryCreate(Typical with { Length = 0d }, Draw(), Bounds, Width, Height, 0, Fps, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLengthIsLimited()
|
||||
{
|
||||
var limited = Create(Typical with { Length = 1e12d });
|
||||
var maximum = Create(Typical with { Length = VolumetricLightSettings.MaximumLength });
|
||||
|
||||
Assert.Equal(maximum.Volume.FarDepth, limited.Volume.FarDepth);
|
||||
Assert.Equal(maximum.Constants.Fade, limited.Constants.Fade);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
internal sealed class GoboPyramid
|
||||
{
|
||||
const int Channels = 4;
|
||||
const float MaximumAlpha = 1f;
|
||||
|
||||
readonly float[][] levels = new float[VolumetricLightSettings.GoboLevelCount][];
|
||||
readonly int[] widths = new int[VolumetricLightSettings.GoboLevelCount];
|
||||
readonly int[] heights = new int[VolumetricLightSettings.GoboLevelCount];
|
||||
|
||||
public GoboPyramid(int width, int height, Func<int, int, Vector3> emission)
|
||||
: this(width, height, (x, y) => new Vector4(emission(x, y), MaximumAlpha))
|
||||
{
|
||||
}
|
||||
|
||||
public GoboPyramid(int width, int height, Func<int, int, Vector4> texel)
|
||||
{
|
||||
widths[0] = width;
|
||||
heights[0] = height;
|
||||
levels[0] = new float[width * height * Channels];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var value = texel(x, y);
|
||||
var offset = (y * width + x) * Channels;
|
||||
levels[0][offset] = value.X;
|
||||
levels[0][offset + 1] = value.Y;
|
||||
levels[0][offset + 2] = value.Z;
|
||||
levels[0][offset + 3] = value.W;
|
||||
}
|
||||
}
|
||||
|
||||
for (var level = 1; level < levels.Length; level++)
|
||||
{
|
||||
widths[level] = widths[level - 1] / 2;
|
||||
heights[level] = heights[level - 1] / 2;
|
||||
levels[level] = new float[widths[level] * heights[level] * Channels];
|
||||
for (var y = 0; y < heights[level]; y++)
|
||||
{
|
||||
for (var x = 0; x < widths[level]; x++)
|
||||
{
|
||||
for (var channel = 0; channel < Channels; channel++)
|
||||
{
|
||||
var sum = 0f;
|
||||
for (var dy = 0; dy < 2; dy++)
|
||||
{
|
||||
for (var dx = 0; dx < 2; dx++)
|
||||
sum += levels[level - 1][((2 * y + dy) * widths[level - 1] + 2 * x + dx) * Channels + channel];
|
||||
}
|
||||
|
||||
levels[level][(y * widths[level] + x) * Channels + channel] = sum * 0.25f;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Width => widths[0];
|
||||
|
||||
public int Height => heights[0];
|
||||
|
||||
public Vector4 Fetch(int level, int x, int y)
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= widths[level] || y >= heights[level])
|
||||
return Vector4.Zero;
|
||||
|
||||
var offset = (y * widths[level] + x) * Channels;
|
||||
return new Vector4(levels[level][offset], levels[level][offset + 1], levels[level][offset + 2], levels[level][offset + 3]);
|
||||
}
|
||||
|
||||
public Vector4 Bilinear(int level, float u, float v)
|
||||
{
|
||||
var x = u * widths[level] - 0.5f;
|
||||
var y = v * heights[level] - 0.5f;
|
||||
var x0 = (int)MathF.Floor(x);
|
||||
var y0 = (int)MathF.Floor(y);
|
||||
var fx = x - x0;
|
||||
var fy = y - y0;
|
||||
var top = Vector4.Lerp(Fetch(level, x0, y0), Fetch(level, x0 + 1, y0), fx);
|
||||
var bottom = Vector4.Lerp(Fetch(level, x0, y0 + 1), Fetch(level, x0 + 1, y0 + 1), fx);
|
||||
return Vector4.Lerp(top, bottom, fy);
|
||||
}
|
||||
|
||||
public ID2D1Bitmap1[] CreateBitmaps(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var format = new PixelFormat(Format.R32G32B32A32_Float, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
var bitmaps = new ID2D1Bitmap1[levels.Length];
|
||||
for (var level = 0; level < levels.Length; level++)
|
||||
{
|
||||
var stride = widths[level] * Channels * sizeof(float);
|
||||
bitmaps[level] = devices.DeviceContext.CreateBitmap(
|
||||
new SizeI(widths[level], heights[level]), nint.Zero, stride,
|
||||
new BitmapProperties1(format, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
||||
bitmaps[level].CopyFromMemory(MemoryMarshal.AsBytes(levels[level].AsSpan()).ToArray(), stride);
|
||||
}
|
||||
|
||||
return bitmaps;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ShaftShaderModel(ShaftConstants constants, GoboPyramid pyramid, IReadOnlyList<(OccluderPlane Plane, GoboPyramid Image)>? occluders = null)
|
||||
{
|
||||
const float RateEpsilon = 1e-9f;
|
||||
const float UnitScale = 1f / 16777216f;
|
||||
const uint HashStep = 0x9E3779B9u;
|
||||
const uint HashMultiplyA = 0x85EBCA6Bu;
|
||||
const uint HashMultiplyB = 0xC2B2AE35u;
|
||||
const float DustSecondWeight = 0.5f;
|
||||
const float LinearFalloffLevel = 0.9999f;
|
||||
|
||||
readonly ShaftConstants c = constants;
|
||||
readonly GoboPyramid pyramid = pyramid;
|
||||
readonly IReadOnlyList<(OccluderPlane Plane, GoboPyramid Image)> occluders = occluders ?? [];
|
||||
|
||||
static uint Mix(uint value)
|
||||
{
|
||||
value ^= value >> 16;
|
||||
value *= HashMultiplyA;
|
||||
value ^= value >> 13;
|
||||
value *= HashMultiplyB;
|
||||
value ^= value >> 16;
|
||||
return value;
|
||||
}
|
||||
|
||||
static float ToUnit(uint value) => (value >> 8) * UnitScale;
|
||||
|
||||
static float Lattice(int x, int y, int z, uint seed)
|
||||
=> ToUnit(Mix(((uint)x * HashStep) ^ ((uint)y * HashMultiplyA) ^ ((uint)z * HashMultiplyB) ^ seed));
|
||||
|
||||
static float ValueNoise(Vector3 point, uint seed)
|
||||
{
|
||||
var origin = new Vector3(MathF.Floor(point.X), MathF.Floor(point.Y), MathF.Floor(point.Z));
|
||||
var cx = (int)origin.X;
|
||||
var cy = (int)origin.Y;
|
||||
var cz = (int)origin.Z;
|
||||
var fraction = point - origin;
|
||||
var blend = fraction * fraction * (new Vector3(3f) - 2f * fraction);
|
||||
float N(int dx, int dy, int dz) => Lattice(cx + dx, cy + dy, cz + dz, seed);
|
||||
float Lerp(float a, float b, float t) => a + (b - a) * t;
|
||||
return Lerp(
|
||||
Lerp(Lerp(N(0, 0, 0), N(1, 0, 0), blend.X), Lerp(N(0, 1, 0), N(1, 1, 0), blend.X), blend.Y),
|
||||
Lerp(Lerp(N(0, 0, 1), N(1, 0, 1), blend.X), Lerp(N(0, 1, 1), N(1, 1, 1), blend.X), blend.Y),
|
||||
blend.Z);
|
||||
}
|
||||
|
||||
static float Dust(Vector3 point, uint seed)
|
||||
=> (ValueNoise(point, seed) + DustSecondWeight * ValueNoise(point * 2f, Mix(seed))) / (1f + DustSecondWeight);
|
||||
|
||||
Vector3 Row(int index) => new(Get(c.LocalFromCamera, index, 0), Get(c.LocalFromCamera, index, 1), Get(c.LocalFromCamera, index, 2));
|
||||
|
||||
static float Get(Matrix4x4 matrix, int row, int column) => row switch
|
||||
{
|
||||
0 => column switch { 0 => matrix.M11, 1 => matrix.M12, _ => matrix.M13 },
|
||||
1 => column switch { 0 => matrix.M21, 1 => matrix.M22, _ => matrix.M23 },
|
||||
2 => column switch { 0 => matrix.M31, 1 => matrix.M32, _ => matrix.M33 },
|
||||
_ => column switch { 0 => matrix.M41, 1 => matrix.M42, _ => matrix.M43 },
|
||||
};
|
||||
|
||||
Vector4 Plane(int index) => index switch
|
||||
{
|
||||
0 => c.Plane0,
|
||||
1 => c.Plane1,
|
||||
2 => c.Plane2,
|
||||
3 => c.Plane3,
|
||||
4 => c.Plane4,
|
||||
_ => c.Plane5,
|
||||
};
|
||||
|
||||
Vector2 ImagePosition(Vector3 source) => new(c.Gobo.X * source.X + c.Gobo.Y, c.Gobo.Z * source.Y + c.Gobo.W);
|
||||
|
||||
(Vector3 Source, float Travel) FindSource(Vector3 point)
|
||||
{
|
||||
if (c.Focus.W > 0.5f)
|
||||
{
|
||||
var focus = new Vector3(c.Focus.X, c.Focus.Y, c.Focus.Z);
|
||||
var span = focus.Z - point.Z;
|
||||
var ratio = MathF.Abs(span) > RateEpsilon ? -point.Z / span : 0f;
|
||||
var toFocus = focus - point;
|
||||
return (point + toFocus * ratio, toFocus.Length() * MathF.Abs(ratio));
|
||||
}
|
||||
|
||||
var axis = new Vector3(c.Axis.X, c.Axis.Y, c.Axis.Z);
|
||||
var along = point.Z / axis.Z;
|
||||
return (point - axis * along, along);
|
||||
}
|
||||
|
||||
float GetLod(float divisor, float travel)
|
||||
=> MathF.Log2(MathF.Max(MathF.Max(divisor, 2f * c.Beam.Y * travel) / c.March.Z, 1f));
|
||||
|
||||
float GetPhase(Vector3 direction, Vector3 toEye)
|
||||
{
|
||||
var anisotropy = c.Beam.Z;
|
||||
var scatterBase = 1f + anisotropy * anisotropy - 2f * anisotropy * Vector3.Dot(direction, toEye);
|
||||
return (1f - anisotropy * anisotropy) / MathF.Sqrt(scatterBase) / scatterBase;
|
||||
}
|
||||
|
||||
float GetFalloff(float travel)
|
||||
{
|
||||
if (c.Fade.X >= LinearFalloffLevel)
|
||||
return Math.Clamp(1f - travel * c.Fade.Y, 0f, 1f);
|
||||
|
||||
return Math.Clamp((MathF.Exp(c.Beam.X * travel) - c.Fade.X) / (1f - c.Fade.X), 0f, 1f);
|
||||
}
|
||||
|
||||
Vector4 ReadLevel(int level, Vector2 image)
|
||||
{
|
||||
var position = image * MathF.Pow(2f, -level);
|
||||
var u = position.X / (pyramid.Width >> level);
|
||||
var v = position.Y / (pyramid.Height >> level);
|
||||
if (u < 0f || u > 1f || v < 0f || v > 1f)
|
||||
return Vector4.Zero;
|
||||
|
||||
return pyramid.Bilinear(level, u, v);
|
||||
}
|
||||
|
||||
Vector4 SampleGobo(Vector2 image, float lod)
|
||||
{
|
||||
var clamped = Math.Clamp(lod, 0f, VolumetricLightSettings.MaximumGoboLevel);
|
||||
var lower = (int)MathF.Floor(clamped);
|
||||
var upper = Math.Min(lower + 1, VolumetricLightSettings.MaximumGoboLevel);
|
||||
var blend = clamped - lower;
|
||||
var low = ReadLevel(lower, image);
|
||||
return blend <= 0f ? low : Vector4.Lerp(low, ReadLevel(upper, image), blend);
|
||||
}
|
||||
|
||||
float OccluderAlpha(GoboPyramid image, Vector2 position)
|
||||
{
|
||||
var u = position.X / image.Width;
|
||||
var v = position.Y / image.Height;
|
||||
return u < 0f || u > 1f || v < 0f || v > 1f ? 0f : image.Bilinear(0, u, v).W;
|
||||
}
|
||||
|
||||
static float Dot(Vector4 row, Vector3 point) => row.X * point.X + row.Y * point.Y + row.Z * point.Z + row.W;
|
||||
|
||||
float GetTransmission(Vector3 volumePoint, Vector3 sourcePoint)
|
||||
{
|
||||
var transmission = 1f;
|
||||
foreach (var (plane, image) in occluders)
|
||||
{
|
||||
if (!(plane.Strength > 0f))
|
||||
continue;
|
||||
|
||||
var near = Dot(plane.Plane, volumePoint);
|
||||
var span = Dot(plane.Plane, sourcePoint) - near;
|
||||
if (!(MathF.Abs(span) > RateEpsilon))
|
||||
continue;
|
||||
|
||||
var ratio = -near / span;
|
||||
if (!(ratio > 0f && ratio < 1f))
|
||||
continue;
|
||||
|
||||
var crossing = volumePoint + (sourcePoint - volumePoint) * ratio;
|
||||
transmission *= 1f - plane.Strength * OccluderAlpha(image, new Vector2(Dot(plane.ImageX, crossing), Dot(plane.ImageY, crossing)));
|
||||
}
|
||||
|
||||
return transmission;
|
||||
}
|
||||
|
||||
public Vector3 Shade(int pixelX, int pixelY)
|
||||
{
|
||||
var scene = new Vector2(pixelX + 0.5f, pixelY + 0.5f);
|
||||
var footprint = c.Mode.Z;
|
||||
var screen = scene * footprint;
|
||||
var viewBase = screen.X * Row(0) + screen.Y * Row(1);
|
||||
var origin = viewBase + Row(3);
|
||||
var slope = c.View.X;
|
||||
var rayStep = slope * viewBase + Row(2);
|
||||
|
||||
var zLow = -1e30f;
|
||||
var zHigh = c.March.W;
|
||||
var inside = true;
|
||||
for (var index = 0; index < VolumetricLightSettings.PlaneCount; index++)
|
||||
{
|
||||
var plane = Plane(index);
|
||||
var normal = new Vector3(plane.X, plane.Y, plane.Z);
|
||||
var numerator = Vector3.Dot(normal, origin) - plane.W;
|
||||
var rate = Vector3.Dot(normal, rayStep);
|
||||
if (MathF.Abs(rate) > RateEpsilon)
|
||||
{
|
||||
var z = -numerator / rate;
|
||||
if (rate > 0f)
|
||||
zLow = MathF.Max(zLow, z);
|
||||
else
|
||||
zHigh = MathF.Min(zHigh, z);
|
||||
}
|
||||
else if (numerator < 0f)
|
||||
{
|
||||
inside = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!inside || zHigh <= zLow)
|
||||
return Vector3.Zero;
|
||||
|
||||
var (nearSource, nearTravel) = FindSource(origin + zLow * rayStep);
|
||||
var (farSource, farTravel) = FindSource(origin + zHigh * rayStep);
|
||||
var rayLength = rayStep.Length();
|
||||
var pathLength = rayLength * (zHigh - zLow);
|
||||
var middleLod = 0.5f * (GetLod((1f + slope * zLow) * footprint, nearTravel) + GetLod((1f + slope * zHigh) * footprint, farTravel));
|
||||
var texelTravel = (ImagePosition(farSource) - ImagePosition(nearSource)).Length();
|
||||
var wanted = texelTravel * MathF.Pow(2f, -middleLod) / c.March.X;
|
||||
if (c.Dust.X > 0f)
|
||||
wanted = MathF.Max(wanted, pathLength * c.Dust.Y * c.Mode.Y);
|
||||
|
||||
var count = (int)Math.Clamp(MathF.Ceiling(wanted), c.Mode.X, c.March.Y);
|
||||
var lodFloor = MathF.Log2(MathF.Max(texelTravel / count, 1f));
|
||||
var dz = (zHigh - zLow) / count;
|
||||
var stepWeight = rayLength * dz * c.Beam.W;
|
||||
var seed = (uint)c.Dust.Z;
|
||||
var cellX = (int)MathF.Floor(scene.X);
|
||||
var cellY = (int)MathF.Floor(scene.Y);
|
||||
var jitter = ToUnit(Mix(((uint)cellX * HashStep) ^ ((uint)cellY * HashMultiplyA)));
|
||||
var isPoint = c.Focus.W > 0.5f;
|
||||
var toEye = rayStep / rayLength;
|
||||
var axis = new Vector3(c.Axis.X, c.Axis.Y, c.Axis.Z);
|
||||
var focus = new Vector3(c.Focus.X, c.Focus.Y, c.Focus.Z);
|
||||
var parallelPhase = isPoint ? 0f : GetPhase(axis, toEye);
|
||||
var wind = new Vector3(c.Wind.X, c.Wind.Y, c.Wind.Z);
|
||||
var sum = Vector3.Zero;
|
||||
for (var sampleIndex = 0; sampleIndex < count; sampleIndex++)
|
||||
{
|
||||
var z = zLow + (sampleIndex + jitter) * dz;
|
||||
var volumePoint = origin + z * rayStep;
|
||||
var (sourcePoint, travel) = FindSource(volumePoint);
|
||||
var lod = MathF.Max(GetLod((1f + slope * z) * footprint, travel), lodFloor);
|
||||
var gobo = SampleGobo(ImagePosition(sourcePoint), lod);
|
||||
var phase = isPoint ? GetPhase(c.Axis.W * Vector3.Normalize(volumePoint - focus), toEye) : parallelPhase;
|
||||
var density = 1f;
|
||||
if (c.Dust.X > 0f)
|
||||
density = MathF.Max(1f + c.Dust.X * (2f * Dust((volumePoint + wind) * c.Dust.Y, seed) - 1f), 0f);
|
||||
|
||||
sum += new Vector3(gobo.X, gobo.Y, gobo.Z) * (GetFalloff(travel) * phase * density * GetTransmission(volumePoint, sourcePoint));
|
||||
}
|
||||
|
||||
return sum * stepWeight * new Vector3(c.Tint.X, c.Tint.Y, c.Tint.Z);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace VolumetricLight.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();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
|
||||
namespace VolumetricLight.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.VolumetricLight), CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.Equal("体積光", neutral);
|
||||
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.VolumetricLight), 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Reflection;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class ViewTransformTests
|
||||
{
|
||||
const float Tolerance = 2e-2f;
|
||||
const float RelativeTolerance = 1e-5f;
|
||||
const int Cases = 200;
|
||||
const float NearDivisor = 0.1f;
|
||||
|
||||
static readonly Matrix4x4 YmmPerspective = new(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, -0.001f, 0f, 0f, 0f, 1f);
|
||||
|
||||
static DrawDescription Describe(Vector3 draw, Vector3 rotation, Matrix4x4 camera, float? perspectiveDistance = null, BillboardMode billboard = BillboardMode.None)
|
||||
=> new(draw, Vector2.Zero, Vector2.One, rotation, camera, InterpolationMode.Linear, 1d, false, [])
|
||||
{
|
||||
PerspectiveDistance = perspectiveDistance,
|
||||
Billboard = billboard,
|
||||
};
|
||||
|
||||
static Matrix4x4 ReferenceWorld(Vector3 rotation, Vector3 draw)
|
||||
=> Matrix4x4.CreateRotationZ(MathF.PI * rotation.Z / 180f)
|
||||
* Matrix4x4.CreateRotationY(MathF.PI * -rotation.Y / 180f)
|
||||
* Matrix4x4.CreateRotationX(MathF.PI * -rotation.X / 180f)
|
||||
* Matrix4x4.CreateTranslation(draw);
|
||||
|
||||
static Vector2? Project(DrawDescription draw, Vector3 local)
|
||||
{
|
||||
var matrix = ReferenceWorld(draw.Rotation, draw.Draw) * ViewTransform.FinalizeCamera(draw) * YmmPerspective;
|
||||
var clip = Vector4.Transform(new Vector4(local, 1f), matrix);
|
||||
return clip.W > NearDivisor ? new Vector2(clip.X, clip.Y) / clip.W : null;
|
||||
}
|
||||
|
||||
static Matrix4x4 Camera(Random random)
|
||||
=> Matrix4x4.CreateTranslation(-new Vector3(Next(random, 400f), Next(random, 400f), Next(random, 600f)))
|
||||
* Matrix4x4.CreateRotationY(MathF.PI * Next(random, 40f) / 180f, new Vector3(0f, 0f, 1000f))
|
||||
* Matrix4x4.CreateRotationX(MathF.PI * Next(random, 30f) / 180f, new Vector3(0f, 0f, 1000f))
|
||||
* Matrix4x4.CreateRotationZ(MathF.PI * Next(random, 20f) / 180f, new Vector3(0f, 0f, 1000f));
|
||||
|
||||
static float Next(Random random, float range) => (float)(random.NextDouble() * 2d - 1d) * range;
|
||||
|
||||
static Vector3 NextPoint(Random random, float range) => new(Next(random, range), Next(random, range), Next(random, range / 2f));
|
||||
|
||||
static void AssertNear(Vector2 expected, Vector2 actual, string label)
|
||||
{
|
||||
var allowance = Tolerance + RelativeTolerance * MathF.Max(MathF.Abs(expected.X), MathF.Abs(expected.Y));
|
||||
Assert.True(Math.Abs(expected.X - actual.X) <= allowance && Math.Abs(expected.Y - actual.Y) <= allowance, $"{label} {expected} {actual}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFlatItemMapsPlanePointsToTheSamePixels()
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity), out var view));
|
||||
|
||||
Assert.Equal(VolumetricLightSettings.BasePerspectiveSlope, view.Slope);
|
||||
Assert.True(view.TryProject(new Vector3(120f, -45f, 0f), out var screen));
|
||||
AssertNear(new Vector2(120f, -45f), screen, "flat");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PointsTowardTheCameraAreMagnifiedByTheirPerspectiveDivisor()
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity), out var view));
|
||||
|
||||
Assert.True(view.TryProject(new Vector3(100f, 0f, 500f), out var near));
|
||||
Assert.True(view.TryProject(new Vector3(100f, 0f, -1000f), out var far));
|
||||
AssertNear(new Vector2(200f, 0f), near, "near");
|
||||
AssertNear(new Vector2(50f, 0f), far, "far");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PointsAtOrBehindTheEyeAreNotProjected()
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity), out var view));
|
||||
|
||||
Assert.False(view.TryProject(new Vector3(1f, 1f, 1000f), out _));
|
||||
Assert.False(view.TryProject(new Vector3(1f, 1f, 1500f), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRigidTransformAndTheSlopeReproduceTheHostProjection()
|
||||
{
|
||||
var random = new Random(20261025);
|
||||
for (var index = 0; index < Cases; index++)
|
||||
{
|
||||
var draw = Describe(NextPoint(random, 300f), new Vector3(Next(random, 50f), Next(random, 50f), Next(random, 90f)), Camera(random));
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
|
||||
var local = NextPoint(random, 500f);
|
||||
if (Project(draw, local) is { } host)
|
||||
{
|
||||
Assert.True(view.TryProject(local, out var projected));
|
||||
AssertNear(host, projected, $"case {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(600f)]
|
||||
[InlineData(1000f)]
|
||||
[InlineData(2500f)]
|
||||
[InlineData(float.PositiveInfinity)]
|
||||
public void ThePerspectiveDistanceBecomesTheSlope(float distance)
|
||||
{
|
||||
var random = new Random(7);
|
||||
var draw = Describe(NextPoint(random, 200f), new Vector3(10f, -20f, 5f), Camera(random), distance);
|
||||
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
|
||||
Assert.Equal(float.IsPositiveInfinity(distance) ? 0f : -1f / distance, view.Slope, 1e-6f);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(BillboardMode.None)]
|
||||
[InlineData(BillboardMode.Spherical)]
|
||||
[InlineData(BillboardMode.Cylindrical)]
|
||||
public void BillboardingAndTheFieldOfViewKeepTheHostProjection(BillboardMode mode)
|
||||
{
|
||||
var random = new Random(31);
|
||||
for (var index = 0; index < Cases; index++)
|
||||
{
|
||||
var distance = 400f + (float)random.NextDouble() * 4000f;
|
||||
var draw = Describe(NextPoint(random, 250f), new Vector3(Next(random, 40f), Next(random, 40f), Next(random, 40f)), Camera(random), distance, mode);
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
|
||||
var local = NextPoint(random, 400f);
|
||||
if (Project(draw, local) is { } host)
|
||||
{
|
||||
Assert.True(view.TryProject(local, out var projected));
|
||||
AssertNear(host, projected, $"{mode} case {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACameraWithItsOwnPerspectivePartIsSeparatedFromItsRigidPart()
|
||||
{
|
||||
var camera = Matrix4x4.CreateTranslation(120f, -30f, -200f) * Matrix4x4.CreateRotationY(0.4f, new Vector3(0f, 0f, 1000f)) * ViewTransform.CreateSlope(0.0004f);
|
||||
var draw = Describe(new Vector3(40f, 10f, 80f), new Vector3(15f, 25f, -10f), camera);
|
||||
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
|
||||
Assert.Equal(VolumetricLightSettings.BasePerspectiveSlope + 0.0004f, view.Slope, 1e-6f);
|
||||
Assert.True(view.TryProject(new Vector3(70f, 20f, 30f), out var projected));
|
||||
AssertNear(Project(draw, new Vector3(70f, 20f, 30f))!.Value, projected, "perspective camera");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheInverseReturnsCameraSpaceToThePlane()
|
||||
{
|
||||
var random = new Random(5);
|
||||
var draw = Describe(NextPoint(random, 200f), new Vector3(10f, 30f, -15f), Camera(random));
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var view));
|
||||
|
||||
var local = new Vector3(33f, -77f, 12f);
|
||||
var camera = Vector3.Transform(local, view.CameraFromLocal);
|
||||
var back = Vector3.Transform(camera, view.LocalFromCamera);
|
||||
|
||||
Assert.True(Vector3.Distance(local, back) < 1e-2f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADegenerateCameraIsRejected()
|
||||
{
|
||||
Assert.False(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, default), out _));
|
||||
Assert.False(ViewTransform.TryCreate(Describe(new Vector3(float.NaN, 0f, 0f), Vector3.Zero, Matrix4x4.Identity), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePerspectivePartThatPutsTheEyeBehindThePlaneIsRejected()
|
||||
{
|
||||
var camera = ViewTransform.CreateSlope(0.002f);
|
||||
|
||||
Assert.False(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, camera), out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(90f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, -1f)]
|
||||
[InlineData(-90f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)]
|
||||
[InlineData(0f, 90f, 0f, 1f, 0f, 0f, 0f, 0f, 1f)]
|
||||
[InlineData(0f, -90f, 0f, 1f, 0f, 0f, 0f, 0f, -1f)]
|
||||
[InlineData(0f, 0f, 90f, 1f, 0f, 0f, 0f, 1f, 0f)]
|
||||
[InlineData(0f, 0f, -90f, 1f, 0f, 0f, 0f, -1f, 0f)]
|
||||
public void ARotationTurnsTheItemTheWayTheHostTurnsIt(float rotationX, float rotationY, float rotationZ, float fromX, float fromY, float fromZ, float toX, float toY, float toZ)
|
||||
{
|
||||
var turned = Vector3.Transform(new Vector3(fromX, fromY, fromZ), ViewTransform.CreateWorld(new Vector3(rotationX, rotationY, rotationZ), Vector3.Zero));
|
||||
|
||||
Assert.True(Vector3.Distance(new Vector3(toX, toY, toZ), turned) < 1e-5f, $"{turned}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePositionMovesTheItemAfterItHasTurned()
|
||||
{
|
||||
var moved = Vector3.Transform(new Vector3(1f, 0f, 0f), ViewTransform.CreateWorld(new Vector3(0f, 0f, 90f), new Vector3(10f, 20f, 30f)));
|
||||
|
||||
Assert.True(Vector3.Distance(new Vector3(10f, 21f, 30f), moved) < 1e-4f, $"{moved}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWorldMatrixMatchesTheHost()
|
||||
{
|
||||
if (!HostAssemblyResolver.IsConfigured)
|
||||
Assert.Skip("ホストの場所が設定されていません。");
|
||||
|
||||
var type = Assembly.LoadFrom(Path.Combine(HostAssemblyResolver.Directory, "YukkuriMovieMaker.dll")).GetType("YukkuriMovieMaker.Player.Video.Effects.DrawingEffect");
|
||||
var create = type?.GetMethod("CreateWorldMatrix", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
|
||||
if (create is null)
|
||||
Assert.Skip("ホストに姿勢の行列の作成が見つかりません。");
|
||||
|
||||
var random = new Random(7);
|
||||
for (var index = 0; index < Cases; index++)
|
||||
{
|
||||
var rotation = new Vector3(Next(random, 180f), Next(random, 180f), Next(random, 180f));
|
||||
var draw = NextPoint(random, 300f);
|
||||
|
||||
var host = (Matrix4x4)create.Invoke(null, [rotation, draw, Matrix4x4.Identity])!;
|
||||
var ours = ViewTransform.CreateWorld(rotation, draw);
|
||||
|
||||
Assert.True(MaximumDifference(host, ours) < 1e-4f, $"{index}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APointTooCloseToTheEyeIsNotProjected()
|
||||
{
|
||||
Assert.True(ViewTransform.TryCreate(Describe(Vector3.Zero, Vector3.Zero, Matrix4x4.Identity), out var view));
|
||||
var eyeDepth = -1f / view.Slope;
|
||||
var gap = (float)VolumetricLightSettings.MinimumPerspectiveDivisor / -view.Slope;
|
||||
|
||||
Assert.False(view.TryProject(new Vector3(100f, 50f, eyeDepth - 0.5f * gap), out _));
|
||||
Assert.True(view.TryProject(new Vector3(100f, 50f, eyeDepth - 2f * gap), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFinalizedCameraMatchesTheHost()
|
||||
{
|
||||
if (!HostAssemblyResolver.IsConfigured)
|
||||
Assert.Skip("ホストの場所が設定されていません。");
|
||||
|
||||
var type = Assembly.LoadFrom(Path.Combine(HostAssemblyResolver.Directory, "YukkuriMovieMaker.dll")).GetType("YukkuriMovieMaker.Player.Video.CameraFinalizer");
|
||||
var apply = type?.GetMethod("Apply", BindingFlags.Public | BindingFlags.Static);
|
||||
if (apply is null)
|
||||
Assert.Skip("ホストにカメラの確定処理が見つかりません。");
|
||||
|
||||
var random = new Random(99);
|
||||
foreach (var mode in new[] { BillboardMode.None, BillboardMode.Spherical, BillboardMode.Cylindrical })
|
||||
{
|
||||
for (var index = 0; index < Cases; index++)
|
||||
{
|
||||
float? distance = index % 3 == 0 ? null : 300f + (float)random.NextDouble() * 5000f;
|
||||
var draw = Describe(NextPoint(random, 250f), new Vector3(Next(random, 40f), Next(random, 40f), Next(random, 40f)), Camera(random), distance, mode);
|
||||
|
||||
var host = (DrawDescription)apply.Invoke(null, [draw])!;
|
||||
var ours = ViewTransform.FinalizeCamera(draw);
|
||||
|
||||
Assert.True(MaximumDifference(host.Camera, ours) < 1e-4f, $"{mode} {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static float MaximumDifference(Matrix4x4 first, Matrix4x4 second)
|
||||
=> new[]
|
||||
{
|
||||
first.M11 - second.M11, first.M12 - second.M12, first.M13 - second.M13, first.M14 - second.M14,
|
||||
first.M21 - second.M21, first.M22 - second.M22, first.M23 - second.M23, first.M24 - second.M24,
|
||||
first.M31 - second.M31, first.M32 - second.M32, first.M33 - second.M33, first.M34 - second.M34,
|
||||
first.M41 - second.M41, first.M42 - second.M42, first.M43 - second.M43, first.M44 - second.M44,
|
||||
}.Max(MathF.Abs);
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class VolumetricLightEffectProcessorTests
|
||||
{
|
||||
const int Width = 96;
|
||||
const int Height = 64;
|
||||
const int Length = 30;
|
||||
const int Tolerance = 3;
|
||||
const int MarkedFrame = 10;
|
||||
const int GlassMargin = 6;
|
||||
const int GlassPeriod = 32;
|
||||
const byte GlassLevel = 110;
|
||||
|
||||
static readonly Size Canvas = new(320, 240);
|
||||
|
||||
static Bgra Glass(int x, int y)
|
||||
{
|
||||
var column = x % GlassPeriod;
|
||||
if (column < GlassMargin || column >= GlassPeriod - GlassMargin || y < GlassMargin || y >= Height - GlassMargin)
|
||||
return Bgra.Opaque(8, 8, 8);
|
||||
|
||||
return (x / GlassPeriod) switch
|
||||
{
|
||||
0 => Bgra.Opaque(20, 30, GlassLevel),
|
||||
1 => Bgra.Opaque(30, GlassLevel, 40),
|
||||
_ => Bgra.Opaque(GlassLevel, 60, 20),
|
||||
};
|
||||
}
|
||||
|
||||
static VolumetricLightEffect Effect(Action<VolumetricLightEffect>? configure = null)
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
configure?.Invoke(effect);
|
||||
return effect;
|
||||
}
|
||||
|
||||
static VolumetricLightEffect Dusty()
|
||||
=> Effect(effect =>
|
||||
{
|
||||
effect.DustAmount.Values[0].Value = 60d;
|
||||
effect.DustSpeed.Values[0].Value = 200d;
|
||||
});
|
||||
|
||||
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, DrawDescription? draw = null)
|
||||
{
|
||||
processor.Update(EffectDescriptions.At(frame, Length, draw ?? EffectDescriptions.Flat, Canvas));
|
||||
return Rendering.Capture(devices, processor.Output);
|
||||
}
|
||||
|
||||
static Rendering RenderOnce(IGraphicsDevicesAndContext devices, VolumetricLightEffect effect, int frame, DrawDescription? draw = null, Func<int, int, Bgra>? pixels = null)
|
||||
{
|
||||
using var source = new SourceImage(devices, Width, Height, pixels ?? Glass);
|
||||
using var processor = effect.CreateVideoEffect(devices);
|
||||
processor.SetInput(source.Bitmap);
|
||||
return RenderFrame(devices, processor, frame, draw);
|
||||
}
|
||||
|
||||
static bool IsLit(Rendering rendering, int x, int y)
|
||||
{
|
||||
var pixel = rendering[x, y];
|
||||
return pixel.Red != 0 || pixel.Green != 0 || pixel.Blue != 0;
|
||||
}
|
||||
|
||||
static int LitPixels(Rendering rendering) => rendering.Coordinates().Count(point => IsLit(rendering, point.X, point.Y));
|
||||
|
||||
static bool InsideSource(int x, int y) => x >= 0 && y >= 0 && x < Width && y < Height;
|
||||
|
||||
static void AssertClose(Bgra expected, Bgra actual, string where)
|
||||
{
|
||||
Assert.True(Math.Abs(expected.Blue - actual.Blue) <= Tolerance, $"{where} blue {expected} {actual}");
|
||||
Assert.True(Math.Abs(expected.Green - actual.Green) <= Tolerance, $"{where} green {expected} {actual}");
|
||||
Assert.True(Math.Abs(expected.Red - actual.Red) <= Tolerance, $"{where} red {expected} {actual}");
|
||||
Assert.True(Math.Abs(expected.Alpha - actual.Alpha) <= Tolerance, $"{where} alpha {expected} {actual}");
|
||||
}
|
||||
|
||||
static DrawDescription Posed(Vector3 draw, Vector3 rotation) => EffectDescriptions.Flat with { Draw = draw, Rotation = rotation };
|
||||
|
||||
[Fact]
|
||||
public void TheProcessorBakesThePoseIntoTheScreen()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var posed = EffectDescriptions.Flat with
|
||||
{
|
||||
Draw = new Vector3(10f, 20f, 30f),
|
||||
Rotation = new Vector3(5f, 6f, 7f),
|
||||
Zoom = new Vector2(1.2f, 0.9f),
|
||||
Invert = true,
|
||||
Opacity = 0.5d,
|
||||
};
|
||||
|
||||
var baked = processor.Update(EffectDescriptions.At(0, Length, posed, Canvas));
|
||||
|
||||
Assert.Equal(posed with
|
||||
{
|
||||
Draw = Vector3.Zero,
|
||||
Zoom = Vector2.One,
|
||||
Rotation = Vector3.Zero,
|
||||
Camera = Matrix4x4.Identity,
|
||||
PerspectiveDistance = null,
|
||||
Billboard = BillboardMode.None,
|
||||
Invert = false,
|
||||
}, baked);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 0f, 1d)]
|
||||
[InlineData(1f, 0f, 1d)]
|
||||
[InlineData(0f, 1f, 1d)]
|
||||
[InlineData(1f, 1f, 0d)]
|
||||
public void ADegeneratePoseLeavesTheItemUntouched(float zoomX, float zoomY, double opacity)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var degenerate = EffectDescriptions.Flat with { Zoom = new Vector2(zoomX, zoomY), Opacity = opacity };
|
||||
|
||||
var draw = processor.Update(EffectDescriptions.At(0, Length, degenerate, Canvas));
|
||||
var rendering = Rendering.Capture(context, processor.Output);
|
||||
|
||||
Assert.Equal(degenerate, draw);
|
||||
Assert.Equal((0, 0, Width, 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]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASourceBeyondTheSizeLimitPassesThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
const int Oversize = VolumetricLightSettings.MaximumSourceDimension + 1;
|
||||
using var source = new SourceImage(context, Oversize, 4, (x, _) => x % 2 == 0 ? Bgra.Opaque(200, 200, 200) : Bgra.Transparent);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var draw = processor.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
var rendering = Rendering.Capture(context, processor.Output);
|
||||
|
||||
Assert.Equal(EffectDescriptions.Flat, draw);
|
||||
Assert.Equal((0, 0, Oversize, 4), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
Assert.All(Enumerable.Range(0, 64), x => Assert.Equal(source[x, 1], rendering[x, 1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutLightTheSourceIsReproducedWhereItStands()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect(effect => effect.Intensity.Values[0].Value = 0d).CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.Equal((0, 0, Width, Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
Assert.All(rendering.Coordinates(), point => AssertClose(source[point.X, point.Y], rendering[point.X, point.Y], $"{point}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALightBelowTheThresholdLeavesOnlyTheSource()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var dark = RenderOnce(context, Effect(effect => effect.Threshold.Values[0].Value = 100d), 0);
|
||||
var off = RenderOnce(context, Effect(effect => effect.Intensity.Values[0].Value = 0d), 0);
|
||||
|
||||
Assert.All(dark.Coordinates(), point =>
|
||||
{
|
||||
if (InsideSource(point.X, point.Y))
|
||||
Assert.Equal(off[point.X, point.Y], dark[point.X, point.Y]);
|
||||
else
|
||||
Assert.False(IsLit(dark, point.X, point.Y), $"{point}");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaftsReachBeyondTheSourceAndNeverLeaveTheCanvas()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var rendering = RenderOnce(context, Effect(), 0);
|
||||
|
||||
var outside = rendering.Coordinates().Count(point => !InsideSource(point.X, point.Y) && IsLit(rendering, point.X, point.Y));
|
||||
Assert.True(outside > Width * Height / 2, $"{outside}");
|
||||
Assert.True(rendering.Left >= -Canvas.Width / 2 && rendering.Top >= -Canvas.Height / 2);
|
||||
Assert.True(rendering.Right <= Canvas.Width / 2 && rendering.Bottom <= Canvas.Height / 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HidingTheSourceKeepsTheShaftsAndRemovesOnlyTheSource()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var shown = RenderOnce(context, Effect(), 0);
|
||||
var hidden = RenderOnce(context, Effect(effect => effect.ShowSource = false), 0);
|
||||
|
||||
Assert.True(LitPixels(hidden) > Width * Height / 2);
|
||||
Assert.All(hidden.Coordinates().Where(point => !InsideSource(point.X, point.Y)), point => AssertClose(shown[point.X, point.Y], hidden[point.X, point.Y], $"{point}"));
|
||||
Assert.All(Enumerable.Range(GlassMargin, Width - 2 * GlassMargin).Where(x => x % GlassPeriod == GlassPeriod / 2), x =>
|
||||
{
|
||||
var y = Height / 2;
|
||||
var expected = Glass(x, y).Premultiplied();
|
||||
Assert.True(shown[x, y].Red - hidden[x, y].Red >= expected.Red - Tolerance - 1, $"{x} red");
|
||||
Assert.Equal(byte.MaxValue, shown[x, y].Alpha);
|
||||
Assert.Equal(0, hidden[x, y].Alpha);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBakedSourceFillsTheProjectedQuadOfARotatedItem()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var posed = Posed(new Vector3(-30f, -20f, 0f), new Vector3(10f, 40f, -15f));
|
||||
Assert.True(ViewTransform.TryCreate(posed, out var view));
|
||||
var corners = new[] { new Vector3(0f, 0f, 0f), new Vector3(Width, 0f, 0f), new Vector3(Width, Height, 0f), new Vector3(0f, Height, 0f) };
|
||||
var projected = corners.Select(corner =>
|
||||
{
|
||||
Assert.True(view.TryProject(corner, out var screen));
|
||||
return screen;
|
||||
}).ToArray();
|
||||
|
||||
var rendering = RenderOnce(context, Effect(effect => effect.Intensity.Values[0].Value = 0d), 0, posed);
|
||||
|
||||
var covered = rendering.Coordinates().Where(point => rendering[point.X, point.Y].Alpha > 0).ToArray();
|
||||
Assert.NotEmpty(covered);
|
||||
Assert.InRange(covered.Min(point => point.X), projected.Min(point => point.X) - 2d, projected.Min(point => point.X) + 2d);
|
||||
Assert.InRange(covered.Max(point => point.X) + 1, projected.Max(point => point.X) - 2d, projected.Max(point => point.X) + 2d);
|
||||
Assert.InRange(covered.Min(point => point.Y), projected.Min(point => point.Y) - 2d, projected.Min(point => point.Y) + 2d);
|
||||
Assert.InRange(covered.Max(point => point.Y) + 1, projected.Max(point => point.Y) - 2d, projected.Max(point => point.Y) + 2d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLightFollowsTheItemWhenItIsRotatedOrMoved()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var flat = RenderOnce(context, Effect(), 0);
|
||||
var rotated = RenderOnce(context, Effect(), 0, Posed(Vector3.Zero, new Vector3(0f, 35f, 0f)));
|
||||
var moved = RenderOnce(context, Effect(), 0, Posed(new Vector3(40f, 30f, 0f), Vector3.Zero));
|
||||
|
||||
Assert.False(flat.SamePixelsAs(rotated));
|
||||
Assert.False(flat.SamePixelsAs(moved));
|
||||
Assert.True(LitPixels(rotated) > Width * Height / 2);
|
||||
Assert.True(LitPixels(moved) > Width * Height / 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturningToAFrameReproducesItExactly()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Dusty().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var first = RenderFrame(context, processor, MarkedFrame);
|
||||
var other = RenderFrame(context, processor, 2 * MarkedFrame);
|
||||
var again = RenderFrame(context, processor, MarkedFrame);
|
||||
|
||||
Assert.False(first.SamePixelsAs(other));
|
||||
Assert.True(first.SamePixelsAs(again));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANewProcessorDrawsTheSameLightAsOneThatAlreadyDrewAnotherFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var used = Dusty().CreateVideoEffect(context);
|
||||
used.SetInput(source.Bitmap);
|
||||
RenderFrame(context, used, 0);
|
||||
using var fresh = Dusty().CreateVideoEffect(context);
|
||||
fresh.SetInput(source.Bitmap);
|
||||
|
||||
var reused = RenderFrame(context, used, MarkedFrame);
|
||||
var created = RenderFrame(context, fresh, MarkedFrame);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(created));
|
||||
}
|
||||
|
||||
public static TheoryData<string> Settings => new()
|
||||
{
|
||||
"direction",
|
||||
"elevation",
|
||||
"spread",
|
||||
"length",
|
||||
"intensity",
|
||||
"threshold",
|
||||
"tint",
|
||||
"falloff",
|
||||
"lamp",
|
||||
"scattering",
|
||||
"source",
|
||||
"dust-amount",
|
||||
"dust-size",
|
||||
"dust-speed",
|
||||
"dust-direction",
|
||||
"seed",
|
||||
"quality",
|
||||
};
|
||||
|
||||
static void Change(string setting, VolumetricLightEffect effect)
|
||||
{
|
||||
switch (setting)
|
||||
{
|
||||
case "direction": effect.Direction.Values[0].Value = -45d; break;
|
||||
case "elevation": effect.Elevation.Values[0].Value = 30d; break;
|
||||
case "spread": effect.Spread.Values[0].Value = -12d; break;
|
||||
case "length": effect.Length.Values[0].Value = 500d; break;
|
||||
case "intensity": effect.Intensity.Values[0].Value = 220d; break;
|
||||
case "threshold": effect.Threshold.Values[0].Value = 30d; break;
|
||||
case "tint": effect.Tint = System.Windows.Media.Color.FromRgb(255, 140, 40); break;
|
||||
case "falloff": effect.Falloff.Values[0].Value = 10d; break;
|
||||
case "lamp": effect.LampSize.Values[0].Value = 12d; break;
|
||||
case "scattering": effect.Scattering.Values[0].Value = -50d; break;
|
||||
case "source": effect.ShowSource = false; break;
|
||||
case "dust-amount": effect.DustAmount.Values[0].Value = 100d; break;
|
||||
case "dust-size": effect.DustSize.Values[0].Value = 60d; break;
|
||||
case "dust-speed": effect.DustSpeed.Values[0].Value = -300d; break;
|
||||
case "dust-direction": effect.DustDirection.Values[0].Value = 20d; break;
|
||||
case "seed": effect.Seed = 123; break;
|
||||
default: effect.Quality = VolumetricLightQuality.Ultra; break;
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Settings))]
|
||||
public void EverySettingChangedAfterTheFirstFrameReachesTheShader(string setting)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
var effect = Dusty();
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var before = RenderFrame(context, processor, MarkedFrame);
|
||||
|
||||
Change(setting, effect);
|
||||
var after = RenderFrame(context, processor, MarkedFrame);
|
||||
|
||||
var expected = Dusty();
|
||||
Change(setting, expected);
|
||||
var fresh = RenderOnce(context, expected, MarkedFrame);
|
||||
Assert.False(before.SamePixelsAs(after), $"{setting} unchanged");
|
||||
Assert.True(after.SamePixelsAs(fresh), $"{setting} differs from a new processor");
|
||||
}
|
||||
|
||||
public static TheoryData<string> PoseChanges => new()
|
||||
{
|
||||
"zoom",
|
||||
"invert",
|
||||
"move",
|
||||
"rotate",
|
||||
"camera",
|
||||
};
|
||||
|
||||
static DrawDescription ChangedPose(string name) => name switch
|
||||
{
|
||||
"zoom" => EffectDescriptions.Flat with { Zoom = new Vector2(1.4f, 0.8f) },
|
||||
"invert" => EffectDescriptions.Flat with { Invert = true },
|
||||
"move" => EffectDescriptions.Flat with { Draw = new Vector3(-30f, 20f, 40f) },
|
||||
"rotate" => EffectDescriptions.Flat with { Rotation = new Vector3(10f, 30f, 5f) },
|
||||
_ => EffectDescriptions.Flat with { Camera = Matrix4x4.CreateTranslation(-20f, 10f, 60f) },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(PoseChanges))]
|
||||
public void EveryPoseChangedAfterTheFirstFrameReachesTheLight(string name)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
|
||||
var after = RenderFrame(context, processor, 0, ChangedPose(name));
|
||||
|
||||
var fresh = RenderOnce(context, Effect(), 0, ChangedPose(name));
|
||||
Assert.False(before.SamePixelsAs(after), name);
|
||||
Assert.True(after.SamePixelsAs(fresh), name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFrameThatCannotBeDrawnLeavesNoTraceOnTheFramesAroundIt()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var first = RenderFrame(context, processor, 0);
|
||||
|
||||
var hidden = RenderFrame(context, processor, 1, EffectDescriptions.Flat with { Opacity = 0d });
|
||||
var again = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.Equal((0, 0, Width, Height), (hidden.Left, hidden.Top, hidden.Width, hidden.Height));
|
||||
Assert.All(hidden.Coordinates(), point => Assert.Equal(source[point.X, point.Y], hidden[point.X, point.Y]));
|
||||
Assert.True(first.SamePixelsAs(again));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnimatedParametersAreReadAtEachFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
var animated = new VolumetricLightEffect();
|
||||
animated.Direction.CopyFrom(Linear(-120d, -60d));
|
||||
animated.Intensity.CopyFrom(Linear(60d, 160d));
|
||||
using var processor = animated.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var first = RenderFrame(context, processor, 0);
|
||||
var middle = RenderFrame(context, processor, Length / 2);
|
||||
|
||||
var constant = Effect(effect =>
|
||||
{
|
||||
effect.Direction.Values[0].Value = animated.Direction.GetValue(Length / 2, Length, EffectDescriptions.Fps);
|
||||
effect.Intensity.Values[0].Value = animated.Intensity.GetValue(Length / 2, Length, EffectDescriptions.Fps);
|
||||
});
|
||||
var expected = RenderOnce(context, constant, Length / 2);
|
||||
Assert.False(first.SamePixelsAs(middle));
|
||||
Assert.True(middle.SamePixelsAs(expected));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDustDriftsOnlyWhenItHasSpeedAndAmount()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var standing = Effect(effect => { effect.DustAmount.Values[0].Value = 60d; effect.DustSpeed.Values[0].Value = 0d; });
|
||||
var drifting = Dusty();
|
||||
var clear = Effect(effect => effect.DustSpeed.Values[0].Value = 200d);
|
||||
|
||||
Assert.True(RenderOnce(context, standing, 0).SamePixelsAs(RenderOnce(context, standing, MarkedFrame)));
|
||||
Assert.False(RenderOnce(context, drifting, 0).SamePixelsAs(RenderOnce(context, drifting, MarkedFrame)));
|
||||
Assert.True(RenderOnce(context, clear, 0).SamePixelsAs(RenderOnce(context, clear, MarkedFrame)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSeedChangesTheDustAndOnlyTheDust()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
var plain = RenderOnce(context, Effect(), 0);
|
||||
var plainSeeded = RenderOnce(context, Effect(effect => effect.Seed = 55), 0);
|
||||
var dust = RenderOnce(context, Effect(effect => effect.DustAmount.Values[0].Value = 80d), 0);
|
||||
var dustSeeded = RenderOnce(context, Effect(effect => { effect.DustAmount.Values[0].Value = 80d; effect.Seed = 55; }), 0);
|
||||
|
||||
Assert.True(plain.SamePixelsAs(plainSeeded));
|
||||
Assert.False(dust.SamePixelsAs(dustSeeded));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryQualityDrawsTheShaftsWithinTheCanvas()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
|
||||
foreach (var quality in Enum.GetValues<VolumetricLightQuality>())
|
||||
{
|
||||
var rendering = RenderOnce(context, Effect(effect => effect.Quality = quality), 0);
|
||||
|
||||
Assert.True(LitPixels(rendering) > Width * Height, $"{quality}");
|
||||
Assert.True(rendering.Left >= -Canvas.Width / 2 && rendering.Right <= Canvas.Width / 2 && rendering.Top >= -Canvas.Height / 2 && rendering.Bottom <= Canvas.Height / 2, $"{quality}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALengthOfZeroLeavesTheItemUntouched()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect(effect => effect.Length.Values[0].Value = 0d).CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var draw = processor.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
var rendering = Rendering.Capture(context, processor.Output);
|
||||
|
||||
Assert.Equal(EffectDescriptions.Flat, draw);
|
||||
Assert.Equal((0, 0, Width, 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]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASourceFarOffTheCanvasLeavesNothingToDraw()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var far = Posed(new Vector3(0f, -9000f, 0f), Vector3.Zero);
|
||||
|
||||
var draw = processor.Update(EffectDescriptions.At(0, Length, far, Canvas));
|
||||
|
||||
Assert.Equal(Vector3.Zero, draw.Draw);
|
||||
Assert.Equal(Vector2.One, draw.Zoom);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailureWhileUpdatingIsNotSwallowed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var processor = Effect().CreateVideoEffect(context);
|
||||
|
||||
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailureWhileCreatingTheProcessorIsNotSwallowed()
|
||||
{
|
||||
Assert.ThrowsAny<Exception>(() => Effect().CreateVideoEffect(null!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class VolumetricLightEffectTests
|
||||
{
|
||||
static PropertyInfo Property(string name) => typeof(VolumetricLightEffect).GetProperty(name)!;
|
||||
|
||||
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
|
||||
|
||||
static Animation[] Animations(VolumetricLightEffect effect)
|
||||
=> [effect.Direction, effect.Elevation, effect.Spread, effect.Length, effect.Intensity, effect.Threshold, effect.Falloff, effect.LampSize, effect.Scattering, effect.DustAmount, effect.DustSize, effect.DustSpeed, effect.DustDirection];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(VolumetricLightEffect.Direction), -90d, -360d, 360d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Elevation), 55d, -89d, 89d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Spread), 10d, -85d, 85d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Length), 1200d, 0d, 100000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Intensity), 150d, 0d, 1000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Threshold), 8d, 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Falloff), 60d, 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.LampSize), 1.5d, 0d, 30d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Scattering), 30d, -95d, 95d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustAmount), 0d, 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSize), 220d, 8d, 4000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSpeed), 40d, -5000d, 5000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustDirection), -90d, -360d, 360d)]
|
||||
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
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 TheRangesMatchTheLimitsTheModelCovers()
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
Assert.Equal(-VolumetricLightSettings.MaximumElevationDegrees, effect.Elevation.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumElevationDegrees, effect.Elevation.MaxValue);
|
||||
Assert.Equal(-VolumetricLightSettings.MaximumSpreadDegrees, effect.Spread.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumSpreadDegrees, effect.Spread.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumLength, effect.Length.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumIntensityPercent, effect.Intensity.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumLampRadiusDegrees, effect.LampSize.MaxValue);
|
||||
Assert.Equal(-VolumetricLightSettings.MaximumAnisotropyPercent, effect.Scattering.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumAnisotropyPercent, effect.Scattering.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.MinimumDustSize, effect.DustSize.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumDustSize, effect.DustSize.MaxValue);
|
||||
Assert.Equal(-VolumetricLightSettings.MaximumDustSpeed, effect.DustSpeed.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumDustSpeed, effect.DustSpeed.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.PercentScale, effect.Falloff.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.PercentScale, effect.Threshold.MaxValue);
|
||||
Assert.Equal(VolumetricLightSettings.PercentScale, effect.DustAmount.MaxValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefaultsKeepTheSourceVisibleAtStandardQualityWithTheDustOff()
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
Assert.True(effect.ShowSource);
|
||||
Assert.Equal(VolumetricLightQuality.Standard, effect.Quality);
|
||||
Assert.Equal(Colors.White, effect.Tint);
|
||||
Assert.Equal(0, effect.Seed);
|
||||
Assert.Equal(0, effect.OcclusionChannel);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-3, 0)]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(5, 5)]
|
||||
[InlineData(99, VolumetricLightSettings.MaximumOcclusionChannel)]
|
||||
public void TheOcclusionChannelIsClampedToItsRange(int value, int expected)
|
||||
{
|
||||
var effect = new VolumetricLightEffect { OcclusionChannel = 4 };
|
||||
|
||||
effect.OcclusionChannel = value;
|
||||
|
||||
Assert.Equal(expected, effect.OcclusionChannel);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-5000, -VolumetricLightSettings.MaximumSeed)]
|
||||
[InlineData(5000, VolumetricLightSettings.MaximumSeed)]
|
||||
[InlineData(-3, -3)]
|
||||
[InlineData(42, 42)]
|
||||
public void TheSeedIsClampedToItsRange(int value, int expected)
|
||||
{
|
||||
var effect = new VolumetricLightEffect { Seed = value };
|
||||
|
||||
Assert.Equal(expected, effect.Seed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAnimatedParametersAreListedOnceAndReused()
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
var method = typeof(VolumetricLightEffect).GetMethod("GetAnimatables", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
var first = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
|
||||
var second = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
|
||||
|
||||
Assert.Same(first, second);
|
||||
Assert.Equal(Animations(effect), first);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLabelIsTheLocalizedEffectName()
|
||||
{
|
||||
Assert.Equal(Texts.VolumetricLight, new VolumetricLightEffect().Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryAnimatedParameterReceivesTheAnimationParameters()
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
|
||||
|
||||
Assert.Equal(13, Animations(effect).Length);
|
||||
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(int.MaxValue)]
|
||||
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
|
||||
{
|
||||
var effect = new VolumetricLightEffect();
|
||||
|
||||
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
|
||||
|
||||
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAuthorIsDeclared()
|
||||
{
|
||||
var details = typeof(VolumetricLightEffect).GetCustomAttribute<PluginDetailsAttribute>()!;
|
||||
|
||||
Assert.Equal("routersys", details.AuthorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsRegisteredForDecorationWithoutAviUtlSupport()
|
||||
{
|
||||
var attribute = typeof(VolumetricLightEffect).GetCustomAttribute<VideoEffectAttribute>()!;
|
||||
|
||||
Assert.Equal(nameof(Texts.VolumetricLight), attribute.Name);
|
||||
Assert.Equal([VideoEffectCategories.Decoration], attribute.Categories);
|
||||
Assert.Equal(
|
||||
[nameof(Texts.TagVolumetricLight), nameof(Texts.TagVolumeLight), nameof(Texts.TagGodRay), nameof(Texts.TagLightShaft), nameof(Texts.TagCrepuscularRay), nameof(Texts.TagTyndall)],
|
||||
attribute.Keywords);
|
||||
Assert.False(attribute.IsAviUtlSupported);
|
||||
Assert.True(attribute.IsEffectItemSupported);
|
||||
Assert.Equal(typeof(Texts), attribute.ResourceType);
|
||||
Assert.Equal(Texts.VolumetricLight, attribute.GetName());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(VolumetricLightEffect.Direction), nameof(Texts.DirectionGroup), nameof(Texts.Direction), nameof(Texts.DirectionDescription), 0)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Elevation), nameof(Texts.DirectionGroup), nameof(Texts.Elevation), nameof(Texts.ElevationDescription), 1)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Spread), nameof(Texts.DirectionGroup), nameof(Texts.Spread), nameof(Texts.SpreadDescription), 2)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Length), nameof(Texts.DirectionGroup), nameof(Texts.Length), nameof(Texts.LengthDescription), 3)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Intensity), nameof(Texts.LightGroup), nameof(Texts.Intensity), nameof(Texts.IntensityDescription), 10)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Threshold), nameof(Texts.LightGroup), nameof(Texts.Threshold), nameof(Texts.ThresholdDescription), 11)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Tint), nameof(Texts.LightGroup), nameof(Texts.Tint), nameof(Texts.TintDescription), 12)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Falloff), nameof(Texts.BeamGroup), nameof(Texts.Falloff), nameof(Texts.FalloffDescription), 20)]
|
||||
[InlineData(nameof(VolumetricLightEffect.LampSize), nameof(Texts.BeamGroup), nameof(Texts.LampSize), nameof(Texts.LampSizeDescription), 21)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Scattering), nameof(Texts.BeamGroup), nameof(Texts.Scattering), nameof(Texts.ScatteringDescription), 22)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustAmount), nameof(Texts.DustGroup), nameof(Texts.DustAmount), nameof(Texts.DustAmountDescription), 30)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSize), nameof(Texts.DustGroup), nameof(Texts.DustSize), nameof(Texts.DustSizeDescription), 31)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSpeed), nameof(Texts.DustGroup), nameof(Texts.DustSpeed), nameof(Texts.DustSpeedDescription), 32)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustDirection), nameof(Texts.DustGroup), nameof(Texts.DustDirection), nameof(Texts.DustDirectionDescription), 33)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Seed), nameof(Texts.DustGroup), nameof(Texts.Seed), nameof(Texts.SeedDescription), 34)]
|
||||
[InlineData(nameof(VolumetricLightEffect.OcclusionChannel), nameof(Texts.OcclusionGroup), nameof(Texts.OcclusionChannel), nameof(Texts.OcclusionChannelDescription), 50)]
|
||||
[InlineData(nameof(VolumetricLightEffect.ShowSource), nameof(Texts.OutputGroup), nameof(Texts.ShowSource), nameof(Texts.ShowSourceDescription), 40)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Quality), nameof(Texts.OutputGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 41)]
|
||||
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
|
||||
{
|
||||
var display = Attribute<DisplayAttribute>(property);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NoTwoParametersShareAnOrder()
|
||||
{
|
||||
var orders = typeof(VolumetricLightEffect).GetProperties()
|
||||
.Select(property => property.GetCustomAttribute<DisplayAttribute>())
|
||||
.OfType<DisplayAttribute>()
|
||||
.Select(display => display.Order)
|
||||
.ToArray();
|
||||
|
||||
Assert.Equal(18, orders.Length);
|
||||
Assert.Equal(orders.Length, orders.Distinct().Count());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(VolumetricLightEffect.Direction), "F1", "°", -180d, 180d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Elevation), "F1", "°", -89d, 89d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Spread), "F1", "°", -60d, 60d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Length), "F0", "px", 0d, 4000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Intensity), "F1", "%", 0d, 300d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Threshold), "F1", "%", 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Falloff), "F1", "%", 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.LampSize), "F1", "°", 0d, 10d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.Scattering), "F0", "%", -90d, 90d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustAmount), "F0", "%", 0d, 100d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSize), "F0", "px", 20d, 1000d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustSpeed), "F0", "px/s", -500d, 500d)]
|
||||
[InlineData(nameof(VolumetricLightEffect.DustDirection), "F1", "°", -180d, 180d)]
|
||||
public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum)
|
||||
{
|
||||
var slider = Attribute<AnimationSliderAttribute>(property);
|
||||
|
||||
Assert.Equal(format, slider.StringFormat);
|
||||
Assert.Equal(unit, slider.UnitText);
|
||||
Assert.Equal(minimum, slider.DefaultMin);
|
||||
Assert.Equal(maximum, slider.DefaultMax);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSeedIsEditedWithATextBoxAndTheQualityWithAComboBox()
|
||||
{
|
||||
Assert.NotNull(Attribute<TextBoxSliderAttribute>(nameof(VolumetricLightEffect.Seed)));
|
||||
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(VolumetricLightEffect.Quality)));
|
||||
Assert.NotNull(Attribute<ColorPickerAttribute>(nameof(VolumetricLightEffect.Tint)));
|
||||
Assert.NotNull(Attribute<ToggleSliderAttribute>(nameof(VolumetricLightEffect.ShowSource)));
|
||||
Assert.NotNull(Attribute<TextBoxSliderAttribute>(nameof(VolumetricLightEffect.OcclusionChannel)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EverySettingSurvivesAProjectRoundTrip()
|
||||
{
|
||||
var effect = new VolumetricLightEffect
|
||||
{
|
||||
Tint = Color.FromRgb(255, 140, 40),
|
||||
ShowSource = false,
|
||||
Seed = -321,
|
||||
OcclusionChannel = 4,
|
||||
Quality = VolumetricLightQuality.Ultra,
|
||||
};
|
||||
var values = new[] { 135d, 40d, -22.5d, 800d, 180d, 20d, 45d, 4d, -35d, 65d, 310d, -120d, 15d };
|
||||
foreach (var (animation, value) in Animations(effect).Zip(values))
|
||||
animation.Values[0].Value = value;
|
||||
|
||||
var clone = Json.GetClone(effect)!;
|
||||
|
||||
Assert.NotSame(effect, clone);
|
||||
Assert.Equal(Color.FromRgb(255, 140, 40), clone.Tint);
|
||||
Assert.False(clone.ShowSource);
|
||||
Assert.Equal(-321, clone.Seed);
|
||||
Assert.Equal(4, clone.OcclusionChannel);
|
||||
Assert.Equal(VolumetricLightQuality.Ultra, clone.Quality);
|
||||
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
using System.Drawing;
|
||||
using System.Numerics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class VolumetricLightOccluderEffectProcessorTests
|
||||
{
|
||||
const int Width = 96;
|
||||
const int Height = 64;
|
||||
const int Length = 30;
|
||||
const int GlassMargin = 6;
|
||||
const int GlassPeriod = 32;
|
||||
const byte GlassLevel = 110;
|
||||
const int BarWidth = 8;
|
||||
|
||||
static readonly Size Canvas = new(320, 240);
|
||||
static readonly DrawDescription InFront = EffectDescriptions.Flat with { Draw = new Vector3(0f, 56f, 80f) };
|
||||
|
||||
static Bgra Glass(int x, int y)
|
||||
{
|
||||
var column = x % GlassPeriod;
|
||||
if (column < GlassMargin || column >= GlassPeriod - GlassMargin || y < GlassMargin || y >= Height - GlassMargin)
|
||||
return Bgra.Opaque(8, 8, 8);
|
||||
|
||||
return (x / GlassPeriod) switch
|
||||
{
|
||||
0 => Bgra.Opaque(20, 30, GlassLevel),
|
||||
1 => Bgra.Opaque(30, GlassLevel, 40),
|
||||
_ => Bgra.Opaque(GlassLevel, 60, 20),
|
||||
};
|
||||
}
|
||||
|
||||
static Bgra Bars(int x, int y) => (x / BarWidth) % 2 == 0 ? Bgra.Opaque(20, 20, 20) : Bgra.Transparent;
|
||||
|
||||
static VolumetricLightEffect Light(int channel)
|
||||
=> new() { OcclusionChannel = channel };
|
||||
|
||||
static VolumetricLightOccluderEffect Blocker(int channel = 1, double strength = 100d)
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect { Channel = channel };
|
||||
effect.Strength.Values[0].Value = strength;
|
||||
return effect;
|
||||
}
|
||||
|
||||
sealed class Item : IDisposable
|
||||
{
|
||||
readonly IGraphicsDevicesAndContext context;
|
||||
readonly SourceImage source;
|
||||
readonly Guid scene;
|
||||
|
||||
public Item(GraphicsDevices devices, YukkuriMovieMaker.Plugin.Effects.VideoEffectBase effect, Func<int, int, Bgra> pixels, Guid scene = default)
|
||||
{
|
||||
this.scene = scene;
|
||||
context = devices.CreateContext();
|
||||
source = new SourceImage(context, Width, Height, pixels);
|
||||
Processor = effect.CreateVideoEffect(context);
|
||||
Processor.SetInput(source.Bitmap);
|
||||
}
|
||||
|
||||
public IVideoEffectProcessor Processor { get; }
|
||||
|
||||
public SourceImage Source => source;
|
||||
|
||||
public DrawDescription Update(int frame, DrawDescription draw, Guid? moveTo = null)
|
||||
=> Processor.Update(EffectDescriptions.At(frame, Length, draw, Canvas, moveTo ?? scene));
|
||||
|
||||
public Rendering Render(int frame, DrawDescription draw, Guid? moveTo = null)
|
||||
{
|
||||
Update(frame, draw, moveTo);
|
||||
return Rendering.Capture(context, Processor.Output);
|
||||
}
|
||||
|
||||
public Rendering Capture() => Rendering.Capture(context, Processor.Output);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Processor.Dispose();
|
||||
source.Dispose();
|
||||
context.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static bool IsLit(Rendering rendering, int x, int y)
|
||||
{
|
||||
var pixel = rendering[x, y];
|
||||
return pixel.Red != 0 || pixel.Green != 0 || pixel.Blue != 0;
|
||||
}
|
||||
|
||||
static long OutsideLight(Rendering rendering)
|
||||
=> rendering.Coordinates()
|
||||
.Where(point => point.X < 0 || point.Y < 0 || point.X >= Width || point.Y >= Height)
|
||||
.Sum(point => (long)rendering[point.X, point.Y].Red + rendering[point.X, point.Y].Green + rendering[point.X, point.Y].Blue);
|
||||
|
||||
static Occluder[] Snapshot(IGraphicsDevicesAndContext context, int channel, int frame = 0, Guid scene = default)
|
||||
{
|
||||
using var lease = OccluderRegistry.Acquire(context, scene, channel);
|
||||
var snapshot = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
lease.Group.Snapshot(snapshot, frame);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOccluderPassesTheImageThroughAndKeepsTheDrawDescription()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var item = new Item(devices, Blocker(), Bars);
|
||||
|
||||
var draw = item.Update(0, InFront);
|
||||
var rendering = item.Capture();
|
||||
|
||||
Assert.Equal(InFront, draw);
|
||||
Assert.Equal((0, 0, Width, Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(item.Source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOccluderPublishesItsStrengthFromTheParameterAndTheOpacityToItsChannel()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var item = new Item(devices, Blocker(2, 40d), Bars);
|
||||
|
||||
item.Update(0, InFront with { Opacity = 0.5d });
|
||||
var snapshot = Snapshot(context, 2);
|
||||
|
||||
Assert.Equal(0.2f, snapshot[0].Strength, 5);
|
||||
Assert.All(snapshot.Skip(1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
Assert.All(Snapshot(context, 1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOccluderPublishesTheViewOfItsPose()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var item = new Item(devices, Blocker(), Bars);
|
||||
var draw = EffectDescriptions.Flat with { Draw = new Vector3(10f, -20f, 30f), Rotation = new Vector3(5f, 15f, 25f), Zoom = new Vector2(1.5f, 0.5f), Invert = true };
|
||||
Assert.True(ViewTransform.TryCreate(draw, out var expected));
|
||||
|
||||
item.Update(0, draw);
|
||||
var published = Snapshot(context, 1)[0];
|
||||
|
||||
Assert.Equal(expected, published.View);
|
||||
Assert.Equal(GoboMapping.Create(draw.Zoom, draw.Invert, draw.CenterPoint), published.Gobo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheNumberMovesTheOccluderToTheNewChannel()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var effect = Blocker(1);
|
||||
using var item = new Item(devices, effect, Bars);
|
||||
item.Update(0, InFront);
|
||||
Assert.True(Snapshot(context, 1)[0].Strength > 0f);
|
||||
|
||||
effect.Channel = 3;
|
||||
item.Update(1, InFront);
|
||||
|
||||
Assert.All(Snapshot(context, 1, 1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
Assert.True(Snapshot(context, 3, 1)[0].Strength > 0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisposingTheOccluderWithdrawsItFromTheChannel()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var item = new Item(devices, Blocker(), Bars);
|
||||
item.Update(0, InFront);
|
||||
Assert.True(Snapshot(context, 1)[0].Strength > 0f);
|
||||
|
||||
item.Dispose();
|
||||
|
||||
Assert.All(Snapshot(context, 1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisposingTheLightLetsGoOfItsNumber()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
var light = Light(1).CreateVideoEffect(context);
|
||||
light.SetInput(source.Bitmap);
|
||||
light.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
var held = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
var group = held.Group;
|
||||
|
||||
light.Dispose();
|
||||
held.Dispose();
|
||||
|
||||
using var again = OccluderRegistry.Acquire(context, Guid.Empty, 1);
|
||||
Assert.NotSame(group, again.Group);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyFourOccludersCountOnOneChannelAndTheFifthIsIgnored()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var items = Enumerable.Range(0, VolumetricLightSettings.OccluderCapacity + 1).Select(_ => new Item(devices, Blocker(), Bars)).ToArray();
|
||||
try
|
||||
{
|
||||
foreach (var item in items)
|
||||
item.Update(0, InFront);
|
||||
var snapshot = Snapshot(context, 1);
|
||||
|
||||
Assert.All(snapshot, occluder => Assert.True(occluder.Strength > 0f));
|
||||
items[0].Dispose();
|
||||
foreach (var item in items.Skip(1))
|
||||
item.Update(1, InFront);
|
||||
Assert.All(Snapshot(context, 1, 1), occluder => Assert.True(occluder.Strength > 0f));
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var item in items.Skip(1))
|
||||
item.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 0f, 1d)]
|
||||
[InlineData(1f, 1f, 0d)]
|
||||
public void ADegeneratePoseCastsNoShadow(float zoomX, float zoomY, double opacity)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var item = new Item(devices, Blocker(), Bars);
|
||||
|
||||
item.Update(0, InFront with { Zoom = new Vector2(zoomX, zoomY), Opacity = opacity });
|
||||
|
||||
Assert.All(Snapshot(context, 1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAnInputNothingIsPublishedAndNothingFails()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var processor = Blocker().CreateVideoEffect(context);
|
||||
|
||||
var draw = processor.Update(EffectDescriptions.At(0, Length, InFront, Canvas));
|
||||
|
||||
Assert.Equal(InFront, draw);
|
||||
Assert.All(Snapshot(context, 1), occluder => Assert.Equal(0f, occluder.Strength));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailureWhileUpdatingIsNotSwallowed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var processor = Blocker().CreateVideoEffect(context);
|
||||
|
||||
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderInFrontOfTheShaftsCastsAShadowIntoThem()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
var clear = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
occluder.Update(0, InFront);
|
||||
var shadowed = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
var before = OutsideLight(clear);
|
||||
var after = OutsideLight(shadowed);
|
||||
var darker = shadowed.Coordinates().Count(point => shadowed[point.X, point.Y].Red + shadowed[point.X, point.Y].Green + shadowed[point.X, point.Y].Blue < (clear[point.X, point.Y].Red + clear[point.X, point.Y].Green + clear[point.X, point.Y].Blue) * 0.8);
|
||||
Assert.True(before > 0);
|
||||
Assert.True(after < before * 0.9, $"{after} {before}");
|
||||
Assert.True(darker > Width * Height / 4, $"{darker}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderPublishedForAnotherFrameCastsNoShadowUntilThatFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
var clearNow = light.Render(0, EffectDescriptions.Flat);
|
||||
var clearLater = light.Render(15, EffectDescriptions.Flat);
|
||||
|
||||
occluder.Update(15, InFront);
|
||||
|
||||
Assert.True(clearNow.SamePixelsAs(light.Render(0, EffectDescriptions.Flat)));
|
||||
Assert.True(OutsideLight(light.Render(15, EffectDescriptions.Flat)) < OutsideLight(clearLater) * 0.9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderInAnotherSceneNeverReachesTheLight()
|
||||
{
|
||||
var home = Guid.NewGuid();
|
||||
var away = Guid.NewGuid();
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass, home);
|
||||
using var foreign = new Item(devices, Blocker(), Bars, away);
|
||||
var clear = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
foreign.Update(0, InFront);
|
||||
Assert.True(clear.SamePixelsAs(light.Render(0, EffectDescriptions.Flat)));
|
||||
|
||||
using var native = new Item(devices, Blocker(), Bars, home);
|
||||
native.Update(0, InFront);
|
||||
Assert.True(OutsideLight(light.Render(0, EffectDescriptions.Flat)) < OutsideLight(clear) * 0.9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALightThatMovesToAnotherSceneFollowsTheOccludersThereAndLeavesTheOldOnes()
|
||||
{
|
||||
var home = Guid.NewGuid();
|
||||
var away = Guid.NewGuid();
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass, home);
|
||||
using var occluder = new Item(devices, Blocker(), Bars, away);
|
||||
var clear = light.Render(0, EffectDescriptions.Flat);
|
||||
occluder.Update(0, InFront);
|
||||
|
||||
Assert.True(OutsideLight(light.Render(0, EffectDescriptions.Flat, away)) < OutsideLight(clear) * 0.9);
|
||||
Assert.True(clear.SamePixelsAs(light.Render(0, EffectDescriptions.Flat, home)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderThatMovesToAnotherSceneLeavesTheLightsOfTheOldOne()
|
||||
{
|
||||
var home = Guid.NewGuid();
|
||||
var away = Guid.NewGuid();
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass, home);
|
||||
using var occluder = new Item(devices, Blocker(), Bars, home);
|
||||
var clear = light.Render(0, EffectDescriptions.Flat);
|
||||
occluder.Update(0, InFront);
|
||||
Assert.True(OutsideLight(light.Render(0, EffectDescriptions.Flat)) < OutsideLight(clear) * 0.9);
|
||||
|
||||
occluder.Update(0, InFront, away);
|
||||
|
||||
Assert.True(clear.SamePixelsAs(light.Render(0, EffectDescriptions.Flat)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EachSceneKeepsItsOwnFourOccluderSlotsOnTheSameNumber()
|
||||
{
|
||||
var home = Guid.NewGuid();
|
||||
var away = Guid.NewGuid();
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var items = Enumerable.Range(0, VolumetricLightSettings.OccluderCapacity + 1)
|
||||
.Select(index => new Item(devices, Blocker(), Bars, index < VolumetricLightSettings.OccluderCapacity ? home : away))
|
||||
.ToArray();
|
||||
try
|
||||
{
|
||||
foreach (var item in items)
|
||||
item.Update(0, InFront);
|
||||
|
||||
Assert.All(Snapshot(context, 1, 0, home), occluder => Assert.True(occluder.Strength > 0f));
|
||||
Assert.True(Snapshot(context, 1, 0, away)[0].Strength > 0f);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var item in items)
|
||||
item.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALightIgnoresOccludersOfAnotherNumberAndWhenItsOwnNumberIsZero()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var other = new Item(devices, Light(2), Glass);
|
||||
using var off = new Item(devices, Light(0), Glass);
|
||||
var clearOther = other.Render(0, EffectDescriptions.Flat);
|
||||
var clearOff = off.Render(0, EffectDescriptions.Flat);
|
||||
using var occluder = new Item(devices, Blocker(1), Bars);
|
||||
|
||||
occluder.Update(0, InFront);
|
||||
|
||||
Assert.True(clearOther.SamePixelsAs(other.Render(0, EffectDescriptions.Flat)));
|
||||
Assert.True(clearOff.SamePixelsAs(off.Render(0, EffectDescriptions.Flat)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderAfterTheLightOnTheSameItemIsIgnoredInsteadOfBreakingTheGraph()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
using var alone = new Item(devices, Light(1), Glass);
|
||||
var expected = alone.Render(0, EffectDescriptions.Flat);
|
||||
using var light = Light(1).CreateVideoEffect(context);
|
||||
light.SetInput(source.Bitmap);
|
||||
using var blocker = Blocker().CreateVideoEffect(context);
|
||||
blocker.SetInput(light.Output);
|
||||
|
||||
var draw = light.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
blocker.Update(EffectDescriptions.At(0, Length, draw, Canvas));
|
||||
light.Update(EffectDescriptions.At(1, Length, EffectDescriptions.Flat, Canvas));
|
||||
var chained = Rendering.Capture(context, blocker.Output);
|
||||
|
||||
Assert.True(expected.SamePixelsAs(chained));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderBehindOtherEffectsOfALightOnTheSameItemIsIgnoredToo()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Width, Height, Glass);
|
||||
var lightEffect = Light(0);
|
||||
using var light = lightEffect.CreateVideoEffect(context);
|
||||
light.SetInput(source.Bitmap);
|
||||
using var blur = new Vortice.Direct2D1.Effects.GaussianBlur(context.DeviceContext) { StandardDeviation = 2f };
|
||||
using var lightOutput = light.Output;
|
||||
blur.SetInput(0, lightOutput, true);
|
||||
using var blurred = blur.Output;
|
||||
using var blocker = Blocker().CreateVideoEffect(context);
|
||||
blocker.SetInput(blurred);
|
||||
var draw = light.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
blocker.Update(EffectDescriptions.At(0, Length, draw, Canvas));
|
||||
var before = Rendering.Capture(context, blurred);
|
||||
|
||||
lightEffect.OcclusionChannel = 1;
|
||||
light.Update(EffectDescriptions.At(0, Length, EffectDescriptions.Flat, Canvas));
|
||||
blocker.Update(EffectDescriptions.At(0, Length, draw, Canvas));
|
||||
var after = Rendering.Capture(context, blurred);
|
||||
|
||||
Assert.True(before.SamePixelsAs(after));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOccluderOnTheSameNumberReachesEveryLightThatUsesIt()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var first = new Item(devices, Light(1), Glass);
|
||||
using var second = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
var clearFirst = first.Render(0, EffectDescriptions.Flat);
|
||||
var clearSecond = second.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
occluder.Update(0, InFront);
|
||||
var shadowedFirst = first.Render(0, EffectDescriptions.Flat);
|
||||
var shadowedSecond = second.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
Assert.True(OutsideLight(shadowedFirst) < OutsideLight(clearFirst) * 0.9);
|
||||
Assert.True(OutsideLight(shadowedSecond) < OutsideLight(clearSecond) * 0.9);
|
||||
Assert.True(shadowedFirst.SamePixelsAs(shadowedSecond));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithdrawingTheOccluderRestoresTheLightExactly()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
var clear = light.Render(0, EffectDescriptions.Flat);
|
||||
var occluder = new Item(devices, Blocker(), Bars);
|
||||
occluder.Update(0, InFront);
|
||||
var shadowed = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
occluder.Dispose();
|
||||
var restored = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
Assert.False(clear.SamePixelsAs(shadowed));
|
||||
Assert.True(clear.SamePixelsAs(restored));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovingTheOccluderMovesTheShadowTheSameWayAsANewlyBuiltScene()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
var moved = InFront with { Draw = new Vector3(24f, 70f, 120f), Rotation = new Vector3(0f, 20f, 10f) };
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
occluder.Update(0, InFront);
|
||||
var first = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
occluder.Update(1, moved);
|
||||
var second = light.Render(1, EffectDescriptions.Flat);
|
||||
|
||||
using var freshLight = new Item(devices, Light(2), Glass);
|
||||
using var freshOccluder = new Item(devices, Blocker(2), Bars);
|
||||
freshOccluder.Update(1, moved);
|
||||
var fresh = freshLight.Render(1, EffectDescriptions.Flat);
|
||||
Assert.False(first.SamePixelsAs(second));
|
||||
Assert.True(second.SamePixelsAs(fresh));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovingTheLightMovesTheShadowTheSameWayAsANewlyBuiltScene()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
var moved = EffectDescriptions.Flat with { Draw = new Vector3(20f, -10f, 0f), Rotation = new Vector3(0f, 15f, 0f) };
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
occluder.Update(0, InFront);
|
||||
var first = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
var second = light.Render(0, moved);
|
||||
|
||||
using var freshLight = new Item(devices, Light(2), Glass);
|
||||
using var freshOccluder = new Item(devices, Blocker(2), Bars);
|
||||
freshOccluder.Update(0, InFront);
|
||||
var fresh = freshLight.Render(0, moved);
|
||||
Assert.False(first.SamePixelsAs(second));
|
||||
Assert.True(second.SamePixelsAs(fresh));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLightFollowsAChangeOfItsOwnNumber()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
var effect = Light(0);
|
||||
using var light = new Item(devices, effect, Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
occluder.Update(0, InFront);
|
||||
var off = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
effect.OcclusionChannel = 1;
|
||||
var on = light.Render(0, EffectDescriptions.Flat);
|
||||
effect.OcclusionChannel = 0;
|
||||
var offAgain = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
Assert.True(OutsideLight(on) < OutsideLight(off) * 0.9);
|
||||
Assert.True(off.SamePixelsAs(offAgain));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdatingTheItemsAtTheSameTimeGivesTheSameLightAsOneAfterAnother()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var light = new Item(devices, Light(1), Glass);
|
||||
using var occluder = new Item(devices, Blocker(), Bars);
|
||||
occluder.Update(0, InFront);
|
||||
var sequential = light.Render(0, EffectDescriptions.Flat);
|
||||
|
||||
for (var repeat = 0; repeat < 20; repeat++)
|
||||
{
|
||||
Parallel.Invoke(() => occluder.Update(repeat % 3, InFront), () => light.Update(repeat % 3, EffectDescriptions.Flat));
|
||||
var parallel = light.Capture();
|
||||
Assert.True(sequential.SamePixelsAs(parallel), $"{repeat}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Reflection;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class VolumetricLightOccluderEffectTests
|
||||
{
|
||||
static PropertyInfo Property(string name) => typeof(VolumetricLightOccluderEffect).GetProperty(name)!;
|
||||
|
||||
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
|
||||
|
||||
[Fact]
|
||||
public void TheChannelStartsAtOneAndStaysWithinTheNumbersTheLightAccepts()
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect();
|
||||
|
||||
Assert.Equal(1, effect.Channel);
|
||||
effect.Channel = 5;
|
||||
effect.Channel = -4;
|
||||
Assert.Equal(1, effect.Channel);
|
||||
effect.Channel = 5;
|
||||
effect.Channel = 0;
|
||||
Assert.Equal(1, effect.Channel);
|
||||
effect.Channel = 99;
|
||||
Assert.Equal(VolumetricLightSettings.MaximumOcclusionChannel, effect.Channel);
|
||||
effect.Channel = 5;
|
||||
Assert.Equal(5, effect.Channel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStrengthStartsFullAndStaysWithinPercent()
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect();
|
||||
|
||||
Assert.Equal(100d, effect.Strength.DefaultValue);
|
||||
Assert.Equal(0d, effect.Strength.MinValue);
|
||||
Assert.Equal(VolumetricLightSettings.MaximumOccluderStrengthPercent, effect.Strength.MaxValue);
|
||||
Assert.Equal(100d, effect.Strength.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStrengthIsTheOnlyAnimatedParameterAndIsListedOnce()
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect();
|
||||
var method = typeof(VolumetricLightOccluderEffect).GetMethod("GetAnimatables", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
var first = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
|
||||
var second = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
|
||||
|
||||
Assert.Same(first, second);
|
||||
Assert.Equal([effect.Strength], first);
|
||||
effect.SetAnimationParameters(90, EffectDescriptions.Fps);
|
||||
Assert.Equal(90, effect.Strength.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLabelIsTheLocalizedEffectName()
|
||||
{
|
||||
Assert.Equal(Texts.VolumetricLightOccluder, new VolumetricLightOccluderEffect().Label);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(int.MaxValue)]
|
||||
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect();
|
||||
|
||||
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
|
||||
|
||||
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsRegisteredForDecorationWithoutAviUtlSupport()
|
||||
{
|
||||
var attribute = typeof(VolumetricLightOccluderEffect).GetCustomAttribute<VideoEffectAttribute>()!;
|
||||
|
||||
Assert.Equal(nameof(Texts.VolumetricLightOccluder), attribute.Name);
|
||||
Assert.Equal([VideoEffectCategories.Decoration], attribute.Categories);
|
||||
Assert.Equal([nameof(Texts.TagVolumetricLight), nameof(Texts.TagGodRay), nameof(Texts.TagShadow), nameof(Texts.TagLightBlocking)], attribute.Keywords);
|
||||
Assert.False(attribute.IsAviUtlSupported);
|
||||
Assert.Equal(typeof(Texts), attribute.ResourceType);
|
||||
Assert.Equal("routersys", typeof(VolumetricLightOccluderEffect).GetCustomAttribute<PluginDetailsAttribute>()!.AuthorName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(VolumetricLightOccluderEffect.Channel), nameof(Texts.OccluderChannel), nameof(Texts.OccluderChannelDescription), 0)]
|
||||
[InlineData(nameof(VolumetricLightOccluderEffect.Strength), nameof(Texts.OccluderStrength), nameof(Texts.OccluderStrengthDescription), 1)]
|
||||
public void EveryParameterIsDisplayedInTheBlockingGroupInOrder(string property, string name, string description, int order)
|
||||
{
|
||||
var display = Attribute<DisplayAttribute>(property);
|
||||
|
||||
Assert.Equal(nameof(Texts.OcclusionGroup), display.GroupName);
|
||||
Assert.Equal(name, display.Name);
|
||||
Assert.Equal(description, display.Description);
|
||||
Assert.Equal(order, display.Order);
|
||||
Assert.Equal(typeof(Texts), display.ResourceType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChannelIsEditedWithATextBoxAndTheStrengthWithASlider()
|
||||
{
|
||||
var channel = Attribute<TextBoxSliderAttribute>(nameof(VolumetricLightOccluderEffect.Channel));
|
||||
var strength = Attribute<AnimationSliderAttribute>(nameof(VolumetricLightOccluderEffect.Strength));
|
||||
|
||||
Assert.Equal("F0", channel.StringFormat);
|
||||
Assert.Equal((1d, (double)VolumetricLightSettings.MaximumOcclusionChannel), (channel.DefaultMin, channel.DefaultMax));
|
||||
Assert.Equal(("F1", "%", 0d, 100d), (strength.StringFormat, strength.UnitText, strength.DefaultMin, strength.DefaultMax));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EverySettingSurvivesAProjectRoundTrip()
|
||||
{
|
||||
var effect = new VolumetricLightOccluderEffect { Channel = 3 };
|
||||
effect.Strength.Values[0].Value = 42.5d;
|
||||
|
||||
var clone = Json.GetClone(effect)!;
|
||||
|
||||
Assert.NotSame(effect, clone);
|
||||
Assert.Equal(3, clone.Channel);
|
||||
Assert.Equal(42.5d, clone.Strength.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace VolumetricLight.Tests;
|
||||
|
||||
public sealed class VolumetricLightSettingsTests
|
||||
{
|
||||
const float Tolerance = 1e-6f;
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, 45d)]
|
||||
[InlineData(90d, 30d)]
|
||||
[InlineData(-135d, -60d)]
|
||||
[InlineData(200d, 10d)]
|
||||
public void TheAxisIsAUnitVector(double azimuth, double elevation)
|
||||
{
|
||||
Assert.Equal(1f, VolumetricLightSettings.GetAxis(azimuth, elevation).Length(), Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroDegreesPointsRightAndNinetyDegreesPointsUpOnTheScreen()
|
||||
{
|
||||
var right = VolumetricLightSettings.GetAxis(0d, 45d);
|
||||
var up = VolumetricLightSettings.GetAxis(90d, 45d);
|
||||
|
||||
Assert.True(right.X > 0f);
|
||||
Assert.Equal(0f, right.Y, Tolerance);
|
||||
Assert.Equal(0f, up.X, Tolerance);
|
||||
Assert.True(up.Y < 0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePlaneComponentFollowsTheCosineOfTheElevation()
|
||||
{
|
||||
var axis = VolumetricLightSettings.GetAxis(30d, 60d);
|
||||
|
||||
Assert.Equal(MathF.Sin(MathF.PI / 3f), axis.Z, Tolerance);
|
||||
Assert.Equal(0.5f * MathF.Cos(MathF.PI / 6f), axis.X, Tolerance);
|
||||
Assert.Equal(-0.5f * MathF.Sin(MathF.PI / 6f), axis.Y, Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(35d, 35d)]
|
||||
[InlineData(-35d, -35d)]
|
||||
[InlineData(0d, 1d)]
|
||||
[InlineData(0.4d, 1d)]
|
||||
[InlineData(-0.4d, -1d)]
|
||||
[InlineData(120d, 89d)]
|
||||
[InlineData(-120d, -89d)]
|
||||
public void TheElevationKeepsAwayFromThePlaneAndFromTheAxisOfTheCamera(double elevation, double expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.ClampElevationDegrees(elevation), 9);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, true)]
|
||||
[InlineData(0.005d, true)]
|
||||
[InlineData(-0.005d, true)]
|
||||
[InlineData(0.01d, false)]
|
||||
[InlineData(-0.01d, false)]
|
||||
[InlineData(20d, false)]
|
||||
public void ASpreadBelowAHundredthOfADegreeIsParallel(double spread, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.IsParallel(spread));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(45d, 100d, 100d)]
|
||||
[InlineData(-45d, 100d, -100d)]
|
||||
[InlineData(30d, 50d, 86.60254037844386d)]
|
||||
public void TheFocalDistanceMakesTheCornerRaySpreadByTheGivenAngle(double spread, double halfDiagonal, double expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.GetFocalDistance(spread, halfDiagonal), 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSpreadIsLimitedBeforeTheTangentGrowsWithoutBound()
|
||||
{
|
||||
var limit = Math.Tan(85d * Math.PI / 180d);
|
||||
|
||||
Assert.Equal(100d / limit, VolumetricLightSettings.GetFocalDistance(120d, 100d), 9);
|
||||
Assert.Equal(-100d / limit, VolumetricLightSettings.GetFocalDistance(-120d, 100d), 9);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, 1000d, 0d)]
|
||||
[InlineData(50d, 1000d, -6.931471805599453e-4d)]
|
||||
[InlineData(-10d, 1000d, 0d)]
|
||||
[InlineData(99d, 1000d, -4.605170185988091e-3d)]
|
||||
[InlineData(100d, 1000d, -4.605170185988091e-3d)]
|
||||
[InlineData(60d, 0d, 0d)]
|
||||
public void TheFalloffExponentLosesTheGivenFractionOverTheLength(double percent, double length, double expected)
|
||||
{
|
||||
Assert.Equal((float)expected, VolumetricLightSettings.GetFalloffExponent(percent, length), 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFadeCarriesTheLevelAtTheEndAndTheInverseLength()
|
||||
{
|
||||
var fade = VolumetricLightSettings.GetFade(60d, 1000d);
|
||||
|
||||
Assert.Equal(0.4f, fade.X, Tolerance);
|
||||
Assert.Equal(0.001f, fade.Y, Tolerance);
|
||||
Assert.Equal(Vector4.Zero, VolumetricLightSettings.GetFade(60d, 0d) with { X = 0f });
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, 0d)]
|
||||
[InlineData(10d, 10d)]
|
||||
[InlineData(30d, 30d)]
|
||||
[InlineData(100d, 30d)]
|
||||
[InlineData(-5d, 0d)]
|
||||
public void ThePenumbraGrowsWithTheTangentOfTheLimitedSourceSize(double degrees, double limited)
|
||||
{
|
||||
Assert.Equal(MathF.Tan((float)(limited * Math.PI / 180d)), VolumetricLightSettings.GetPenumbraSlope(degrees), Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(30d, 0.3f)]
|
||||
[InlineData(-30d, -0.3f)]
|
||||
[InlineData(200d, 0.95f)]
|
||||
[InlineData(-200d, -0.95f)]
|
||||
public void TheAnisotropyStaysInsideThePhaseFunctionRange(double percent, float expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.GetAnisotropy(percent), Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100d, 500d, 0.002f)]
|
||||
[InlineData(50d, 500d, 0.001f)]
|
||||
[InlineData(5000d, 500d, 0.02f)]
|
||||
[InlineData(-10d, 500d, 0f)]
|
||||
[InlineData(100d, 0d, 0f)]
|
||||
public void TheGainFollowsTheIntensityAndTheSizeOfTheSource(double intensity, double halfDiagonal, float expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.GetGain(intensity, halfDiagonal), Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(50d, 0.5f)]
|
||||
[InlineData(-5d, 0f)]
|
||||
[InlineData(150d, 1f)]
|
||||
public void TheThresholdIsAFractionOfTheBrightnessRange(double percent, float expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.GetThreshold(percent), Tolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(220d, 1f / 220f)]
|
||||
[InlineData(1d, 0.125f)]
|
||||
[InlineData(1e9d, 1f / 4000f)]
|
||||
public void TheDustFrequencyIsTheInverseOfTheClampedSize(double size, float expected)
|
||||
{
|
||||
Assert.Equal(expected, VolumetricLightSettings.GetDustFrequency(size), Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HigherQualityLooksFinerAndWiderAndNeverRendersAtALowerResolution()
|
||||
{
|
||||
var standard = VolumetricLightSettings.GetQualityLimits(VolumetricLightQuality.Standard);
|
||||
var high = VolumetricLightSettings.GetQualityLimits(VolumetricLightQuality.High);
|
||||
var ultra = VolumetricLightSettings.GetQualityLimits(VolumetricLightQuality.Ultra);
|
||||
|
||||
Assert.True(standard.StepTexels > high.StepTexels && high.StepTexels > ultra.StepTexels);
|
||||
Assert.True(standard.MaximumSteps < high.MaximumSteps && high.MaximumSteps < ultra.MaximumSteps);
|
||||
Assert.True(standard.ResolutionScale <= high.ResolutionScale && high.ResolutionScale <= ultra.ResolutionScale);
|
||||
Assert.Equal(1f, ultra.ResolutionScale);
|
||||
Assert.All(new[] { standard, high, ultra }, limits => Assert.True(limits.MaximumSteps >= VolumetricLightSettings.MinimumSteps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheNearestPerspectiveDivisorIsOneOverTheLargestScreen()
|
||||
{
|
||||
Assert.Equal(1f / 8192f, VolumetricLightSettings.MinimumPerspectiveDivisor);
|
||||
Assert.Equal(-1f / 1000f, VolumetricLightSettings.BasePerspectiveSlope);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePyramidHasOneLevelPerHalving()
|
||||
{
|
||||
Assert.Equal(VolumetricLightSettings.GoboLevelCount - 1, VolumetricLightSettings.MaximumGoboLevel);
|
||||
Assert.Equal(0.5f, VolumetricLightSettings.GoboLevelScale);
|
||||
Assert.Equal(6, VolumetricLightSettings.PlaneCount);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
"project": "VolumetricLight.csproj",
|
||||
"test-runner": "mtp",
|
||||
"coverage-analysis": "off",
|
||||
"concurrency": 4,
|
||||
"additional-timeout": 30000,
|
||||
"mutate": [
|
||||
"**/*.cs",
|
||||
"!**/YMM4-GitHubUpdateNotifier/**",
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using SharpGen.Runtime;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
|
||||
namespace VolumetricLight;
|
||||
|
||||
internal sealed class OccluderGroup : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly DisposeCollector _disposer = new();
|
||||
private readonly AffineTransform2D[] _relays = new AffineTransform2D[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly ID2D1Image[] _outputs = new ID2D1Image[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly ID2D1Image?[] _published = new ID2D1Image?[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly Occluder[] _requested = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly int[] _frames = new int[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly bool[] _blocked = new bool[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly int[] _checked = new int[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly HashSet<nint> _consumers = [];
|
||||
private int _version;
|
||||
private readonly Occluder[] _occluders = new Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly bool[] _claimed = new bool[VolumetricLightSettings.OccluderCapacity];
|
||||
private readonly ID2D1Image _empty;
|
||||
private bool _disposed;
|
||||
|
||||
public OccluderGroup(ID2D1DeviceContext context)
|
||||
{
|
||||
var flood = new Flood(context) { Color = Vector4.Zero };
|
||||
var crop = new Crop(context) { Rectangle = Vector4.Zero };
|
||||
_disposer.Collect(flood);
|
||||
_disposer.Collect(crop);
|
||||
using (var floodOutput = flood.Output)
|
||||
crop.SetInput(0, floodOutput, true);
|
||||
_empty = crop.Output;
|
||||
_disposer.Collect(_empty);
|
||||
for (var index = 0; index < _relays.Length; index++)
|
||||
{
|
||||
var relay = new AffineTransform2D(context) { InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor };
|
||||
_disposer.Collect(relay);
|
||||
relay.SetInput(0, _empty, true);
|
||||
_relays[index] = relay;
|
||||
_outputs[index] = relay.Output;
|
||||
_disposer.Collect(_outputs[index]);
|
||||
}
|
||||
}
|
||||
|
||||
public ID2D1Image GetOutput(int slot) => _outputs[slot];
|
||||
|
||||
public bool IsOccupied
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
return Array.IndexOf(_claimed, true) >= 0;
|
||||
}
|
||||
}
|
||||
|
||||
public OccluderSlot? Claim()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
return null;
|
||||
|
||||
for (var index = 0; index < _claimed.Length; index++)
|
||||
{
|
||||
if (_claimed[index])
|
||||
continue;
|
||||
|
||||
_claimed[index] = true;
|
||||
return new OccluderSlot(this, index);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Snapshot(Span<Occluder> destination, int frame)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
for (var index = 0; index < destination.Length; index++)
|
||||
destination[index] = !_disposed && index < _occluders.Length && _frames[index] == frame ? _occluders[index] : default;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddConsumer(nint effect)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || !_consumers.Add(effect))
|
||||
return;
|
||||
|
||||
_version++;
|
||||
for (var index = 0; index < _claimed.Length; index++)
|
||||
{
|
||||
if (_claimed[index] && _published[index] is { } image)
|
||||
Apply(index, image);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveConsumer(nint effect)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_consumers.Remove(effect))
|
||||
_version++;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
_disposed = true;
|
||||
_disposer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
internal void Publish(int index, ID2D1Image image, in Occluder occluder, int frame)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || !_claimed[index])
|
||||
return;
|
||||
|
||||
_requested[index] = occluder;
|
||||
_frames[index] = frame;
|
||||
if (!ReferenceEquals(_published[index], image) || _checked[index] != _version)
|
||||
{
|
||||
_published[index] = image;
|
||||
Apply(index, image);
|
||||
}
|
||||
else
|
||||
{
|
||||
_occluders[index] = _blocked[index] ? default : occluder;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void Retire(int index)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_claimed[index])
|
||||
return;
|
||||
|
||||
_claimed[index] = false;
|
||||
_occluders[index] = default;
|
||||
_requested[index] = default;
|
||||
_published[index] = null;
|
||||
_blocked[index] = false;
|
||||
if (!_disposed)
|
||||
_relays[index].SetInput(0, _empty, true);
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(int index, ID2D1Image image)
|
||||
{
|
||||
_checked[index] = _version;
|
||||
_blocked[index] = DependsOnConsumer(image);
|
||||
_relays[index].SetInput(0, _blocked[index] ? _empty : image, true);
|
||||
_occluders[index] = _blocked[index] ? default : _requested[index];
|
||||
}
|
||||
|
||||
private bool DependsOnConsumer(ID2D1Image image)
|
||||
{
|
||||
if (_consumers.Count == 0)
|
||||
return false;
|
||||
|
||||
var visited = new HashSet<nint>();
|
||||
var pending = new Stack<ID2D1Image>();
|
||||
var owned = new List<IDisposable>();
|
||||
pending.Push(image);
|
||||
try
|
||||
{
|
||||
while (pending.TryPop(out var current))
|
||||
{
|
||||
var effect = current.QueryInterfaceOrNull<ID2D1Effect>();
|
||||
if (effect is null)
|
||||
continue;
|
||||
|
||||
owned.Add(effect);
|
||||
if (_consumers.Contains(effect.NativePointer))
|
||||
return true;
|
||||
if (!visited.Add(effect.NativePointer))
|
||||
continue;
|
||||
|
||||
for (var input = 0; input < effect.InputCount; input++)
|
||||
{
|
||||
var source = effect.GetInput(input);
|
||||
if (source is null)
|
||||
continue;
|
||||
|
||||
owned.Add(source);
|
||||
pending.Push(source);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var disposable in owned)
|
||||
disposable.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OccluderSlot(OccluderGroup group, int index) : IDisposable
|
||||
{
|
||||
private int _retired;
|
||||
|
||||
public void Publish(ID2D1Image image, in Occluder occluder, int frame) => group.Publish(index, image, occluder, frame);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _retired, 1) == 0)
|
||||
group.Retire(index);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OccluderLease : IDisposable
|
||||
{
|
||||
private readonly OccluderBoard _board;
|
||||
private readonly (Guid Scene, int Channel) _key;
|
||||
private int _released;
|
||||
|
||||
internal OccluderLease(OccluderBoard board, (Guid Scene, int Channel) key, OccluderGroup group)
|
||||
{
|
||||
_board = board;
|
||||
_key = key;
|
||||
Group = group;
|
||||
}
|
||||
|
||||
public OccluderGroup Group { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0)
|
||||
_board.Release(_key);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OccluderBoard
|
||||
{
|
||||
private sealed class Entry(OccluderGroup group)
|
||||
{
|
||||
public OccluderGroup Group { get; } = group;
|
||||
|
||||
public int References { get; set; }
|
||||
}
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<(Guid Scene, int Channel), Entry> _entries = [];
|
||||
|
||||
public OccluderLease Acquire(IGraphicsDevicesAndContext devices, Guid scene, int channel)
|
||||
{
|
||||
var key = (scene, channel);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_entries.TryGetValue(key, out var entry))
|
||||
{
|
||||
entry = new Entry(new OccluderGroup(devices.DeviceContext));
|
||||
_entries.Add(key, entry);
|
||||
}
|
||||
|
||||
entry.References++;
|
||||
return new OccluderLease(this, key, entry.Group);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Release((Guid Scene, int Channel) key)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_entries.TryGetValue(key, out var entry) || --entry.References > 0)
|
||||
return;
|
||||
|
||||
_entries.Remove(key);
|
||||
entry.Group.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class OccluderRegistry
|
||||
{
|
||||
private static readonly ConditionalWeakTable<D2DDevices, OccluderBoard> Boards = [];
|
||||
|
||||
public static OccluderLease Acquire(IGraphicsDevicesAndContext devices, Guid scene, int channel)
|
||||
=> Boards.GetValue(devices.D2D, _ => new OccluderBoard()).Acquire(devices, scene, channel);
|
||||
}
|
||||
|
||||
internal sealed class OccluderLink
|
||||
{
|
||||
private OccluderGroup? _group;
|
||||
private int _frame;
|
||||
|
||||
public OccluderGroup? Group
|
||||
{
|
||||
get => Volatile.Read(ref _group);
|
||||
set => Volatile.Write(ref _group, value);
|
||||
}
|
||||
|
||||
public int Frame
|
||||
{
|
||||
get => Volatile.Read(ref _frame);
|
||||
set => Volatile.Write(ref _frame, value);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class OccluderLinks
|
||||
{
|
||||
private static readonly ConcurrentDictionary<int, OccluderLink> Links = [];
|
||||
private static int _next;
|
||||
|
||||
public static int Register(OccluderLink link)
|
||||
{
|
||||
var id = Interlocked.Increment(ref _next);
|
||||
Links[id] = link;
|
||||
return id;
|
||||
}
|
||||
|
||||
public static void Unregister(int id) => Links.TryRemove(id, out _);
|
||||
|
||||
public static bool TryGet(int id, out OccluderLink link) => Links.TryGetValue(id, out link!);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace VolumetricLight;
|
||||
|
||||
[InlineArray(VolumetricLightSettings.OccluderCapacity)]
|
||||
internal struct OccluderPlaneSet
|
||||
{
|
||||
private Vector4 _first;
|
||||
}
|
||||
|
||||
internal readonly record struct Occluder(ViewTransform View, GoboMapping Gobo, float Strength)
|
||||
{
|
||||
public static float GetStrength(double percent, double opacity)
|
||||
=> (float)(Math.Clamp(percent, 0.0, VolumetricLightSettings.MaximumOccluderStrengthPercent) / VolumetricLightSettings.PercentScale * Math.Clamp(opacity, 0.0, 1.0));
|
||||
}
|
||||
|
||||
internal readonly record struct OccluderPlane(Vector4 Plane, Vector4 ImageX, Vector4 ImageY, float Strength)
|
||||
{
|
||||
public static OccluderPlane Create(in Matrix4x4 cameraFromLight, in Occluder occluder)
|
||||
{
|
||||
var toOccluder = cameraFromLight * occluder.View.LocalFromCamera;
|
||||
if (!ViewTransform.IsFinite(toOccluder) || !(occluder.Strength > 0f))
|
||||
return default;
|
||||
|
||||
var plane = new OccluderPlane(
|
||||
Column(toOccluder, 2),
|
||||
Column(toOccluder, 0) * occluder.Gobo.ScaleX + new Vector4(0f, 0f, 0f, occluder.Gobo.OffsetX),
|
||||
Column(toOccluder, 1) * occluder.Gobo.ScaleY + new Vector4(0f, 0f, 0f, occluder.Gobo.OffsetY),
|
||||
occluder.Strength);
|
||||
return IsFinite(plane.Plane) && IsFinite(plane.ImageX) && IsFinite(plane.ImageY) ? plane : default;
|
||||
}
|
||||
|
||||
private static bool IsFinite(Vector4 value)
|
||||
=> float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z) && float.IsFinite(value.W);
|
||||
|
||||
private static Vector4 Column(in Matrix4x4 matrix, int index) => index switch
|
||||
{
|
||||
0 => new Vector4(matrix.M11, matrix.M21, matrix.M31, matrix.M41),
|
||||
1 => new Vector4(matrix.M12, matrix.M22, matrix.M32, matrix.M42),
|
||||
_ => new Vector4(matrix.M13, matrix.M23, matrix.M33, matrix.M43),
|
||||
};
|
||||
}
|
||||
@@ -36,6 +36,9 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
Mode,
|
||||
Fade,
|
||||
OutputBounds,
|
||||
CameraFromLocal,
|
||||
Link,
|
||||
Revision,
|
||||
}
|
||||
|
||||
public Matrix4x4 LocalFromCamera { set => SetValue((int)PropertyIndex.LocalFromCamera, value); }
|
||||
@@ -57,6 +60,9 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
public Vector4 Mode { set => SetValue((int)PropertyIndex.Mode, value); }
|
||||
public Vector4 Fade { set => SetValue((int)PropertyIndex.Fade, value); }
|
||||
public Vector4 OutputBounds { set => SetValue((int)PropertyIndex.OutputBounds, value); }
|
||||
public Matrix4x4 CameraFromLocal { set => SetValue((int)PropertyIndex.CameraFromLocal, value); }
|
||||
public int Link { set => SetValue((int)PropertyIndex.Link, value); }
|
||||
public int Revision { set => SetValue((int)PropertyIndex.Revision, value); }
|
||||
|
||||
public void Apply(in ShaftConstants next, in ShaftConstants last, bool force)
|
||||
{
|
||||
@@ -98,15 +104,20 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
Fade = next.Fade;
|
||||
if (force || last.OutputBounds != next.OutputBounds)
|
||||
OutputBounds = next.OutputBounds;
|
||||
if (force || last.CameraFromLocal != next.CameraFromLocal)
|
||||
CameraFromLocal = next.CameraFromLocal;
|
||||
}
|
||||
|
||||
[CustomEffect(VolumetricLightSettings.GoboLevelCount)]
|
||||
[CustomEffect(VolumetricLightSettings.GoboLevelCount + VolumetricLightSettings.OccluderCapacity)]
|
||||
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
private ConstantBuffer _cb;
|
||||
private Vector4 _outputBounds;
|
||||
private RawRect _outputRect;
|
||||
private readonly RawRect[] _levelRects = new RawRect[VolumetricLightSettings.GoboLevelCount];
|
||||
private readonly RawRect[] _inputRects = new RawRect[VolumetricLightSettings.GoboLevelCount + VolumetricLightSettings.OccluderCapacity];
|
||||
private Matrix4x4 _cameraFromLocal = Matrix4x4.Identity;
|
||||
private int _link;
|
||||
private int _revision;
|
||||
|
||||
[CustomEffectProperty(PropertyType.Matrix4x4, (int)PropertyIndex.LocalFromCamera)]
|
||||
public Matrix4x4 LocalFromCamera { get => _cb.LocalFromCamera; set { _cb.LocalFromCamera = ViewTransform.IsFinite(value) ? value : default; UpdateConstants(); } }
|
||||
@@ -177,6 +188,15 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
}
|
||||
}
|
||||
|
||||
[CustomEffectProperty(PropertyType.Matrix4x4, (int)PropertyIndex.CameraFromLocal)]
|
||||
public Matrix4x4 CameraFromLocal { get => _cameraFromLocal; set { _cameraFromLocal = ViewTransform.IsFinite(value) ? value : Matrix4x4.Identity; UpdateConstants(); } }
|
||||
|
||||
[CustomEffectProperty(PropertyType.Int32, (int)PropertyIndex.Link)]
|
||||
public int Link { get => _link; set { _link = value; UpdateConstants(); } }
|
||||
|
||||
[CustomEffectProperty(PropertyType.Int32, (int)PropertyIndex.Revision)]
|
||||
public int Revision { get => _revision; set { _revision = value; UpdateConstants(); } }
|
||||
|
||||
public EffectImpl() : base(ShaderResourceUri.Get("Shaft"))
|
||||
{
|
||||
}
|
||||
@@ -191,6 +211,7 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
|
||||
try
|
||||
{
|
||||
ResolveOccluders();
|
||||
drawInformation.SetPixelShaderConstantBuffer(_cb);
|
||||
}
|
||||
catch (Exception exception)
|
||||
@@ -200,24 +221,47 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolveOccluders()
|
||||
{
|
||||
_cb.OccluderStrength = default;
|
||||
if (!OccluderLinks.TryGet(_link, out var link) || link.Group is not { } group)
|
||||
return;
|
||||
|
||||
Span<Occluder> occluders = stackalloc Occluder[VolumetricLightSettings.OccluderCapacity];
|
||||
Span<float> strengths = stackalloc float[VolumetricLightSettings.OccluderCapacity];
|
||||
group.Snapshot(occluders, link.Frame);
|
||||
for (var index = 0; index < occluders.Length; index++)
|
||||
{
|
||||
var plane = OccluderPlane.Create(_cameraFromLocal, occluders[index]);
|
||||
_cb.OccluderPlanes[index] = plane.Plane;
|
||||
_cb.OccluderImageX[index] = plane.ImageX;
|
||||
_cb.OccluderImageY[index] = plane.ImageY;
|
||||
strengths[index] = plane.Strength;
|
||||
}
|
||||
|
||||
_cb.OccluderStrength = new Vector4(strengths[0], strengths[1], strengths[2], strengths[3]);
|
||||
}
|
||||
|
||||
public override void MapInputRectsToOutputRect(
|
||||
RawRect[] inputRects,
|
||||
RawRect[] inputOpaqueSubRects,
|
||||
out RawRect outputRect,
|
||||
out RawRect outputOpaqueSubRect)
|
||||
{
|
||||
for (var index = 0; index < _levelRects.Length; index++)
|
||||
_levelRects[index] = inputRects[index];
|
||||
for (var index = 0; index < _inputRects.Length; index++)
|
||||
_inputRects[index] = inputRects[index];
|
||||
outputRect = _outputRect;
|
||||
outputOpaqueSubRect = default;
|
||||
}
|
||||
|
||||
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
||||
{
|
||||
for (var index = 0; index < _levelRects.Length; index++)
|
||||
for (var index = 0; index < _inputRects.Length; index++)
|
||||
{
|
||||
var rect = _levelRects[index];
|
||||
inputRects[index] = new RawRect(rect.Left - 1, rect.Top - 1, rect.Right + 1, rect.Bottom + 1);
|
||||
var rect = _inputRects[index];
|
||||
inputRects[index] = rect.Right > rect.Left && rect.Bottom > rect.Top
|
||||
? new RawRect(rect.Left - 1, rect.Top - 1, rect.Right + 1, rect.Bottom + 1)
|
||||
: rect;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,6 +284,10 @@ internal sealed class ShaftCustomEffect : D2D1CustomShaderEffectBase
|
||||
public Vector4 Wind;
|
||||
public Vector4 Mode;
|
||||
public Vector4 Fade;
|
||||
public OccluderPlaneSet OccluderPlanes;
|
||||
public OccluderPlaneSet OccluderImageX;
|
||||
public OccluderPlaneSet OccluderImageY;
|
||||
public Vector4 OccluderStrength;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,8 @@ internal readonly record struct ShaftConstants(
|
||||
Vector4 Wind,
|
||||
Vector4 Mode,
|
||||
Vector4 Fade,
|
||||
Vector4 OutputBounds);
|
||||
Vector4 OutputBounds,
|
||||
Matrix4x4 CameraFromLocal);
|
||||
|
||||
internal readonly record struct ShaftScene(ShaftConstants Constants, float Scale, ScreenRect Canvas, ScreenRect Shaft, ViewTransform View, LightVolume Volume)
|
||||
{
|
||||
@@ -96,7 +97,8 @@ internal readonly record struct ShaftScene(ShaftConstants Constants, float Scale
|
||||
new Vector4((float)(Math.Cos(windAngle) * windOffset), (float)(-Math.Sin(windAngle) * windOffset), 0f, 0f),
|
||||
new Vector4(VolumetricLightSettings.MinimumSteps, DustTapsPerCell, 1f / limits.ResolutionScale, 0f),
|
||||
VolumetricLightSettings.GetFade(parameters.Falloff, length),
|
||||
shaft.ToVector());
|
||||
shaft.ToVector(),
|
||||
view.CameraFromLocal);
|
||||
scene = new ShaftScene(constants, limits.ResolutionScale, canvas, shaft, view, volume);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -52,3 +52,13 @@ TagGodRay,,ゴッドレイ,god ray,耶稣光,耶穌光,god ray,god ray,god ray,g
|
||||
TagLightShaft,,光芒,light shaft,光芒,光芒,빛줄기,haz de luz,شعاع ضوء,berkas cahaya
|
||||
TagCrepuscularRay,,薄明光線,crepuscular ray,曙暮光线,曙暮光線,박명 광선,rayo crepuscular,أشعة الشفق,sinar krepuskular
|
||||
TagTyndall,,チンダル現象,tyndall effect,丁达尔效应,丁達爾效應,틴들 현상,efecto Tyndall,تأثير تندال,efek Tyndall
|
||||
VolumetricLightOccluder,,体積光の遮光,Volumetric Light Blocker,体积光遮光,體積光遮光,볼류메트릭 라이트 차단,Bloqueo de luz volumétrica,حاجب الإضاءة الحجمية,Penghalang Cahaya Volumetrik
|
||||
OcclusionGroup,,遮光,Light Blocking,遮光,遮光,빛 차단,Bloqueo de luz,حجب الضوء,Penghalang Cahaya
|
||||
OcclusionChannel,,遮光の番号,Blocking Number,遮光编号,遮光編號,차단 번호,Número de bloqueo,رقم الحجب,Nomor Penghalang
|
||||
OcclusionChannelDescription,,同じ番号を選んだ「体積光の遮光」のアイテムが、光の筋を遮って影を落とします。0 のときは何も遮りません。番号ごとに遮れるアイテムは 4 つまでです。,Items with Volumetric Light Blocker set to the same number block the light shafts and cast shadows. 0 means nothing blocks the light. Up to 4 items per number.,附加了相同编号“体积光遮光”的项目会遮挡光束并投下阴影。为 0 时不遮挡。每个编号最多 4 个项目。,套用相同編號「體積光遮光」的項目會遮擋光束並投下陰影。為 0 時不遮擋。每個編號最多 4 個項目。,같은 번호의 '볼류메트릭 라이트 차단'을 적용한 아이템이 빛줄기를 가려 그림자를 드리웁니다. 0이면 아무것도 가리지 않습니다. 번호당 최대 4개입니다.,Los elementos con Bloqueo de luz volumétrica del mismo número bloquean los haces de luz y proyectan sombras. Con 0 no se bloquea nada. Hasta 4 elementos por número.,العناصر التي تحمل «حاجب الإضاءة الحجمية» بالرقم نفسه تحجب أشعة الضوء وتلقي ظلالًا. القيمة 0 تعني عدم الحجب. حتى 4 عناصر لكل رقم.,Item dengan Penghalang Cahaya Volumetrik bernomor sama menghalangi berkas cahaya dan menjatuhkan bayangan. Nilai 0 berarti tidak ada yang menghalangi. Maksimal 4 item per nomor.
|
||||
OccluderChannel,,番号,Number,编号,編號,번호,Número,الرقم,Nomor
|
||||
OccluderChannelDescription,,同じ番号を選んだ「体積光」の光の筋を、このアイテムが遮ります。番号ごとに遮れるアイテムは 4 つまでです。,This item blocks the light shafts of Volumetric Light effects that use the same number. Up to 4 items per number.,此项目会遮挡选择了相同编号的“体积光”的光束。每个编号最多 4 个项目。,此項目會遮擋選用相同編號的「體積光」的光束。每個編號最多 4 個項目。,이 아이템은 같은 번호를 고른 '볼류메트릭 라이트'의 빛줄기를 가립니다. 번호당 최대 4개입니다.,Este elemento bloquea los haces de luz de los efectos Luz volumétrica que usan el mismo número. Hasta 4 elementos por número.,يحجب هذا العنصر أشعة الإضاءة الحجمية التي تستخدم الرقم نفسه. حتى 4 عناصر لكل رقم.,Item ini menghalangi berkas Cahaya Volumetrik yang memakai nomor sama. Maksimal 4 item per nomor.
|
||||
OccluderStrength,,遮る強さ,Blocking Strength,遮挡强度,遮擋強度,차단 강도,Intensidad del bloqueo,شدة الحجب,Kekuatan Penghalang
|
||||
OccluderStrengthDescription,,アイテムの不透明な部分が光をどれだけ遮るかです。100% で光を通さず、0% で遮りません。,How much the opaque parts of the item block the light. 100% lets no light through; 0% blocks nothing.,项目不透明部分遮挡光线的程度。100% 完全遮挡,0% 不遮挡。,項目不透明部分遮擋光線的程度。100% 完全遮擋,0% 不遮擋。,아이템의 불투명한 부분이 빛을 가리는 정도입니다. 100%는 빛을 완전히 가리고 0%는 가리지 않습니다.,Cuánta luz bloquean las partes opacas del elemento. 100 % no deja pasar luz; 0 % no bloquea nada.,مقدار حجب الأجزاء المعتمة من العنصر للضوء. 100% لا يسمح بمرور الضوء و0% لا يحجب شيئًا.,Seberapa besar bagian buram item menghalangi cahaya. 100% tidak meneruskan cahaya; 0% tidak menghalangi.
|
||||
TagShadow,,影,Shadow,阴影,陰影,그림자,Sombra,ظل,Bayangan
|
||||
TagLightBlocking,,遮光,Light blocking,遮光,遮光,빛 차단,Bloqueo de luz,حجب الضوء,Penghalang cahaya
|
||||
|
@@ -44,7 +44,7 @@ public sealed class VolumetricLightEffect : VideoEffectBase
|
||||
|
||||
[Display(GroupName = nameof(Texts.LightGroup), Name = nameof(Texts.Intensity), Description = nameof(Texts.IntensityDescription), Order = 10, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 300)]
|
||||
public Animation Intensity { get; } = new Animation(100, 0, VolumetricLightSettings.MaximumIntensityPercent);
|
||||
public Animation Intensity { get; } = new Animation(150, 0, VolumetricLightSettings.MaximumIntensityPercent);
|
||||
|
||||
[Display(GroupName = nameof(Texts.LightGroup), Name = nameof(Texts.Threshold), Description = nameof(Texts.ThresholdDescription), Order = 11, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 100)]
|
||||
@@ -103,6 +103,16 @@ public sealed class VolumetricLightEffect : VideoEffectBase
|
||||
public VolumetricLightQuality Quality { get => _quality; set => Set(ref _quality, value); }
|
||||
private VolumetricLightQuality _quality = VolumetricLightQuality.Standard;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OcclusionGroup), Name = nameof(Texts.OcclusionChannel), Description = nameof(Texts.OcclusionChannelDescription), Order = 50, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 0, VolumetricLightSettings.MaximumOcclusionChannel)]
|
||||
[Range(0, VolumetricLightSettings.MaximumOcclusionChannel)]
|
||||
public int OcclusionChannel
|
||||
{
|
||||
get => _occlusionChannel;
|
||||
set => Set(ref _occlusionChannel, Math.Clamp(value, 0, VolumetricLightSettings.MaximumOcclusionChannel));
|
||||
}
|
||||
private int _occlusionChannel;
|
||||
|
||||
private IAnimatable[]? _animatables;
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
@@ -50,6 +50,12 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
private ShaftConstants _constants;
|
||||
private ZoomState _zoomState;
|
||||
private bool _hasZoomState;
|
||||
private readonly OccluderLink _link = new();
|
||||
private int _linkId;
|
||||
private OccluderLease? _lease;
|
||||
private int _occlusionChannel = -1;
|
||||
private Guid _occlusionScene;
|
||||
private int _revision;
|
||||
|
||||
public override DrawDescription Update(EffectDescription effectDescription)
|
||||
{
|
||||
@@ -95,6 +101,8 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
{
|
||||
SetScale(scene.Scale);
|
||||
Apply(scene.Constants);
|
||||
_link.Frame = effectDescription.TimelinePosition.Frame;
|
||||
SetOcclusion(effectDescription.SceneId, Math.Clamp(_item.OcclusionChannel, 0, VolumetricLightSettings.MaximumOcclusionChannel));
|
||||
SetShaft(ShaftState.Shaft);
|
||||
}
|
||||
|
||||
@@ -207,6 +215,35 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
_constants = next;
|
||||
}
|
||||
|
||||
private void SetOcclusion(Guid scene, int channel)
|
||||
{
|
||||
if (_occlusionChannel != channel || _occlusionScene != scene)
|
||||
{
|
||||
ReleaseOcclusion();
|
||||
_lease = channel > 0 ? OccluderRegistry.Acquire(_devices, scene, channel) : null;
|
||||
_lease?.Group.AddConsumer(_shaft!.NativePointer);
|
||||
for (var slot = 0; slot < VolumetricLightSettings.OccluderCapacity; slot++)
|
||||
_shaft!.SetInput(VolumetricLightSettings.GoboLevelCount + slot, _lease?.Group.GetOutput(slot) ?? _emptyOutput, true);
|
||||
|
||||
_link.Group = _lease?.Group;
|
||||
_occlusionChannel = channel;
|
||||
_occlusionScene = scene;
|
||||
}
|
||||
|
||||
if (_lease?.Group.IsOccupied == true)
|
||||
_shaft!.Revision = unchecked(++_revision);
|
||||
}
|
||||
|
||||
private void ReleaseOcclusion()
|
||||
{
|
||||
_link.Group = null;
|
||||
if (_shaft is { } shaft)
|
||||
_lease?.Group.RemoveConsumer(shaft.NativePointer);
|
||||
_lease?.Dispose();
|
||||
_lease = null;
|
||||
_occlusionChannel = -1;
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var emission = new EmissionCustomEffect(devices);
|
||||
@@ -222,8 +259,21 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
_shaft = shaft;
|
||||
disposer.Collect(emission);
|
||||
disposer.Collect(shaft);
|
||||
_linkId = OccluderLinks.Register(_link);
|
||||
shaft.Link = _linkId;
|
||||
|
||||
var context = devices.DeviceContext;
|
||||
var flood = new Flood(context) { Color = Vector4.Zero };
|
||||
var emptyCrop = new Crop(context) { Rectangle = Vector4.Zero };
|
||||
disposer.Collect(flood);
|
||||
disposer.Collect(emptyCrop);
|
||||
using (var floodOutput = flood.Output)
|
||||
emptyCrop.SetInput(0, floodOutput, true);
|
||||
_emptyOutput = emptyCrop.Output;
|
||||
disposer.Collect(_emptyOutput);
|
||||
for (var slot = 0; slot < VolumetricLightSettings.OccluderCapacity; slot++)
|
||||
shaft.SetInput(VolumetricLightSettings.GoboLevelCount + slot, _emptyOutput, true);
|
||||
|
||||
var previous = emission.Output;
|
||||
disposer.Collect(previous);
|
||||
shaft.SetInput(0, previous, true);
|
||||
@@ -269,15 +319,6 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
_renderOutput = _render.Output;
|
||||
disposer.Collect(_renderOutput);
|
||||
|
||||
var flood = new Flood(context) { Color = Vector4.Zero };
|
||||
var emptyCrop = new Crop(context) { Rectangle = Vector4.Zero };
|
||||
disposer.Collect(flood);
|
||||
disposer.Collect(emptyCrop);
|
||||
using (var floodOutput = flood.Output)
|
||||
emptyCrop.SetInput(0, floodOutput, true);
|
||||
_emptyOutput = emptyCrop.Output;
|
||||
disposer.Collect(_emptyOutput);
|
||||
|
||||
_composite = new Composite(context) { InputCount = 2, Mode = CompositeMode.Plus };
|
||||
_composite.SetValue((int)Property.Precision, BufferPrecision.PerChannel16Float);
|
||||
disposer.Collect(_composite);
|
||||
@@ -318,13 +359,15 @@ internal sealed class VolumetricLightEffectProcessor(IGraphicsDevicesAndContext
|
||||
level?.SetInput(0, null, true);
|
||||
if (_shaft is { } shaft)
|
||||
{
|
||||
for (var index = 0; index < VolumetricLightSettings.GoboLevelCount; index++)
|
||||
for (var index = 0; index < VolumetricLightSettings.GoboLevelCount + VolumetricLightSettings.OccluderCapacity; index++)
|
||||
shaft.SetInput(index, null, true);
|
||||
}
|
||||
|
||||
_composite?.SetInput(0, null, true);
|
||||
_composite?.SetInput(1, null, true);
|
||||
_clip?.SetInput(0, null, true);
|
||||
ReleaseOcclusion();
|
||||
OccluderLinks.Unregister(_linkId);
|
||||
_isFirst = true;
|
||||
_hasZoomState = false;
|
||||
_sourceState = SourceState.None;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
|
||||
namespace VolumetricLight;
|
||||
|
||||
[PluginDetails(AuthorName = "routersys")]
|
||||
[VideoEffect(
|
||||
nameof(Texts.VolumetricLightOccluder),
|
||||
[VideoEffectCategories.Decoration],
|
||||
[nameof(Texts.TagVolumetricLight), nameof(Texts.TagGodRay), nameof(Texts.TagShadow), nameof(Texts.TagLightBlocking)],
|
||||
IsAviUtlSupported = false,
|
||||
ResourceType = typeof(Texts))]
|
||||
public sealed class VolumetricLightOccluderEffect : VideoEffectBase
|
||||
{
|
||||
public override string Label => Texts.VolumetricLightOccluder;
|
||||
|
||||
public VolumetricLightOccluderEffect()
|
||||
{
|
||||
VolumetricLightTelemetry.EnsureStartedOnce();
|
||||
VolumetricLightUpdateNotifier.EnsureCheckedOnce();
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.OcclusionGroup), Name = nameof(Texts.OccluderChannel), Description = nameof(Texts.OccluderChannelDescription), Order = 0, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 1, VolumetricLightSettings.MaximumOcclusionChannel)]
|
||||
[Range(1, VolumetricLightSettings.MaximumOcclusionChannel)]
|
||||
public int Channel
|
||||
{
|
||||
get => _channel;
|
||||
set => Set(ref _channel, Math.Clamp(value, 1, VolumetricLightSettings.MaximumOcclusionChannel));
|
||||
}
|
||||
private int _channel = 1;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OcclusionGroup), Name = nameof(Texts.OccluderStrength), Description = nameof(Texts.OccluderStrengthDescription), Order = 1, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 100)]
|
||||
public Animation Strength { get; } = new Animation(100, 0, VolumetricLightSettings.MaximumOccluderStrengthPercent);
|
||||
|
||||
private IAnimatable[]? _animatables;
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
=> new VolumetricLightOccluderEffectProcessor(devices, this);
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables() => _animatables ??= [Strength];
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Player.Video.Effects;
|
||||
|
||||
namespace VolumetricLight;
|
||||
|
||||
internal sealed class VolumetricLightOccluderEffectProcessor(IGraphicsDevicesAndContext devices, VolumetricLightOccluderEffect item) : VideoEffectProcessorBase(devices)
|
||||
{
|
||||
private readonly IGraphicsDevicesAndContext _devices = devices;
|
||||
private readonly VolumetricLightOccluderEffect _item = item;
|
||||
private OccluderLease? _lease;
|
||||
private OccluderSlot? _slot;
|
||||
private int _channel;
|
||||
private Guid _scene;
|
||||
|
||||
public override DrawDescription Update(EffectDescription effectDescription)
|
||||
{
|
||||
try
|
||||
{
|
||||
UpdateCore(effectDescription);
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
VolumetricLightTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateCore(EffectDescription effectDescription)
|
||||
{
|
||||
if (input is null)
|
||||
return;
|
||||
|
||||
var draw = effectDescription.DrawDescription;
|
||||
var channel = Math.Clamp(_item.Channel, 1, VolumetricLightSettings.MaximumOcclusionChannel);
|
||||
var scene = effectDescription.SceneId;
|
||||
if (_lease is null || _channel != channel || _scene != scene)
|
||||
{
|
||||
Release();
|
||||
_lease = OccluderRegistry.Acquire(_devices, scene, channel);
|
||||
_channel = channel;
|
||||
_scene = scene;
|
||||
}
|
||||
|
||||
_slot ??= _lease.Group.Claim();
|
||||
if (_slot is null)
|
||||
return;
|
||||
|
||||
var frame = effectDescription.ItemPosition.Frame;
|
||||
var length = effectDescription.ItemDuration.Frame;
|
||||
var strength = Occluder.GetStrength(_item.Strength.GetValue(frame, length, effectDescription.FPS), draw.Opacity);
|
||||
var occluder = draw.Zoom.X != 0f && draw.Zoom.Y != 0f && ViewTransform.TryCreate(draw, out var view)
|
||||
? new Occluder(view, GoboMapping.Create(draw.Zoom, draw.Invert, draw.CenterPoint), strength)
|
||||
: default;
|
||||
_slot.Publish(input, occluder, effectDescription.TimelinePosition.Frame);
|
||||
}
|
||||
|
||||
private void Release()
|
||||
{
|
||||
_slot?.Dispose();
|
||||
_slot = null;
|
||||
_lease?.Dispose();
|
||||
_lease = null;
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) => null;
|
||||
|
||||
protected override void setInput(ID2D1Image? input)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void ClearEffectChain()
|
||||
{
|
||||
try
|
||||
{
|
||||
Release();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
VolumetricLightTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ internal static class VolumetricLightSettings
|
||||
public const int PlaneCount = 6;
|
||||
public const float ParallelEpsilon = 1e-6f;
|
||||
|
||||
public const int OccluderCapacity = 4;
|
||||
public const int MaximumOcclusionChannel = 8;
|
||||
public const double MaximumOccluderStrengthPercent = PercentScale;
|
||||
|
||||
public static QualityLimits GetQualityLimits(VolumetricLightQuality quality) => quality switch
|
||||
{
|
||||
VolumetricLightQuality.High => new QualityLimits(0.5f, 1.5, 128),
|
||||
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.5 MiB |
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.6 MiB |
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.0 MiB |
新しいイシューから参照
ユーザーをブロックする