コミットを比較

...
30 コミット
作成者 SHA1 メッセージ 日付
routersys 96558947ed Gitea Actions のワークフローを直す 2026-11-08 13:05:42 +09:00
routersys d9fcd6fcfc Gitea Actions のワークフローを直す 2026-11-08 10:15:17 +09:00
routersys b3703e1afc Gitea Actions のワークフローを直す 2026-11-08 09:48:15 +09:00
routersys 20e19a9d9f 過去のタグ用ワークフローを消す 2026-11-08 03:57:47 +09:00
routersys 64e5799493 Gitea Actions のワークフローを直す 2026-11-08 03:55:52 +09:00
routersys 87c861bc16 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:34:20 +09:00
routersys 9e8fd2d897 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:06:49 +09:00
routersys 50b21ccb01 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:35:57 +09:00
routersys 8fe4a86246 Gitea Actions のワークフローを直す 2026-11-07 22:07:52 +09:00
routersys cce60990e2 Gitea Actions のワークフローを足す 2026-11-07 19:52:56 +09:00
routersys cf62a6ef5d 画像の参照先をGiteaへ移す 2026-11-07 18:21:33 +09:00
routersys 8d4f771f8d サブモジュールの参照先をGiteaへ移す 2026-11-07 18:17:35 +09:00
routersys dc2e015b1a READMEの数式をLaTeXで書く 2026-10-20 19:06:24 +09:00
routersys b0a0c5cc8f バージョンをv1.20.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.3 のコミットから作成しました
2026-07-05 19:52:33 +09:00
routersys 40f1322042 [fast]に小処理時の低速化リスクの注意書きを追加 2026-07-05 19:37:27 +09:00
routersys d1b0439611 バージョンをv1.20.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.2 のコミットから作成しました
2026-07-05 19:19:02 +09:00
routersys 30d6f62d15 READMEを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:52 +09:00
routersys ac3a1e350e サイトを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:45 +09:00
routersys 0a7a2c7d40 全言語ドキュメントを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:39 +09:00
routersys 1a97536bc5 テストへ[fast]の強制委譲を検証する項目を追加 2026-07-05 19:17:29 +09:00
routersys 8f954c7a2e 従来エンジンにもforce引数を復元 2026-07-05 19:17:21 +09:00
routersys 20509b19c9 ワーカーにforce引数を復元し[fast]で強制委譲 2026-07-05 19:17:13 +09:00
routersys e4bdf0df19 GPU処理にforce引数を追加しきい値を無視可能に 2026-07-05 19:17:06 +09:00
routersys 1f421dd158 バージョンをv1.20.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.1 のコミットから作成しました
2026-07-05 18:45:22 +09:00
routersys e56a2d85d7 CHANGELOGをv1.20.1の内容へ更新 2026-07-05 18:45:22 +09:00
routersys 969cf52299 READMEを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 01785267fc サイトを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 206001888c 全言語ドキュメントを自動GPU委譲の仕様へ更新 2026-07-05 18:24:07 +09:00
routersys 7c8776dd05 MoonSharpの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys d6756ad3c8 ワーカーの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
33個のファイルの変更、600行の追加、155行の削除

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

+228
ファイルの表示
@@ -0,0 +1,228 @@
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@v4
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
- 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" = "LuaScript-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
env:
CI: 'true'
run: |
dotnet build LuaScript/LuaScript.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:Platform=x64
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "LuaScript/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/LuaScript"
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
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 "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- 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: .github/CHANGELOG.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)"
}
}
+11 -52
ファイルの表示
@@ -1,69 +1,28 @@
# v1.20.0 - Lua スクリプト for YMM4
# v1.20.3 - Lua スクリプト for YMM4
画像加工を GPU へ委譲する高速化マーカー [fast] を追加したリリースです。obj.fill / obj.convolve / obj.resize の呼び出しの直前に [fast] を置くと、その処理を Direct3D 11 のピクセルシェーダーで実行します。AviUtl に無い YMM4 独自の拡張で、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で動作します。[fast] を付けない呼び出しは従来どおり CPU で実行し、既存のスクリプトの実行結果は変わりません。あわせて、エディタの補完候補へ fast を登録し、高速ランタイムのタイムアウト計測からホスト側の処理時間を除外する修正を行いました。
[fast] マーカーの注意書きを補うドキュメント更新リリースです。v1.20.2 で [fast] は obj.fill / obj.convolve / obj.resize の処理量のしきい値を無視して GPU へ委譲する仕様になりましたが、処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回り、かえって遅くなる場合があることを明記しました。動作に関わる実装、API、実行結果、エラーの扱いに変更はありません。
---
## 新機能
## 変更
### [fast] 高速化マーカー
### [fast] は小さな処理で遅くなる場合があることを明記
対象の呼び出しと同じ行の直前、または直前の単独の行に置きます。
[fast] は obj.fill / obj.convolve / obj.resize のしきい値を無視しますが、GPU への委譲には往復コストがあります。処理量が小さいときは CPU 実行のほうが速い場合があるため、README、サイト、付属ドキュメントに注意書きを追加しました。
[fast]
obj.convolve(kernel, 5)
[fast] obj.fill(0, 0, 0, 0)
[fast] obj.resize(obj.w * 2, obj.h * 2)
- 対象は obj.fill / obj.convolve / obj.resize の 3 関数です。マーカーは内部プリミティブ(__fast_fill / __fast_convolve / __fast_resize)への書き換えとして展開します。
- 3 関数以外へ付けるとエラー「[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.」をマーカーの行へ表示します。この場合マーカーだけを取り除き、対象の呼び出しは通常どおり実行します。拡張構文の書き換え診断はエディタの誤り表示へ届くよう全経路へ通しました。
- t[fast] のような添字アクセス、テーブルコンストラクタのキー、文字列やコメントの中の [fast] は書き換えません。
- GPU で実行できない場合は、同じ呼び出しを従来の CPU 実装で実行します。処理は失敗せず、結果は CPU 実行と同じです。
GPU 実行が成立する条件は次のとおりです。いずれかを満たさない場合は自動で CPU 実行になります。
- Direct3D 11 のハードウェアデバイスが利用できること。ソフトウェアラスタライザ(WARP)へは委譲しません。CPU 実装より遅くなるためです。
- 処理量がしきい値以上であること。fill は画像全体で 1,048,576 画素以上、矩形指定では同じ画素数に加えて塗り面積が画像の 3/4 以上、resize は出力が 262,144 画素以上、convolve は画素数×係数の個数が 262,144 以上です。小さな処理は委譲の往復コストが上回るため CPU で実行します。
- convolve のカーネルは 31×31 までです。それを超えるサイズは CPU で実行します。
- 初回に小さな検証画像で GPU の結果を CPU 基準とバイト単位で比較し、一致した組み合わせだけを GPU へ委譲すること。不一致の環境やカーネルでは CPU 実行へ戻ります。検証の結果は fill と resize はモードごとに、convolve はカーネル・除数・オフセットの組ごとに記憶します(最大 64 組)。
### 補完候補への fast の登録
エディタの補完辞書へ fast を登録しました。[fa まで入力すると fast が候補の先頭に現れ、別の単語へ置き換わる誤補完を避けられます。構文規則の属性に IsCatalog と Keyword を追加し、登録が必要な構文拡張のキーワードをソースジェネレーターが補完カタログへ自動で載せる仕組みです。
---
## 修正
### 高速ランタイムのタイムアウトからホスト側の処理時間を除外
高速ランタイムのタイムアウト(5000ms)は、これまで画像の読み込み・シーン描画・GPU 委譲などホスト側コールバックに費やした時間もスクリプトの実行時間として計上していました。このためホスト側の処理が遅い環境では、スクリプト自体は制限内に収まるのにタイムアウトと判定され、[fast] の CPU フォールバックが動作しない問題がありました。コールバックの所要時間を計測して実行予算から除外し、タイムアウトが監視する対象をスクリプトの実行時間だけへ正しました。
### ハードウェアデバイスの再生成に予算制限を適用
GPU 実行が失敗し続ける環境で、Direct3D 11 デバイスを毎フレーム作り直し続ける問題を修正しました。再生成の予算(3 回)を使い切った後はハードウェア実行を無効化し、以後は即座に CPU 実行へ移ります。
- 付属の 8 言語ドキュメントの [fast] の節へ、同じ注意書きを追加しました。
---
## 互換性・後方互換
- [fast] を付けない obj.fill / obj.convolve / obj.resize は従来と同一の CPU 実装で実行し、結果はバイト単位まで変わりません。
- [fast] は AviUtl / AviUtl2 に存在しない YMM4 独自の拡張です。AviUtl 向けに書かれた既存スクリプトへの影響はありません。
- GPU 委譲は事前の検証で CPU 基準と一致した組み合わせに限って行い、成立しない場合は常に CPU 実装が結果を保証します。
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.19.2 までの構文拡張と既存の API に変更はありません。
- 補完候補は fast の 1 語が増えるのみで、既存の候補と順序の規則(長さ順)は変わりません。
- 動作に関わる実装の変更はありません。
- API、構文、エンジンの自動振り分け、GPU 検証、CPU への自動フォールバックに変更はありません。
- v1.20.2 の [fast] の強制委譲仕様に変更はありません。
---
## 内部実装
- GPU 基盤を専用プロジェクト LuaScript.Gpu へ分離しました。obj.pixelshader の実行器(PixelShaderRunner)を移設し、[fast] の 3 演算(GpuFillOperation / GpuConvolveOperation / GpuResizeOperation)と入口の GpuPixelBufferProcessor を追加しました。演算はロックで直列化し、実行器のデバイスと定数バッファ・レンダーターゲット・ステージングテクスチャを再利用します。
- 委譲の契約は IPixelBufferProcessor として Runtime に置き、プラグイン層が GPU 実装を注入します。従来エンジンは AviUtlScriptContext の fill / convolve / resize に明示フラグ accelerate を追加して委譲し、既定値 false のため既存呼び出しの経路は変わりません。
- CPU 基準の実装は PixelBufferSoftwareProcessor として共有化しました。従来エンジンの実行とGPU 検証の基準の両方が同じコードを参照し、基準の二重管理をなくしています。等価性の基準は従来どおり MoonSharp です。
- 内部シェーダー(fill / convolve / resize の HLSL)は、GpuPixelOperationShaderAttribute を読むソースジェネレーターがビルド時に DXBC へ事前コンパイルし、実行メソッドを partial として発行します。実行時のシェーダーコンパイルは発生しません。ユーザーの obj.pixelshader は従来どおり実行時コンパイルです。畳み込みシェーダーは HLSL の予約語との衝突を修正しています。
- 高速ランタイムはプロセス間手順へ呼出種別 CbKindPixelProcess を 1 つ追加しました。畳み込みのカーネルはタグ領域へ double 列として渡します。ホストの処理失敗は「画像を変更しない」を表す 0、プロセッサ不在は -1 で伝え、-1 を受けたワーカーはその実行内の以後の委譲を試みません。
- タイムアウトの修正は、コールバック 1 回ごとの所要時間を実行予算へ加算する方式です。予算と開始時刻のローカル変数 2 つのみで、毎フレームの割り当てはありません。
- 補完への登録は、構文規則の生成物(LuaSyntaxRuleRegistry)へ CatalogKeywords 配列を追加し、補完ソースが候補構築時に連結する形です。キーワードの文字列は規則クラスの定数を属性と判定処理で共有し、重複定義がありません。
- ソースジェネレーターは Lua / Gpu の領域へ整理し、型宣言を 1 ファイル 1 型へ分離しました。増分生成のキャッシュ鍵は EquatableArray へ統一しています。
- テストは 3396 件です。v1.19.2 の 3366 件から、[fast] の書き換え(同一行・単独行・ブロック内・非対象の括弧の除外・診断の行番号)、両エンジンの高速化プリミティブの往復、ホストプロセッサの呼び出しと既定経路の除外、タイムアウト予算の除外、補完カタログの fast を検証しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
- 動作に関わるコード変更はありません。
- リリース対象のバージョン表記を v1.20.3 へ更新しました。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.20.0
Luaスクリプト for YMM4 v1.20.3
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+1 -1
ファイルの表示
@@ -1,3 +1,3 @@
[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
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
+1 -1
ファイルの表示
@@ -5,7 +5,7 @@
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
+2 -2
ファイルの表示
@@ -15,13 +15,13 @@ namespace LuaScript.Engine.Processing
private readonly float[] _constants = new float[1024];
private readonly List<ConvolveValidation> _validations = [];
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
return false;
long work = (long)width * height * size * size;
if (work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
return false;
SetConstants(width, height, kernel, size, divisor, offset);
+3 -3
ファイルの表示
@@ -16,7 +16,7 @@ namespace LuaScript.Engine.Processing
private bool? _fullValidated;
private bool? _partialValidated;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
return false;
@@ -25,14 +25,14 @@ namespace LuaScript.Engine.Processing
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
if (full)
{
if (pixels < FillFullThreshold || !EnsureFullValidated())
if (!force && pixels < FillFullThreshold || !EnsureFullValidated())
return false;
SetConstants(r, g, b, a);
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
}
long area = (long)fillWidth * fillHeight;
if (pixels < FillPartialThreshold || area * 4L < pixels * 3L || !EnsurePartialValidated())
if (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
return false;
SetConstants(r, g, b, a);
+6 -6
ファイルの表示
@@ -9,22 +9,22 @@ namespace LuaScript.Engine.Processing
private readonly GpuConvolveOperation _convolve = new(runner);
private readonly GpuResizeOperation _resize = new(runner);
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
lock (_gate)
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight);
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force);
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
lock (_gate)
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset);
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset, force);
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
lock (_gate)
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
}
}
}
+2 -2
ファイルの表示
@@ -16,14 +16,14 @@ namespace LuaScript.Engine.Processing
private bool? _nearestValidated;
private bool? _linearValidated;
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
target = null;
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
return false;
long pixels = (long)targetWidth * targetHeight;
if (pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
if (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
return false;
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+6 -6
ファイルの表示
@@ -511,7 +511,7 @@ namespace LuaScript
private byte[]? _resizeSource;
private byte[]? _resizeBuffer;
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h, bool accelerate = false)
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
@@ -526,7 +526,7 @@ namespace LuaScript
if (x1 <= x0 || y1 <= y0)
return;
if (accelerate && PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0) == true)
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0, force) == true)
{
_isPixelsDirty = true;
return;
@@ -621,7 +621,7 @@ namespace LuaScript
}
}
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool accelerate = false)
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
@@ -629,7 +629,7 @@ namespace LuaScript
int cw = ImageWidth;
int ch = ImageHeight;
if (accelerate && PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset) == true)
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, force) == true)
{
_isPixelsDirty = true;
return;
@@ -639,7 +639,7 @@ namespace LuaScript
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
}
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool accelerate = false)
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
@@ -650,7 +650,7 @@ namespace LuaScript
int cw = ImageWidth;
int ch = ImageHeight;
if (accelerate && PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed) == true && processed is not null)
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed, force) == true && processed is not null)
{
ReplaceBuffer(processed, newWidth, newHeight);
return;
+3 -3
ファイルの表示
@@ -2,10 +2,10 @@ namespace LuaScript
{
internal interface IPixelBufferProcessor
{
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight);
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false);
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset);
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false);
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target);
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false);
}
}
+10 -9
ファイルの表示
@@ -411,11 +411,12 @@ namespace LuaScript.Engine
_pixelProcessTarget = new byte[pixelLength];
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
bool force = view.ReadDouble(NativeProtocol.CallbackResultOffset + 9 * 8) != 0d;
processed = operation switch
{
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength),
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength, force),
_ => false,
};
}
@@ -424,7 +425,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
}
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
double r = view.ReadDouble(offset + 1 * 8);
@@ -437,13 +438,13 @@ namespace LuaScript.Engine
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight))
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int size = (int)view.ReadDouble(offset + 1 * 8);
@@ -458,13 +459,13 @@ namespace LuaScript.Engine
_pixelProcessKernel = new double[taps];
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset))
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength)
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
@@ -476,7 +477,7 @@ namespace LuaScript.Engine
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
return false;
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target) || target is null)
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target, force) || target is null)
return false;
WriteRegion(_pixelOffset, target, (int)length);
view.Write(NativeProtocol.OffWidth, targetWidth);
+6 -6
ファイルの表示
@@ -1017,7 +1017,7 @@ namespace LuaScript
[LuaFunction("fill")]
private DynValue Fill(CallbackArguments args) => FillCore(args, false);
private DynValue FillCore(CallbackArguments args, bool accelerate)
private DynValue FillCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
@@ -1033,7 +1033,7 @@ namespace LuaScript
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
ctx.FillBuffer(r, g, b, a, x, y, w, h, accelerate);
ctx.FillBuffer(r, g, b, a, x, y, w, h, force);
return DynValue.Void;
}
@@ -1088,7 +1088,7 @@ namespace LuaScript
[LuaFunction("convolve")]
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args, false);
private DynValue ConvolveCore(CallbackArguments args, bool accelerate)
private DynValue ConvolveCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
@@ -1115,14 +1115,14 @@ namespace LuaScript
divisor = 1d;
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
_activeContext.Convolve(_kernelScratch, size, divisor, offset, accelerate);
_activeContext.Convolve(_kernelScratch, size, divisor, offset, force);
return DynValue.Void;
}
[LuaFunction("resize")]
private DynValue Resize(CallbackArguments args) => ResizeCore(args, false);
private DynValue ResizeCore(CallbackArguments args, bool accelerate)
private DynValue ResizeCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2)
@@ -1134,7 +1134,7 @@ namespace LuaScript
return DynValue.Void;
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
_activeContext.Resize(w, h, linear, accelerate);
_activeContext.Resize(w, h, linear, force);
RefreshObjDimensions();
return DynValue.Void;
}
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+70
ファイルの表示
@@ -52,6 +52,76 @@ namespace LuaScript.Tests
return buffer;
}
private sealed class RecordingProcessor : IPixelBufferProcessor
{
public int FillCalls;
public int ConvolveCalls;
public int ResizeCalls;
public bool LastFillForce;
public bool LastConvolveForce;
public bool LastResizeForce;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
FillCalls++;
LastFillForce = force;
return false;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
ConvolveCalls++;
LastConvolveForce = force;
return false;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
ResizeCalls++;
LastResizeForce = force;
target = null;
return false;
}
}
[Fact]
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
Assert.False(processor.LastFillForce);
Assert.False(processor.LastConvolveForce);
Assert.False(processor.LastResizeForce);
}
[Fact]
public void FastMarker_ForcesPixelProcessorRegardlessOfSize()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("__fast_fill(200, 100, 50, 255) __fast_convolve({1,1,1,1,1,1,1,1,1}, 3) __fast_resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.True(processor.LastFillForce);
Assert.True(processor.LastConvolveForce);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void Fill_WholeBuffer_WritesPremultipliedColor()
{
+150 -10
ファイルの表示
@@ -1926,6 +1926,7 @@ namespace LuaScript.Tests
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.True(processor.LastFillForce);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
@@ -1952,6 +1953,7 @@ namespace LuaScript.Tests
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.True(processor.LastConvolveForce);
Assert.Equal(0x42, pixels[0]);
Assert.Equal(0x42, pixels[^1]);
}
@@ -1985,10 +1987,11 @@ namespace LuaScript.Tests
Assert.NotNull(result);
Assert.Equal(0x43, result![0]);
Assert.Equal(0x43, result[^1]);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void PixelProcess_DefaultFill_SkipsHostProcessor()
public void PixelProcess_DefaultFill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
@@ -2000,14 +2003,18 @@ namespace LuaScript.Tests
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.FillCalls);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.False(processor.LastFillForce);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_DefaultConvolve_SkipsHostProcessor()
public void PixelProcess_DefaultConvolve_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
@@ -2019,14 +2026,20 @@ namespace LuaScript.Tests
bool ok = RunWorker(
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ConvolveCalls);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.False(processor.LastConvolveForce);
}
[Fact]
public void PixelProcess_DefaultResize_SkipsHostProcessor()
public void PixelProcess_DefaultResize_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
@@ -2038,12 +2051,133 @@ namespace LuaScript.Tests
bool ok = RunWorker(
"obj.resize(512, 512, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out bool replaced, out _, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(replaced);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
Assert.False(processor.LastResizeForce);
}
[Fact]
public void PixelProcess_BelowThresholdFill_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 64, h = 64;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.FillCalls);
}
[Fact]
public void PixelProcess_BelowThresholdConvolve_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 8, h = 8;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ConvolveCalls);
}
[Fact]
public void PixelProcess_BelowThresholdResize_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.resize(4, 4, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ResizeCalls);
}
[Fact]
public void PixelProcess_ForcedFastFill_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 64, h = 64;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_fill(10, 20, 30, 40)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.FillCalls);
Assert.True(processor.LastFillForce);
}
[Fact]
public void PixelProcess_ForcedFastConvolve_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 8, h = 8;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.ConvolveCalls);
Assert.True(processor.LastConvolveForce);
}
[Fact]
public void PixelProcess_ForcedFastResize_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_resize(4, 4, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.ResizeCalls);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void HostCallbackTime_DoesNotConsumeScriptTimeout()
{
@@ -2295,35 +2429,41 @@ namespace LuaScript.Tests
public int TargetWidth { get; private set; }
public int TargetHeight { get; private set; }
public bool Linear { get; private set; }
public bool LastFillForce { get; private set; }
public bool LastConvolveForce { get; private set; }
public bool LastResizeForce { get; private set; }
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
FillCalls++;
LastFillForce = force;
if (!FillResult)
return false;
Array.Fill(target, (byte)0x41, 0, width * height * 4);
return true;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
ConvolveCalls++;
Size = size;
Divisor = divisor;
Offset = offset;
Kernel = kernel.AsSpan(0, size * size).ToArray();
LastConvolveForce = force;
if (!ConvolveResult)
return false;
Array.Fill(target, (byte)0x42, 0, width * height * 4);
return true;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
ResizeCalls++;
TargetWidth = targetWidth;
TargetHeight = targetHeight;
Linear = linear;
LastResizeForce = force;
target = null;
if (!ResizeResult)
return false;
+1 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.0</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+9 -3
ファイルの表示
@@ -975,13 +975,19 @@
<1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة.
○ [fast] (علامة التسريع) * امتداد خاص بـ YMM4
وضع [fast] مباشرة قبل استدعاء obj.fill / obj.convolve / obj.resize
يفوّض تلك العملية إلى وحدة معالجة الرسوميات. افتراضيًا تُنفَّذ هذه العمليات
على المعالج. يمكن وضع العلامة في سطر مستقل أو في السطر نفسه.
تُفوَّض obj.fill / obj.convolve / obj.resize إلى وحدة معالجة الرسوميات
تلقائيًا عندما يتجاوز حجم المعالجة حدًا معينًا ويتم التحقق من تطابق نتيجة
وحدة معالجة الرسوميات مع نتيجة المعالج. تتجاهل [fast] هذا الحد وتفرض
التفويض إلى وحدة معالجة الرسوميات. عند عدم توفر وحدة معالجة الرسوميات
أو عدم تطابق نتيجتها مع المعالج، ترجع [fast] تلقائيًا إلى المعالج. يمكن
وضع العلامة في سطر مستقل أو في السطر نفسه.
مثال: [fast]
obj.convolve(kernel, 5)
* يظهر خطأ عندما يسبق [fast] أي شيء غير هذه الدوال الثلاث.
* يعمل في محرك MoonSharp والمحرك الأصلي على حد سواء.
* عند أحمال المعالجة الصغيرة، قد تتجاوز تكلفة الذهاب والإياب
الخاصة بتفويض وحدة معالجة الرسوميات تكلفة التنفيذ على المعالج،
فقد تجعل [fast] الأداء أبطأ بدلاً من أسرع.
- أمثلة على النصوص البرمجية -
+10 -3
ファイルの表示
@@ -1014,13 +1014,20 @@
<1..<5> excludes the upper bound. The left side is evaluated once.
o [fast] (acceleration marker) * YMM4 extension
Placing [fast] right before a call to obj.fill / obj.convolve /
obj.resize delegates that operation to the GPU. By default these run
on the CPU. The marker may be on its own line or on the same line.
obj.fill / obj.convolve / obj.resize are delegated to the GPU
automatically when the workload exceeds a threshold and the GPU
result is verified to match the CPU. [fast] ignores that
workload threshold and forces GPU delegation. When no GPU is
available or the GPU result does not match the CPU, [fast]
still falls back to the CPU automatically. The marker may be
on its own line or on the same line.
Example: [fast]
obj.convolve(kernel, 5)
* An error is shown when [fast] precedes anything other than those three functions.
* Works in both the MoonSharp and native engines.
* For small workloads, the round-trip cost of delegating to the GPU
can exceed plain CPU execution, so [fast] may make things slower
rather than faster.
- Script Examples -
+10 -3
ファイルの表示
@@ -1035,13 +1035,20 @@
<1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez.
o [fast] (marcador de aceleración) * extensión de YMM4
Colocar [fast] justo antes de una llamada a obj.fill / obj.convolve /
obj.resize delega esa operación a la GPU. De forma predeterminada se
ejecutan en la CPU. El marcador puede ir en su propia línea o en la misma.
obj.fill / obj.convolve / obj.resize se delegan automáticamente a la
GPU cuando la carga supera un umbral y el resultado de la GPU se
verifica como idéntico al de la CPU. [fast] ignora ese umbral de
carga y fuerza la delegación a la GPU. Cuando no hay GPU disponible
o el resultado de la GPU no coincide con el de la CPU, [fast]
sigue recayendo automáticamente en la CPU. El marcador puede ir
en su propia línea o en la misma.
Ejemplo: [fast]
obj.convolve(kernel, 5)
* Se muestra un error cuando [fast] precede a algo distinto de esas tres funciones.
* Funciona tanto en el motor MoonSharp como en el nativo.
* En cargas pequeñas, el costo de ida y vuelta de delegar a la GPU
puede superar al de ejecutar en CPU, por lo que [fast] puede
hacer las cosas más lentas en vez de más rápidas.
- Ejemplos de script -
+9 -3
ファイルの表示
@@ -1025,14 +1025,20 @@
<1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali.
o [fast] (penanda akselerasi) * ekstensi YMM4
Menempatkan [fast] tepat sebelum panggilan obj.fill / obj.convolve /
obj.resize mendelegasikan operasi tersebut ke GPU. Secara default
operasi ini berjalan di CPU. Penanda boleh di baris tersendiri atau
obj.fill / obj.convolve / obj.resize didelegasikan ke GPU secara
otomatis ketika beban kerja melebihi ambang batas dan hasil GPU
terverifikasi sama dengan CPU. [fast] mengabaikan ambang batas
beban kerja tersebut dan memaksa delegasi ke GPU. Saat GPU tidak
tersedia atau hasil GPU tidak sama dengan CPU, [fast] tetap
otomatis kembali ke CPU. Penanda boleh di baris tersendiri atau
di baris yang sama.
Contoh: [fast]
obj.convolve(kernel, 5)
* Kesalahan ditampilkan jika [fast] mendahului selain ketiga fungsi tersebut.
* Berfungsi pada mesin MoonSharp maupun native.
* Untuk beban kerja kecil, biaya bolak-balik pendelegasian ke GPU
bisa melebihi eksekusi CPU biasa, sehingga [fast] justru bisa
membuat lebih lambat, bukan lebih cepat.
- Contoh Skrip -
+9 -4
ファイルの表示
@@ -982,14 +982,19 @@
<1..<5> は上限を含みません。左辺は 1 度だけ評価します。
○[fast](高速化マーカー) ※YMM4独自拡張
obj.fill / obj.convolve / obj.resize の呼び出しの直前に [fast] を
置くと、その処理を GPU へ委譲します。標準ではこれらは CPU で実行
します。マーカーは単独の行に置いても、同じ行に続けて書いても
構いません。
obj.fill / obj.convolve / obj.resize は、処理量がしきい値以上で
GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲
します。[fast] を付けると、この処理量のしきい値を無視して強制的
に GPU へ委譲します。GPU が使えない環境や GPU の結果が CPU と
一致しない環境では、[fast] を付けても CPU へ自動的に戻ります。
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。
例:[fast]
obj.convolve(kernel, 5)
※ [fast] を付けた対象が上記 3 関数以外のときはエラーを表示します。
※ 従来エンジンと高速ランタイムの両方で動作します。
※ 処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行
を上回ることがあり、[fast] を付けるとかえって遅くなる場合が
あります。
- スクリプト例 -
+7 -2
ファイルの表示
@@ -971,13 +971,18 @@
<1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다.
○ [fast] (가속 마커) ※YMM4 고유 확장
obj.fill / obj.convolve / obj.resize 호출 바로 앞에 [fast]를 두면
해당 처리를 GPU에 위임합니다. 기본적으로 이들은 CPU에서 실행합니다.
obj.fill / obj.convolve / obj.resize는 처리량이 임계값 이상이고
GPU 결과가 CPU와 일치함이 확인되면 자동으로 GPU에 위임합니다.
[fast]를 붙이면 이 처리량 임계값을 무시하고 강제로 GPU에
위임합니다. GPU를 사용할 수 없거나 GPU 결과가 CPU와 일치하지
않는 환경에서는 [fast]를 붙여도 자동으로 CPU로 되돌아갑니다.
마커는 단독 행에 두어도, 같은 행에 이어 써도 됩니다.
예: [fast]
obj.convolve(kernel, 5)
※ [fast]를 붙인 대상이 위 3개 함수가 아니면 오류를 표시합니다.
※ 기존 엔진과 고속 런타임 양쪽에서 동작합니다.
※ 처리량이 작을 때는 GPU 위임 자체의 왕복 비용이 CPU 실행보다
커서, [fast]를 붙이면 오히려 느려질 수 있습니다.
- 스크립트 예 -
+7 -3
ファイルの表示
@@ -929,13 +929,17 @@
<1..<5> 不包含上限。左侧只求值一次。
○ [fast](加速标记) ※YMM4专有扩展
在 obj.fill / obj.convolve / obj.resize 的调用前面加上 [fast],即可
将该处理委托给 GPU。默认情况下这些处理在 CPU 上执行。标记可以单独
占一行,也可以写在同一行。
当处理量达到阈值且 GPU 结果经验证与 CPU 一致时,obj.fill /
obj.convolve / obj.resize 会自动委托给 GPU。加上 [fast] 会
无视处理量阈值,强制委托给 GPU。若环境没有 GPU,或 GPU 结果
与 CPU 不一致,[fast] 仍会自动回退到 CPU。标记可以单独占一行,
也可以写在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修饰的目标不是上述 3 个函数,则显示错误。
※ 在传统引擎和高速运行时上均可运行。
※ 处理量较小时,委托给 GPU 本身的往返开销可能超过 CPU 执行,
加上 [fast] 反而可能更慢。
- 脚本示例 -
+7 -3
ファイルの表示
@@ -930,13 +930,17 @@
<1..<5> 不包含上限。左側只求值一次。
○ [fast](加速標記) ※YMM4專有擴充
在 obj.fill / obj.convolve / obj.resize 的呼叫前面加上 [fast],即可
將該處理委派給 GPU。預設情況下這些處理在 CPU 上執行。標記可以單獨
佔一行,也可以寫在同一行。
當處理量達到閾值且 GPU 結果經驗證與 CPU 一致時,obj.fill /
obj.convolve / obj.resize 會自動委派給 GPU。加上 [fast] 會
無視處理量閾值,強制委派給 GPU。若環境沒有 GPU,或 GPU 結果
與 CPU 不一致,[fast] 仍會自動回退到 CPU。標記可以單獨佔一行,
也可以寫在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修飾的目標不是上述 3 個函式,則顯示錯誤。
※ 在傳統引擎與高速執行環境上皆可運行。
※ 處理量較小時,委派給 GPU 本身的往返成本可能超過 CPU 執行,
加上 [fast] 反而可能更慢。
- 腳本範例 -
+4 -4
ファイルの表示
@@ -11,7 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
![Image](https://github.com/routersys/YMM4-LuaScript/blob/main/docs/LuaScript.png)
![Image](https://git.routersys.com/routersys/YMM4-LuaScript/raw/branch/main/docs/LuaScript.png)
---
@@ -93,7 +93,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
| `obj.ox`, `obj.oy` | 変更可 | 中心点オフセット。描画の中心位置(CenterPoint.X/Y)に反映される |
| `obj.oz` | 変更可(出力には未使用) | 値はスクリプト実行後に読み戻されるが、現状の出力計算では使用されない |
| `obj.sx`, `obj.sy` | 変更可 | X/Y 方向の独立した拡大率。`obj.zoom` / `obj.aspect` の変更より優先される |
| `obj.zoom`, `obj.aspect` | 変更可 | `obj.sx` / `obj.sy` が同時に変更されていない場合のみ、`zoom × (1 ± aspect)` として sx/sy に反映される |
| `obj.zoom`, `obj.aspect` | 変更可 | `obj.sx` / `obj.sy` が同時に変更されていない場合のみ、$\mathrm{zoom} \times (1 \pm \mathrm{aspect})$ として sx/sy に反映される |
| `obj.alpha` | 変更可 | 不透明度(0.0〜255.0)。出力時に 255 で除算され、0.0〜1.0 の Opacity に変換される |
| `obj.rx`, `obj.ry`, `obj.rz` | 変更可 | 回転角(度)。対応する `obj.rxr` / `obj.ryr` / `obj.rzr` が同時に変更されている場合はそちらが優先される |
| `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される |
@@ -261,7 +261,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
- **パイプ**: `x |> f`(`f((x))`。左辺を第 1 引数に渡す)、`x |> clamp(0, 255)`(`clamp((x), 0, 255)`)
- **補間文字列**: `` `x={a}` ``(`("x=" .. tostring(a))`。`{ }` の中に式を書く。拡張構文も使える)
- **範囲判定**: `x in <1..5>`(`1 <= x and x <= 5`)、`<1..<5>`(上限を含まない)
- **高速化マーカー**(YMM4 独自拡張): `[fast]` を `obj.fill` / `obj.convolve` / `obj.resize` の呼び出しの直前(単独行でも同一行でも可)に置くと、その処理を GPU へ委譲する。標準は CPU。文の先頭でのみ働くため `t[fast]` のような添字アクセスには影響しない
- **高速化マーカー**(YMM4 独自拡張): `obj.fill` / `obj.convolve` / `obj.resize` は処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき自動で GPU へ委譲する。呼び出しの直前(単独行でも同一行でも可)に `[fast]` を置くと、このしきい値を無視して強制的に GPU へ委譲する。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、`[fast]` を付けても CPU へ自動的に戻る。処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、`[fast]` を付けるとかえって遅くなる場合がある。文の先頭でのみ働くため `t[fast]` のような添字アクセスには影響しない
各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。
@@ -294,7 +294,7 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
ネイティブ実行には次の制約があります。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜$2^{31}$未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
> 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。
+1 -1
ファイルの表示
@@ -383,7 +383,7 @@ obj.convolve({ -1,-1,-1, -1,8,-1, -1,-1,-1 }, 3, 1, 0) -- 輪郭抽出</code></
</p>
<p>
<code>obj.fill</code>・<code>obj.convolve</code>・<code>obj.resize</code> は標準では CPU で実行します。呼び出しの直前(単独行でも同一行でも可)に <code>[fast]</code> を置くと処理を GPU へ委譲します。詳細は <a href="syntax.html">拡張構文</a> を参照してください。
<code>obj.fill</code>・<code>obj.convolve</code>・<code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。呼び出しの直前(単独行でも同一行でも可)に <code>[fast]</code> を置くと、このしきい値を無視して強制的に GPU へ委譲します。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、<code>[fast]</code> を付けても CPU へ自動的に戻ります。処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、<code>[fast]</code> を付けるとかえって遅くなる場合があります。詳細は <a href="syntax.html">拡張構文</a> を参照してください。
</p>
<h3>アンカーポイント</h3>
+5 -5
ファイルの表示
@@ -252,17 +252,17 @@ end</code></pre>
<h2>[fast] 高速化マーカー</h2>
<p>
<code>obj.fill</code> <code>obj.convolve</code> <code>obj.resize</code> の直前に <code>[fast]</code> を置くと、その処理を GPU へ委譲します。標準ではこれらは CPU で実行します。<strong>YMM4 独自拡張</strong>です。
<code>obj.fill</code> <code>obj.convolve</code> <code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。<code>[fast]</code> を付けると、このしきい値を無視して強制的に GPU へ委譲します。<strong>YMM4 独自拡張</strong>です。
</p>
<table>
<tr><th>書き方</th><th>意味</th></tr>
<tr><td><code>[fast]</code> の次の行に <code>obj.convolve(k, 5)</code></td><td>畳み込みを GPU で実行する</td></tr>
<tr><td><code>obj.convolve(k, 5)</code></td><td>畳み込みを CPU で実行する</td></tr>
<tr><td><code>[fast]</code> の次の行に <code>obj.convolve(k, 5)</code></td><td>しきい値を無視して GPU へ委譲を強制する</td></tr>
<tr><td><code>obj.convolve(k, 5)</code></td><td>処理量に応じて自動で GPU / CPU を判定する</td></tr>
</table>
<p>
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。トラックバーで負荷を変えられるようにしておくと、重い設定のときだけ GPU の恩恵を受けられます。
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、<code>[fast]</code> を付けても自動で CPU 実行に戻ります。
</p>
<pre><code>--track@size:Size,1,15,3,2
@@ -274,7 +274,7 @@ for i = 1, n * n do k[i] = 1 end
obj.convolve(k, n)</code></pre>
<div class="note">
文の先頭でのみマーカーとして働くため、<code>t[fast]</code> のような添字アクセスは変換しません。<code>[fast]</code> を付けた対象が上記 3 関数以外のときはエラーを表示します。従来エンジンと高速ランタイムの両方で動作します。
文の先頭でのみマーカーとして働くため、<code>t[fast]</code> のような添字アクセスは変換しません。<code>[fast]</code> を付けた対象が上記 3 関数以外のときはエラーを表示します。GPU 側の検証(ハードウェア対応と CPU との一致確認)は変わらず行われるため、結果が変わることはありません。従来エンジンと高速ランタイムの両方で動作します。処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、<code>[fast]</code> を付けるとかえって遅くなる場合があります。
</div>
<div class="pager">
+16 -13
ファイルの表示
@@ -160,9 +160,10 @@ local function flushDraws()
k32.WaitForSingleObject(workEvent, INFINITE)
end
local function tryPixelProcess(kind)
local function tryPixelProcess(kind, force)
if not pixelProcessAvailable then return false end
cbResult[0] = kind
cbResult[9] = force and 1 or 0
i32[OFF_CB_FOUND] = 0
i32[OFF_CB_KIND] = CB_KIND_PIXELPROCESS
i32[OFF_STATUS] = STATUS_CALLBACK
@@ -864,7 +865,7 @@ function obj.copybuffer(dst, src)
end
end
local function fillImpl(accel, r, g, b, a, x, y, w, h)
local function fillImpl(force, r, g, b, a, x, y, w, h)
ensurePixels()
flushPixelData()
r = r or 0; g = g or 0; b = b or 0; a = a or 255
@@ -878,11 +879,13 @@ local function fillImpl(accel, r, g, b, a, x, y, w, h)
local imageArea = width * height
local fillArea = (x1 - x0) * (y1 - y0)
local fullFill = x0 == 0 and y0 == 0 and x1 == width and y1 == height
local usePixelProcess = false
if fullFill then
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_FULL_THRESHOLD
else
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD and fillArea * 4 >= imageArea * 3
local usePixelProcess = force
if not usePixelProcess then
if fullFill then
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_FULL_THRESHOLD
else
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD and fillArea * 4 >= imageArea * 3
end
end
cbResult[1] = r
cbResult[2] = g
@@ -892,7 +895,7 @@ local function fillImpl(accel, r, g, b, a, x, y, w, h)
cbResult[6] = y0
cbResult[7] = x1 - x0
cbResult[8] = y1 - y0
if accel and usePixelProcess and tryPixelProcess(PIXEL_PROCESS_FILL) then
if usePixelProcess and tryPixelProcess(PIXEL_PROCESS_FILL, force) then
dirty = true
pdValid = false
pdDirty = false
@@ -977,7 +980,7 @@ function obj.putpixelregion(x, y, w, h, data)
pdValid = false
end
local function convolveImpl(accel, kernel, size, divisor, offset)
local function convolveImpl(force, kernel, size, divisor, offset)
if type(kernel) ~= "table" then return end
size = math.floor(size or 0)
if size < 1 or size % 2 == 0 then return end
@@ -994,7 +997,7 @@ local function convolveImpl(accel, kernel, size, divisor, offset)
local inv = divisor or sum
if inv == 0 then inv = 1 end
offset = offset or 0
if accel and taps * 8 <= CB_TAG_MAX and width * height * taps >= PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD then
if taps * 8 <= CB_TAG_MAX and (force or width * height * taps >= PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD) then
cbResult[1] = size
cbResult[2] = inv
cbResult[3] = offset
@@ -1002,7 +1005,7 @@ local function convolveImpl(accel, kernel, size, divisor, offset)
cbTagD[i - 1] = k[i]
end
i32[OFF_CB_TAGLEN] = taps * 8
if tryPixelProcess(PIXEL_PROCESS_CONVOLVE) then
if tryPixelProcess(PIXEL_PROCESS_CONVOLVE, force) then
dirty = true
pdValid = false
pdDirty = false
@@ -1064,7 +1067,7 @@ end
function obj.convolve(kernel, size, divisor, offset) convolveImpl(false, kernel, size, divisor, offset) end
function __fast_convolve(kernel, size, divisor, offset) convolveImpl(true, kernel, size, divisor, offset) end
local function resizeImpl(accel, newW, newH, mode)
local function resizeImpl(force, newW, newH, mode)
newW = math.floor(newW or 0); newH = math.floor(newH or 0)
if newW < 1 then newW = 1 end
if newH < 1 then newH = 1 end
@@ -1077,7 +1080,7 @@ local function resizeImpl(accel, newW, newH, mode)
cbResult[1] = newW
cbResult[2] = newH
cbResult[3] = linear and 1 or 0
if accel and newW * newH >= PIXEL_PROCESS_RESIZE_THRESHOLD and tryPixelProcess(PIXEL_PROCESS_RESIZE) then
if (force or newW * newH >= PIXEL_PROCESS_RESIZE_THRESHOLD) and tryPixelProcess(PIXEL_PROCESS_RESIZE, force) then
width = newW; height = newH
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
dirty = true