LuaJIT画像処理をGPU委譲

このコミットが含まれているのは:
routersys committed 2026-07-05 11:19:28 +09:00
1 親 b732dd1b90
コミット 406a4c1a1b
5ファイル変更
+316 -3

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

+98 -2
ファイルの表示
@@ -44,6 +44,8 @@ namespace LuaScript.Engine
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;
@@ -81,6 +83,7 @@ namespace LuaScript.Engine
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor,
out bool pixelsDirty,
out bool bufferReplaced,
out int resultWidth,
@@ -124,6 +127,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
@@ -164,7 +168,7 @@ namespace LuaScript.Engine
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader);
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
}
_workEvent.Set();
}
@@ -332,7 +336,8 @@ namespace LuaScript.Engine
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader)
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
@@ -382,9 +387,100 @@ namespace LuaScript.Engine
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);
processed = operation switch
{
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength),
_ => 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)
{
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))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
{
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))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength)
{
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) || 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);
+5
ファイルの表示
@@ -67,6 +67,11 @@ namespace LuaScript.Engine
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 DrawEntryDoubles = 24;
+133
ファイルの表示
@@ -28,6 +28,7 @@ namespace LuaScript.Tests
private Action<string, SceneValue> _sceneSet = (_, _) => { };
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
private PixelShaderInvoke? _runPixelShader;
private IPixelBufferProcessor? _pixelProcessor;
public void Dispose() => _worker.Dispose();
@@ -77,6 +78,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet,
_loadAudio,
_runPixelShader,
_pixelProcessor,
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
resultPixels = null;
@@ -114,6 +116,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet,
_loadAudio,
_runPixelShader,
null,
out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -1905,6 +1908,85 @@ namespace LuaScript.Tests
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
[Fact]
public void PixelProcess_Fill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 1024, h = 1024;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_Convolve_PassesKernelToHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 200, h = 200;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.Equal(0x42, pixels[0]);
Assert.Equal(0x42, pixels[^1]);
}
[Fact]
public void PixelProcess_Resize_ReplacesBufferWithHostResult()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.resize(512, 512, 'nearest') obj.x = obj.w obj.y = obj.h",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool replaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(replaced);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
Assert.Equal(512d, processor.TargetWidth);
Assert.Equal(512d, processor.TargetHeight);
Assert.False(processor.Linear);
Assert.Equal(512d, fields[NativeProtocol.X]);
Assert.Equal(512d, fields[NativeProtocol.Y]);
Assert.NotNull(result);
Assert.Equal(0x43, result![0]);
Assert.Equal(0x43, result[^1]);
}
[Fact]
public void Fill_WritesPremultipliedColor()
{
@@ -2116,5 +2198,56 @@ namespace LuaScript.Tests
Assert.Equal(2d, fields[NativeProtocol.Y]);
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
}
private sealed class RecordingPixelProcessor : IPixelBufferProcessor
{
public bool FillResult { get; init; }
public bool ConvolveResult { get; init; }
public bool ResizeResult { get; init; }
public int FillCalls { get; private set; }
public int ConvolveCalls { get; private set; }
public int Size { get; private set; }
public double Divisor { get; private set; }
public double Offset { get; private set; }
public double[] Kernel { get; private set; } = [];
public int TargetWidth { get; private set; }
public int TargetHeight { get; private set; }
public bool Linear { get; private set; }
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
FillCalls++;
if (!FillResult)
return false;
Array.Fill(target, (byte)0x41, 0, width * height * 4);
return true;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
ConvolveCalls++;
Size = size;
Divisor = divisor;
Offset = offset;
Kernel = kernel.AsSpan(0, size * size).ToArray();
if (!ConvolveResult)
return false;
Array.Fill(target, (byte)0x42, 0, width * height * 4);
return true;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
TargetWidth = targetWidth;
TargetHeight = targetHeight;
Linear = linear;
target = null;
if (!ResizeResult)
return false;
target = new byte[targetWidth * targetHeight * 4];
Array.Fill(target, (byte)0x43);
return true;
}
}
}
}
+1
ファイルの表示
@@ -1079,6 +1079,7 @@ namespace LuaScript
_nativeSceneSet,
_loadAudio,
_nativeRunPixelShader,
_pixelProcessor,
out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error);
+79 -1
ファイルの表示
@@ -99,6 +99,14 @@ local CB_KIND_LOADSCENE = 15
local CB_KIND_LOADBRUSH = 16
local CB_KIND_BRUSH = 17
local CB_KIND_GETAUDIO = 18
local CB_KIND_PIXELPROCESS = 19
local PIXEL_PROCESS_FILL = 0
local PIXEL_PROCESS_CONVOLVE = 1
local PIXEL_PROCESS_RESIZE = 2
local PIXEL_PROCESS_FILL_FULL_THRESHOLD = 1048576
local PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD = 1048576
local PIXEL_PROCESS_RESIZE_THRESHOLD = 262144
local PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD = 262144
local MAX_PIXEL_BUFFER = 3840 * 2160 * 4
local SHADER_META_DOUBLES = 20
local SHADER_CONSTANTS_MAX = 1024
@@ -134,6 +142,7 @@ local drawTarget = "frame"
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
local convSrcData, convSrcCap = nil, 0
local resizeSrcData, resizeSrcCap = nil, 0
local pixelProcessAvailable = true
local function ensurePixels()
if pixelsValid then return end
@@ -151,6 +160,19 @@ local function flushDraws()
k32.WaitForSingleObject(workEvent, INFINITE)
end
local function tryPixelProcess(kind)
if not pixelProcessAvailable then return false end
cbResult[0] = kind
i32[OFF_CB_FOUND] = 0
i32[OFF_CB_KIND] = CB_KIND_PIXELPROCESS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local found = i32[OFF_CB_FOUND]
if found < 0 then pixelProcessAvailable = false end
return found == 1
end
local function ringSlot(kind)
local n = ringD[0]
if n >= DRAW_RING_CAPACITY then
@@ -853,6 +875,29 @@ function obj.fill(r, g, b, a, x, y, w, h)
local x1 = clamp(x + w, 0, width)
local y1 = clamp(y + h, 0, height)
if x1 <= x0 or y1 <= y0 then return end
local imageArea = width * height
local fillArea = (x1 - x0) * (y1 - y0)
local fullFill = x0 == 0 and y0 == 0 and x1 == width and y1 == height
local usePixelProcess = false
if fullFill then
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_FULL_THRESHOLD
else
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD and fillArea * 4 >= imageArea * 3
end
cbResult[1] = r
cbResult[2] = g
cbResult[3] = b
cbResult[4] = a
cbResult[5] = x0
cbResult[6] = y0
cbResult[7] = x1 - x0
cbResult[8] = y1 - y0
if usePixelProcess and tryPixelProcess(PIXEL_PROCESS_FILL) then
dirty = true
pdValid = false
pdDirty = false
return
end
local aK = clamp(a, 0, 255) / 255
local pb = math.floor(clamp(b * aK, 0, 255))
local pg = math.floor(clamp(g * aK, 0, 255))
@@ -946,6 +991,21 @@ function obj.convolve(kernel, size, divisor, offset)
local inv = divisor or sum
if inv == 0 then inv = 1 end
offset = offset or 0
if taps * 8 <= CB_TAG_MAX and width * height * taps >= PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD then
cbResult[1] = size
cbResult[2] = inv
cbResult[3] = offset
for i = 1, taps do
cbTagD[i - 1] = k[i]
end
i32[OFF_CB_TAGLEN] = taps * 8
if tryPixelProcess(PIXEL_PROCESS_CONVOLVE) then
dirty = true
pdValid = false
pdDirty = false
return
end
end
local total = width * height * 4
if not convSrcData or convSrcCap < total then
convSrcData = ffi.new("double[?]", total)
@@ -1007,6 +1067,24 @@ function obj.resize(newW, newH, mode)
ensurePixels()
flushPixelData()
local cw, ch = width, height
local linear = mode ~= "nearest"
cbResult[1] = newW
cbResult[2] = newH
cbResult[3] = linear and 1 or 0
if newW * newH >= PIXEL_PROCESS_RESIZE_THRESHOLD and tryPixelProcess(PIXEL_PROCESS_RESIZE) then
width = newW; height = newH
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
return
end
local srcCount = cw * ch * 4
if not resizeSrcData or resizeSrcCap < srcCount then
resizeSrcData = ffi.new("uint8_t[?]", srcCount)
@@ -1014,7 +1092,6 @@ function obj.resize(newW, newH, mode)
end
ffi.copy(resizeSrcData, pixels, srcCount)
local src = resizeSrcData
local linear = mode ~= "nearest"
for y = 0, newH - 1 do
for x = 0, newW - 1 do
local o = pixels + (y * newW + x) * 4
@@ -1477,6 +1554,7 @@ while true do
pixelsValid = false
pdValid = false
pdDirty = false
pixelProcessAvailable = i32[OFF_CB_FOUND] > 0
frameBufferValid = false
ringD[0] = 0
local version = i32[OFF_SCRIPT_VERSION]