コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
96558947ed
|
||
|
|
d9fcd6fcfc
|
||
|
|
b3703e1afc
|
||
|
|
20e19a9d9f
|
||
|
|
64e5799493
|
||
|
|
87c861bc16
|
||
|
|
9e8fd2d897
|
||
|
|
50b21ccb01
|
||
|
|
8fe4a86246
|
||
|
|
cce60990e2
|
||
|
|
cf62a6ef5d
|
||
|
|
8d4f771f8d
|
||
|
|
dc2e015b1a
|
||
|
|
b0a0c5cc8f
|
||
|
|
40f1322042
|
||
|
|
d1b0439611
|
||
|
|
30d6f62d15
|
||
|
|
ac3a1e350e
|
||
|
|
0a7a2c7d40
|
||
|
|
1a97536bc5
|
||
|
|
8f954c7a2e
|
||
|
|
20509b19c9
|
||
|
|
e4bdf0df19
|
||
|
|
1f421dd158
|
||
|
|
e56a2d85d7
|
||
|
|
969cf52299
|
||
|
|
01785267fc
|
||
|
|
206001888c
|
||
|
|
7c8776dd05
|
||
|
|
d6756ad3c8
|
||
|
|
57c3b346d8
|
||
|
|
55dde273ae
|
||
|
|
a6a9963c85
|
||
|
|
fb7614d6fb
|
||
|
|
a7a8c6b117
|
||
|
|
8b59897992
|
||
|
|
0d8f1e5102
|
||
|
|
e6165ca5a3
|
||
|
|
2bd54674c1
|
||
|
|
9a733807e8
|
||
|
|
f14c689353
|
||
|
|
d4443a1eef
|
||
|
|
b618a3093b
|
||
|
|
a03ba45f2a
|
||
|
|
56c38b2891
|
||
|
|
68b730e6d2
|
||
|
|
ce7b15121c
|
||
|
|
50b20e3060
|
||
|
|
c1f4fa2dc5
|
||
|
|
af9c5af173
|
||
|
|
406a4c1a1b
|
||
|
|
b732dd1b90
|
||
|
|
1e93df21ef
|
||
|
|
3bd6133bef
|
||
|
|
0c05fe2198
|
||
|
|
775791d1e1
|
||
|
|
a291d66567
|
||
|
|
31d26c0a70
|
||
|
|
88b95cc09a
|
||
|
|
9ff328d03a
|
||
|
|
481bce261e
|
||
|
|
421acf1a6a
|
||
|
|
1d01e9d275
|
||
|
|
1a3394b8f5
|
||
|
|
52bbff8284
|
||
|
|
b150970f83
|
||
|
|
6ce23d486a
|
||
|
|
024723a029
|
||
|
|
4746f01134
|
||
|
|
f2ea36ba49
|
||
|
|
adf47608d2
|
||
|
|
f916c810dc
|
||
|
|
9b86a3cb10
|
||
|
|
0fd1194596
|
||
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
||
|
|
8428057eb4
|
||
|
|
1133daf764
|
||
|
|
b09070e8df
|
||
|
|
cde0b8f498
|
||
|
|
916dd278b2
|
||
|
|
d6d0792207
|
||
|
|
a7bae506a7
|
||
|
|
d05906de7b
|
||
|
|
a8300041e3
|
||
|
|
8bd0d2bc0e
|
||
|
|
cf5f4acf72
|
||
|
|
0d6709d518
|
||
|
|
12bd10164b
|
||
|
|
6287e74fe5
|
||
|
|
8956b7c8d5
|
||
|
|
60c6a37f89
|
||
|
|
9a9c2ec405
|
||
|
|
103b612082
|
||
|
|
9e1da1839e
|
||
|
|
c19e12aa87
|
||
|
|
ed4c38772f
|
||
|
|
d31fd77aee
|
||
|
|
eb0199131d
|
||
|
|
36935bdf1d
|
||
|
|
7d9a9f1cb8
|
||
|
|
3ce2483062
|
||
|
|
fc8a07f935
|
||
|
|
d1279c25fa
|
||
|
|
048c6d6707
|
||
|
|
3a29862423
|
||
|
|
8c69864456
|
||
|
|
8a7b328db4
|
||
|
|
8517bf5f50
|
||
|
|
b928101e3e
|
||
|
|
7fb671e8c6
|
||
|
|
20ff47edce
|
||
|
|
8f9b7c725f
|
||
|
|
499f8ba078
|
||
|
|
66f2d398b7
|
||
|
|
935bca6fbb
|
||
|
|
4c7ef12361
|
||
|
|
65e7864221
|
||
|
|
25430c4dcf
|
||
|
|
f0234d21e4
|
||
|
|
bfe23707f0
|
||
|
|
e74af227d8
|
||
|
|
2b5901379f
|
||
|
|
deb94b3f29
|
||
|
|
74a65b7a8b
|
||
|
|
a4cc0f3220
|
||
|
|
86f889cbd2
|
||
|
|
c2f48230f3
|
||
|
|
4153956b37
|
||
|
|
3763db1cfc
|
||
|
|
9bcab1ae28
|
||
|
|
6e13a4d1c2
|
||
|
|
8dc87d63be
|
||
|
|
0afb7afc21
|
||
|
|
2769a29808
|
||
|
|
1f21b4c49c
|
||
|
|
cafc6d6e48
|
||
|
|
49a2ce29b2
|
||
|
|
d728c8d056
|
||
|
|
b6eac20941
|
||
|
|
d8589007b3
|
||
|
|
85596f76f7
|
||
|
|
018999ff5e
|
||
|
|
c5da497bb3
|
||
|
|
f46cb08f85
|
||
|
|
b0a5293b89
|
||
|
|
67a1b4fa31
|
||
|
|
2d0fb2c47a
|
||
|
|
45d5164afa
|
||
|
|
ba20fc8187
|
||
|
|
669b24c2b3
|
||
|
|
91a3e3f762
|
||
|
|
722ae62326
|
||
|
|
fee1f293c7
|
||
|
|
b6764fe637
|
||
|
|
01e368207d
|
||
|
|
29ea2ea45c
|
||
|
|
1d60d8b245
|
||
|
|
8f2aafdffd
|
検索条件に一致するファイルはありません
@@ -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
-26
@@ -1,43 +1,28 @@
|
|||||||
# v1.13.4 - Lua スクリプト for YMM4
|
# v1.20.3 - Lua スクリプト for YMM4
|
||||||
|
|
||||||
環境情報を取得する obj.getinfo を追加したリリースです。
|
[fast] マーカーの注意書きを補うドキュメント更新リリースです。v1.20.2 で [fast] は obj.fill / obj.convolve / obj.resize の処理量のしきい値を無視して GPU へ委譲する仕様になりましたが、処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回り、かえって遅くなる場合があることを明記しました。動作に関わる実装、API、実行結果、エラーの扱いに変更はありません。
|
||||||
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
|
|
||||||
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 新機能
|
## 変更
|
||||||
|
|
||||||
### obj.getinfo による環境情報の取得
|
### [fast] は小さな処理で遅くなる場合があることを明記
|
||||||
|
|
||||||
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
|
[fast] は obj.fill / obj.convolve / obj.resize のしきい値を無視しますが、GPU への委譲には往復コストがあります。処理量が小さいときは CPU 実行のほうが速い場合があるため、README、サイト、付属ドキュメントに注意書きを追加しました。
|
||||||
|
|
||||||
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
|
- 付属の 8 言語ドキュメントの [fast] の節へ、同じ注意書きを追加しました。
|
||||||
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
|
|
||||||
- "saving" は、動画を出力中のときだけ true を返します。
|
|
||||||
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
|
|
||||||
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
|
|
||||||
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
|
|
||||||
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
|
|
||||||
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
|
|
||||||
|
|
||||||
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 互換性・後方互換
|
## 互換性・後方互換
|
||||||
|
|
||||||
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
|
- 動作に関わる実装の変更はありません。
|
||||||
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
|
- API、構文、エンジンの自動振り分け、GPU 検証、CPU への自動フォールバックに変更はありません。
|
||||||
- v1.13.3 までの仕様に変更はありません。
|
- v1.20.2 の [fast] の強制委譲仕様に変更はありません。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 内部実装
|
## 内部実装
|
||||||
|
|
||||||
- プラグインを依存関係の層ごとに LuaScript.Kernel、LuaScript.Compat、LuaScript.Media、LuaScript.Runtime、および本体の 5 つのアセンブリへ分割しました。名前空間は据え置き、参照の向きを一方向へ整理しています。
|
- 動作に関わるコード変更はありません。
|
||||||
- Lua API の登録と毎フレームの変数投影を、属性から生成するソースジェネレータへ移行しました。入力補完の候補もこの宣言から生成し、手書きの一覧を廃止しました。関数を 1 つ追加すると、登録と補完へ自動的に反映されます。
|
- リリース対象のバージョン表記を v1.20.3 へ更新しました。
|
||||||
- Kernel、Compat、Runtime の各プロジェクトを 1 ファイル 1 クラスへ整理し、ドメインごとのフォルダへ再配置しました。エンジンのテーブル管理は LuaScope へ汎用化しています。
|
|
||||||
- 映像デコーダを LuaScript.Media プロジェクトへ分離し、ツールバーを View と ViewModel へ分離しました。ViewModel はフレームワークに依存しない構成へ整理しています。
|
|
||||||
- obj.getinfo の実装では、BPMグリッドの情報を YMM4 のシーンから取得し、script_path と version は本体からエンジンへ渡します。経過時間は両エンジンがそれぞれ高精度タイマーで計測します。
|
|
||||||
- テストは 3113 件です。v1.13.3 の 3092 件から、obj.getinfo の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
|
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
========================================
|
========================================
|
||||||
Luaスクリプト for YMM4 v1.13.4
|
Luaスクリプト for YMM4 v1.20.3
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||||
ピクセルを直接制御できるプラグインです。
|
ピクセルを直接制御できるプラグインです。
|
||||||
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
||||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
|
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
|
||||||
対応しています。
|
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
|
||||||
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
||||||
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ jobs:
|
|||||||
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/LuaScript.Runtime.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/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||||
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||||
|
|||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
[submodule "YukkuriMovieMaker.Generator"]
|
[submodule "YukkuriMovieMaker.Generator"]
|
||||||
path = YukkuriMovieMaker.Generator
|
path = YukkuriMovieMaker.Generator
|
||||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlAudioConverter
|
||||||
|
{
|
||||||
|
public const int MaxSamples = 1024;
|
||||||
|
public const int SpectrumWindow = 1024;
|
||||||
|
public const int FourierWindow = 2048;
|
||||||
|
public const int SpectrumBins = SpectrumWindow / 2;
|
||||||
|
|
||||||
|
private const double PcmScale = 32768d;
|
||||||
|
|
||||||
|
private readonly double[] _mono = new double[FourierWindow];
|
||||||
|
private readonly double[] _real = new double[FourierWindow];
|
||||||
|
private readonly double[] _imag = new double[FourierWindow];
|
||||||
|
|
||||||
|
private enum DataKind
|
||||||
|
{
|
||||||
|
Unknown,
|
||||||
|
Pcm,
|
||||||
|
Spectrum,
|
||||||
|
Fourier,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RequiredFrames(string type, int size)
|
||||||
|
{
|
||||||
|
var (kind, _) = Parse(type);
|
||||||
|
return kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => ResolveCount(kind, size),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
DataKind.Fourier => FourierWindow,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||||
|
{
|
||||||
|
var (kind, channel) = Parse(type);
|
||||||
|
if (kind == DataKind.Unknown || frames <= 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int window = kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
_ => FourierWindow,
|
||||||
|
};
|
||||||
|
FillMono(interleaved, frames, channel, window);
|
||||||
|
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case DataKind.Pcm:
|
||||||
|
{
|
||||||
|
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
case DataKind.Spectrum:
|
||||||
|
{
|
||||||
|
int bands = ResolveCount(kind, size);
|
||||||
|
Fft(SpectrumWindow);
|
||||||
|
double scale = 2d / SpectrumWindow * PcmScale;
|
||||||
|
for (int b = 0; b < bands; b++)
|
||||||
|
{
|
||||||
|
int start = b * SpectrumBins / bands;
|
||||||
|
int end = (b + 1) * SpectrumBins / bands;
|
||||||
|
if (end <= start)
|
||||||
|
end = start + 1;
|
||||||
|
double sum = 0d;
|
||||||
|
for (int bin = start; bin < end; bin++)
|
||||||
|
sum += Magnitude(bin);
|
||||||
|
destination[b] = sum / (end - start) * scale;
|
||||||
|
}
|
||||||
|
return bands;
|
||||||
|
}
|
||||||
|
case DataKind.Fourier:
|
||||||
|
{
|
||||||
|
int count = ResolveCount(kind, size);
|
||||||
|
Fft(FourierWindow);
|
||||||
|
double scale = 2d / FourierWindow;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Magnitude(i + 1) * scale;
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ResolveCount(DataKind kind, int size)
|
||||||
|
{
|
||||||
|
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||||
|
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||||
|
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (DataKind Kind, int Channel) Parse(string type)
|
||||||
|
{
|
||||||
|
int channel = 0;
|
||||||
|
int length = type.Length;
|
||||||
|
if (length >= 2 && type[length - 2] == '.')
|
||||||
|
{
|
||||||
|
char suffix = type[length - 1];
|
||||||
|
if (suffix == 'l')
|
||||||
|
channel = 1;
|
||||||
|
else if (suffix == 'r')
|
||||||
|
channel = 2;
|
||||||
|
if (channel != 0)
|
||||||
|
length -= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = type.AsSpan(0, length);
|
||||||
|
DataKind kind = DataKind.Unknown;
|
||||||
|
if (name.SequenceEqual("pcm"))
|
||||||
|
kind = DataKind.Pcm;
|
||||||
|
else if (name.SequenceEqual("spectrum"))
|
||||||
|
kind = DataKind.Spectrum;
|
||||||
|
else if (name.SequenceEqual("fourier"))
|
||||||
|
kind = DataKind.Fourier;
|
||||||
|
return (kind, channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||||
|
{
|
||||||
|
int available = Math.Min(frames, window);
|
||||||
|
for (int i = 0; i < available; i++)
|
||||||
|
{
|
||||||
|
float left = interleaved[i * 2];
|
||||||
|
float right = interleaved[i * 2 + 1];
|
||||||
|
_mono[i] = channel switch
|
||||||
|
{
|
||||||
|
1 => left,
|
||||||
|
2 => right,
|
||||||
|
_ => (left + right) * 0.5d,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (int i = available; i < window; i++)
|
||||||
|
_mono[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double Magnitude(int bin) =>
|
||||||
|
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||||
|
|
||||||
|
private void Fft(int n)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
_real[i] = _mono[i];
|
||||||
|
_imag[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1, j = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
int bit = n >> 1;
|
||||||
|
for (; (j & bit) != 0; bit >>= 1)
|
||||||
|
j ^= bit;
|
||||||
|
j |= bit;
|
||||||
|
if (i < j)
|
||||||
|
{
|
||||||
|
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||||
|
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int len = 2; len <= n; len <<= 1)
|
||||||
|
{
|
||||||
|
double angle = -2d * Math.PI / len;
|
||||||
|
double wRe = Math.Cos(angle);
|
||||||
|
double wIm = Math.Sin(angle);
|
||||||
|
for (int i = 0; i < n; i += len)
|
||||||
|
{
|
||||||
|
double curRe = 1d;
|
||||||
|
double curIm = 0d;
|
||||||
|
for (int k = 0; k < len / 2; k++)
|
||||||
|
{
|
||||||
|
int a = i + k;
|
||||||
|
int b = i + k + len / 2;
|
||||||
|
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||||
|
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||||
|
_real[b] = _real[a] - tRe;
|
||||||
|
_imag[b] = _imag[a] - tIm;
|
||||||
|
_real[a] += tRe;
|
||||||
|
_imag[a] += tIm;
|
||||||
|
double nextRe = curRe * wRe - curIm * wIm;
|
||||||
|
curIm = curRe * wIm + curIm * wRe;
|
||||||
|
curRe = nextRe;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.13.4</Version>
|
<Version>1.20.3</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||||
|
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlPixelShaderLibrary
|
||||||
|
{
|
||||||
|
private const string SectionMarker = "--[[pixelshader@";
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
|
||||||
|
|
||||||
|
private readonly Dictionary<string, string>? _shaders;
|
||||||
|
|
||||||
|
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
|
||||||
|
|
||||||
|
public int Count => _shaders?.Count ?? 0;
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Parse(string? source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return Empty;
|
||||||
|
|
||||||
|
Dictionary<string, string>? shaders = null;
|
||||||
|
int index = 0;
|
||||||
|
while (index < source.Length)
|
||||||
|
{
|
||||||
|
int lineStart = index;
|
||||||
|
int lineBreak = source.IndexOf('\n', index);
|
||||||
|
index = lineBreak < 0 ? source.Length : lineBreak + 1;
|
||||||
|
|
||||||
|
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
|
||||||
|
if (!MatchesMarker(source, i))
|
||||||
|
continue;
|
||||||
|
i += SectionMarker.Length;
|
||||||
|
|
||||||
|
int nameStart = i;
|
||||||
|
while (i < source.Length && IsEntryPointChar(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i == nameStart || i >= source.Length || source[i] != ':')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string name = source[nameStart..i];
|
||||||
|
int bodyStart = i + 1;
|
||||||
|
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
|
||||||
|
if (bodyEnd < 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
|
||||||
|
index = bodyEnd + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGet(string name, out string hlsl)
|
||||||
|
{
|
||||||
|
hlsl = string.Empty;
|
||||||
|
if (_shaders is null || string.IsNullOrEmpty(name))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
string local = at < 0 ? name : name[..at];
|
||||||
|
if (_shaders.TryGetValue(local, out var found))
|
||||||
|
{
|
||||||
|
hlsl = found;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string EntryPointOf(string name)
|
||||||
|
{
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
return at < 0 ? name : name[..at];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool MatchesMarker(string text, int index) =>
|
||||||
|
index + SectionMarker.Length <= text.Length &&
|
||||||
|
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
|
||||||
|
|
||||||
|
private static bool IsEntryPointChar(char c) =>
|
||||||
|
ScriptParserHelper.IsNameChar(c) || c == '_';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
namespace LuaScript.Compat
|
namespace LuaScript.Compat
|
||||||
{
|
{
|
||||||
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||||
|
|
||||||
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(source))
|
if (string.IsNullOrEmpty(source))
|
||||||
return (source, []);
|
return (source, [], [], []);
|
||||||
|
|
||||||
var lines = ScriptParserHelper.SplitLines(source);
|
var lines = ScriptParserHelper.SplitLines(source);
|
||||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||||
@@ -28,7 +29,10 @@ namespace LuaScript.Compat
|
|||||||
AppendDeclarations(lines[i], prelude);
|
AppendDeclarations(lines[i], prelude);
|
||||||
|
|
||||||
if (!hasSection && prelude.Count == 0)
|
if (!hasSection && prelude.Count == 0)
|
||||||
return (source, []);
|
{
|
||||||
|
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||||
|
return (code, [], changed, preludeless);
|
||||||
|
}
|
||||||
|
|
||||||
var builder = new StringBuilder(source.Length + 64);
|
var builder = new StringBuilder(source.Length + 64);
|
||||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||||
@@ -45,7 +49,8 @@ namespace LuaScript.Compat
|
|||||||
lineMap[row++] = i;
|
lineMap[row++] = i;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (builder.ToString(), lineMap);
|
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||||
|
return (rewritten, lineMap, changedLines, diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AppendDeclarations(string line, List<string> prelude)
|
private static void AppendDeclarations(string line, List<string> prelude)
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxExtensions
|
||||||
|
{
|
||||||
|
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return (source, [], []);
|
||||||
|
|
||||||
|
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||||
|
var context = new LuaRewriteContext(tokens);
|
||||||
|
var rules = LuaSyntaxRuleRegistry.Rules;
|
||||||
|
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var current = context.Current;
|
||||||
|
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool matched = false;
|
||||||
|
foreach (var rule in rules)
|
||||||
|
{
|
||||||
|
if (rule.TryApply(context))
|
||||||
|
{
|
||||||
|
matched = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matched)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var diagnostics = context.Diagnostics;
|
||||||
|
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using LuaScript.Engine.Kernel;
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
namespace LuaScript.Compat
|
namespace LuaScript.Compat
|
||||||
{
|
{
|
||||||
@@ -35,15 +35,7 @@ namespace LuaScript.Compat
|
|||||||
if (string.IsNullOrEmpty(script))
|
if (string.IsNullOrEmpty(script))
|
||||||
return None;
|
return None;
|
||||||
|
|
||||||
List<LuaToken> tokens;
|
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||||
try
|
|
||||||
{
|
|
||||||
tokens = LuaLexer.Tokenize(script);
|
|
||||||
}
|
|
||||||
catch (KernelUnsupportedException)
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
HashSet<string>? members = null;
|
HashSet<string>? members = null;
|
||||||
bool color = false;
|
bool color = false;
|
||||||
@@ -51,26 +43,52 @@ namespace LuaScript.Compat
|
|||||||
for (int i = 0; i < tokens.Count; i++)
|
for (int i = 0; i < tokens.Count; i++)
|
||||||
{
|
{
|
||||||
var token = tokens[i];
|
var token = tokens[i];
|
||||||
if (token.Kind != LuaTokenKind.Name)
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (token.Text == "color")
|
if (token.Text == "color")
|
||||||
{
|
{
|
||||||
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
int previous = PreviousSignificant(tokens, i);
|
||||||
|
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||||
color = true;
|
color = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (token.Text == "obj" &&
|
if (token.Text == "obj")
|
||||||
i + 2 < tokens.Count &&
|
|
||||||
tokens[i + 1].IsSymbol(".") &&
|
|
||||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
|
||||||
{
|
{
|
||||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
int dot = NextSignificant(tokens, i + 1);
|
||||||
|
if (dot < 0 || !tokens[dot].IsOperator("."))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
int member = NextSignificant(tokens, dot + 1);
|
||||||
|
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ScriptParameterUsage(members, color);
|
return new ScriptParameterUsage(members, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal interface ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
bool TryApply(LuaRewriteContext context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaKeywords
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> Reserved = new()
|
||||||
|
{
|
||||||
|
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||||
|
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
|
||||||
|
"then", "true", "until", "while",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly HashSet<string> ExpressionSafe = new()
|
||||||
|
{
|
||||||
|
"and", "or", "not", "nil", "true", "false",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsReserved(string name) => Reserved.Contains(name);
|
||||||
|
|
||||||
|
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaRangeParts
|
||||||
|
{
|
||||||
|
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
|
||||||
|
{
|
||||||
|
Start = start;
|
||||||
|
Stop = stop;
|
||||||
|
Step = step;
|
||||||
|
Exclusive = exclusive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Start { get; }
|
||||||
|
|
||||||
|
public string Stop { get; }
|
||||||
|
|
||||||
|
public string? Step { get; }
|
||||||
|
|
||||||
|
public bool Exclusive { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class LuaRangeSyntax
|
||||||
|
{
|
||||||
|
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
|
||||||
|
{
|
||||||
|
parts = default;
|
||||||
|
end = open;
|
||||||
|
|
||||||
|
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int position = open + 1;
|
||||||
|
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bool exclusive = false;
|
||||||
|
int caret = NextSignificant(input, position);
|
||||||
|
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||||
|
{
|
||||||
|
exclusive = true;
|
||||||
|
position = caret + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? step = null;
|
||||||
|
if (stopTerminator == ",")
|
||||||
|
{
|
||||||
|
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||||
|
return false;
|
||||||
|
step = stepText;
|
||||||
|
}
|
||||||
|
else if (stopTerminator != ">")
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
parts = new LuaRangeParts(start, stop, step, exclusive);
|
||||||
|
end = position;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
terminator = string.Empty;
|
||||||
|
int start = position;
|
||||||
|
int depth = 0;
|
||||||
|
int count = input.Count;
|
||||||
|
|
||||||
|
while (position < count)
|
||||||
|
{
|
||||||
|
var token = input[position];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
return false;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return false;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||||
|
{
|
||||||
|
terminator = token.Text;
|
||||||
|
text = Trim(input, start, position);
|
||||||
|
position++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal sealed class LuaRewriteContext
|
||||||
|
{
|
||||||
|
private readonly List<LuaSyntaxToken> _input;
|
||||||
|
private readonly List<LuaSyntaxToken> _output;
|
||||||
|
private List<int>? _changedLines;
|
||||||
|
private List<LuaRewriteDiagnostic>? _diagnostics;
|
||||||
|
private int _line = 1;
|
||||||
|
private int _lastChangedLine;
|
||||||
|
private int _temporaries;
|
||||||
|
|
||||||
|
public LuaRewriteContext(List<LuaSyntaxToken> input)
|
||||||
|
{
|
||||||
|
_input = input;
|
||||||
|
_output = new List<LuaSyntaxToken>(input.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LuaSyntaxToken> Input => _input;
|
||||||
|
|
||||||
|
public List<LuaSyntaxToken> Output => _output;
|
||||||
|
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
public bool Changed { get; private set; }
|
||||||
|
|
||||||
|
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||||
|
|
||||||
|
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
|
||||||
|
|
||||||
|
public void AddDiagnostic(string message)
|
||||||
|
{
|
||||||
|
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool AtEnd => Index >= _input.Count;
|
||||||
|
|
||||||
|
public LuaSyntaxToken Current => _input[Index];
|
||||||
|
|
||||||
|
public void Advance() => Index++;
|
||||||
|
|
||||||
|
public void Emit(LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
_output.Add(token);
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
_line++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitRaw(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitOperator(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string NextTemporary() => "__lc" + _temporaries++;
|
||||||
|
|
||||||
|
public int NextSignificant(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!_input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
for (int i = _output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
break;
|
||||||
|
if (_output[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
token = _output[i];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
token = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int NextSignificantSameLine(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (_input[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitWord(string word)
|
||||||
|
{
|
||||||
|
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
|
||||||
|
if (Index < _input.Count && !_input[Index].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MarkChanged()
|
||||||
|
{
|
||||||
|
Changed = true;
|
||||||
|
if (_line == _lastChangedLine)
|
||||||
|
return;
|
||||||
|
(_changedLines ??= new List<int>()).Add(_line);
|
||||||
|
_lastChangedLine = _line;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryReadTrailingLvalue(out int start, out string text)
|
||||||
|
{
|
||||||
|
start = _output.Count;
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0 || token.Text == ".")
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name)
|
||||||
|
{
|
||||||
|
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
start = begin;
|
||||||
|
text = Concat(begin, end);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPopOrOperand(out string text)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth == 0 && token.Text is "=" or "," or ";")
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
text = Concat(begin, end);
|
||||||
|
_output.RemoveRange(begin, _output.Count - begin);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
|
||||||
|
|
||||||
|
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
|
||||||
|
|
||||||
|
public string ReadLineExpression()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text == ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ReadForwardOrOperand()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Serialize()
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
foreach (var token in _output)
|
||||||
|
builder.Append(token.Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Concat(int begin, int end)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_output[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string TrimmedRange(int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && _input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && _input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxFacts
|
||||||
|
{
|
||||||
|
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxLexer
|
||||||
|
{
|
||||||
|
private static readonly string[] Operators =
|
||||||
|
{
|
||||||
|
"...", "..=", "??=", "||=", "&&=",
|
||||||
|
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
|
||||||
|
"=>", "|>",
|
||||||
|
"+=", "-=", "*=", "/=", "%=", "^=",
|
||||||
|
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
|
||||||
|
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
|
||||||
|
"!", "&", "|", "?", "~",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static List<LuaSyntaxToken> Tokenize(string source)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int i = 0;
|
||||||
|
int length = source.Length;
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
|
||||||
|
if (c == '\r' || c == '\n')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
|
||||||
|
i += 2;
|
||||||
|
else
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipComment(source, i + 2);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '[')
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipLongBracket(source, i, level);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '`')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipNumber(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsNameStart(c))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && IsNamePart(source[i]))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? op = MatchOperator(source, i);
|
||||||
|
if (op is not null)
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
|
||||||
|
i += op.Length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? MatchOperator(string source, int index)
|
||||||
|
{
|
||||||
|
int remaining = source.Length - index;
|
||||||
|
foreach (var op in Operators)
|
||||||
|
{
|
||||||
|
if (op.Length > remaining)
|
||||||
|
continue;
|
||||||
|
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
|
||||||
|
return op;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipNumber(string source, int i)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == 'p' || source[i] == 'P'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipComment(string source, int i)
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
return SkipLongBracket(source, i, level);
|
||||||
|
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && source[i] != '\n' && source[i] != '\r')
|
||||||
|
i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LongBracketLevel(string source, int i)
|
||||||
|
{
|
||||||
|
if (i >= source.Length || source[i] != '[')
|
||||||
|
return -1;
|
||||||
|
int j = i + 1;
|
||||||
|
int level = 0;
|
||||||
|
while (j < source.Length && source[j] == '=')
|
||||||
|
{
|
||||||
|
level++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return j < source.Length && source[j] == '[' ? level : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLongBracket(string source, int i, int level)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
i += level + 2;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
if (source[i] == ']')
|
||||||
|
{
|
||||||
|
int j = i + 1;
|
||||||
|
int count = 0;
|
||||||
|
while (j < length && source[j] == '=')
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (count == level && j < length && source[j] == ']')
|
||||||
|
return j + 1;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipShortString(string source, int start)
|
||||||
|
{
|
||||||
|
char quote = source[start];
|
||||||
|
int i = start + 1;
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
return i + 1;
|
||||||
|
if (c == '\n' || c == '\r')
|
||||||
|
return i;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||||
|
|
||||||
|
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||||
|
|
||||||
|
private static bool IsDigit(char c) => c >= '0' && c <= '9';
|
||||||
|
|
||||||
|
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||||
|
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||||
|
{
|
||||||
|
public int Order { get; } = order;
|
||||||
|
|
||||||
|
public bool IsCatalog { get; set; }
|
||||||
|
|
||||||
|
public string Keyword { get; set; } = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaSyntaxToken
|
||||||
|
{
|
||||||
|
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
|
||||||
|
{
|
||||||
|
Kind = kind;
|
||||||
|
Text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LuaSyntaxTokenKind Kind { get; }
|
||||||
|
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
|
||||||
|
|
||||||
|
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
|
||||||
|
|
||||||
|
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal enum LuaSyntaxTokenKind
|
||||||
|
{
|
||||||
|
Whitespace,
|
||||||
|
Newline,
|
||||||
|
Comment,
|
||||||
|
String,
|
||||||
|
InterpolatedString,
|
||||||
|
Number,
|
||||||
|
Name,
|
||||||
|
Operator,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(70)]
|
||||||
|
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? connective = Connective(context.Current.Text);
|
||||||
|
if (connective is null)
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} {connective} ({value})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Connective(string op) => op switch
|
||||||
|
{
|
||||||
|
"+=" => "+",
|
||||||
|
"-=" => "-",
|
||||||
|
"*=" => "*",
|
||||||
|
"/=" => "/",
|
||||||
|
"%=" => "%",
|
||||||
|
"^=" => "^",
|
||||||
|
"..=" => "..",
|
||||||
|
"||=" => "or",
|
||||||
|
"&&=" => "and",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(80)]
|
||||||
|
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??="))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(90)]
|
||||||
|
internal sealed class IncrementRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("++"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} + 1");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(10)]
|
||||||
|
internal sealed class IsNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int notIndex = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int after = context.NextSignificant(notIndex + 1);
|
||||||
|
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Index = notIndex + 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(20)]
|
||||||
|
internal sealed class IsRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int next = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("==");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(30)]
|
||||||
|
internal sealed class NotEqualRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!="))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
|
||||||
|
internal sealed class LuaFastRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
private const string MarkerKeyword = "fast";
|
||||||
|
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
|
||||||
|
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("["))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int nameIndex = context.NextSignificant(context.Index + 1);
|
||||||
|
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int closeIndex = context.NextSignificant(nameIndex + 1);
|
||||||
|
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int targetIndex = context.NextSignificant(closeIndex + 1);
|
||||||
|
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
|
||||||
|
{
|
||||||
|
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||||
|
context.Index = funcIndex + 1;
|
||||||
|
context.EmitRaw("__fast_" + function);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.AddDiagnostic(Message);
|
||||||
|
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||||
|
context.Index = targetIndex;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
|
||||||
|
{
|
||||||
|
funcIndex = -1;
|
||||||
|
function = string.Empty;
|
||||||
|
if (!context.Input[objIndex].IsName("obj"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int dot = context.NextSignificant(objIndex + 1);
|
||||||
|
if (dot < 0 || !context.Input[dot].IsOperator("."))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int name = context.NextSignificant(dot + 1);
|
||||||
|
if (name < 0)
|
||||||
|
return false;
|
||||||
|
string text = context.Input[name].Text;
|
||||||
|
if (text is not ("fill" or "convolve" or "resize"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int paren = context.NextSignificant(name + 1);
|
||||||
|
if (paren < 0 || !context.Input[paren].IsOperator("("))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
funcIndex = name;
|
||||||
|
function = text;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitBetween(LuaRewriteContext context, int from, int to)
|
||||||
|
{
|
||||||
|
for (int i = from; i < to; i++)
|
||||||
|
context.Emit(context.Input[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(5)]
|
||||||
|
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string text = context.Current.Text;
|
||||||
|
int end = text.Length;
|
||||||
|
if (end >= 2 && text[end - 1] == '`')
|
||||||
|
end--;
|
||||||
|
string content = text.Substring(1, end - 1);
|
||||||
|
|
||||||
|
var pieces = new List<string>();
|
||||||
|
var literal = new StringBuilder();
|
||||||
|
int i = 0;
|
||||||
|
while (i < content.Length)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (c == '\\' && i + 1 < content.Length)
|
||||||
|
{
|
||||||
|
literal.Append(content[i]);
|
||||||
|
literal.Append(content[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
int close = FindClosingBrace(content, i + 1);
|
||||||
|
if (close < 0)
|
||||||
|
{
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
string expression = content.Substring(i + 1, close - i - 1).Trim();
|
||||||
|
if (expression.Length > 0)
|
||||||
|
{
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
|
||||||
|
}
|
||||||
|
i = close + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
if (pieces.Count == 0)
|
||||||
|
{
|
||||||
|
context.EmitRaw("\"\"");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (pieces.Count == 1)
|
||||||
|
{
|
||||||
|
context.EmitRaw(pieces[0]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
context.EmitRaw($"({string.Join(" .. ", pieces)})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
|
||||||
|
{
|
||||||
|
if (literal.Length == 0)
|
||||||
|
return;
|
||||||
|
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
|
||||||
|
literal.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBrace(string content, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
char quote = '\0';
|
||||||
|
for (int i = from; i < content.Length; i++)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (quote != '\0')
|
||||||
|
{
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
quote = '\0';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
quote = c;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '}')
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(35)]
|
||||||
|
internal sealed class LuaLambdaRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("=>"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
if (!TryNormalizeParameters(target, out string parameters))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int body = context.NextSignificant(context.Index + 1);
|
||||||
|
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string expression = context.ReadForwardOrOperand();
|
||||||
|
if (expression.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryNormalizeParameters(string text, out string parameters)
|
||||||
|
{
|
||||||
|
parameters = string.Empty;
|
||||||
|
text = text.Trim();
|
||||||
|
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
|
||||||
|
if (wrapped)
|
||||||
|
text = text.Substring(1, text.Length - 2).Trim();
|
||||||
|
|
||||||
|
if (text.Length == 0)
|
||||||
|
return wrapped;
|
||||||
|
|
||||||
|
var names = text.Split(',');
|
||||||
|
for (int i = 0; i < names.Length; i++)
|
||||||
|
{
|
||||||
|
string name = names[i].Trim();
|
||||||
|
if (name == "...")
|
||||||
|
{
|
||||||
|
if (i != names.Length - 1)
|
||||||
|
return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!IsName(name) || LuaKeywords.IsReserved(name))
|
||||||
|
return false;
|
||||||
|
if (!wrapped && names.Length > 1)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsName(string text)
|
||||||
|
{
|
||||||
|
if (text.Length == 0)
|
||||||
|
return false;
|
||||||
|
if (text[0] != '_' && !char.IsLetter(text[0]))
|
||||||
|
return false;
|
||||||
|
for (int i = 1; i < text.Length; i++)
|
||||||
|
{
|
||||||
|
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(40)]
|
||||||
|
internal sealed class LogicalNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("not");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(50)]
|
||||||
|
internal sealed class AndAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("&&"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("and");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(60)]
|
||||||
|
internal sealed class OrAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("||"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("or");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(100)]
|
||||||
|
internal sealed class NilCoalesceRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string right = context.ReadForwardOrOperand();
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(110)]
|
||||||
|
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
|
||||||
|
string replacement = parts.Step is null
|
||||||
|
? $"= {parts.Start}, {stopExpression}"
|
||||||
|
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
|
||||||
|
context.EmitRaw(replacement);
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(98)]
|
||||||
|
internal sealed class LuaPipeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("|>"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int targetStart = context.NextSignificant(context.Index + 1);
|
||||||
|
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
var segment = ReadSegment(context);
|
||||||
|
string call = BuildCall(segment, left);
|
||||||
|
context.EmitRaw(call);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int depth = 0;
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var token = context.Current;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";" or "|>")
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.Add(token);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
while (tokens.Count > 0 && tokens[0].IsTrivia)
|
||||||
|
tokens.RemoveAt(0);
|
||||||
|
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
|
||||||
|
tokens.RemoveAt(tokens.Count - 1);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
|
||||||
|
{
|
||||||
|
string argument = $"({left})";
|
||||||
|
if (segment.Count == 0)
|
||||||
|
return argument;
|
||||||
|
|
||||||
|
if (segment[segment.Count - 1].IsOperator(")"))
|
||||||
|
{
|
||||||
|
int open = FindOpeningParen(segment);
|
||||||
|
if (open > 0)
|
||||||
|
{
|
||||||
|
string callee = Concat(segment, 0, open);
|
||||||
|
string arguments = Concat(segment, open + 1, segment.Count - 1);
|
||||||
|
return arguments.Length == 0
|
||||||
|
? $"{callee}({argument})"
|
||||||
|
: $"{callee}({argument}, {arguments})";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $"{Concat(segment, 0, segment.Count)}({argument})";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = segment.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = segment[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth--;
|
||||||
|
if (depth == 0)
|
||||||
|
return token.Text == "(" ? i : -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && segment[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && segment[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(segment[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(108)]
|
||||||
|
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
if (IsForHeader(context))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
if (parts.Step is not null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
string upper = parts.Exclusive ? "<" : "<=";
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsForHeader(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var output = context.Output;
|
||||||
|
for (int i = output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return false;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "do" or "then")
|
||||||
|
return false;
|
||||||
|
if (token.Text == "for")
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(92)]
|
||||||
|
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int accessor = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (accessor < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (context.Input[accessor].IsOperator("."))
|
||||||
|
return TryApplyMember(context, accessor);
|
||||||
|
if (context.Input[accessor].IsOperator("["))
|
||||||
|
return TryApplyIndex(context, accessor);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int name = context.NextSignificantSameLine(accessor + 1);
|
||||||
|
if (name < 0)
|
||||||
|
return false;
|
||||||
|
var token = context.Input[name];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = name + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int close = FindClosingBracket(context, accessor + 1);
|
||||||
|
if (close < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string key = Concat(context, accessor + 1, close);
|
||||||
|
if (key.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = close + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBracket(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text == "]")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(LuaRewriteContext context, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(96)]
|
||||||
|
internal sealed class LuaTernaryRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int thenStart = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int colon = FindColon(context, context.Index + 1);
|
||||||
|
if (colon < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int elseStart = context.NextSignificantSameLine(colon + 1);
|
||||||
|
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string condition))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Index++;
|
||||||
|
string thenExpression = ReadUntil(context, colon);
|
||||||
|
context.Index = colon + 1;
|
||||||
|
string elseExpression = context.ReadForwardOrOperand();
|
||||||
|
|
||||||
|
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindColon(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
return -1;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "," or ";" or "?")
|
||||||
|
return -1;
|
||||||
|
if (token.Text == ":")
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadUntil(LuaRewriteContext context, int stop)
|
||||||
|
{
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
int begin = context.Index;
|
||||||
|
int end = stop;
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderClass(
|
||||||
|
string Namespace,
|
||||||
|
EquatableArray<GpuShaderTypePart> TypeChain,
|
||||||
|
EquatableArray<GpuShaderMethod> Methods,
|
||||||
|
EquatableArray<string> Errors);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderFile(string Path, string Source);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderMethod(
|
||||||
|
string Accessibility,
|
||||||
|
bool IsStatic,
|
||||||
|
string ReturnType,
|
||||||
|
string MethodName,
|
||||||
|
EquatableArray<GpuShaderParameter> Parameters,
|
||||||
|
string FileName,
|
||||||
|
string EntryPoint,
|
||||||
|
GpuShaderInvocation Invocation);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
|
||||||
|
}
|
||||||
@@ -0,0 +1,436 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
[Generator]
|
||||||
|
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var classes = context.SyntaxProvider
|
||||||
|
.CreateSyntaxProvider(
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
|
||||||
|
static (ctx, _) => CreateClass(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
var files = context.AdditionalTextsProvider
|
||||||
|
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
|
||||||
|
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
|
||||||
|
.Collect()
|
||||||
|
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
|
||||||
|
{
|
||||||
|
var (model, files) = source;
|
||||||
|
var resolved = Resolve(model, files);
|
||||||
|
if (resolved.Errors.Length > 0)
|
||||||
|
{
|
||||||
|
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.Node is not ClassDeclarationSyntax declaration)
|
||||||
|
return null;
|
||||||
|
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var attributes = type.GetAttributes()
|
||||||
|
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
|
||||||
|
.ToArray();
|
||||||
|
if (attributes.Length == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var chain = new List<GpuShaderTypePart>();
|
||||||
|
for (var current = type; current is not null; current = current.ContainingType)
|
||||||
|
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
|
||||||
|
|
||||||
|
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
|
||||||
|
var errors = ImmutableArray.CreateBuilder<string>();
|
||||||
|
|
||||||
|
foreach (var attribute in attributes)
|
||||||
|
{
|
||||||
|
if (attribute.ConstructorArguments.Length < 3 ||
|
||||||
|
attribute.ConstructorArguments[0].Value is not string methodName ||
|
||||||
|
attribute.ConstructorArguments[1].Value is not string fileName ||
|
||||||
|
attribute.ConstructorArguments[2].Value is not string entryPoint)
|
||||||
|
{
|
||||||
|
errors.Add("GPU shader attribute arguments are invalid");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
|
||||||
|
if (candidates.Length == 0)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}' was not found");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (candidates.Length > 1)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}' is ambiguous");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var method = candidates[0];
|
||||||
|
string? error = Validate(method, fileName, entryPoint, out var invocation);
|
||||||
|
if (error is not null)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}': {error}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
|
||||||
|
foreach (var parameter in method.Parameters)
|
||||||
|
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
|
||||||
|
|
||||||
|
methods.Add(new GpuShaderMethod(
|
||||||
|
AccessibilityName(method.DeclaredAccessibility),
|
||||||
|
method.IsStatic,
|
||||||
|
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||||
|
method.Name,
|
||||||
|
new EquatableArray<GpuShaderParameter>([.. parameters]),
|
||||||
|
Normalize(fileName),
|
||||||
|
entryPoint,
|
||||||
|
invocation));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GpuShaderClass(
|
||||||
|
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
|
||||||
|
new EquatableArray<GpuShaderTypePart>([.. chain]),
|
||||||
|
new EquatableArray<GpuShaderMethod>([.. methods]),
|
||||||
|
new EquatableArray<string>([.. errors]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
|
||||||
|
if (string.IsNullOrWhiteSpace(fileName))
|
||||||
|
return "file name is empty";
|
||||||
|
if (string.IsNullOrWhiteSpace(entryPoint))
|
||||||
|
return "entry point is empty";
|
||||||
|
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
|
||||||
|
return "return type must be bool";
|
||||||
|
|
||||||
|
var parameters = method.Parameters;
|
||||||
|
if (parameters.Length == 4 &&
|
||||||
|
IsReadOnlySpanSingle(parameters[0].Type) &&
|
||||||
|
IsByteArray(parameters[1].Type) &&
|
||||||
|
IsInt32(parameters[2].Type) &&
|
||||||
|
IsInt32(parameters[3].Type))
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parameters.Length == 5 &&
|
||||||
|
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
|
||||||
|
IsReadOnlySpanSingle(parameters[1].Type) &&
|
||||||
|
IsByteArray(parameters[2].Type) &&
|
||||||
|
IsInt32(parameters[3].Type) &&
|
||||||
|
IsInt32(parameters[4].Type))
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "signature is invalid";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
|
||||||
|
{
|
||||||
|
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
|
||||||
|
var errors = ImmutableArray.CreateBuilder<string>();
|
||||||
|
errors.AddRange(model.Errors);
|
||||||
|
|
||||||
|
foreach (var method in model.Methods)
|
||||||
|
{
|
||||||
|
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
|
||||||
|
if (matched.Length == 0)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (matched.Length > 1)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
|
||||||
|
if (failure is not null)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
methods.Add(new GpuShaderMethodSource(method, bytecode));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GpuShaderResolution([.. methods], [.. errors]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Matches(string filePath, string registrationPath)
|
||||||
|
{
|
||||||
|
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
return type is INamedTypeSymbol named &&
|
||||||
|
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
|
||||||
|
named.TypeArguments.Length == 1 &&
|
||||||
|
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||||
|
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
|
||||||
|
display.Contains("PixelShaderInput", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsByteArray(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
return type is IArrayTypeSymbol array &&
|
||||||
|
array.Rank == 1 &&
|
||||||
|
array.ElementType.SpecialType == SpecialType.System_Byte;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
|
||||||
|
|
||||||
|
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
|
||||||
|
|
||||||
|
private static string AccessibilityName(Accessibility accessibility)
|
||||||
|
{
|
||||||
|
return accessibility switch
|
||||||
|
{
|
||||||
|
Accessibility.Public => "public",
|
||||||
|
Accessibility.Internal => "internal",
|
||||||
|
Accessibility.Protected => "protected",
|
||||||
|
Accessibility.ProtectedAndInternal => "private protected",
|
||||||
|
Accessibility.ProtectedOrInternal => "protected internal",
|
||||||
|
_ => "private",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ParameterPrefix(IParameterSymbol parameter)
|
||||||
|
{
|
||||||
|
return parameter.RefKind switch
|
||||||
|
{
|
||||||
|
RefKind.In => "in ",
|
||||||
|
RefKind.Ref => "ref ",
|
||||||
|
RefKind.Out => "out ",
|
||||||
|
_ => string.Empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine("namespace " + model.Namespace);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
}
|
||||||
|
|
||||||
|
int indent = model.Namespace.Length > 0 ? 1 : 0;
|
||||||
|
foreach (var type in model.TypeChain)
|
||||||
|
{
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
|
||||||
|
builder.AppendLine(type.Name);
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
indent++;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < sources.Length; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.AppendLine();
|
||||||
|
EmitMethod(builder, indent, sources[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
indent--;
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
|
||||||
|
{
|
||||||
|
var method = source.Method;
|
||||||
|
string field = "s_shader_" + method.MethodName;
|
||||||
|
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append("private static readonly byte[] ");
|
||||||
|
builder.Append(field);
|
||||||
|
builder.Append(" = global::System.Convert.FromBase64String(");
|
||||||
|
builder.Append(Literal(source.Bytecode));
|
||||||
|
builder.AppendLine(");");
|
||||||
|
builder.AppendLine();
|
||||||
|
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append(method.Accessibility);
|
||||||
|
builder.Append(' ');
|
||||||
|
if (method.IsStatic)
|
||||||
|
builder.Append("static ");
|
||||||
|
builder.Append("partial ");
|
||||||
|
builder.Append(method.ReturnType);
|
||||||
|
builder.Append(' ');
|
||||||
|
builder.Append(method.MethodName);
|
||||||
|
builder.Append('(');
|
||||||
|
for (int i = 0; i < method.Parameters.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append(", ");
|
||||||
|
var parameter = method.Parameters[i];
|
||||||
|
builder.Append(parameter.Prefix);
|
||||||
|
builder.Append(parameter.Type);
|
||||||
|
builder.Append(' ');
|
||||||
|
builder.Append(parameter.Name);
|
||||||
|
}
|
||||||
|
builder.AppendLine(")");
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
AppendIndent(builder, indent + 1);
|
||||||
|
builder.Append("return Run(");
|
||||||
|
builder.Append(field);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Resources);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Constants);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Target);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Width);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Height);
|
||||||
|
builder.AppendLine(");");
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendIndent(StringBuilder builder, int indent)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < indent; i++)
|
||||||
|
builder.Append(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitErrors(ImmutableArray<string> errors)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
foreach (var error in errors)
|
||||||
|
builder.AppendLine("#error " + error);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HintName(GpuShaderClass model)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder("GpuPixelOperationShader");
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
{
|
||||||
|
builder.Append('.');
|
||||||
|
builder.Append(HintPart(model.Namespace));
|
||||||
|
}
|
||||||
|
foreach (var type in model.TypeChain)
|
||||||
|
{
|
||||||
|
builder.Append('.');
|
||||||
|
builder.Append(HintPart(type.Name));
|
||||||
|
}
|
||||||
|
builder.Append(".g.cs");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ErrorHintName(GpuShaderClass model)
|
||||||
|
{
|
||||||
|
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HintPart(string value)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(value.Length);
|
||||||
|
foreach (char c in value)
|
||||||
|
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Literal(string value)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(value.Length + 2);
|
||||||
|
builder.Append('"');
|
||||||
|
foreach (char c in value)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '\\':
|
||||||
|
builder.Append(@"\\");
|
||||||
|
break;
|
||||||
|
case '"':
|
||||||
|
builder.Append("\\\"");
|
||||||
|
break;
|
||||||
|
case '\0':
|
||||||
|
builder.Append(@"\0");
|
||||||
|
break;
|
||||||
|
case '\a':
|
||||||
|
builder.Append(@"\a");
|
||||||
|
break;
|
||||||
|
case '\b':
|
||||||
|
builder.Append(@"\b");
|
||||||
|
break;
|
||||||
|
case '\f':
|
||||||
|
builder.Append(@"\f");
|
||||||
|
break;
|
||||||
|
case '\n':
|
||||||
|
builder.Append(@"\n");
|
||||||
|
break;
|
||||||
|
case '\r':
|
||||||
|
builder.Append(@"\r");
|
||||||
|
break;
|
||||||
|
case '\t':
|
||||||
|
builder.Append(@"\t");
|
||||||
|
break;
|
||||||
|
case '\v':
|
||||||
|
builder.Append(@"\v");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (char.IsControl(c))
|
||||||
|
{
|
||||||
|
builder.Append(@"\u");
|
||||||
|
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
builder.Append(c);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.Append('"');
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal static class ShaderCompiler
|
||||||
|
{
|
||||||
|
private const string Profile = "ps_5_0";
|
||||||
|
|
||||||
|
public static string? Compile(string source, string entryPoint, out string bytecode)
|
||||||
|
{
|
||||||
|
bytecode = string.Empty;
|
||||||
|
byte[] data = Encoding.UTF8.GetBytes(source);
|
||||||
|
IntPtr code = IntPtr.Zero;
|
||||||
|
IntPtr errors = IntPtr.Zero;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
|
||||||
|
if (hr < 0 || code == IntPtr.Zero)
|
||||||
|
return ReadError(errors, hr);
|
||||||
|
bytecode = Convert.ToBase64String(ReadBlob(code));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (DllNotFoundException)
|
||||||
|
{
|
||||||
|
return "the Direct3D shader compiler is unavailable on this build host";
|
||||||
|
}
|
||||||
|
catch (EntryPointNotFoundException)
|
||||||
|
{
|
||||||
|
return "the Direct3D shader compiler is unavailable on this build host";
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Release(errors);
|
||||||
|
Release(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] ReadBlob(IntPtr blob)
|
||||||
|
{
|
||||||
|
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||||
|
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||||
|
var buffer = new byte[size];
|
||||||
|
Marshal.Copy(pointer, buffer, 0, size);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadError(IntPtr blob, int hr)
|
||||||
|
{
|
||||||
|
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
|
||||||
|
if (blob == IntPtr.Zero)
|
||||||
|
return fallback;
|
||||||
|
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||||
|
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||||
|
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
|
||||||
|
return message.Length > 0 ? message : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Release(IntPtr unknown)
|
||||||
|
{
|
||||||
|
if (unknown != IntPtr.Zero)
|
||||||
|
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
|
||||||
|
{
|
||||||
|
IntPtr table = Marshal.ReadIntPtr(instance);
|
||||||
|
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
|
||||||
|
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate uint ReleaseDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
|
||||||
|
private static extern int D3DCompile(
|
||||||
|
byte[] srcData,
|
||||||
|
IntPtr srcDataSize,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
|
||||||
|
IntPtr defines,
|
||||||
|
IntPtr include,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string target,
|
||||||
|
uint flags1,
|
||||||
|
uint flags2,
|
||||||
|
out IntPtr code,
|
||||||
|
out IntPtr errorMsgs);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,60 +5,6 @@ using Microsoft.CodeAnalysis.Text;
|
|||||||
|
|
||||||
namespace LuaScript.Generator
|
namespace LuaScript.Generator
|
||||||
{
|
{
|
||||||
internal enum LuaParameterKind
|
|
||||||
{
|
|
||||||
ExecutionContext,
|
|
||||||
Arguments,
|
|
||||||
DynValue,
|
|
||||||
Double,
|
|
||||||
Int,
|
|
||||||
Bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal enum LuaReturnKind
|
|
||||||
{
|
|
||||||
DynValue,
|
|
||||||
Double,
|
|
||||||
Void,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
|
||||||
|
|
||||||
internal sealed record LuaFunctionModel(
|
|
||||||
string LuaName,
|
|
||||||
string MethodName,
|
|
||||||
LuaReturnKind ReturnKind,
|
|
||||||
EquatableArray<LuaParameterModel> Parameters);
|
|
||||||
|
|
||||||
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
|
||||||
|
|
||||||
internal enum LuaUpdateKind
|
|
||||||
{
|
|
||||||
Direct,
|
|
||||||
OptionalValue,
|
|
||||||
OptionalReference,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
|
|
||||||
|
|
||||||
internal sealed record LuaCatalogEntry(
|
|
||||||
string Table,
|
|
||||||
string Name,
|
|
||||||
bool IsFunction,
|
|
||||||
EquatableArray<string> Parameters);
|
|
||||||
|
|
||||||
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
|
||||||
|
|
||||||
internal sealed record LuaTableModel(
|
|
||||||
string Namespace,
|
|
||||||
EquatableArray<LuaTypePart> TypeChain,
|
|
||||||
string TableName,
|
|
||||||
string ContextType,
|
|
||||||
EquatableArray<LuaFunctionModel> Functions,
|
|
||||||
EquatableArray<LuaConstantModel> Constants,
|
|
||||||
EquatableArray<LuaUpdateModel> Updates,
|
|
||||||
EquatableArray<LuaCatalogEntry> Entries);
|
|
||||||
|
|
||||||
[Generator]
|
[Generator]
|
||||||
public sealed class LuaApiGenerator : IIncrementalGenerator
|
public sealed class LuaApiGenerator : IIncrementalGenerator
|
||||||
{
|
{
|
||||||
@@ -309,12 +255,30 @@ namespace LuaScript.Generator
|
|||||||
|
|
||||||
var returnType = method.ReturnType;
|
var returnType = method.ReturnType;
|
||||||
LuaUpdateKind kind;
|
LuaUpdateKind kind;
|
||||||
|
ITypeSymbol valueType;
|
||||||
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||||
|
{
|
||||||
kind = LuaUpdateKind.OptionalValue;
|
kind = LuaUpdateKind.OptionalValue;
|
||||||
|
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
|
||||||
|
}
|
||||||
else if (returnType.IsReferenceType)
|
else if (returnType.IsReferenceType)
|
||||||
|
{
|
||||||
kind = LuaUpdateKind.OptionalReference;
|
kind = LuaUpdateKind.OptionalReference;
|
||||||
|
valueType = returnType;
|
||||||
|
}
|
||||||
else
|
else
|
||||||
|
{
|
||||||
kind = LuaUpdateKind.Direct;
|
kind = LuaUpdateKind.Direct;
|
||||||
|
valueType = returnType;
|
||||||
|
}
|
||||||
|
|
||||||
|
var valueKind = valueType.SpecialType switch
|
||||||
|
{
|
||||||
|
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
|
||||||
|
SpecialType.System_Boolean => LuaValueKind.Boolean,
|
||||||
|
SpecialType.System_String => LuaValueKind.String,
|
||||||
|
_ => LuaValueKind.Other,
|
||||||
|
};
|
||||||
|
|
||||||
bool inCatalog = true;
|
bool inCatalog = true;
|
||||||
foreach (var argument in attribute.NamedArguments)
|
foreach (var argument in attribute.NamedArguments)
|
||||||
@@ -325,7 +289,7 @@ namespace LuaScript.Generator
|
|||||||
|
|
||||||
if (inCatalog)
|
if (inCatalog)
|
||||||
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||||
return new LuaUpdateModel(luaName, method.Name, kind);
|
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string FormatDouble(double value) =>
|
private static string FormatDouble(double value) =>
|
||||||
@@ -387,13 +351,19 @@ namespace LuaScript.Generator
|
|||||||
switch (update.Kind)
|
switch (update.Kind)
|
||||||
{
|
{
|
||||||
case LuaUpdateKind.OptionalValue:
|
case LuaUpdateKind.OptionalValue:
|
||||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
|
||||||
|
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
|
||||||
break;
|
break;
|
||||||
case LuaUpdateKind.OptionalReference:
|
case LuaUpdateKind.OptionalReference:
|
||||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
|
||||||
|
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
|
||||||
|
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -409,6 +379,13 @@ namespace LuaScript.Generator
|
|||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
|
||||||
|
{
|
||||||
|
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
|
||||||
|
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
|
||||||
|
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
|
||||||
|
};
|
||||||
|
|
||||||
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||||
{
|
{
|
||||||
var rendered = new List<string>();
|
var rendered = new List<string>();
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaCatalogEntry(
|
||||||
|
string Table,
|
||||||
|
string Name,
|
||||||
|
bool IsFunction,
|
||||||
|
EquatableArray<string> Parameters);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaFunctionModel(
|
||||||
|
string LuaName,
|
||||||
|
string MethodName,
|
||||||
|
LuaReturnKind ReturnKind,
|
||||||
|
EquatableArray<LuaParameterModel> Parameters);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaParameterKind
|
||||||
|
{
|
||||||
|
ExecutionContext,
|
||||||
|
Arguments,
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Int,
|
||||||
|
Bool,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaReturnKind
|
||||||
|
{
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Void,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
[Generator]
|
||||||
|
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
|
||||||
|
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var rules = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
RuleAttributeName,
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => CreateModel(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
|
||||||
|
{
|
||||||
|
if (models.Length == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
int order = 0;
|
||||||
|
var arguments = context.Attributes[0].ConstructorArguments;
|
||||||
|
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||||
|
order = value;
|
||||||
|
|
||||||
|
bool isCatalog = false;
|
||||||
|
string keyword = string.Empty;
|
||||||
|
foreach (var argument in context.Attributes[0].NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
|
||||||
|
isCatalog = catalogValue;
|
||||||
|
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
|
||||||
|
keyword = keywordValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||||
|
{
|
||||||
|
var ordered = models
|
||||||
|
.OrderBy(static m => m.Order)
|
||||||
|
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine("namespace LuaScript.Compat.Syntax");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var model in ordered)
|
||||||
|
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||||
|
builder.AppendLine(" };");
|
||||||
|
|
||||||
|
var keywords = ordered
|
||||||
|
.Where(static m => m.CatalogKeyword.Length > 0)
|
||||||
|
.Select(static m => m.CatalogKeyword)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (keywords.Length == 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var keyword in keywords)
|
||||||
|
builder.AppendLine($" \"{keyword}\",");
|
||||||
|
builder.AppendLine(" };");
|
||||||
|
}
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaTableModel(
|
||||||
|
string Namespace,
|
||||||
|
EquatableArray<LuaTypePart> TypeChain,
|
||||||
|
string TableName,
|
||||||
|
string ContextType,
|
||||||
|
EquatableArray<LuaFunctionModel> Functions,
|
||||||
|
EquatableArray<LuaConstantModel> Constants,
|
||||||
|
EquatableArray<LuaUpdateModel> Updates,
|
||||||
|
EquatableArray<LuaCatalogEntry> Entries);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaUpdateKind
|
||||||
|
{
|
||||||
|
Direct,
|
||||||
|
OptionalValue,
|
||||||
|
OptionalReference,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaValueKind
|
||||||
|
{
|
||||||
|
Number,
|
||||||
|
Boolean,
|
||||||
|
String,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netstandard2.0</TargetFramework>
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.13.4</Version>
|
<Version>1.20.3</Version>
|
||||||
<IsRoslynComponent>true</IsRoslynComponent>
|
<IsRoslynComponent>true</IsRoslynComponent>
|
||||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
|
||||||
|
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int ConvolveWorkThreshold = 262144;
|
||||||
|
private const int MaxConvolveSize = 31;
|
||||||
|
private const int MaxConvolveValidationCount = 64;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
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, bool force = false)
|
||||||
|
{
|
||||||
|
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
long work = (long)width * height * size * size;
|
||||||
|
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
SetConstants(width, height, kernel, size, divisor, offset);
|
||||||
|
_resources[0] = new PixelShaderInput(target, width, height);
|
||||||
|
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < _validations.Count; i++)
|
||||||
|
{
|
||||||
|
if (_validations[i].Matches(kernel, size, divisor, offset))
|
||||||
|
return _validations[i].Valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_validations.Count >= MaxConvolveValidationCount)
|
||||||
|
_validations.Clear();
|
||||||
|
|
||||||
|
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
|
||||||
|
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
int probeWidth = Math.Min(width, 8);
|
||||||
|
int probeHeight = Math.Min(height, 7);
|
||||||
|
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
|
||||||
|
var cpu = (byte[])probe.Clone();
|
||||||
|
var gpu = (byte[])probe.Clone();
|
||||||
|
double[]? scratch = null;
|
||||||
|
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
|
||||||
|
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
|
||||||
|
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
|
||||||
|
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
_constants[0] = width;
|
||||||
|
_constants[1] = height;
|
||||||
|
_constants[2] = (float)divisor;
|
||||||
|
_constants[3] = (float)offset;
|
||||||
|
_constants[4] = size;
|
||||||
|
_constants[5] = size / 2;
|
||||||
|
_constants[6] = 0f;
|
||||||
|
_constants[7] = 0f;
|
||||||
|
int taps = size * size;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
_constants[i + 8] = (float)kernel[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
|
||||||
|
return false;
|
||||||
|
int taps = size * size;
|
||||||
|
if (kernel.Length < taps || taps + 8 > 1024)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
{
|
||||||
|
if (!IsFloatCompatible(kernel[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsFloatCompatible(double value)
|
||||||
|
{
|
||||||
|
return double.IsFinite(value) && float.IsFinite((float)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private sealed class ConvolveValidation
|
||||||
|
{
|
||||||
|
private readonly double[] _kernel;
|
||||||
|
private readonly int _size;
|
||||||
|
private readonly double _divisor;
|
||||||
|
private readonly double _offset;
|
||||||
|
|
||||||
|
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
|
||||||
|
{
|
||||||
|
int taps = size * size;
|
||||||
|
_kernel = new double[taps];
|
||||||
|
Array.Copy(kernel, _kernel, taps);
|
||||||
|
_size = size;
|
||||||
|
_divisor = divisor;
|
||||||
|
_offset = offset;
|
||||||
|
Valid = valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Valid { get; }
|
||||||
|
|
||||||
|
public bool Matches(double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
|
||||||
|
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
|
||||||
|
return false;
|
||||||
|
int taps = size * size;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
{
|
||||||
|
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
|
||||||
|
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
|
||||||
|
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int FillFullThreshold = 1048576;
|
||||||
|
private const int FillPartialThreshold = 1048576;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
private readonly float[] _constants = new float[8];
|
||||||
|
|
||||||
|
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, bool force = false)
|
||||||
|
{
|
||||||
|
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
long pixels = (long)width * height;
|
||||||
|
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
|
||||||
|
if (full)
|
||||||
|
{
|
||||||
|
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 (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
SetConstants(r, g, b, a);
|
||||||
|
_constants[4] = x;
|
||||||
|
_constants[5] = y;
|
||||||
|
_constants[6] = x + fillWidth;
|
||||||
|
_constants[7] = y + fillHeight;
|
||||||
|
_resources[0] = new PixelShaderInput(target, width, height);
|
||||||
|
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureFullValidated()
|
||||||
|
{
|
||||||
|
if (_fullValidated.HasValue)
|
||||||
|
return _fullValidated.Value;
|
||||||
|
|
||||||
|
const int width = 7;
|
||||||
|
const int height = 5;
|
||||||
|
var source = CreateProbe(width, height);
|
||||||
|
var cpu = (byte[])source.Clone();
|
||||||
|
var gpu = (byte[])source.Clone();
|
||||||
|
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
|
||||||
|
SetConstants(23d, 197d, 89d, 173d);
|
||||||
|
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
|
||||||
|
return _fullValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsurePartialValidated()
|
||||||
|
{
|
||||||
|
if (_partialValidated.HasValue)
|
||||||
|
return _partialValidated.Value;
|
||||||
|
|
||||||
|
const int width = 7;
|
||||||
|
const int height = 5;
|
||||||
|
var source = CreateProbe(width, height);
|
||||||
|
var cpu = (byte[])source.Clone();
|
||||||
|
var gpu = (byte[])source.Clone();
|
||||||
|
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
|
||||||
|
SetConstants(23d, 197d, 89d, 173d);
|
||||||
|
_constants[4] = 1f;
|
||||||
|
_constants[5] = 2f;
|
||||||
|
_constants[6] = 5f;
|
||||||
|
_constants[7] = 4f;
|
||||||
|
_resources[0] = new PixelShaderInput(gpu, width, height);
|
||||||
|
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
|
||||||
|
return _partialValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetConstants(double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||||
|
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||||
|
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||||
|
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||||
|
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
|
_constants[0] = pr / 255f;
|
||||||
|
_constants[1] = pg / 255f;
|
||||||
|
_constants[2] = pb / 255f;
|
||||||
|
_constants[3] = pa / 255f;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AreFinite(double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CreateProbe(int width, int height)
|
||||||
|
{
|
||||||
|
var data = new byte[width * height * 4];
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int index = (y * width + x) * 4;
|
||||||
|
byte a = (byte)((x * 31 + y * 47) & 255);
|
||||||
|
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
|
||||||
|
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
|
||||||
|
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
|
||||||
|
data[index + 3] = a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
|
||||||
|
{
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly GpuFillOperation _fill = new(runner);
|
||||||
|
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, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
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, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
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, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
|
||||||
|
{
|
||||||
|
protected const int MaxTextureSize = 16384;
|
||||||
|
|
||||||
|
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
|
||||||
|
{
|
||||||
|
return runner.TryRunHardware(
|
||||||
|
bytecode,
|
||||||
|
resources,
|
||||||
|
constants,
|
||||||
|
PixelShaderBlend.Copy,
|
||||||
|
PixelShaderSampler.None,
|
||||||
|
target,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
out _) == PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
|
||||||
|
{
|
||||||
|
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool IsTextureSizeSupported(int width, int height)
|
||||||
|
{
|
||||||
|
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool Equal(byte[] expected, byte[] actual)
|
||||||
|
{
|
||||||
|
return expected.AsSpan().SequenceEqual(actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
|
||||||
|
{
|
||||||
|
var data = new byte[probeWidth * probeHeight * 4];
|
||||||
|
for (int y = 0; y < probeHeight; y++)
|
||||||
|
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||||
|
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
|
||||||
|
{
|
||||||
|
public string MethodName { get; } = methodName;
|
||||||
|
|
||||||
|
public string FileName { get; } = fileName;
|
||||||
|
|
||||||
|
public string EntryPoint { get; } = entryPoint;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
|
||||||
|
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
|
||||||
|
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int ResizeThreshold = 262144;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
private readonly float[] _constants = new float[4];
|
||||||
|
|
||||||
|
private byte[] _target = [];
|
||||||
|
private bool? _nearestValidated;
|
||||||
|
private bool? _linearValidated;
|
||||||
|
|
||||||
|
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 (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||||
|
{
|
||||||
|
if (_nearestValidated.HasValue)
|
||||||
|
return _nearestValidated.Value;
|
||||||
|
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
|
||||||
|
return _nearestValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||||
|
{
|
||||||
|
if (_linearValidated.HasValue)
|
||||||
|
return _linearValidated.Value;
|
||||||
|
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
|
||||||
|
return _linearValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
|
||||||
|
{
|
||||||
|
int probeWidth = Math.Min(sourceWidth, 8);
|
||||||
|
int probeHeight = Math.Min(sourceHeight, 7);
|
||||||
|
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
|
||||||
|
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
|
||||||
|
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
|
||||||
|
byte[]? sourceScratch = null;
|
||||||
|
byte[]? targetScratch = null;
|
||||||
|
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
|
||||||
|
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||||
|
{
|
||||||
|
int count = checked(targetWidth * targetHeight * 4);
|
||||||
|
if (_target.Length != count)
|
||||||
|
_target = new byte[count];
|
||||||
|
|
||||||
|
_constants[0] = sourceWidth;
|
||||||
|
_constants[1] = sourceHeight;
|
||||||
|
_constants[2] = targetWidth;
|
||||||
|
_constants[3] = targetHeight;
|
||||||
|
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
|
||||||
|
target = _target;
|
||||||
|
return linear
|
||||||
|
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
|
||||||
|
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.20.3</Version>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="LuaScript" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
|
||||||
|
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
|
<AdditionalFiles Include="Shaders\*.hlsl" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="SharpGen.Runtime">
|
||||||
|
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.Direct3D11">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.DirectX">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.D3DCompiler.dll">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.DXGI.dll">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.Mathematics">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using Vortice.D3DCompiler;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Direct3D11;
|
||||||
|
using Vortice.DXGI;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Shader
|
||||||
|
{
|
||||||
|
internal sealed unsafe class PixelShaderRunner : IPixelShaderRunner, IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxResources = 8;
|
||||||
|
private const int ConstantBufferSize = 4096;
|
||||||
|
private const int RandomSeed = 20260704;
|
||||||
|
|
||||||
|
private const string VertexShaderSource = """
|
||||||
|
struct VsOutput { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
|
||||||
|
VsOutput vsmain(uint id : SV_VertexID)
|
||||||
|
{
|
||||||
|
VsOutput output;
|
||||||
|
float2 t = float2((id << 1) & 2, id & 2);
|
||||||
|
output.uv = t;
|
||||||
|
output.pos = float4(t.x * 2.0 - 1.0, 1.0 - t.y * 2.0, 0.0, 1.0);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static readonly FeatureLevel[] s_featureLevels = [FeatureLevel.Level_11_0];
|
||||||
|
|
||||||
|
private sealed record CompiledShader(ID3D11PixelShader? Shader, string? Error);
|
||||||
|
|
||||||
|
private struct InputSlot
|
||||||
|
{
|
||||||
|
public ID3D11Texture2D? Texture;
|
||||||
|
public ID3D11ShaderResourceView? View;
|
||||||
|
public int Width;
|
||||||
|
public int Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly Lock _locker = new();
|
||||||
|
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
|
||||||
|
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
|
||||||
|
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
|
||||||
|
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
|
||||||
|
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
|
||||||
|
|
||||||
|
private byte[] _compositeBuffer = [];
|
||||||
|
|
||||||
|
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||||
|
|
||||||
|
public Action<string, Exception?>? Logger { get; set; }
|
||||||
|
|
||||||
|
private ID3D11Device? _device;
|
||||||
|
private ID3D11DeviceContext? _context;
|
||||||
|
private DriverType _driverType;
|
||||||
|
private ID3D11VertexShader? _vertexShader;
|
||||||
|
private ID3D11Buffer? _constantBuffer;
|
||||||
|
private ID3D11RasterizerState? _rasterizer;
|
||||||
|
private readonly ID3D11BlendState?[] _blendStates = new ID3D11BlendState?[4];
|
||||||
|
private readonly ID3D11SamplerState?[] _samplerStates = new ID3D11SamplerState?[6];
|
||||||
|
private ID3D11Texture2D? _randomTexture;
|
||||||
|
private ID3D11ShaderResourceView? _randomView;
|
||||||
|
private ID3D11Texture2D? _targetTexture;
|
||||||
|
private ID3D11RenderTargetView? _targetView;
|
||||||
|
private int _targetWidth;
|
||||||
|
private int _targetHeight;
|
||||||
|
private ID3D11Texture2D? _stagingTexture;
|
||||||
|
private int _stagingWidth;
|
||||||
|
private int _stagingHeight;
|
||||||
|
|
||||||
|
private bool _disposed;
|
||||||
|
private bool _unavailable;
|
||||||
|
private bool _hardwareUnavailable;
|
||||||
|
private bool _failureLogged;
|
||||||
|
private int _recreateBudget = 3;
|
||||||
|
|
||||||
|
public PixelShaderRunStatus TryRun(
|
||||||
|
string hlsl,
|
||||||
|
string entryPoint,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (!CanRun(target, targetWidth, targetHeight))
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!EnsureDevice())
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
var compiled = GetOrCompile(hlsl, entryPoint);
|
||||||
|
if (compiled.Shader is null)
|
||||||
|
{
|
||||||
|
error = compiled.Error;
|
||||||
|
return PixelShaderRunStatus.CompileError;
|
||||||
|
}
|
||||||
|
|
||||||
|
Execute(compiled.Shader, resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||||
|
return PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
HandleFailure(ex);
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public PixelShaderRunStatus TryRunHardware(
|
||||||
|
byte[] bytecode,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (!CanRun(target, targetWidth, targetHeight))
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!EnsureHardwareDevice())
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||||
|
return PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
HandleFailure(ex);
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
|
||||||
|
{
|
||||||
|
return !_disposed && !_unavailable &&
|
||||||
|
targetWidth > 0 && targetHeight > 0 &&
|
||||||
|
(long)target.Length >= (long)targetWidth * targetHeight * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Invalidate()
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
ReleaseShaders();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
return;
|
||||||
|
_disposed = true;
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureDevice()
|
||||||
|
{
|
||||||
|
if (_device is not null)
|
||||||
|
return true;
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
{
|
||||||
|
MarkUnavailable(null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_recreateBudget--;
|
||||||
|
|
||||||
|
DriverType driverType;
|
||||||
|
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||||
|
{
|
||||||
|
driverType = DriverType.Hardware;
|
||||||
|
}
|
||||||
|
else if (TryCreateDevice(DriverType.Warp, out device, out context))
|
||||||
|
{
|
||||||
|
driverType = DriverType.Warp;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MarkUnavailable(null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InitializeDevice(device, context, driverType, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureHardwareDevice()
|
||||||
|
{
|
||||||
|
if (_device is not null)
|
||||||
|
return _driverType == DriverType.Hardware;
|
||||||
|
if (_hardwareUnavailable)
|
||||||
|
return false;
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
{
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_recreateBudget--;
|
||||||
|
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||||
|
{
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InitializeDevice(device, context, DriverType.Hardware, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
|
||||||
|
var vertexShader = device!.CreateVertexShader(vsBytecode);
|
||||||
|
_device = device;
|
||||||
|
_context = context;
|
||||||
|
_driverType = driverType;
|
||||||
|
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
|
||||||
|
_vertexShader = vertexShader;
|
||||||
|
_constantBuffer = device.CreateBuffer(new BufferDescription(
|
||||||
|
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
|
||||||
|
_rasterizer = device.CreateRasterizerState(RasterizerDescription.CullNone);
|
||||||
|
CreateBlendStates(device);
|
||||||
|
CreateSamplerStates(device);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(_device, device))
|
||||||
|
{
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
context?.Dispose();
|
||||||
|
device?.Dispose();
|
||||||
|
}
|
||||||
|
if (markUnavailable)
|
||||||
|
MarkUnavailable(ex);
|
||||||
|
else
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryCreateDevice(DriverType driverType, out ID3D11Device? device, out ID3D11DeviceContext? context)
|
||||||
|
{
|
||||||
|
device = null;
|
||||||
|
context = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = D3D11.D3D11CreateDevice(
|
||||||
|
null, driverType, DeviceCreationFlags.BgraSupport, s_featureLevels,
|
||||||
|
out device, out context);
|
||||||
|
if (result.Success && device is not null && context is not null)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
context?.Dispose();
|
||||||
|
device?.Dispose();
|
||||||
|
device = null;
|
||||||
|
context = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateBlendStates(ID3D11Device device)
|
||||||
|
{
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Copy] = null;
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Mask] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.Zero, Blend.One, Blend.Zero, Blend.SourceAlpha));
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Draw] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.One, Blend.InverseSourceAlpha, Blend.One, Blend.InverseSourceAlpha));
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Add] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.One, Blend.One, Blend.One, Blend.One));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateSamplerStates(ID3D11Device device)
|
||||||
|
{
|
||||||
|
_samplerStates[(int)PixelShaderSampler.None] = null;
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Clip] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Border);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Clamp] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Clamp);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Loop] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Wrap);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Mirror] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Mirror);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Dot] = CreateSampler(device, Filter.MinMagMipPoint, TextureAddressMode.Border);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ID3D11SamplerState CreateSampler(ID3D11Device device, Filter filter, TextureAddressMode address)
|
||||||
|
{
|
||||||
|
var description = new SamplerDescription(filter, address, address, address)
|
||||||
|
{
|
||||||
|
BorderColor = new Color4(0f, 0f, 0f, 0f),
|
||||||
|
};
|
||||||
|
return device.CreateSamplerState(description);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompiledShader GetOrCompile(string hlsl, string entryPoint)
|
||||||
|
{
|
||||||
|
var key = (hlsl, entryPoint);
|
||||||
|
if (_shaders.TryGetValue(key, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
CompiledShader compiled;
|
||||||
|
byte[] source = Encoding.UTF8.GetBytes(hlsl);
|
||||||
|
var result = Compiler.Compile(source, entryPoint, string.Empty, "ps_5_0", out var bytecode, out var errors);
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
{
|
||||||
|
compiled = new CompiledShader(null, errors?.AsString()?.Trim() ?? result.ToString());
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
compiled = new CompiledShader(_device!.CreatePixelShader(bytecode.AsSpan()), null);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_shaders[key] = compiled;
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
|
||||||
|
{
|
||||||
|
if (_precompiled.TryGetValue(bytecode, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var shader = _device!.CreatePixelShader(bytecode);
|
||||||
|
_precompiled[bytecode] = shader;
|
||||||
|
return shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
|
||||||
|
{
|
||||||
|
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
throw new InvalidOperationException(errors?.AsString() ?? result.ToString());
|
||||||
|
return bytecode.AsBytes();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Execute(
|
||||||
|
ID3D11PixelShader shader,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int width,
|
||||||
|
int height)
|
||||||
|
{
|
||||||
|
var context = _context!;
|
||||||
|
|
||||||
|
bool composite = blend.Mode == PixelShaderBlendMode.Composite;
|
||||||
|
EnsureTarget(width, height);
|
||||||
|
if (!composite && blend.Mode != PixelShaderBlendMode.Copy)
|
||||||
|
UploadPixels(_targetTexture!, target, width, height);
|
||||||
|
|
||||||
|
UploadConstants(constants);
|
||||||
|
BindResources(resources);
|
||||||
|
|
||||||
|
context.OMSetRenderTargets(_targetView!);
|
||||||
|
context.OMSetBlendState(composite ? null : _blendStates[(int)blend.Mode]);
|
||||||
|
context.RSSetViewport(0f, 0f, width, height);
|
||||||
|
context.RSSetState(_rasterizer);
|
||||||
|
context.IASetInputLayout(null);
|
||||||
|
context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
|
||||||
|
context.VSSetShader(_vertexShader);
|
||||||
|
context.PSSetShader(shader);
|
||||||
|
context.PSSetConstantBuffer(0, _constantBuffer);
|
||||||
|
context.PSSetSampler(0, _samplerStates[(int)sampler]);
|
||||||
|
context.PSSetShaderResources(0, _boundViews);
|
||||||
|
context.Draw(3, 0);
|
||||||
|
context.PSSetShaderResources(0, _nullViews);
|
||||||
|
context.UnsetRenderTargets();
|
||||||
|
|
||||||
|
if (composite)
|
||||||
|
{
|
||||||
|
int length = width * height * 4;
|
||||||
|
if (_compositeBuffer.Length < length)
|
||||||
|
_compositeBuffer = new byte[length];
|
||||||
|
ReadBack(_compositeBuffer, width, height);
|
||||||
|
Compositor.TryCompose(target, width, height, _compositeBuffer, width, height,
|
||||||
|
new DrawCommand(width * 0.5, height * 0.5, 0d, 1d, 1d, 0d, null, 0d, blend.CompositeBlend));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ReadBack(target, width, height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureTarget(int width, int height)
|
||||||
|
{
|
||||||
|
if (_targetTexture is null || _targetWidth != width || _targetHeight != height)
|
||||||
|
{
|
||||||
|
_targetView?.Dispose();
|
||||||
|
_targetTexture?.Dispose();
|
||||||
|
_targetTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Default,
|
||||||
|
BindFlags = BindFlags.RenderTarget,
|
||||||
|
});
|
||||||
|
_targetView = _device.CreateRenderTargetView(_targetTexture);
|
||||||
|
_targetWidth = width;
|
||||||
|
_targetHeight = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_stagingTexture is null || _stagingWidth != width || _stagingHeight != height)
|
||||||
|
{
|
||||||
|
_stagingTexture?.Dispose();
|
||||||
|
_stagingTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Staging,
|
||||||
|
CPUAccessFlags = CpuAccessFlags.Read,
|
||||||
|
});
|
||||||
|
_stagingWidth = width;
|
||||||
|
_stagingHeight = height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UploadPixels(ID3D11Texture2D texture, byte[] pixels, int width, int height)
|
||||||
|
{
|
||||||
|
fixed (byte* source = pixels)
|
||||||
|
_context!.UpdateSubresource(texture, 0, null, (nint)source, width * 4, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UploadConstants(ReadOnlySpan<float> constants)
|
||||||
|
{
|
||||||
|
var mapped = _context!.Map(_constantBuffer!, MapMode.WriteDiscard);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var destination = new Span<float>((void*)mapped.DataPointer, ConstantBufferSize / sizeof(float));
|
||||||
|
constants.CopyTo(destination);
|
||||||
|
destination[constants.Length..].Clear();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_context.Unmap(_constantBuffer!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindResources(ReadOnlySpan<PixelShaderInput> resources)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < MaxResources; i++)
|
||||||
|
{
|
||||||
|
if (i >= resources.Length)
|
||||||
|
{
|
||||||
|
_boundViews[i] = null!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var resource = resources[i];
|
||||||
|
if (resource.IsRandom)
|
||||||
|
{
|
||||||
|
_boundViews[i] = EnsureRandomView();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ref var slot = ref _inputs[i];
|
||||||
|
if (slot.Texture is null || slot.Width != resource.Width || slot.Height != resource.Height)
|
||||||
|
{
|
||||||
|
slot.View?.Dispose();
|
||||||
|
slot.Texture?.Dispose();
|
||||||
|
slot.Texture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = resource.Width,
|
||||||
|
Height = resource.Height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Default,
|
||||||
|
BindFlags = BindFlags.ShaderResource,
|
||||||
|
});
|
||||||
|
slot.View = _device.CreateShaderResourceView(slot.Texture);
|
||||||
|
slot.Width = resource.Width;
|
||||||
|
slot.Height = resource.Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
UploadPixels(slot.Texture, resource.Data!, resource.Width, resource.Height);
|
||||||
|
_boundViews[i] = slot.View!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ID3D11ShaderResourceView EnsureRandomView()
|
||||||
|
{
|
||||||
|
if (_randomView is not null)
|
||||||
|
return _randomView;
|
||||||
|
|
||||||
|
int size = PixelShaderInput.RandomSize;
|
||||||
|
var values = new float[size * size];
|
||||||
|
var random = new Random(RandomSeed);
|
||||||
|
for (int i = 0; i < values.Length; i++)
|
||||||
|
values[i] = (float)random.NextDouble();
|
||||||
|
|
||||||
|
fixed (float* source = values)
|
||||||
|
{
|
||||||
|
_randomTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = size,
|
||||||
|
Height = size,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.R32_Float,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Immutable,
|
||||||
|
BindFlags = BindFlags.ShaderResource,
|
||||||
|
}, [new SubresourceData((nint)source, size * sizeof(float))]);
|
||||||
|
}
|
||||||
|
_randomView = _device!.CreateShaderResourceView(_randomTexture);
|
||||||
|
return _randomView;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReadBack(byte[] target, int width, int height)
|
||||||
|
{
|
||||||
|
var context = _context!;
|
||||||
|
context.CopyResource(_stagingTexture!, _targetTexture!);
|
||||||
|
var mapped = context.Map(_stagingTexture!, 0, MapMode.Read);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
int rowBytes = width * 4;
|
||||||
|
byte* source = (byte*)mapped.DataPointer;
|
||||||
|
fixed (byte* destination = target)
|
||||||
|
{
|
||||||
|
if (mapped.RowPitch == rowBytes)
|
||||||
|
{
|
||||||
|
Buffer.MemoryCopy(source, destination, target.Length, (long)rowBytes * height);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (int row = 0; row < height; row++)
|
||||||
|
Buffer.MemoryCopy(
|
||||||
|
source + (long)mapped.RowPitch * row,
|
||||||
|
destination + (long)rowBytes * row,
|
||||||
|
rowBytes, rowBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
context.Unmap(_stagingTexture!, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleFailure(Exception ex)
|
||||||
|
{
|
||||||
|
if (!_failureLogged)
|
||||||
|
{
|
||||||
|
_failureLogged = true;
|
||||||
|
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||||
|
}
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
_unavailable = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MarkUnavailable(Exception? ex)
|
||||||
|
{
|
||||||
|
_unavailable = true;
|
||||||
|
if (_failureLogged)
|
||||||
|
return;
|
||||||
|
_failureLogged = true;
|
||||||
|
if (ex is null)
|
||||||
|
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
|
||||||
|
else
|
||||||
|
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
|
||||||
|
|
||||||
|
private void ReleaseShaders()
|
||||||
|
{
|
||||||
|
foreach (var compiled in _shaders.Values)
|
||||||
|
compiled.Shader?.Dispose();
|
||||||
|
_shaders.Clear();
|
||||||
|
foreach (var shader in _precompiled.Values)
|
||||||
|
shader.Dispose();
|
||||||
|
_precompiled.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReleaseDeviceObjects()
|
||||||
|
{
|
||||||
|
ReleaseShaders();
|
||||||
|
for (int i = 0; i < _inputs.Length; i++)
|
||||||
|
{
|
||||||
|
_inputs[i].View?.Dispose();
|
||||||
|
_inputs[i].Texture?.Dispose();
|
||||||
|
_inputs[i] = default;
|
||||||
|
_boundViews[i] = null!;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _blendStates.Length; i++)
|
||||||
|
{
|
||||||
|
_blendStates[i]?.Dispose();
|
||||||
|
_blendStates[i] = null;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _samplerStates.Length; i++)
|
||||||
|
{
|
||||||
|
_samplerStates[i]?.Dispose();
|
||||||
|
_samplerStates[i] = null;
|
||||||
|
}
|
||||||
|
_randomView?.Dispose();
|
||||||
|
_randomView = null;
|
||||||
|
_randomTexture?.Dispose();
|
||||||
|
_randomTexture = null;
|
||||||
|
_targetView?.Dispose();
|
||||||
|
_targetView = null;
|
||||||
|
_targetTexture?.Dispose();
|
||||||
|
_targetTexture = null;
|
||||||
|
_targetWidth = 0;
|
||||||
|
_targetHeight = 0;
|
||||||
|
_stagingTexture?.Dispose();
|
||||||
|
_stagingTexture = null;
|
||||||
|
_stagingWidth = 0;
|
||||||
|
_stagingHeight = 0;
|
||||||
|
_constantBuffer?.Dispose();
|
||||||
|
_constantBuffer = null;
|
||||||
|
_rasterizer?.Dispose();
|
||||||
|
_rasterizer = null;
|
||||||
|
_vertexShader?.Dispose();
|
||||||
|
_vertexShader = null;
|
||||||
|
_context?.Dispose();
|
||||||
|
_context = null;
|
||||||
|
_device?.Dispose();
|
||||||
|
_device = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 values[256];
|
||||||
|
};
|
||||||
|
|
||||||
|
float get_value(uint index)
|
||||||
|
{
|
||||||
|
uint row = index >> 2;
|
||||||
|
uint column = index & 3u;
|
||||||
|
float4 value = values[row];
|
||||||
|
if (column == 0u)
|
||||||
|
return value.x;
|
||||||
|
if (column == 1u)
|
||||||
|
return value.y;
|
||||||
|
if (column == 2u)
|
||||||
|
return value.z;
|
||||||
|
return value.w;
|
||||||
|
}
|
||||||
|
|
||||||
|
float convolve_channel(float value)
|
||||||
|
{
|
||||||
|
return floor(saturate(value) * 255.0) / 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 convolve(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
int width = (int)get_value(0u);
|
||||||
|
int height = (int)get_value(1u);
|
||||||
|
float divisor = get_value(2u);
|
||||||
|
float offset = get_value(3u) / 255.0;
|
||||||
|
int kernelSize = (int)get_value(4u);
|
||||||
|
int radius = (int)get_value(5u);
|
||||||
|
float4 sum = 0.0;
|
||||||
|
|
||||||
|
for (int ky = 0; ky < kernelSize; ky++)
|
||||||
|
{
|
||||||
|
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
|
||||||
|
for (int kx = 0; kx < kernelSize; kx++)
|
||||||
|
{
|
||||||
|
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
|
||||||
|
float kv = get_value((uint)(8 + ky * kernelSize + kx));
|
||||||
|
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
|
||||||
|
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
|
||||||
|
sum += float4(rgb, sourceValue.a) * kv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float3 rgbOut = saturate(sum.rgb / divisor + offset);
|
||||||
|
float alpha = saturate(sum.a / divisor + offset);
|
||||||
|
return float4(
|
||||||
|
convolve_channel(rgbOut.r * alpha),
|
||||||
|
convolve_channel(rgbOut.g * alpha),
|
||||||
|
convolve_channel(rgbOut.b * alpha),
|
||||||
|
convolve_channel(alpha));
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 color;
|
||||||
|
float4 rect;
|
||||||
|
};
|
||||||
|
|
||||||
|
float4 fill_full(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 fill_partial(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
uint4 r = (uint4)rect;
|
||||||
|
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
|
||||||
|
return color;
|
||||||
|
return source[p];
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 size;
|
||||||
|
};
|
||||||
|
|
||||||
|
float channel(float value)
|
||||||
|
{
|
||||||
|
return floor(saturate(value) * 255.0) / 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_pack(float4 value)
|
||||||
|
{
|
||||||
|
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
uint sourceWidth = (uint)size.x;
|
||||||
|
uint sourceHeight = (uint)size.y;
|
||||||
|
uint targetWidth = (uint)size.z;
|
||||||
|
uint targetHeight = (uint)size.w;
|
||||||
|
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
|
||||||
|
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
|
||||||
|
return source[uint2(sx, sy)];
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_linear(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
float sourceWidth = size.x;
|
||||||
|
float sourceHeight = size.y;
|
||||||
|
float targetWidth = size.z;
|
||||||
|
float targetHeight = size.w;
|
||||||
|
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||||
|
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||||
|
int x0 = (int)floor(u);
|
||||||
|
int y0 = (int)floor(v);
|
||||||
|
float tx = u - x0;
|
||||||
|
float ty = v - y0;
|
||||||
|
int maxX = (int)sourceWidth - 1;
|
||||||
|
int maxY = (int)sourceHeight - 1;
|
||||||
|
uint xA = (uint)clamp(x0, 0, maxX);
|
||||||
|
uint yA = (uint)clamp(y0, 0, maxY);
|
||||||
|
uint xB = (uint)clamp(x0 + 1, 0, maxX);
|
||||||
|
uint yB = (uint)clamp(y0 + 1, 0, maxY);
|
||||||
|
float4 c00 = source[uint2(xA, yA)];
|
||||||
|
float4 c10 = source[uint2(xB, yA)];
|
||||||
|
float4 c01 = source[uint2(xA, yB)];
|
||||||
|
float4 c11 = source[uint2(xB, yB)];
|
||||||
|
float4 top = c00 * (1.0 - tx) + c10 * tx;
|
||||||
|
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
|
||||||
|
return resize_pack(top * (1.0 - ty) + bottom * ty);
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ namespace LuaScript.Engine.Kernel
|
|||||||
internal sealed class KernelExtractor
|
internal sealed class KernelExtractor
|
||||||
{
|
{
|
||||||
private readonly List<KExpr> _bindings = [];
|
private readonly List<KExpr> _bindings = [];
|
||||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||||
|
|
||||||
private string _widthVariable = string.Empty;
|
private string _widthVariable = string.Empty;
|
||||||
@@ -46,25 +46,26 @@ namespace LuaScript.Engine.Kernel
|
|||||||
|
|
||||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||||
return null;
|
return null;
|
||||||
if (index + 1 != block.Count)
|
int tail = index + 1;
|
||||||
|
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||||
|
tail++;
|
||||||
|
if (tail != block.Count)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||||
return null;
|
return null;
|
||||||
|
_scope.Remove(outerVar);
|
||||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||||
return null;
|
return null;
|
||||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||||
return null;
|
return null;
|
||||||
|
_scope.Remove(innerVar);
|
||||||
if (outerAxis == innerAxis)
|
if (outerAxis == innerAxis)
|
||||||
return null;
|
return null;
|
||||||
if (_pixelDataVariable is not null &&
|
if (_pixelDataVariable is not null &&
|
||||||
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||||
return null;
|
return null;
|
||||||
if (_scope.ContainsKey(outerVar))
|
|
||||||
_scope.Remove(outerVar);
|
|
||||||
if (_scope.ContainsKey(innerVar))
|
|
||||||
_scope.Remove(innerVar);
|
|
||||||
|
|
||||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||||
@@ -72,6 +73,13 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool IsPutPixelData(LuaStmt statement) =>
|
||||||
|
_pixelDataVariable is not null &&
|
||||||
|
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||||
|
IsObjectMethod(call, "putpixeldata") &&
|
||||||
|
call.Arguments[0] is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
private bool TryBindPixelData(LocalStmt local)
|
private bool TryBindPixelData(LocalStmt local)
|
||||||
{
|
{
|
||||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||||
@@ -105,6 +113,9 @@ namespace LuaScript.Engine.Kernel
|
|||||||
case AssignStmt assign:
|
case AssignStmt assign:
|
||||||
BindAssign(assign);
|
BindAssign(assign);
|
||||||
break;
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||||
if (writeChannel == 0) outR = value;
|
if (writeChannel == 0) outR = value;
|
||||||
@@ -140,11 +151,25 @@ namespace LuaScript.Engine.Kernel
|
|||||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
return uniform == KernelUniform.Width;
|
return uniform == KernelUniform.Width;
|
||||||
|
if (expression is NameExpr { } alias &&
|
||||||
|
TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
return aliased == KernelUniform.Width;
|
||||||
return _pixelDataVariable is not null &&
|
return _pixelDataVariable is not null &&
|
||||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||||
|
{
|
||||||
|
uniform = reference.Uniform;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uniform = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||||
{
|
{
|
||||||
channel = 0;
|
channel = 0;
|
||||||
@@ -221,6 +246,9 @@ namespace LuaScript.Engine.Kernel
|
|||||||
case AssignStmt assign:
|
case AssignStmt assign:
|
||||||
BindAssign(assign);
|
BindAssign(assign);
|
||||||
break;
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -276,6 +304,76 @@ namespace LuaScript.Engine.Kernel
|
|||||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void LowerConditional(IfStmt statement) =>
|
||||||
|
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||||
|
|
||||||
|
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||||
|
{
|
||||||
|
var clause = clauses[index];
|
||||||
|
var condition = LowerBool(clause.Condition);
|
||||||
|
var baseline = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
LowerBranchBody(clause.Body);
|
||||||
|
var taken = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
if (index + 1 < clauses.Count)
|
||||||
|
LowerConditional(clauses, index + 1, elseBody);
|
||||||
|
else if (elseBody is not null)
|
||||||
|
LowerBranchBody(elseBody);
|
||||||
|
var skipped = _scope;
|
||||||
|
|
||||||
|
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||||
|
foreach (var name in baseline.Keys)
|
||||||
|
{
|
||||||
|
int whenTrue = taken[name];
|
||||||
|
int whenFalse = skipped[name];
|
||||||
|
merged[name] = whenTrue == whenFalse
|
||||||
|
? whenTrue
|
||||||
|
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||||
|
}
|
||||||
|
_scope = merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
Dictionary<string, int>? shadowed = null;
|
||||||
|
HashSet<string>? introduced = null;
|
||||||
|
foreach (var statement in body)
|
||||||
|
{
|
||||||
|
switch (statement)
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
foreach (var name in local.Names)
|
||||||
|
{
|
||||||
|
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||||
|
continue;
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||||
|
else
|
||||||
|
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||||
|
}
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt nested:
|
||||||
|
LowerConditional(nested);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shadowed is not null)
|
||||||
|
foreach (var (name, slot) in shadowed)
|
||||||
|
_scope[name] = slot;
|
||||||
|
if (introduced is not null)
|
||||||
|
foreach (var name in introduced)
|
||||||
|
_scope.Remove(name);
|
||||||
|
}
|
||||||
|
|
||||||
private void EnsureNotCoordinateName(string name)
|
private void EnsureNotCoordinateName(string name)
|
||||||
{
|
{
|
||||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||||
@@ -343,6 +441,16 @@ namespace LuaScript.Engine.Kernel
|
|||||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||||
return UseUniform(uniform);
|
return UseUniform(uniform);
|
||||||
|
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
member.Target is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Width);
|
||||||
|
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Height);
|
||||||
|
}
|
||||||
|
|
||||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,6 +582,20 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
{
|
||||||
|
if (aliased == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (aliased == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.13.4</Version>
|
<Version>1.20.3</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.13.4</Version>
|
<Version>1.20.3</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ namespace LuaScript.Anchor
|
|||||||
|
|
||||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||||
|
|
||||||
|
public static int NormalizeCount(string group, int count)
|
||||||
|
{
|
||||||
|
if (count <= 0 && string.Equals(group, TrackGroup, StringComparison.Ordinal))
|
||||||
|
return 1;
|
||||||
|
return ClampCount(count);
|
||||||
|
}
|
||||||
|
|
||||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||||
{
|
{
|
||||||
switch (option)
|
switch (option)
|
||||||
@@ -52,6 +59,35 @@ namespace LuaScript.Anchor
|
|||||||
z = 0d;
|
z = 0d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ImmutableList<LuaAnchorPoint> SetPosition(
|
||||||
|
ImmutableList<LuaAnchorPoint> source, string group, int index, double x, double y, double z)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < source.Count; i++)
|
||||||
|
{
|
||||||
|
var a = source[i];
|
||||||
|
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return source.SetItem(i, new LuaAnchorPoint
|
||||||
|
{
|
||||||
|
Group = group,
|
||||||
|
Index = index,
|
||||||
|
X = x,
|
||||||
|
Y = y,
|
||||||
|
Z = z,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return source.Add(new LuaAnchorPoint
|
||||||
|
{
|
||||||
|
Group = group,
|
||||||
|
Index = index,
|
||||||
|
X = x,
|
||||||
|
Y = y,
|
||||||
|
Z = z,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ namespace LuaScript.Api
|
|||||||
}
|
}
|
||||||
|
|
||||||
var candidates = Keywords
|
var candidates = Keywords
|
||||||
|
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
|
||||||
.Concat(globals)
|
.Concat(globals)
|
||||||
.Concat(tableMembers.Keys)
|
.Concat(tableMembers.Keys)
|
||||||
.Concat(tableMembers.Values.SelectMany(x => x))
|
.Concat(tableMembers.Values.SelectMany(x => x))
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using LuaScript.Anchor;
|
using LuaScript.Anchor;
|
||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
namespace LuaScript
|
namespace LuaScript
|
||||||
{
|
{
|
||||||
@@ -71,6 +72,12 @@ namespace LuaScript
|
|||||||
|
|
||||||
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
|
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
|
||||||
|
|
||||||
|
public Func<string, double, (byte[] Buffer, int Width, int Height)>? SceneImageLoader { get; set; }
|
||||||
|
|
||||||
|
public Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; }
|
||||||
|
|
||||||
|
public Func<string, string, int, (int Count, int Rate, double[] Data)>? AudioLoader { get; set; }
|
||||||
|
|
||||||
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||||
@@ -155,11 +162,71 @@ namespace LuaScript
|
|||||||
_buffers["t"] = temp;
|
_buffers["t"] = temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
|
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command with { Blend = 0d });
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
internal IPixelShaderRunner? ShaderRunner { get; set; }
|
||||||
|
|
||||||
|
internal IPixelBufferProcessor? PixelProcessor { get; set; }
|
||||||
|
|
||||||
|
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
|
||||||
|
|
||||||
|
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
|
||||||
|
TryReadBuffer(id, out data, out width, out height);
|
||||||
|
|
||||||
|
internal bool TryGetShaderTarget(string id, out byte[] data, out int width, out int height)
|
||||||
|
{
|
||||||
|
data = [];
|
||||||
|
width = 0;
|
||||||
|
height = 0;
|
||||||
|
switch (BufferKind(id, out string key))
|
||||||
|
{
|
||||||
|
case 'o':
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return false;
|
||||||
|
data = _pixelBuffer;
|
||||||
|
width = ImageWidth;
|
||||||
|
height = ImageHeight;
|
||||||
|
return true;
|
||||||
|
case 't':
|
||||||
|
case 'c':
|
||||||
|
if (!_buffers.TryGetValue(key, out var stored))
|
||||||
|
{
|
||||||
|
int w = Math.Max(1, ImageWidth);
|
||||||
|
int h = Math.Max(1, ImageHeight);
|
||||||
|
stored = (new byte[w * h * 4], w, h);
|
||||||
|
_buffers[key] = stored;
|
||||||
|
}
|
||||||
|
data = stored.Data;
|
||||||
|
width = stored.Width;
|
||||||
|
height = stored.Height;
|
||||||
|
return true;
|
||||||
|
case 'f':
|
||||||
|
GetFrameBuffer(out data, out width, out height);
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal bool NotifyShaderTargetWritten(string id)
|
||||||
|
{
|
||||||
|
switch (BufferKind(id, out _))
|
||||||
|
{
|
||||||
|
case 'o':
|
||||||
|
MarkPixelsDirty();
|
||||||
|
return false;
|
||||||
|
case 'f':
|
||||||
|
ReplaceBuffer(_frameBuffer, _frameBufferWidth, _frameBufferHeight);
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal bool CopyBuffer(string dst, string src)
|
internal bool CopyBuffer(string dst, string src)
|
||||||
{
|
{
|
||||||
if (!TryReadBuffer(src, out var data, out int w, out int h))
|
if (!TryReadBuffer(src, out var data, out int w, out int h))
|
||||||
@@ -192,11 +259,47 @@ namespace LuaScript
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
case 'f':
|
||||||
|
GetFrameBuffer(out data, out width, out height);
|
||||||
|
return true;
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private byte[] _frameBuffer = [];
|
||||||
|
private int _frameBufferWidth;
|
||||||
|
private int _frameBufferHeight;
|
||||||
|
private bool _frameBufferValid;
|
||||||
|
|
||||||
|
internal void ResetFrameBuffer() => _frameBufferValid = false;
|
||||||
|
|
||||||
|
private void GetFrameBuffer(out byte[] data, out int width, out int height)
|
||||||
|
{
|
||||||
|
int w = Math.Max(1, SceneWidth);
|
||||||
|
int h = Math.Max(1, SceneHeight);
|
||||||
|
int length = w * h * 4;
|
||||||
|
if (_frameBuffer.Length < length)
|
||||||
|
{
|
||||||
|
_frameBuffer = new byte[length];
|
||||||
|
_frameBufferValid = false;
|
||||||
|
}
|
||||||
|
if (!_frameBufferValid || _frameBufferWidth != w || _frameBufferHeight != h)
|
||||||
|
{
|
||||||
|
Array.Clear(_frameBuffer, 0, length);
|
||||||
|
_frameBufferWidth = w;
|
||||||
|
_frameBufferHeight = h;
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is not null && !ReferenceEquals(_pixelBuffer, _frameBuffer))
|
||||||
|
Compositor.TryCompose(_frameBuffer, w, h, _pixelBuffer, ImageWidth, ImageHeight,
|
||||||
|
new DrawCommand(w * 0.5 + X, h * 0.5 + Y, 0d, Zoom, Alpha / 255d, Aspect, null, 1d, 0d));
|
||||||
|
_frameBufferValid = true;
|
||||||
|
}
|
||||||
|
data = _frameBuffer;
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
}
|
||||||
|
|
||||||
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||||
{
|
{
|
||||||
int n = width * height * 4;
|
int n = width * height * 4;
|
||||||
@@ -403,5 +506,158 @@ namespace LuaScript
|
|||||||
p[3] = (byte)Math.Clamp(a, 0d, 255d);
|
p[3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private double[]? _convolveSource;
|
||||||
|
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 force = false)
|
||||||
|
{
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int cw = ImageWidth;
|
||||||
|
int ch = ImageHeight;
|
||||||
|
int x0 = Math.Clamp(x, 0, cw);
|
||||||
|
int y0 = Math.Clamp(y, 0, ch);
|
||||||
|
int x1 = Math.Clamp(x + w, 0, cw);
|
||||||
|
int y1 = Math.Clamp(y + h, 0, ch);
|
||||||
|
if (x1 <= x0 || y1 <= y0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0, force) == true)
|
||||||
|
{
|
||||||
|
_isPixelsDirty = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_isPixelsDirty = true;
|
||||||
|
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
|
||||||
|
{
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
int cw = ImageWidth;
|
||||||
|
int ch = ImageHeight;
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
{
|
||||||
|
Array.Clear(destination, 0, w * h * 4);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fixed (byte* buf = _pixelBuffer)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < h; j++)
|
||||||
|
{
|
||||||
|
int sy = y + j;
|
||||||
|
for (int i = 0; i < w; i++)
|
||||||
|
{
|
||||||
|
int sx = x + i;
|
||||||
|
int di = (j * w + i) * 4;
|
||||||
|
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
|
||||||
|
{
|
||||||
|
destination[di] = 0d;
|
||||||
|
destination[di + 1] = 0d;
|
||||||
|
destination[di + 2] = 0d;
|
||||||
|
destination[di + 3] = 0d;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
byte* p = buf + (sy * cw + sx) * 4;
|
||||||
|
double a = p[3];
|
||||||
|
if (a <= 0d)
|
||||||
|
{
|
||||||
|
destination[di] = 0d;
|
||||||
|
destination[di + 1] = 0d;
|
||||||
|
destination[di + 2] = 0d;
|
||||||
|
destination[di + 3] = 0d;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
double s = 255d / a;
|
||||||
|
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||||
|
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||||
|
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||||
|
destination[di + 3] = a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
|
||||||
|
{
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int cw = ImageWidth;
|
||||||
|
int ch = ImageHeight;
|
||||||
|
_isPixelsDirty = true;
|
||||||
|
|
||||||
|
fixed (byte* buf = _pixelBuffer)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < h; j++)
|
||||||
|
{
|
||||||
|
int dy = y + j;
|
||||||
|
if ((uint)dy >= (uint)ch)
|
||||||
|
continue;
|
||||||
|
for (int i = 0; i < w; i++)
|
||||||
|
{
|
||||||
|
int dx = x + i;
|
||||||
|
if ((uint)dx >= (uint)cw)
|
||||||
|
continue;
|
||||||
|
int si = (j * w + i) * 4;
|
||||||
|
double a = Math.Clamp(source[si + 3], 0d, 255d);
|
||||||
|
double aK = a / 255d;
|
||||||
|
byte* p = buf + (dy * cw + dx) * 4;
|
||||||
|
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
|
||||||
|
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
|
||||||
|
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
|
||||||
|
p[3] = (byte)a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||||
|
{
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int cw = ImageWidth;
|
||||||
|
int ch = ImageHeight;
|
||||||
|
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, force) == true)
|
||||||
|
{
|
||||||
|
_isPixelsDirty = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_isPixelsDirty = true;
|
||||||
|
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool force = false)
|
||||||
|
{
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
newWidth = Math.Max(1, newWidth);
|
||||||
|
newHeight = Math.Max(1, newHeight);
|
||||||
|
int cw = ImageWidth;
|
||||||
|
int ch = ImageHeight;
|
||||||
|
|
||||||
|
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed, force) == true && processed is not null)
|
||||||
|
{
|
||||||
|
ReplaceBuffer(processed, newWidth, newHeight);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
|
||||||
|
ReplaceBuffer(dst, newWidth, newHeight);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
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 force = false);
|
||||||
|
|
||||||
|
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 force = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,6 +37,17 @@ namespace LuaScript.Engine
|
|||||||
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||||
private byte[] _stringValueBytes = new byte[256];
|
private byte[] _stringValueBytes = new byte[256];
|
||||||
private byte[] _sceneValueBytes = new byte[256];
|
private byte[] _sceneValueBytes = new byte[256];
|
||||||
|
private byte[] _objectMetaBytes = new byte[256];
|
||||||
|
|
||||||
|
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
|
||||||
|
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
|
||||||
|
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
|
||||||
|
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
|
||||||
|
private byte[] _shaderTarget = [];
|
||||||
|
private byte[] _pixelProcessTarget = [];
|
||||||
|
private double[] _pixelProcessKernel = [];
|
||||||
|
|
||||||
|
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
|
||||||
|
|
||||||
public LuaJitWorker(string nativeDir, string scriptPath)
|
public LuaJitWorker(string nativeDir, string scriptPath)
|
||||||
{
|
{
|
||||||
@@ -63,11 +74,16 @@ namespace LuaScript.Engine
|
|||||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||||
|
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||||
Action<DrawCommand> addDraw,
|
Action<DrawCommand> addDraw,
|
||||||
Action<string, int, bool, int, double[]> setAnchor,
|
Action<string, int, bool, int, double[]> setAnchor,
|
||||||
Func<string, SceneValue> sceneGetValue,
|
Func<string, SceneValue> sceneGetValue,
|
||||||
Action<string, SceneValue> sceneSetValue,
|
Action<string, SceneValue> sceneSetValue,
|
||||||
|
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||||
|
PixelShaderInvoke? runPixelShader,
|
||||||
|
IPixelBufferProcessor? pixelProcessor,
|
||||||
out bool pixelsDirty,
|
out bool pixelsDirty,
|
||||||
out bool bufferReplaced,
|
out bool bufferReplaced,
|
||||||
out int resultWidth,
|
out int resultWidth,
|
||||||
@@ -111,16 +127,18 @@ namespace LuaScript.Engine
|
|||||||
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
|
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
|
||||||
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
||||||
view.Write(NativeProtocol.OffErrorLen, 0);
|
view.Write(NativeProtocol.OffErrorLen, 0);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
|
||||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||||
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
|
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
|
||||||
|
|
||||||
_workEvent!.Set();
|
_workEvent!.Set();
|
||||||
|
|
||||||
var stopwatch = Stopwatch.StartNew();
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
long budget = timeoutMs;
|
||||||
int status;
|
int status;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
|
long remaining = budget - stopwatch.ElapsedMilliseconds;
|
||||||
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
|
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
|
||||||
{
|
{
|
||||||
KillWorker();
|
KillWorker();
|
||||||
@@ -132,6 +150,7 @@ namespace LuaScript.Engine
|
|||||||
if (status != NativeProtocol.StatusCallback)
|
if (status != NativeProtocol.StatusCallback)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
long callbackStart = stopwatch.ElapsedMilliseconds;
|
||||||
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||||
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
||||||
{
|
{
|
||||||
@@ -151,8 +170,9 @@ namespace LuaScript.Engine
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
|
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
|
||||||
}
|
}
|
||||||
|
budget += stopwatch.ElapsedMilliseconds - callbackStart;
|
||||||
_workEvent.Set();
|
_workEvent.Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +197,7 @@ namespace LuaScript.Engine
|
|||||||
bufferReplaced = resultWidth != width || resultHeight != height;
|
bufferReplaced = resultWidth != width || resultHeight != height;
|
||||||
|
|
||||||
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
||||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
|
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > PixelRegionCapacity)
|
||||||
{
|
{
|
||||||
error = "native worker reported a pixel buffer beyond capacity";
|
error = "native worker reported a pixel buffer beyond capacity";
|
||||||
return false;
|
return false;
|
||||||
@@ -196,7 +216,39 @@ namespace LuaScript.Engine
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
long offset = _view.PointerOffset + _pixelOffset;
|
long offset = _view.PointerOffset + _pixelOffset;
|
||||||
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
|
access((nint)(ptr + offset), PixelRegionCapacity);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
handle.ReleasePointer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private unsafe void ReadRegion(long offset, byte[] destination, int length)
|
||||||
|
{
|
||||||
|
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||||
|
byte* ptr = null;
|
||||||
|
handle.AcquirePointer(ref ptr);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
fixed (byte* dst = destination)
|
||||||
|
Buffer.MemoryCopy(ptr + _view.PointerOffset + offset, dst, destination.Length, length);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
handle.ReleasePointer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private unsafe void WriteRegion(long offset, byte[] source, int length)
|
||||||
|
{
|
||||||
|
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||||
|
byte* ptr = null;
|
||||||
|
handle.AcquirePointer(ref ptr);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
fixed (byte* src = source)
|
||||||
|
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + offset, (ulong)handle.ByteLength - (ulong)(_view.PointerOffset + offset), (ulong)length);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -280,10 +332,15 @@ namespace LuaScript.Engine
|
|||||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||||
|
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||||
Action<string, int, bool, int, double[]> setAnchor,
|
Action<string, int, bool, int, double[]> setAnchor,
|
||||||
Func<string, SceneValue> sceneGetValue,
|
Func<string, SceneValue> sceneGetValue,
|
||||||
Action<string, SceneValue> sceneSetValue)
|
Action<string, SceneValue> sceneSetValue,
|
||||||
|
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||||
|
PixelShaderInvoke? runPixelShader,
|
||||||
|
IPixelBufferProcessor? pixelProcessor)
|
||||||
{
|
{
|
||||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||||
switch (kind)
|
switch (kind)
|
||||||
@@ -303,6 +360,15 @@ namespace LuaScript.Engine
|
|||||||
case NativeProtocol.CbKindLoadMovie:
|
case NativeProtocol.CbKindLoadMovie:
|
||||||
ResolveLoadMovieCallback(view, loadMovie);
|
ResolveLoadMovieCallback(view, loadMovie);
|
||||||
break;
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadScene:
|
||||||
|
ResolveLoadSceneCallback(view, loadScene);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadBrush:
|
||||||
|
ResolveLoadBrushCallback(view, loadBrush);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindBrush:
|
||||||
|
ResolveBrushCallback(view, loadBrush);
|
||||||
|
break;
|
||||||
case NativeProtocol.CbKindEffect:
|
case NativeProtocol.CbKindEffect:
|
||||||
ResolveEffectCallback(view, addEffect);
|
ResolveEffectCallback(view, addEffect);
|
||||||
break;
|
break;
|
||||||
@@ -315,9 +381,237 @@ namespace LuaScript.Engine
|
|||||||
case NativeProtocol.CbKindSceneSet:
|
case NativeProtocol.CbKindSceneSet:
|
||||||
ResolveSceneSetCallback(view, sceneSetValue);
|
ResolveSceneSetCallback(view, sceneSetValue);
|
||||||
break;
|
break;
|
||||||
|
case NativeProtocol.CbKindGetAudio:
|
||||||
|
ResolveGetAudioCallback(view, loadAudio);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindPixelShaderStage:
|
||||||
|
ResolveShaderStageCallback(view);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindPixelShaderRun:
|
||||||
|
ResolveShaderRunCallback(view, runPixelShader);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindPixelProcess:
|
||||||
|
ResolvePixelProcessCallback(view, pixelProcessor);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
|
||||||
|
{
|
||||||
|
bool processed = false;
|
||||||
|
if (pixelProcessor is not null)
|
||||||
|
{
|
||||||
|
int width = view.ReadInt32(NativeProtocol.OffWidth);
|
||||||
|
int height = view.ReadInt32(NativeProtocol.OffHeight);
|
||||||
|
long length = (long)width * height * 4;
|
||||||
|
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
|
||||||
|
{
|
||||||
|
int pixelLength = (int)length;
|
||||||
|
if (_pixelProcessTarget.Length < pixelLength)
|
||||||
|
_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, force),
|
||||||
|
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength, force),
|
||||||
|
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength, force),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
double g = view.ReadDouble(offset + 2 * 8);
|
||||||
|
double b = view.ReadDouble(offset + 3 * 8);
|
||||||
|
double a = view.ReadDouble(offset + 4 * 8);
|
||||||
|
int x = (int)view.ReadDouble(offset + 5 * 8);
|
||||||
|
int y = (int)view.ReadDouble(offset + 6 * 8);
|
||||||
|
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
|
||||||
|
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, force))
|
||||||
|
return false;
|
||||||
|
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
double divisor = view.ReadDouble(offset + 2 * 8);
|
||||||
|
double kernelOffset = view.ReadDouble(offset + 3 * 8);
|
||||||
|
if (size < 1 || (size & 1) == 0)
|
||||||
|
return false;
|
||||||
|
int taps = size * size;
|
||||||
|
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
|
||||||
|
return false;
|
||||||
|
if (_pixelProcessKernel.Length < taps)
|
||||||
|
_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, force))
|
||||||
|
return false;
|
||||||
|
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength, bool force)
|
||||||
|
{
|
||||||
|
long offset = NativeProtocol.CallbackResultOffset;
|
||||||
|
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
|
||||||
|
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
|
||||||
|
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
|
||||||
|
long length = (long)targetWidth * targetHeight * 4;
|
||||||
|
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||||
|
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||||
|
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, force) || target is null)
|
||||||
|
return false;
|
||||||
|
WriteRegion(_pixelOffset, target, (int)length);
|
||||||
|
view.Write(NativeProtocol.OffWidth, targetWidth);
|
||||||
|
view.Write(NativeProtocol.OffHeight, targetHeight);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
|
||||||
|
{
|
||||||
|
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||||
|
int width = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
|
||||||
|
int height = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
|
||||||
|
int slot = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
|
||||||
|
if ((uint)slot >= NativeProtocol.ShaderResourcesMax ||
|
||||||
|
!TryStageShaderInput(slot, width, height, NativeProtocol.ShaderImageOffset(_allocatedSize)))
|
||||||
|
{
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryStageShaderInput(int slot, int width, int height, long sourceOffset)
|
||||||
|
{
|
||||||
|
long length = (long)width * height * 4;
|
||||||
|
if (width <= 0 || height <= 0 || length > NativeProtocol.MaxPixelBufferSize)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ref byte[]? data = ref _shaderResourceData[slot];
|
||||||
|
if (data is null || data.Length < length)
|
||||||
|
data = new byte[length];
|
||||||
|
ReadRegion(sourceOffset, data, (int)length);
|
||||||
|
_shaderInputs[slot] = new PixelShaderInput(data, width, height);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveShaderRunCallback(MemoryMappedViewAccessor view, PixelShaderInvoke? runPixelShader)
|
||||||
|
{
|
||||||
|
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string name = ResolveTag(tagLen);
|
||||||
|
|
||||||
|
int resourceCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaResourceCount * 8), 0, NativeProtocol.ShaderResourcesMax);
|
||||||
|
int blendMode = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaBlendMode * 8);
|
||||||
|
double compositeBlend = view.ReadDouble(meta + NativeProtocol.ShaderMetaCompositeBlend * 8);
|
||||||
|
int samplerValue = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaSampler * 8);
|
||||||
|
int constantCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaConstantCount * 8), 0, NativeProtocol.ShaderConstantsMax);
|
||||||
|
int targetWidth = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
|
||||||
|
int targetHeight = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
|
||||||
|
int targetKind = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
|
||||||
|
|
||||||
|
for (int i = 0; i < resourceCount; i++)
|
||||||
|
{
|
||||||
|
int kind = (int)view.ReadDouble(meta + (NativeProtocol.ShaderMetaResourceKinds + i) * 8);
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case NativeProtocol.ShaderResourceStaged:
|
||||||
|
break;
|
||||||
|
case NativeProtocol.ShaderResourceRandom:
|
||||||
|
_shaderInputs[i] = PixelShaderInput.Random;
|
||||||
|
break;
|
||||||
|
case NativeProtocol.ShaderResourceObject:
|
||||||
|
if (!TryStageShaderInput(i, view.ReadInt32(NativeProtocol.OffWidth), view.ReadInt32(NativeProtocol.OffHeight), _pixelOffset))
|
||||||
|
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (constantCount > 0)
|
||||||
|
view.ReadArray(NativeProtocol.ShaderConstantsOffset(_allocatedSize), _shaderConstants, 0, constantCount);
|
||||||
|
|
||||||
|
var status = PixelShaderRunStatus.Unavailable;
|
||||||
|
string? error = null;
|
||||||
|
long targetLength = (long)targetWidth * targetHeight * 4;
|
||||||
|
if (runPixelShader is not null &&
|
||||||
|
targetWidth > 0 && targetHeight > 0 &&
|
||||||
|
targetLength <= NativeProtocol.MaxPixelBufferSize &&
|
||||||
|
(targetKind != NativeProtocol.ShaderTargetObject || targetLength <= PixelRegionCapacity))
|
||||||
|
{
|
||||||
|
int length = (int)targetLength;
|
||||||
|
if (_shaderTarget.Length < length)
|
||||||
|
_shaderTarget = new byte[length];
|
||||||
|
long targetOffset = targetKind == NativeProtocol.ShaderTargetObject
|
||||||
|
? _pixelOffset
|
||||||
|
: NativeProtocol.ShaderImageOffset(_allocatedSize);
|
||||||
|
ReadRegion(targetOffset, _shaderTarget, length);
|
||||||
|
|
||||||
|
var blend = blendMode switch
|
||||||
|
{
|
||||||
|
(int)PixelShaderBlendMode.Mask => PixelShaderBlend.Mask,
|
||||||
|
(int)PixelShaderBlendMode.Draw => PixelShaderBlend.Draw,
|
||||||
|
(int)PixelShaderBlendMode.Add => PixelShaderBlend.Add,
|
||||||
|
(int)PixelShaderBlendMode.Composite => PixelShaderBlend.Composite(compositeBlend),
|
||||||
|
_ => PixelShaderBlend.Copy,
|
||||||
|
};
|
||||||
|
var sampler = (uint)samplerValue <= (uint)PixelShaderSampler.Dot
|
||||||
|
? (PixelShaderSampler)samplerValue
|
||||||
|
: PixelShaderSampler.None;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
status = runPixelShader(
|
||||||
|
name,
|
||||||
|
_shaderInputs.AsSpan(0, resourceCount),
|
||||||
|
_shaderConstants.AsSpan(0, constantCount),
|
||||||
|
blend, sampler,
|
||||||
|
_shaderTarget, targetWidth, targetHeight,
|
||||||
|
out error);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
status = PixelShaderRunStatus.Unavailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status == PixelShaderRunStatus.Success)
|
||||||
|
WriteRegion(targetOffset, _shaderTarget, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status == PixelShaderRunStatus.CompileError)
|
||||||
|
{
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(error ?? "obj.pixelshader: compile error");
|
||||||
|
int errorLength = Math.Min(bytes.Length, NativeProtocol.CallbackTagMax);
|
||||||
|
view.WriteArray(NativeProtocol.CallbackTagOffset, bytes, 0, errorLength);
|
||||||
|
view.Write(NativeProtocol.OffCallbackTagLen, errorLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(meta + NativeProtocol.ShaderMetaStatus * 8, (double)status);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
|
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
|
||||||
{
|
{
|
||||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
@@ -382,6 +676,40 @@ namespace LuaScript.Engine
|
|||||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly double[] s_noAudioData = [];
|
||||||
|
|
||||||
|
private void ResolveGetAudioCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
|
||||||
|
string file = Encoding.UTF8.GetString(_callbackTag, 0, separator >= 0 ? separator : tagLen);
|
||||||
|
string type = separator >= 0
|
||||||
|
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
|
||||||
|
: "pcm";
|
||||||
|
int size = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
int rate = 0;
|
||||||
|
double[] data = s_noAudioData;
|
||||||
|
try { (count, rate, data) = loadAudio(file, type, size); }
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
count = 0;
|
||||||
|
rate = 0;
|
||||||
|
data = s_noAudioData;
|
||||||
|
}
|
||||||
|
|
||||||
|
count = Math.Clamp(count, 0, Math.Min(data.Length, NativeProtocol.CallbackTagMax / 8));
|
||||||
|
if (count > 0)
|
||||||
|
view.WriteArray(NativeProtocol.CallbackTagOffset, data, 0, count);
|
||||||
|
view.Write(NativeProtocol.CallbackResultOffset, (double)count);
|
||||||
|
view.Write(NativeProtocol.CallbackResultOffset + 8, (double)rate);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
||||||
{
|
{
|
||||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
@@ -469,6 +797,9 @@ namespace LuaScript.Engine
|
|||||||
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
|
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
|
||||||
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
|
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
|
||||||
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
|
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
|
||||||
|
view.Write(result + NativeProtocol.CbVolume * 8, value.Volume);
|
||||||
|
view.Write(result + NativeProtocol.CbLength * 8, (double)value.Length);
|
||||||
|
WriteObjectMeta(view, value.Character, value.Text, value.Kind);
|
||||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -477,6 +808,27 @@ namespace LuaScript.Engine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void WriteObjectMeta(MemoryMappedViewAccessor view, string character, string text, string kind)
|
||||||
|
{
|
||||||
|
character ??= string.Empty;
|
||||||
|
text ??= string.Empty;
|
||||||
|
kind ??= string.Empty;
|
||||||
|
int maxBytes = Encoding.UTF8.GetMaxByteCount(character.Length + text.Length + kind.Length) + 2;
|
||||||
|
if (_objectMetaBytes.Length < maxBytes)
|
||||||
|
_objectMetaBytes = new byte[Math.Max(maxBytes, _objectMetaBytes.Length * 2)];
|
||||||
|
|
||||||
|
int length = Encoding.UTF8.GetBytes(character, 0, character.Length, _objectMetaBytes, 0);
|
||||||
|
_objectMetaBytes[length++] = 0;
|
||||||
|
length += Encoding.UTF8.GetBytes(text, 0, text.Length, _objectMetaBytes, length);
|
||||||
|
_objectMetaBytes[length++] = 0;
|
||||||
|
length += Encoding.UTF8.GetBytes(kind, 0, kind.Length, _objectMetaBytes, length);
|
||||||
|
if (length > NativeProtocol.CallbackTagMax)
|
||||||
|
length = NativeProtocol.CallbackTagMax;
|
||||||
|
|
||||||
|
view.WriteArray(NativeProtocol.CallbackTagOffset, _objectMetaBytes, 0, length);
|
||||||
|
view.Write(NativeProtocol.OffCallbackTagLen, length);
|
||||||
|
}
|
||||||
|
|
||||||
private void ResolveLoadFigureCallback(
|
private void ResolveLoadFigureCallback(
|
||||||
MemoryMappedViewAccessor view,
|
MemoryMappedViewAccessor view,
|
||||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||||
@@ -496,7 +848,7 @@ namespace LuaScript.Engine
|
|||||||
catch { result = (new byte[4], 1, 1); }
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
int pixelSize = result.w * result.h * 4;
|
int pixelSize = result.w * result.h * 4;
|
||||||
long capacity = view.Capacity - _pixelOffset;
|
long capacity = PixelRegionCapacity;
|
||||||
if (pixelSize > capacity)
|
if (pixelSize > capacity)
|
||||||
{
|
{
|
||||||
result = (new byte[4], 1, 1);
|
result = (new byte[4], 1, 1);
|
||||||
@@ -531,7 +883,7 @@ namespace LuaScript.Engine
|
|||||||
catch { result = (new byte[4], 1, 1); }
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
int pixelSize = result.w * result.h * 4;
|
int pixelSize = result.w * result.h * 4;
|
||||||
long capacity = view.Capacity - _pixelOffset;
|
long capacity = PixelRegionCapacity;
|
||||||
if (pixelSize > capacity)
|
if (pixelSize > capacity)
|
||||||
{
|
{
|
||||||
result = (new byte[4], 1, 1);
|
result = (new byte[4], 1, 1);
|
||||||
@@ -557,7 +909,7 @@ namespace LuaScript.Engine
|
|||||||
catch { result = (new byte[4], 1, 1); }
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
int pixelSize = result.w * result.h * 4;
|
int pixelSize = result.w * result.h * 4;
|
||||||
long capacity = view.Capacity - _pixelOffset;
|
long capacity = PixelRegionCapacity;
|
||||||
if (pixelSize > capacity)
|
if (pixelSize > capacity)
|
||||||
{
|
{
|
||||||
result = (new byte[4], 1, 1);
|
result = (new byte[4], 1, 1);
|
||||||
@@ -584,7 +936,7 @@ namespace LuaScript.Engine
|
|||||||
catch { result = (new byte[4], 1, 1); }
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
int pixelSize = result.w * result.h * 4;
|
int pixelSize = result.w * result.h * 4;
|
||||||
long capacity = view.Capacity - _pixelOffset;
|
long capacity = PixelRegionCapacity;
|
||||||
if (pixelSize > capacity)
|
if (pixelSize > capacity)
|
||||||
{
|
{
|
||||||
result = (new byte[4], 1, 1);
|
result = (new byte[4], 1, 1);
|
||||||
@@ -597,16 +949,100 @@ namespace LuaScript.Engine
|
|||||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
private void ResolveLoadSceneCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadScene)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadScene(name, time); }
|
||||||
|
catch { result = ([], 0, 0); }
|
||||||
|
|
||||||
|
long pixelSize = (long)result.w * result.h * 4;
|
||||||
|
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||||
|
{
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly KeyValuePair<string, object>[] s_noBrushArguments = [];
|
||||||
|
|
||||||
|
private void ResolveLoadBrushCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
|
||||||
|
WriteBrushResult(view, loadBrush, name, s_noBrushArguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveBrushCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||||
{
|
{
|
||||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
|
||||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||||
if (segments.Length == 0)
|
if (segments.Length == 0)
|
||||||
|
{
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteBrushResult(view, loadBrush, segments[0], ParseNamedArguments(segments));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WriteBrushResult(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||||
|
string name,
|
||||||
|
IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||||
|
{
|
||||||
|
long rOff = NativeProtocol.CallbackResultOffset;
|
||||||
|
double width = view.ReadDouble(rOff + 0 * 8);
|
||||||
|
double height = view.ReadDouble(rOff + 1 * 8);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadBrush(name, width, height, arguments); }
|
||||||
|
catch { result = ([], 0, 0); }
|
||||||
|
|
||||||
|
long pixelSize = (long)result.w * result.h * 4;
|
||||||
|
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||||
|
{
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<KeyValuePair<string, object>> ParseNamedArguments(string[] segments)
|
||||||
|
{
|
||||||
|
if (segments.Length < 3)
|
||||||
|
return s_noBrushArguments;
|
||||||
|
|
||||||
string effectName = segments[0];
|
|
||||||
var arguments = new List<KeyValuePair<string, object>>();
|
var arguments = new List<KeyValuePair<string, object>>();
|
||||||
for (int i = 1; i + 1 < segments.Length; i += 2)
|
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||||
{
|
{
|
||||||
@@ -623,8 +1059,19 @@ namespace LuaScript.Engine
|
|||||||
value = raw;
|
value = raw;
|
||||||
arguments.Add(new KeyValuePair<string, object>(key, value));
|
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||||
}
|
}
|
||||||
|
return arguments;
|
||||||
|
}
|
||||||
|
|
||||||
try { addEffect(effectName, arguments); }
|
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
|
||||||
|
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||||
|
if (segments.Length == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
try { addEffect(segments[0], ParseNamedArguments(segments)); }
|
||||||
catch { }
|
catch { }
|
||||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
}
|
}
|
||||||
@@ -643,7 +1090,7 @@ namespace LuaScript.Engine
|
|||||||
|
|
||||||
private void EnsureWorker(int width, int height, int stringCapacity)
|
private void EnsureWorker(int width, int height, int stringCapacity)
|
||||||
{
|
{
|
||||||
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
|
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4 + NativeProtocol.ShaderRegionBytes;
|
||||||
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
|
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
|||||||
@@ -181,9 +181,17 @@ namespace LuaScript
|
|||||||
script.AttachDebugger(_debugger);
|
script.AttachDebugger(_debugger);
|
||||||
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
|
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
|
||||||
_globalRegistrar.RegisterLuaMembers(script.Globals);
|
_globalRegistrar.RegisterLuaMembers(script.Globals);
|
||||||
|
RegisterFastPrimitives(script);
|
||||||
_script = script;
|
_script = script;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void RegisterFastPrimitives(Script script)
|
||||||
|
{
|
||||||
|
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args, true)));
|
||||||
|
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args, true)));
|
||||||
|
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args, true)));
|
||||||
|
}
|
||||||
|
|
||||||
private void EnsureScriptIntegrity()
|
private void EnsureScriptIntegrity()
|
||||||
{
|
{
|
||||||
if (_script is null) return;
|
if (_script is null) return;
|
||||||
@@ -548,6 +556,18 @@ namespace LuaScript
|
|||||||
args[1].String,
|
args[1].String,
|
||||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||||
break;
|
break;
|
||||||
|
case "scene" when args.Count > 1 && args[1].Type == DataType.String:
|
||||||
|
LoadScene(
|
||||||
|
args[1].String,
|
||||||
|
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||||
|
break;
|
||||||
|
case "brush" when args.Count > 1 && args[1].Type == DataType.String:
|
||||||
|
LoadBrush(
|
||||||
|
args[1].String,
|
||||||
|
args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d,
|
||||||
|
args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d,
|
||||||
|
s_noNamedArguments);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
}
|
}
|
||||||
@@ -632,6 +652,135 @@ namespace LuaScript
|
|||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[LuaFunction("pixelshader")]
|
||||||
|
private DynValue PixelShader(CallbackArguments args)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 2 ||
|
||||||
|
args[0].Type != DataType.String || args[1].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
var ctx = _activeContext;
|
||||||
|
var runner = ctx.ShaderRunner;
|
||||||
|
if (runner is null)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
string name = args[0].String;
|
||||||
|
if (!ctx.PixelShaders.TryGet(name, out string hlsl))
|
||||||
|
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' is not defined in this script.");
|
||||||
|
|
||||||
|
int resourceCount = CollectShaderResources(ctx, args.Count > 2 ? args[2] : DynValue.Nil);
|
||||||
|
int constantCount = CollectShaderConstants(args.Count > 3 ? args[3] : DynValue.Nil);
|
||||||
|
var blend = ParseShaderBlend(args.Count > 4 ? args[4] : DynValue.Nil);
|
||||||
|
var sampler = ParseShaderSampler(args.Count > 5 ? args[5] : DynValue.Nil);
|
||||||
|
|
||||||
|
string target = args[1].String;
|
||||||
|
if (!ctx.TryGetShaderTarget(target, out byte[] targetData, out int targetWidth, out int targetHeight))
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
var status = runner.TryRun(
|
||||||
|
hlsl,
|
||||||
|
AviUtlPixelShaderLibrary.EntryPointOf(name),
|
||||||
|
_shaderResources.AsSpan(0, resourceCount),
|
||||||
|
_shaderConstants.AsSpan(0, constantCount),
|
||||||
|
blend, sampler,
|
||||||
|
targetData, targetWidth, targetHeight,
|
||||||
|
out string? error);
|
||||||
|
|
||||||
|
if (status == PixelShaderRunStatus.CompileError)
|
||||||
|
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' failed to compile.\n{error}");
|
||||||
|
if (status == PixelShaderRunStatus.Success && ctx.NotifyShaderTargetWritten(target))
|
||||||
|
RefreshObjDimensions();
|
||||||
|
return DynValue.Void;
|
||||||
|
}
|
||||||
|
|
||||||
|
private const int MaxShaderResources = 8;
|
||||||
|
private const int MaxShaderConstants = 1024;
|
||||||
|
|
||||||
|
private static readonly byte[] s_transparentPixel = new byte[4];
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _shaderResources = new PixelShaderInput[MaxShaderResources];
|
||||||
|
private readonly float[] _shaderConstants = new float[MaxShaderConstants];
|
||||||
|
|
||||||
|
private static PixelShaderInput TransparentShaderResource => new(s_transparentPixel, 1, 1);
|
||||||
|
|
||||||
|
private int CollectShaderResources(AviUtlScriptContext ctx, DynValue value)
|
||||||
|
{
|
||||||
|
if (value.Type == DataType.String)
|
||||||
|
{
|
||||||
|
_shaderResources[0] = ResolveShaderResource(ctx, value.String);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (value.Type != DataType.Table)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
var table = value.Table;
|
||||||
|
int count = table.Length;
|
||||||
|
if (count > MaxShaderResources)
|
||||||
|
throw new ScriptRuntimeException($"obj.pixelshader: too many resources ({count}). Up to {MaxShaderResources} are supported.");
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var entry = table.Get(i + 1);
|
||||||
|
_shaderResources[i] = entry.Type == DataType.String
|
||||||
|
? ResolveShaderResource(ctx, entry.String)
|
||||||
|
: TransparentShaderResource;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PixelShaderInput ResolveShaderResource(AviUtlScriptContext ctx, string id)
|
||||||
|
{
|
||||||
|
if (string.Equals(id, "random", StringComparison.Ordinal))
|
||||||
|
return PixelShaderInput.Random;
|
||||||
|
if (ctx.TryGetShaderResource(id, out var data, out int width, out int height))
|
||||||
|
return new PixelShaderInput(data, width, height);
|
||||||
|
return TransparentShaderResource;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int CollectShaderConstants(DynValue value)
|
||||||
|
{
|
||||||
|
if (value.Type != DataType.Table)
|
||||||
|
return 0;
|
||||||
|
var table = value.Table;
|
||||||
|
int count = table.Length;
|
||||||
|
if (count > MaxShaderConstants)
|
||||||
|
throw new ScriptRuntimeException($"obj.pixelshader: too many constants ({count}). Up to {MaxShaderConstants} are supported.");
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
_shaderConstants[i] = (float)(table.Get(i + 1).CastToNumber() ?? 0d);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PixelShaderBlend ParseShaderBlend(DynValue value)
|
||||||
|
{
|
||||||
|
if (value.Type == DataType.Number)
|
||||||
|
return PixelShaderBlend.Composite(value.Number);
|
||||||
|
if (value.Type != DataType.String)
|
||||||
|
return PixelShaderBlend.Copy;
|
||||||
|
return value.String switch
|
||||||
|
{
|
||||||
|
"copy" => PixelShaderBlend.Copy,
|
||||||
|
"mask" => PixelShaderBlend.Mask,
|
||||||
|
"draw" => PixelShaderBlend.Draw,
|
||||||
|
"add" => PixelShaderBlend.Add,
|
||||||
|
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown blend '{value.String}'. Use copy, mask, draw, add or a blend number."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PixelShaderSampler ParseShaderSampler(DynValue value)
|
||||||
|
{
|
||||||
|
if (value.Type != DataType.String)
|
||||||
|
return PixelShaderSampler.None;
|
||||||
|
return value.String switch
|
||||||
|
{
|
||||||
|
"clip" => PixelShaderSampler.Clip,
|
||||||
|
"clamp" => PixelShaderSampler.Clamp,
|
||||||
|
"loop" => PixelShaderSampler.Loop,
|
||||||
|
"mirror" => PixelShaderSampler.Mirror,
|
||||||
|
"dot" => PixelShaderSampler.Dot,
|
||||||
|
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown sampler '{value.String}'. Use clip, clamp, loop, mirror or dot."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
[LuaFunction("getvalue")]
|
[LuaFunction("getvalue")]
|
||||||
private DynValue GetValue(CallbackArguments args)
|
private DynValue GetValue(CallbackArguments args)
|
||||||
{
|
{
|
||||||
@@ -642,6 +791,47 @@ namespace LuaScript
|
|||||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly double[] s_noAudioData = [];
|
||||||
|
|
||||||
|
[LuaFunction("getaudio")]
|
||||||
|
private DynValue GetAudio(CallbackArguments args)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || _script is null || args.Count < 2 || args[1].Type != DataType.String)
|
||||||
|
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
|
||||||
|
|
||||||
|
string file = args[1].String;
|
||||||
|
string type = args.Count > 2 && args[2].Type == DataType.String ? args[2].String : "pcm";
|
||||||
|
int size = args.Count > 3 ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
int rate = 0;
|
||||||
|
double[] data = s_noAudioData;
|
||||||
|
var loader = _activeContext.AudioLoader;
|
||||||
|
if (loader is not null)
|
||||||
|
(count, rate, data) = loader(file, type, size);
|
||||||
|
if (count > data.Length)
|
||||||
|
count = data.Length;
|
||||||
|
|
||||||
|
var bufArg = args[0];
|
||||||
|
Table? table = bufArg.Type == DataType.Table ? bufArg.Table : null;
|
||||||
|
bool created = false;
|
||||||
|
if (table is null && bufArg.IsNil())
|
||||||
|
{
|
||||||
|
table = new Table(_script);
|
||||||
|
created = true;
|
||||||
|
}
|
||||||
|
if (table is not null)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
table.Set(i + 1, DynValue.NewNumber(data[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return created
|
||||||
|
? DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate), DynValue.NewTable(table!))
|
||||||
|
: DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate));
|
||||||
|
}
|
||||||
|
|
||||||
[LuaFunction("setoption")]
|
[LuaFunction("setoption")]
|
||||||
private DynValue SetOption(CallbackArguments args)
|
private DynValue SetOption(CallbackArguments args)
|
||||||
{
|
{
|
||||||
@@ -699,9 +889,7 @@ namespace LuaScript
|
|||||||
return DynValue.NewNumber(0d);
|
return DynValue.NewNumber(0d);
|
||||||
|
|
||||||
var anchorName = args[0].String;
|
var anchorName = args[0].String;
|
||||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
int count = AnchorSupport.NormalizeCount(anchorName, (int)(args[1].CastToNumber() ?? 0d));
|
||||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
|
||||||
return DynValue.NewNumber(0d);
|
|
||||||
|
|
||||||
var connection = AnchorConnection.None;
|
var connection = AnchorConnection.None;
|
||||||
bool is3D = false;
|
bool is3D = false;
|
||||||
@@ -735,9 +923,19 @@ namespace LuaScript
|
|||||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
|
|
||||||
string name = args[0].String;
|
_activeContext.AddEffect(new AviUtlEffectRequest(args[0].String, CollectNamedArguments(args, 1)));
|
||||||
|
return DynValue.Void;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly KeyValuePair<string, object>[] s_noNamedArguments = [];
|
||||||
|
|
||||||
|
private static IReadOnlyList<KeyValuePair<string, object>> CollectNamedArguments(CallbackArguments args, int start)
|
||||||
|
{
|
||||||
|
if (start + 1 >= args.Count)
|
||||||
|
return s_noNamedArguments;
|
||||||
|
|
||||||
var arguments = new List<KeyValuePair<string, object>>();
|
var arguments = new List<KeyValuePair<string, object>>();
|
||||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
for (int i = start; i + 1 < args.Count; i += 2)
|
||||||
{
|
{
|
||||||
if (args[i].Type != DataType.String)
|
if (args[i].Type != DataType.String)
|
||||||
continue;
|
continue;
|
||||||
@@ -751,8 +949,27 @@ namespace LuaScript
|
|||||||
};
|
};
|
||||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||||
}
|
}
|
||||||
|
return arguments;
|
||||||
|
}
|
||||||
|
|
||||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
[LuaFunction("brush")]
|
||||||
|
private DynValue Brush(CallbackArguments args)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int start = 1;
|
||||||
|
double width = 0d;
|
||||||
|
double height = 0d;
|
||||||
|
if (args.Count > 2 && args[1].Type == DataType.Number && args[2].Type == DataType.Number)
|
||||||
|
{
|
||||||
|
width = args[1].Number;
|
||||||
|
height = args[2].Number;
|
||||||
|
start = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
LoadBrush(args[0].String, width, height, CollectNamedArguments(args, start));
|
||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -778,6 +995,150 @@ namespace LuaScript
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private double[] _regionScratch = [];
|
||||||
|
private double[] _kernelScratch = [];
|
||||||
|
|
||||||
|
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
|
||||||
|
|
||||||
|
private static DynValue[] CreateByteNumbers()
|
||||||
|
{
|
||||||
|
var values = new DynValue[256];
|
||||||
|
for (int i = 0; i < values.Length; i++)
|
||||||
|
values[i] = DynValue.NewNumber(i).AsReadOnly();
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DynValue ChannelValue(double value)
|
||||||
|
{
|
||||||
|
int b = (int)value;
|
||||||
|
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaFunction("fill")]
|
||||||
|
private DynValue Fill(CallbackArguments args) => FillCore(args, false);
|
||||||
|
|
||||||
|
private DynValue FillCore(CallbackArguments args, bool force)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
var ctx = _activeContext;
|
||||||
|
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||||
|
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||||
|
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||||
|
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
|
||||||
|
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
|
||||||
|
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
|
||||||
|
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, force);
|
||||||
|
return DynValue.Void;
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaFunction("getpixelregion")]
|
||||||
|
private DynValue GetPixelRegion(CallbackArguments args)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || _script is null || args.Count < 4)
|
||||||
|
return DynValue.Nil;
|
||||||
|
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||||
|
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||||
|
var table = new Table(_script);
|
||||||
|
if (w <= 0 || h <= 0)
|
||||||
|
return DynValue.NewTable(table);
|
||||||
|
|
||||||
|
int count = w * h * 4;
|
||||||
|
if (_regionScratch.Length < count)
|
||||||
|
_regionScratch = new double[count];
|
||||||
|
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
table.Set(i + 1, ChannelValue(_regionScratch[i]));
|
||||||
|
return DynValue.NewTable(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaFunction("putpixelregion")]
|
||||||
|
private DynValue PutPixelRegion(CallbackArguments args)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||||
|
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||||
|
if (w <= 0 || h <= 0)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int count = w * h * 4;
|
||||||
|
if (_regionScratch.Length < count)
|
||||||
|
_regionScratch = new double[count];
|
||||||
|
var table = args[4].Table;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
|
||||||
|
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
|
||||||
|
return DynValue.Void;
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaFunction("convolve")]
|
||||||
|
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args, false);
|
||||||
|
|
||||||
|
private DynValue ConvolveCore(CallbackArguments args, bool force)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int size = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
if (size < 1 || (size & 1) == 0)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int taps = size * size;
|
||||||
|
var kernel = args[0].Table;
|
||||||
|
if (_kernelScratch.Length < taps)
|
||||||
|
_kernelScratch = new double[taps];
|
||||||
|
double sum = 0d;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
{
|
||||||
|
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
|
||||||
|
_kernelScratch[i] = v;
|
||||||
|
sum += v;
|
||||||
|
}
|
||||||
|
|
||||||
|
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
|
||||||
|
if (divisor == 0d)
|
||||||
|
divisor = 1d;
|
||||||
|
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
|
||||||
|
|
||||||
|
_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 force)
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 2)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
int w = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int h = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
if (w <= 0 || h <= 0)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
|
||||||
|
_activeContext.Resize(w, h, linear, force);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
return DynValue.Void;
|
||||||
|
}
|
||||||
|
|
||||||
private double CurrentAntialias() =>
|
private double CurrentAntialias() =>
|
||||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||||
? value.Number
|
? value.Number
|
||||||
@@ -820,6 +1181,34 @@ namespace LuaScript
|
|||||||
RefreshObjDimensions();
|
RefreshObjDimensions();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void LoadScene(string name, double time)
|
||||||
|
{
|
||||||
|
var ctx = _activeContext!;
|
||||||
|
var loader = ctx.SceneImageLoader;
|
||||||
|
if (loader is null)
|
||||||
|
return;
|
||||||
|
var (buffer, w, h) = loader(name, time);
|
||||||
|
if (w <= 0 || h <= 0)
|
||||||
|
return;
|
||||||
|
ctx.ReplaceBuffer(buffer, w, h);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadBrush(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||||
|
{
|
||||||
|
var ctx = _activeContext!;
|
||||||
|
var loader = ctx.BrushImageLoader;
|
||||||
|
if (loader is null)
|
||||||
|
return;
|
||||||
|
double w = width > 0d ? width : ctx.ImageWidth;
|
||||||
|
double h = height > 0d ? height : ctx.ImageHeight;
|
||||||
|
var (buffer, bw, bh) = loader(name, w, h, arguments);
|
||||||
|
if (bw <= 0 || bh <= 0)
|
||||||
|
return;
|
||||||
|
ctx.ReplaceBuffer(buffer, bw, bh);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
private void LoadMovie(string path, double time)
|
private void LoadMovie(string path, double time)
|
||||||
{
|
{
|
||||||
_mediaLoader ??= _mediaLoaderFactory();
|
_mediaLoader ??= _mediaLoaderFactory();
|
||||||
@@ -833,14 +1222,14 @@ namespace LuaScript
|
|||||||
int w = _activeContext!.ImageWidth;
|
int w = _activeContext!.ImageWidth;
|
||||||
int h = _activeContext.ImageHeight;
|
int h = _activeContext.ImageHeight;
|
||||||
var obj = _objScope.Table;
|
var obj = _objScope.Table;
|
||||||
obj["w"] = w;
|
obj.Set("w", DynValue.NewNumber(w));
|
||||||
obj["h"] = h;
|
obj.Set("h", DynValue.NewNumber(h));
|
||||||
obj["hw"] = w / 2d;
|
obj.Set("hw", DynValue.NewNumber(w / 2d));
|
||||||
obj["hh"] = h / 2d;
|
obj.Set("hh", DynValue.NewNumber(h / 2d));
|
||||||
obj["cx"] = w / 2d;
|
obj.Set("cx", DynValue.NewNumber(w / 2d));
|
||||||
obj["cy"] = h / 2d;
|
obj.Set("cy", DynValue.NewNumber(h / 2d));
|
||||||
obj["cz"] = 0d;
|
obj.Set("cz", DynValue.NewNumber(0d));
|
||||||
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
|
obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||||
@@ -862,6 +1251,11 @@ namespace LuaScript
|
|||||||
["rzr"] = info.Rz * Math.PI / 180d,
|
["rzr"] = info.Rz * Math.PI / 180d,
|
||||||
["alpha"] = info.Alpha,
|
["alpha"] = info.Alpha,
|
||||||
["layer"] = info.Layer,
|
["layer"] = info.Layer,
|
||||||
|
["volume"] = info.Volume,
|
||||||
|
["length"] = info.Length,
|
||||||
|
["character"] = info.Character ?? string.Empty,
|
||||||
|
["text"] = info.Text ?? string.Empty,
|
||||||
|
["kind"] = info.Kind ?? string.Empty,
|
||||||
};
|
};
|
||||||
return DynValue.NewTable(table);
|
return DynValue.NewTable(table);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ namespace LuaScript.Engine
|
|||||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||||
public const int CallbackTagMax = 8192;
|
public const int CallbackTagMax = 8192;
|
||||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||||
public const int CallbackResultCount = 8;
|
public const int CallbackResultCount = 10;
|
||||||
|
|
||||||
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||||
public const int MinStringParamsCapacity = 64 * 1024;
|
public const int MinStringParamsCapacity = 64 * 1024;
|
||||||
@@ -61,6 +61,17 @@ namespace LuaScript.Engine
|
|||||||
public const int CbKindFlushDraws = 10;
|
public const int CbKindFlushDraws = 10;
|
||||||
public const int CbKindSceneGet = 11;
|
public const int CbKindSceneGet = 11;
|
||||||
public const int CbKindSceneSet = 12;
|
public const int CbKindSceneSet = 12;
|
||||||
|
public const int CbKindPixelShaderStage = 13;
|
||||||
|
public const int CbKindPixelShaderRun = 14;
|
||||||
|
public const int CbKindLoadScene = 15;
|
||||||
|
public const int CbKindLoadBrush = 16;
|
||||||
|
public const int CbKindBrush = 17;
|
||||||
|
public const int CbKindGetAudio = 18;
|
||||||
|
public const int CbKindPixelProcess = 19;
|
||||||
|
|
||||||
|
public const int PixelProcessFill = 0;
|
||||||
|
public const int PixelProcessConvolve = 1;
|
||||||
|
public const int PixelProcessResize = 2;
|
||||||
|
|
||||||
public const int DrawRingCapacity = 4096;
|
public const int DrawRingCapacity = 4096;
|
||||||
public const int DrawEntryDoubles = 24;
|
public const int DrawEntryDoubles = 24;
|
||||||
@@ -75,6 +86,8 @@ namespace LuaScript.Engine
|
|||||||
public const int CbRz = 5;
|
public const int CbRz = 5;
|
||||||
public const int CbAlpha = 6;
|
public const int CbAlpha = 6;
|
||||||
public const int CbLayer = 7;
|
public const int CbLayer = 7;
|
||||||
|
public const int CbVolume = 8;
|
||||||
|
public const int CbLength = 9;
|
||||||
|
|
||||||
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||||
|
|
||||||
@@ -153,7 +166,41 @@ namespace LuaScript.Engine
|
|||||||
|
|
||||||
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
||||||
|
|
||||||
|
public const int ShaderMetaDoubles = 20;
|
||||||
|
public const int ShaderConstantsMax = 1024;
|
||||||
|
public const int ShaderResourcesMax = 8;
|
||||||
|
|
||||||
|
public const int ShaderMetaResourceCount = 0;
|
||||||
|
public const int ShaderMetaBlendMode = 1;
|
||||||
|
public const int ShaderMetaCompositeBlend = 2;
|
||||||
|
public const int ShaderMetaSampler = 3;
|
||||||
|
public const int ShaderMetaConstantCount = 4;
|
||||||
|
public const int ShaderMetaImageWidth = 5;
|
||||||
|
public const int ShaderMetaImageHeight = 6;
|
||||||
|
public const int ShaderMetaImageKind = 7;
|
||||||
|
public const int ShaderMetaStatus = 8;
|
||||||
|
public const int ShaderMetaResourceKinds = 9;
|
||||||
|
|
||||||
|
public const int ShaderResourceStaged = 0;
|
||||||
|
public const int ShaderResourceRandom = 1;
|
||||||
|
public const int ShaderResourceTransparent = 2;
|
||||||
|
public const int ShaderResourceObject = 3;
|
||||||
|
|
||||||
|
public const int ShaderTargetExchange = 0;
|
||||||
|
public const int ShaderTargetObject = 1;
|
||||||
|
|
||||||
|
public const long ShaderRegionBytes = ShaderMetaDoubles * 8 + ShaderConstantsMax * 4 + MaxPixelBufferSize;
|
||||||
|
|
||||||
|
public static long ShaderMetaOffset(long bufferSize) => bufferSize - ShaderRegionBytes;
|
||||||
|
|
||||||
|
public static long ShaderConstantsOffset(long bufferSize) => ShaderMetaOffset(bufferSize) + ShaderMetaDoubles * 8;
|
||||||
|
|
||||||
|
public static long ShaderImageOffset(long bufferSize) => ShaderConstantsOffset(bufferSize) + ShaderConstantsMax * 4;
|
||||||
|
|
||||||
public static long BufferSize(int width, int height, int stringCapacity) =>
|
public static long BufferSize(int width, int height, int stringCapacity) =>
|
||||||
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
|
PixelOffset(stringCapacity) + PixelRegionSize(width, height) + ShaderRegionBytes;
|
||||||
|
|
||||||
|
public static long PixelRegionSize(int width, int height) =>
|
||||||
|
(Math.Max((long)width * height * 4, MaxPixelBufferSize) + 7) & ~7L;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal static unsafe class PixelBufferSoftwareProcessor
|
||||||
|
{
|
||||||
|
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||||
|
{
|
||||||
|
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||||
|
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||||
|
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||||
|
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||||
|
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
|
int x1 = x + fillWidth;
|
||||||
|
int y1 = y + fillHeight;
|
||||||
|
|
||||||
|
fixed (byte* buf = target)
|
||||||
|
{
|
||||||
|
for (int py = y; py < y1; py++)
|
||||||
|
{
|
||||||
|
byte* p = buf + (py * width + x) * 4;
|
||||||
|
for (int px = x; px < x1; px++)
|
||||||
|
{
|
||||||
|
p[0] = pb;
|
||||||
|
p[1] = pg;
|
||||||
|
p[2] = pr;
|
||||||
|
p[3] = pa;
|
||||||
|
p += 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
|
||||||
|
{
|
||||||
|
int count = width * height * 4;
|
||||||
|
if (sourceScratch is null || sourceScratch.Length < count)
|
||||||
|
sourceScratch = new double[count];
|
||||||
|
var src = sourceScratch;
|
||||||
|
|
||||||
|
fixed (byte* buf = target)
|
||||||
|
{
|
||||||
|
for (int pi = 0; pi < width * height; pi++)
|
||||||
|
{
|
||||||
|
byte* p = buf + pi * 4;
|
||||||
|
int di = pi * 4;
|
||||||
|
double a = p[3];
|
||||||
|
src[di + 3] = a;
|
||||||
|
if (a <= 0d)
|
||||||
|
{
|
||||||
|
src[di] = 0d;
|
||||||
|
src[di + 1] = 0d;
|
||||||
|
src[di + 2] = 0d;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
double s = 255d / a;
|
||||||
|
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||||
|
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||||
|
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int half = size / 2;
|
||||||
|
|
||||||
|
fixed (byte* buf = target)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
|
||||||
|
for (int ky = 0; ky < size; ky++)
|
||||||
|
{
|
||||||
|
int sy = Math.Clamp(y + ky - half, 0, height - 1);
|
||||||
|
for (int kx = 0; kx < size; kx++)
|
||||||
|
{
|
||||||
|
int sx = Math.Clamp(x + kx - half, 0, width - 1);
|
||||||
|
double kv = kernel[ky * size + kx];
|
||||||
|
int si = (sy * width + sx) * 4;
|
||||||
|
sr += src[si] * kv;
|
||||||
|
sg += src[si + 1] * kv;
|
||||||
|
sb += src[si + 2] * kv;
|
||||||
|
sa += src[si + 3] * kv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
|
||||||
|
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
|
||||||
|
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
|
||||||
|
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
|
||||||
|
double aK = aa / 255d;
|
||||||
|
byte* p = buf + (y * width + x) * 4;
|
||||||
|
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
|
||||||
|
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
|
||||||
|
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
|
||||||
|
p[3] = (byte)aa;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
|
||||||
|
{
|
||||||
|
int srcCount = sourceWidth * sourceHeight * 4;
|
||||||
|
if (sourceScratch is null || sourceScratch.Length < srcCount)
|
||||||
|
sourceScratch = new byte[srcCount];
|
||||||
|
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
|
||||||
|
|
||||||
|
int dstCount = targetWidth * targetHeight * 4;
|
||||||
|
if (targetScratch is null || targetScratch.Length != dstCount)
|
||||||
|
targetScratch = new byte[dstCount];
|
||||||
|
var src = sourceScratch;
|
||||||
|
var dst = targetScratch;
|
||||||
|
|
||||||
|
fixed (byte* s = src)
|
||||||
|
fixed (byte* d = dst)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < targetHeight; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < targetWidth; x++)
|
||||||
|
{
|
||||||
|
byte* o = d + (y * targetWidth + x) * 4;
|
||||||
|
if (!linear)
|
||||||
|
{
|
||||||
|
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
|
||||||
|
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
|
||||||
|
byte* p = s + (sy * sourceWidth + sx) * 4;
|
||||||
|
o[0] = p[0];
|
||||||
|
o[1] = p[1];
|
||||||
|
o[2] = p[2];
|
||||||
|
o[3] = p[3];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||||
|
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||||
|
int x0 = (int)Math.Floor(u);
|
||||||
|
int y0 = (int)Math.Floor(v);
|
||||||
|
double tx = u - x0;
|
||||||
|
double ty = v - y0;
|
||||||
|
for (int c = 0; c < 4; c++)
|
||||||
|
{
|
||||||
|
double acc = 0d;
|
||||||
|
for (int j = 0; j < 2; j++)
|
||||||
|
{
|
||||||
|
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
|
||||||
|
double wy = j == 0 ? 1d - ty : ty;
|
||||||
|
for (int i = 0; i < 2; i++)
|
||||||
|
{
|
||||||
|
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
|
||||||
|
double wx = i == 0 ? 1d - tx : tx;
|
||||||
|
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine
|
||||||
|
{
|
||||||
|
internal delegate PixelShaderRunStatus PixelShaderInvoke(
|
||||||
|
string name,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error);
|
||||||
|
}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.13.4</Version>
|
<Version>1.20.3</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Gpu" />
|
||||||
<InternalsVisibleTo Include="LuaScript" />
|
<InternalsVisibleTo Include="LuaScript" />
|
||||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -9,5 +9,10 @@ namespace LuaScript
|
|||||||
double Zoom,
|
double Zoom,
|
||||||
double Rz,
|
double Rz,
|
||||||
double Alpha,
|
double Alpha,
|
||||||
int Layer);
|
int Layer,
|
||||||
|
int Length,
|
||||||
|
double Volume,
|
||||||
|
string Character,
|
||||||
|
string Text,
|
||||||
|
string Kind);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal interface IPixelShaderRunner
|
||||||
|
{
|
||||||
|
PixelShaderRunStatus TryRun(
|
||||||
|
string hlsl,
|
||||||
|
string entryPoint,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal readonly record struct PixelShaderBlend(PixelShaderBlendMode Mode, double CompositeBlend)
|
||||||
|
{
|
||||||
|
public static PixelShaderBlend Copy { get; } = new(PixelShaderBlendMode.Copy, 0d);
|
||||||
|
|
||||||
|
public static PixelShaderBlend Mask { get; } = new(PixelShaderBlendMode.Mask, 0d);
|
||||||
|
|
||||||
|
public static PixelShaderBlend Draw { get; } = new(PixelShaderBlendMode.Draw, 0d);
|
||||||
|
|
||||||
|
public static PixelShaderBlend Add { get; } = new(PixelShaderBlendMode.Add, 0d);
|
||||||
|
|
||||||
|
public static PixelShaderBlend Composite(double blend) => new(PixelShaderBlendMode.Composite, blend);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal enum PixelShaderBlendMode
|
||||||
|
{
|
||||||
|
Copy,
|
||||||
|
Mask,
|
||||||
|
Draw,
|
||||||
|
Add,
|
||||||
|
Composite,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal readonly record struct PixelShaderInput(byte[]? Data, int Width, int Height)
|
||||||
|
{
|
||||||
|
public const int RandomSize = 256;
|
||||||
|
|
||||||
|
public static PixelShaderInput Random { get; } = new(null, RandomSize, RandomSize);
|
||||||
|
|
||||||
|
public bool IsRandom => Data is null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal enum PixelShaderRunStatus
|
||||||
|
{
|
||||||
|
Success,
|
||||||
|
Unavailable,
|
||||||
|
CompileError,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal enum PixelShaderSampler
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
Clip,
|
||||||
|
Clamp,
|
||||||
|
Loop,
|
||||||
|
Mirror,
|
||||||
|
Dot,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,35 @@ namespace LuaScript.Tests
|
|||||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NormalizeCount_DefaultsTrackToSinglePoint()
|
||||||
|
{
|
||||||
|
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 0));
|
||||||
|
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, -3));
|
||||||
|
Assert.Equal(4, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 4));
|
||||||
|
Assert.Equal(0, AnchorSupport.NormalizeCount("pos", 0));
|
||||||
|
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.NormalizeCount("pos", 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SetPosition_ReplacesOrAppendsAbsolute()
|
||||||
|
{
|
||||||
|
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||||
|
|
||||||
|
var replaced = AnchorSupport.SetPosition(source, "pos", 2, 1, 2, 3);
|
||||||
|
Assert.Single(replaced);
|
||||||
|
Assert.Equal(1, replaced[0].X);
|
||||||
|
Assert.Equal(2, replaced[0].Y);
|
||||||
|
Assert.Equal(3, replaced[0].Z);
|
||||||
|
|
||||||
|
var appended = AnchorSupport.SetPosition(source, "pos", 5, 7, 8, 9);
|
||||||
|
Assert.Equal(2, appended.Count);
|
||||||
|
Assert.Equal(5, appended[1].Index);
|
||||||
|
Assert.Equal(7, appended[1].X);
|
||||||
|
Assert.Equal(8, appended[1].Y);
|
||||||
|
Assert.Equal(9, appended[1].Z);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ApplyOption_SetsConnectionAndDimension()
|
public void ApplyOption_SetsConnectionAndDimension()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class AviUtlAudioConverterTests
|
||||||
|
{
|
||||||
|
private static float[] Interleave(double[] left, double[] right)
|
||||||
|
{
|
||||||
|
var data = new float[left.Length * 2];
|
||||||
|
for (int i = 0; i < left.Length; i++)
|
||||||
|
{
|
||||||
|
data[i * 2] = (float)left[i];
|
||||||
|
data[i * 2 + 1] = (float)right[i];
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RequiredFrames_MatchesTypeWindows()
|
||||||
|
{
|
||||||
|
Assert.Equal(16, AviUtlAudioConverter.RequiredFrames("pcm", 16));
|
||||||
|
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 0));
|
||||||
|
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 99999));
|
||||||
|
Assert.Equal(AviUtlAudioConverter.SpectrumWindow, AviUtlAudioConverter.RequiredFrames("spectrum", 32));
|
||||||
|
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier", 0));
|
||||||
|
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier.l", 0));
|
||||||
|
Assert.Equal(0, AviUtlAudioConverter.RequiredFrames("unknown", 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pcm_ScalesMonoMixTo16BitRange()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
var data = Interleave([0.5d, -1d, 0d], [0.5d, -1d, 1d]);
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
int count = converter.Convert("pcm", data, 3, 3, dest);
|
||||||
|
|
||||||
|
Assert.Equal(3, count);
|
||||||
|
Assert.Equal(16384d, dest[0]);
|
||||||
|
Assert.Equal(-32768d, dest[1]);
|
||||||
|
Assert.Equal(16384d, dest[2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pcm_SelectsChannelBySuffix()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
var data = Interleave([0.25d, 0.25d], [-0.5d, -0.5d]);
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
converter.Convert("pcm.l", data, 2, 2, dest);
|
||||||
|
Assert.Equal(8192d, dest[0]);
|
||||||
|
|
||||||
|
converter.Convert("pcm.r", data, 2, 2, dest);
|
||||||
|
Assert.Equal(-16384d, dest[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pcm_ReturnsFewerWhenSourceIsShort()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
var data = Interleave([0.1d, 0.2d], [0.1d, 0.2d]);
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
int count = converter.Convert("pcm", data, 2, 100, dest);
|
||||||
|
|
||||||
|
Assert.Equal(2, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Spectrum_PeaksInBandContainingSineFrequency()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
const int frames = AviUtlAudioConverter.SpectrumWindow;
|
||||||
|
const int cycle = 64;
|
||||||
|
var mono = new double[frames];
|
||||||
|
for (int i = 0; i < frames; i++)
|
||||||
|
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||||
|
var data = Interleave(mono, mono);
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
int count = converter.Convert("spectrum", data, frames, 32, dest);
|
||||||
|
|
||||||
|
Assert.Equal(32, count);
|
||||||
|
int expectedBand = cycle * 32 / AviUtlAudioConverter.SpectrumBins;
|
||||||
|
int peakBand = 0;
|
||||||
|
for (int i = 1; i < count; i++)
|
||||||
|
{
|
||||||
|
if (dest[i] > dest[peakBand])
|
||||||
|
peakBand = i;
|
||||||
|
}
|
||||||
|
Assert.Equal(expectedBand, peakBand);
|
||||||
|
Assert.True(dest[peakBand] > 1000d);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Fourier_ReturnsNormalizedMagnitudes()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
const int frames = AviUtlAudioConverter.FourierWindow;
|
||||||
|
const int cycle = 8;
|
||||||
|
var mono = new double[frames];
|
||||||
|
for (int i = 0; i < frames; i++)
|
||||||
|
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||||
|
var data = Interleave(mono, mono);
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
int count = converter.Convert("fourier", data, frames, 0, dest);
|
||||||
|
|
||||||
|
Assert.Equal(AviUtlAudioConverter.MaxSamples, count);
|
||||||
|
int peak = 0;
|
||||||
|
for (int i = 1; i < count; i++)
|
||||||
|
{
|
||||||
|
if (dest[i] > dest[peak])
|
||||||
|
peak = i;
|
||||||
|
}
|
||||||
|
Assert.Equal(cycle - 1, peak);
|
||||||
|
Assert.Equal(1d, dest[peak], 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnknownTypeOrEmptySource_YieldsZero()
|
||||||
|
{
|
||||||
|
var converter = new AviUtlAudioConverter();
|
||||||
|
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||||
|
|
||||||
|
Assert.Equal(0, converter.Convert("waveform", new float[8], 4, 4, dest));
|
||||||
|
Assert.Equal(0, converter.Convert("pcm", [], 0, 4, dest));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class AviUtlPixelShaderLibraryTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Parse_EmptyOrNull_ReturnsEmpty()
|
||||||
|
{
|
||||||
|
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(null).Count);
|
||||||
|
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(string.Empty).Count);
|
||||||
|
Assert.Same(AviUtlPixelShaderLibrary.Empty, AviUtlPixelShaderLibrary.Parse(string.Empty));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_SingleShader_ExtractsBody()
|
||||||
|
{
|
||||||
|
var source = "--[[pixelshader@psmain:\nfloat4 psmain(float4 pos : SV_Position) : SV_Target { return 0; }\n]]\nobj.pixelshader(\"psmain\", \"object\", \"object\")";
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||||
|
|
||||||
|
Assert.Equal(1, library.Count);
|
||||||
|
Assert.True(library.TryGet("psmain", out var hlsl));
|
||||||
|
Assert.Contains("float4 psmain", hlsl);
|
||||||
|
Assert.DoesNotContain("]]", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_MultipleShaders_AllExtracted()
|
||||||
|
{
|
||||||
|
var source = "--[[pixelshader@first:\nA\n]]\ncode\n--[[pixelshader@second:\nB\n]]";
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||||
|
|
||||||
|
Assert.Equal(2, library.Count);
|
||||||
|
Assert.True(library.TryGet("first", out var a));
|
||||||
|
Assert.Equal("\nA\n", a);
|
||||||
|
Assert.True(library.TryGet("second", out var b));
|
||||||
|
Assert.Equal("\nB\n", b);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_NameWithUnderscoreAndDigits_Extracted()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@dithering_z2:\nX\n]]");
|
||||||
|
Assert.True(library.TryGet("dithering_z2", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_LeadingWhitespace_Extracted()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse(" \t--[[pixelshader@ps:\nX\n]]");
|
||||||
|
Assert.True(library.TryGet("ps", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_MarkerNotAtLineStart_Ignored()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("local x = 1 --[[pixelshader@ps:\nX\n]]");
|
||||||
|
Assert.Equal(0, library.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_BodyEndsAtFirstDoubleBracket()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nsrc[a[0]]\n]]");
|
||||||
|
Assert.True(library.TryGet("ps", out var hlsl));
|
||||||
|
Assert.Equal("\nsrc[a[0", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_UnterminatedBlock_Ignored()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nfloat4 ps() : SV_Target { return 0; }");
|
||||||
|
Assert.Equal(0, library.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_MissingColon_Ignored()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps\nX\n]]");
|
||||||
|
Assert.Equal(0, library.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_EmptyName_Ignored()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@:\nX\n]]");
|
||||||
|
Assert.Equal(0, library.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_DuplicateName_FirstDefinitionWins()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nA\n]]\n--[[pixelshader@ps:\nB\n]]");
|
||||||
|
Assert.True(library.TryGet("ps", out var hlsl));
|
||||||
|
Assert.Equal("\nA\n", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_CrlfSource_Extracted()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\r\nX\r\n]]\r\n");
|
||||||
|
Assert.True(library.TryGet("ps", out var hlsl));
|
||||||
|
Assert.Equal("\r\nX\r\n", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_InsideSectionBody_Extracted()
|
||||||
|
{
|
||||||
|
var source = "@通常\n--track@a:A,0,100,0\n--[[pixelshader@ps:\nX\n]]\nobj.pixelshader(\"ps\", \"object\", \"object\")";
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||||
|
Assert.True(library.TryGet("ps", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryGet_CrossScriptName_ResolvesLocalPart()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
|
||||||
|
Assert.True(library.TryGet("ps@OtherScript", out var hlsl));
|
||||||
|
Assert.Equal("\nX\n", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryGet_UnknownOrEmptyName_ReturnsFalse()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
|
||||||
|
Assert.False(library.TryGet("other", out _));
|
||||||
|
Assert.False(library.TryGet(string.Empty, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EntryPointOf_StripsScriptSuffix()
|
||||||
|
{
|
||||||
|
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps@Script"));
|
||||||
|
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_ComputeShaderBlock_Ignored()
|
||||||
|
{
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse("--[[computeshader@cs:\nX\n]]");
|
||||||
|
Assert.Equal(0, library.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class AviUtlScriptShaderTests
|
||||||
|
{
|
||||||
|
private const string ShaderBlock = "--[[pixelshader@ps:\nTexture2D src : register(t0);\nfloat4 ps(float4 pos : SV_Position) : SV_Target\n{\n float4 c = src[uint2(floor(pos.xy))];\n return (c.a != 0.0 && c.r > 0.5) ? c : float4(0, 0, 0, 0);\n}\n]]";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Transform_PreservesShaderBlockVerbatim()
|
||||||
|
{
|
||||||
|
var source = ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")";
|
||||||
|
var transformed = AviUtlScript.Transform(source);
|
||||||
|
|
||||||
|
Assert.Contains(ShaderBlock, transformed.Replace("\r\n", "\n"));
|
||||||
|
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||||
|
Assert.True(library.TryGet("ps", out var hlsl));
|
||||||
|
Assert.Contains("c.a != 0.0 && c.r > 0.5", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Transform_SectionedScript_ShaderStaysInSourceLibrary()
|
||||||
|
{
|
||||||
|
var source = "@main\n--track@a:A,0,100,0\n" + ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")\n@sub\nobj.x = 1";
|
||||||
|
var transformed = AviUtlScript.Transform(source);
|
||||||
|
|
||||||
|
Assert.Contains("obj.pixelshader", transformed);
|
||||||
|
Assert.True(AviUtlPixelShaderLibrary.Parse(source).TryGet("ps", out _));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -133,5 +133,42 @@ namespace LuaScript.Tests
|
|||||||
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
|
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
|
||||||
Assert.Equal(500d * expectedRand / 100d, moved);
|
Assert.Equal(500d * expectedRand / 100d, moved);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChangedLines_EmptyWhenNoRewrite()
|
||||||
|
{
|
||||||
|
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||||
|
Assert.Empty(changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
|
||||||
|
{
|
||||||
|
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||||
|
Assert.Equal(new[] { 2 }, changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
|
||||||
|
{
|
||||||
|
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||||
|
Assert.Equal(new[] { 1, 3, 4 }, changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
|
||||||
|
{
|
||||||
|
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||||
|
Assert.Equal(new[] { 1 }, changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
|
||||||
|
{
|
||||||
|
var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||||
|
Assert.NotEmpty(changed);
|
||||||
|
for (int i = 1; i < changed.Length; i++)
|
||||||
|
Assert.True(changed[i] > changed[i - 1]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,12 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||||
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
|
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
|
||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>128 then o=255 else o=32 end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 elseif v>40 then o=64 end obj.setpixel(x,y,o,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>g then r=g end if b<64 and g>32 then b=g elseif b>192 then b=192 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=0 if r>128 then local r=g*0.5 v=r+1 if v>100 then v=100 end else v=r end obj.setpixel(x,y,v,g,b,a) end end")]
|
||||||
|
[InlineData("local w=obj.w local h=obj.h for y=0,h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/w*255,y/h*255,b,a) end end")]
|
||||||
public void CpuKernelMatchesMoonSharp(string script)
|
public void CpuKernelMatchesMoonSharp(string script)
|
||||||
{
|
{
|
||||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||||
@@ -46,6 +52,9 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
|
||||||
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
|
||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||||
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end obj.putpixeldata(pd)")]
|
||||||
|
[InlineData("local data=obj.getpixeldata() local w=data.width local h=data.height for y=0,h-1 do for x=0,w-1 do local i=(y*w+x)*4 local r=data:get(i+1) local g=data:get(i+2) local b=data:get(i+3) data:set(i+1,g) data:set(i+2,b) data:set(i+3,r) end end obj.putpixeldata(data)")]
|
||||||
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local v=(r+g+b)/3 local o=0 if v>128 then o=255 end pd:set(i+1,o) pd:set(i+2,o) pd:set(i+3,o) end end")]
|
||||||
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
||||||
{
|
{
|
||||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
||||||
@@ -60,6 +69,9 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
|
||||||
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) if r>128 then pd:set(i+1,255) end pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||||
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(other)")]
|
||||||
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(pd) obj.putpixeldata(pd)")]
|
||||||
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
||||||
{
|
{
|
||||||
Assert.Null(KernelExtractor.TryExtract(script));
|
Assert.Null(KernelExtractor.TryExtract(script));
|
||||||
@@ -92,8 +104,12 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
[InlineData("for i=0,10 do end")]
|
[InlineData("for i=0,10 do end")]
|
||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
|
||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then obj.setpixel(x,y,255,g,b,a) end end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then local y=0 r=y end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end obj.putpixeldata(pd)")]
|
||||||
|
[InlineData("local w=5 for y=0,obj.h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
public void NonKernelScriptsAreRejected(string script)
|
public void NonKernelScriptsAreRejected(string script)
|
||||||
{
|
{
|
||||||
Assert.Null(KernelExtractor.TryExtract(script));
|
Assert.Null(KernelExtractor.TryExtract(script));
|
||||||
@@ -178,6 +194,8 @@ namespace LuaScript.Tests
|
|||||||
return DynValue.NewTable(pd);
|
return DynValue.NewTable(pd);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
|
||||||
|
|
||||||
engine.Globals["obj"] = obj;
|
engine.Globals["obj"] = obj;
|
||||||
engine.DoString(script);
|
engine.DoString(script);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,18 @@ namespace LuaScript.Tests
|
|||||||
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ConditionalStatementEmitsTernary()
|
||||||
|
{
|
||||||
|
const string script =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 end " +
|
||||||
|
"obj.setpixel(x,y,o,o,o,a) end end";
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(script));
|
||||||
|
Assert.Contains(" ? (", hlsl);
|
||||||
|
Assert.Contains(" > ", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EmissionIsDeterministic()
|
public void EmissionIsDeterministic()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
|
||||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
|
||||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 else o=r end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||||
public void SimdBlockMatchesScalarRow(string script)
|
public void SimdBlockMatchesScalarRow(string script)
|
||||||
{
|
{
|
||||||
var program = KernelExtractor.TryExtract(script);
|
var program = KernelExtractor.TryExtract(script);
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
|
|||||||
"repeat", "return", "then", "true", "until", "while"
|
"repeat", "return", "then", "true", "until", "while"
|
||||||
];
|
];
|
||||||
|
|
||||||
|
private static readonly string[] SyntaxKeywords = ["fast"];
|
||||||
|
|
||||||
private static readonly string[] Globals =
|
private static readonly string[] Globals =
|
||||||
[
|
[
|
||||||
"time", "frame", "totalframe", "framerate",
|
"time", "frame", "totalframe", "framerate",
|
||||||
@@ -47,8 +49,10 @@ namespace LuaScript.Tests
|
|||||||
"obj.getobject", "obj.getpixel", "obj.setpixel",
|
"obj.getobject", "obj.getpixel", "obj.setpixel",
|
||||||
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
||||||
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
||||||
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
"obj.pixelshader",
|
||||||
"obj.setanchor", "obj.effect", "obj.getinfo"
|
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||||
|
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
|
||||||
|
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
|
||||||
]),
|
]),
|
||||||
("math", [
|
("math", [
|
||||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||||
@@ -102,6 +106,7 @@ namespace LuaScript.Tests
|
|||||||
|
|
||||||
private static string[] ExpectedStaticCandidates() =>
|
private static string[] ExpectedStaticCandidates() =>
|
||||||
Keywords
|
Keywords
|
||||||
|
.Concat(SyntaxKeywords)
|
||||||
.Concat(Globals)
|
.Concat(Globals)
|
||||||
.Concat(Namespaces.SelectMany(n => n.Members))
|
.Concat(Namespaces.SelectMany(n => n.Members))
|
||||||
.Distinct()
|
.Distinct()
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
using LuaScript;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class LuaScriptEngineBufferOpsTests
|
||||||
|
{
|
||||||
|
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||||
|
{
|
||||||
|
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] DecodeImage(string path, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||||
|
|
||||||
|
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
|
||||||
|
{
|
||||||
|
var ctx = new AviUtlScriptContext { Framerate = 30 };
|
||||||
|
ctx.SetResolvedBuffer(buffer, width, height);
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
|
||||||
|
{
|
||||||
|
var buffer = new byte[pixels.Length * 4];
|
||||||
|
for (int i = 0; i < pixels.Length; i++)
|
||||||
|
{
|
||||||
|
buffer[i * 4 + 0] = pixels[i].B;
|
||||||
|
buffer[i * 4 + 1] = pixels[i].G;
|
||||||
|
buffer[i * 4 + 2] = pixels[i].R;
|
||||||
|
buffer[i * 4 + 3] = pixels[i].A;
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||||
|
|
||||||
|
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
|
||||||
|
|
||||||
|
var buffer = ctx.GetPixelBuffer()!;
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
Assert.Equal(50, buffer[i * 4 + 0]);
|
||||||
|
Assert.Equal(100, buffer[i * 4 + 1]);
|
||||||
|
Assert.Equal(200, buffer[i * 4 + 2]);
|
||||||
|
Assert.Equal(255, buffer[i * 4 + 3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
|
||||||
|
|
||||||
|
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
|
||||||
|
|
||||||
|
var buffer = ctx.GetPixelBuffer()!;
|
||||||
|
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
|
||||||
|
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||||
|
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetPixelRegion_ReturnsStraightRgba()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
|
||||||
|
|
||||||
|
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
|
||||||
|
|
||||||
|
Assert.Equal(200d, ctx.X);
|
||||||
|
Assert.Equal(100d, ctx.Y);
|
||||||
|
Assert.Equal(50d, ctx.Z);
|
||||||
|
Assert.Equal(255d, ctx.Alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
|
||||||
|
|
||||||
|
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
|
||||||
|
|
||||||
|
Assert.Equal(0d, ctx.X);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PutPixelRegion_WritesPremultipliedColor()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
|
||||||
|
|
||||||
|
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
|
||||||
|
|
||||||
|
var buffer = ctx.GetPixelBuffer()!;
|
||||||
|
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
|
||||||
|
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||||
|
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||||
|
|
||||||
|
engine.Execute(
|
||||||
|
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||||
|
ctx);
|
||||||
|
|
||||||
|
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||||
|
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||||
|
|
||||||
|
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
|
||||||
|
|
||||||
|
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
|
||||||
|
|
||||||
|
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
|
||||||
|
|
||||||
|
var buffer = ctx.GetPixelBuffer()!;
|
||||||
|
Assert.Equal(85, buffer[2]);
|
||||||
|
Assert.Equal(85, buffer[1]);
|
||||||
|
Assert.Equal(85, buffer[0]);
|
||||||
|
Assert.Equal(170, buffer[6]);
|
||||||
|
Assert.Equal(255, buffer[3]);
|
||||||
|
Assert.Equal(255, buffer[7]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resize_Nearest_ReplicatesBlocks()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
|
||||||
|
|
||||||
|
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
|
||||||
|
|
||||||
|
Assert.Equal(4, ctx.ImageWidth);
|
||||||
|
Assert.Equal(4, ctx.ImageHeight);
|
||||||
|
Assert.True(ctx.BufferReplaced);
|
||||||
|
|
||||||
|
var buffer = ctx.GetPixelBuffer()!;
|
||||||
|
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
|
||||||
|
Assert.Equal(13, SampleR(0, 0));
|
||||||
|
Assert.Equal(13, SampleR(1, 1));
|
||||||
|
Assert.Equal(23, SampleR(2, 0));
|
||||||
|
Assert.Equal(33, SampleR(0, 2));
|
||||||
|
Assert.Equal(43, SampleR(3, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resize_UpdatesObjDimensions()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
|
||||||
|
|
||||||
|
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
|
||||||
|
|
||||||
|
Assert.Equal(8, ctx.ImageWidth);
|
||||||
|
Assert.Equal(2, ctx.ImageHeight);
|
||||||
|
Assert.Equal(8d, ctx.X);
|
||||||
|
Assert.Equal(2d, ctx.Y);
|
||||||
|
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
using LuaScript;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class LuaScriptEngineGetAudioTests
|
||||||
|
{
|
||||||
|
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||||
|
{
|
||||||
|
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] DecodeImage(string path, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||||
|
|
||||||
|
private static AviUtlScriptContext NewContext()
|
||||||
|
{
|
||||||
|
return new AviUtlScriptContext
|
||||||
|
{
|
||||||
|
ImageWidth = 2,
|
||||||
|
ImageHeight = 2,
|
||||||
|
Framerate = 30,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAudio_FillsBufferTableFromLoader()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext();
|
||||||
|
|
||||||
|
string? capturedFile = null;
|
||||||
|
string? capturedType = null;
|
||||||
|
int capturedSize = -1;
|
||||||
|
ctx.AudioLoader = (file, type, size) =>
|
||||||
|
{
|
||||||
|
capturedFile = file;
|
||||||
|
capturedType = type;
|
||||||
|
capturedSize = size;
|
||||||
|
return (3, 44100, [1.5d, -2.5d, 3d]);
|
||||||
|
};
|
||||||
|
|
||||||
|
engine.Execute(
|
||||||
|
"local buf = {}\n" +
|
||||||
|
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 3)\n" +
|
||||||
|
"obj.x = n\n" +
|
||||||
|
"obj.y = rate\n" +
|
||||||
|
"obj.z = buf[1]\n" +
|
||||||
|
"obj.ox = buf[2]\n" +
|
||||||
|
"obj.oy = buf[3]",
|
||||||
|
ctx);
|
||||||
|
|
||||||
|
Assert.Equal("audiobuffer", capturedFile);
|
||||||
|
Assert.Equal("pcm", capturedType);
|
||||||
|
Assert.Equal(3, capturedSize);
|
||||||
|
Assert.Equal(3d, ctx.X);
|
||||||
|
Assert.Equal(44100d, ctx.Y);
|
||||||
|
Assert.Equal(1.5d, ctx.Z);
|
||||||
|
Assert.Equal(-2.5d, ctx.Ox);
|
||||||
|
Assert.Equal(3d, ctx.Oy);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAudio_NilBuffer_ReturnsTableAsThirdValue()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext();
|
||||||
|
|
||||||
|
ctx.AudioLoader = (_, type, _) => (2, 48000, [7d, 8d]);
|
||||||
|
|
||||||
|
engine.Execute(
|
||||||
|
"local n, rate, buf = obj.getaudio(nil, 'C:/test.wav', 'spectrum.r', 2)\n" +
|
||||||
|
"obj.x = n\n" +
|
||||||
|
"obj.y = rate\n" +
|
||||||
|
"obj.z = buf[1]\n" +
|
||||||
|
"obj.ox = buf[2]",
|
||||||
|
ctx);
|
||||||
|
|
||||||
|
Assert.Equal(2d, ctx.X);
|
||||||
|
Assert.Equal(48000d, ctx.Y);
|
||||||
|
Assert.Equal(7d, ctx.Z);
|
||||||
|
Assert.Equal(8d, ctx.Ox);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAudio_DefaultsTypeToPcm()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext();
|
||||||
|
|
||||||
|
string? capturedType = null;
|
||||||
|
int capturedSize = -1;
|
||||||
|
ctx.AudioLoader = (_, type, size) =>
|
||||||
|
{
|
||||||
|
capturedType = type;
|
||||||
|
capturedSize = size;
|
||||||
|
return (0, 48000, []);
|
||||||
|
};
|
||||||
|
|
||||||
|
engine.Execute("obj.x = obj.getaudio({}, 'audiobuffer')", ctx);
|
||||||
|
|
||||||
|
Assert.Equal("pcm", capturedType);
|
||||||
|
Assert.Equal(0, capturedSize);
|
||||||
|
Assert.Equal(0d, ctx.X);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAudio_WithoutLoader_ReturnsZero()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext();
|
||||||
|
|
||||||
|
engine.Execute(
|
||||||
|
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||||
|
"obj.x = n\n" +
|
||||||
|
"obj.y = rate\n" +
|
||||||
|
"obj.z = #buf\n" +
|
||||||
|
"obj.ox = obj.getaudio({}, 7)",
|
||||||
|
ctx);
|
||||||
|
|
||||||
|
Assert.Equal(0d, ctx.X);
|
||||||
|
Assert.Equal(0d, ctx.Y);
|
||||||
|
Assert.Equal(0d, ctx.Z);
|
||||||
|
Assert.Equal(0d, ctx.Ox);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAudio_ClampsCountToDataLength()
|
||||||
|
{
|
||||||
|
using var engine = CreateEngine();
|
||||||
|
var ctx = NewContext();
|
||||||
|
|
||||||
|
ctx.AudioLoader = (_, _, _) => (10, 48000, [5d]);
|
||||||
|
|
||||||
|
engine.Execute(
|
||||||
|
"local n, _, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 10)\n" +
|
||||||
|
"obj.x = n\n" +
|
||||||
|
"obj.y = #buf",
|
||||||
|
ctx);
|
||||||
|
|
||||||
|
Assert.Equal(1d, ctx.X);
|
||||||
|
Assert.Equal(1d, ctx.Y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
149ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする