using LuaScript.Anchor; using LuaScript.Compat; namespace LuaScript { internal sealed class AviUtlScriptContext { public IReadOnlyList? AnchorSource { get; set; } private readonly List _anchorRequests = []; public IReadOnlyList AnchorRequests => _anchorRequests; internal void AddAnchorRequest(in AnchorRequestData request) => _anchorRequests.Add(request); internal void ClearAnchorRequests() => _anchorRequests.Clear(); public bool IsPlaying { get; set; } public bool IsPaused { get; set; } public string SceneId { get; set; } = string.Empty; public int ImageWidth { get; set; } public int ImageHeight { get; set; } public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public double Ox { get; set; } public double Oy { get; set; } public double Oz { get; set; } public double Sx { get; set; } public double Sy { get; set; } public double Zoom { get; set; } public double Aspect { get; set; } public double Alpha { get; set; } public double Rx { get; set; } public double Ry { get; set; } public double Rz { get; set; } public double Track0 { get; set; } public double Track1 { get; set; } public double Track2 { get; set; } public double Track3 { get; set; } public double Slider0 { get; set; } public double Slider1 { get; set; } public double Slider2 { get; set; } public double Slider3 { get; set; } public bool Check0 { get; set; } public bool Check1 { get; set; } public bool Check2 { get; set; } public bool Check3 { get; set; } public bool HasColor { get; set; } public double ColorValue { get; set; } public bool? DrawStateOverride { get; set; } public double Time { get; set; } public int Frame { get; set; } public int TotalFrame { get; set; } public double TotalTime { get; set; } public int Framerate { get; set; } public int TimelineFrame { get; set; } public double TimelineTime { get; set; } public int SceneWidth { get; set; } public int SceneHeight { get; set; } public int Layer { get; set; } public int Index { get; set; } public int Num { get; set; } public Func? ResolverProvider { get; set; } public Func? SceneImageLoader { get; set; } public Func>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; } public Func? AudioLoader { get; set; } private readonly Dictionary _stringParameters = new(StringComparer.Ordinal); public IReadOnlyDictionary StringParameters => _stringParameters; internal void SetStringParameter(string name, string? value) => _stringParameters[name] = value ?? string.Empty; private const double Epsilon = 1e-10; private readonly List _objectQueries = []; public IReadOnlyList ObjectQueries => _objectQueries; private readonly SceneValueSession _sceneValues = new(); public IReadOnlyList SceneValueQueries => _sceneValues.Queries; internal object? SceneScope { get; set; } internal void BeginSceneValues() => _sceneValues.Begin(SceneScope ?? this, SceneId, TimelineFrame, Layer); internal void PublishSceneValues() => _sceneValues.Publish(); public SceneValue GetSceneValue(string name) => _sceneValues.Get(name); public void SetSceneValue(string name, SceneValue value) => _sceneValues.Set(name, value); private readonly List _effectRequests = []; public IReadOnlyList EffectRequests => _effectRequests; internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request); internal void ClearEffects() => _effectRequests.Clear(); internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance; private readonly List _drawCommands = []; public IReadOnlyList DrawCommands => _drawCommands; internal void AddDraw(DrawCommand command) => _drawCommands.Add(command); internal void ClearDraws() => _drawCommands.Clear(); private bool _drawTargetTemp; internal void ResetDrawTarget() => _drawTargetTemp = false; internal void SetDrawTarget(bool temp, int width, int height, bool hasSize) { _drawTargetTemp = temp; if (temp && hasSize) { int w = Math.Max(1, width); int h = Math.Max(1, height); _buffers["t"] = (new byte[w * h * 4], w, h); } } internal void SubmitDraw(DrawCommand command) { if (!_drawTargetTemp) { _drawCommands.Add(command); return; } CompositeToTemp(command); } private void CompositeToTemp(DrawCommand command) { EnsurePixelBuffer(); var src = _pixelBuffer; if (src is null) return; if (!_buffers.TryGetValue("t", out var temp)) { int w = Math.Max(1, ImageWidth); int h = Math.Max(1, ImageHeight); temp = (new byte[w * h * 4], w, h); _buffers["t"] = temp; } Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command with { Blend = 0d }); } private readonly Dictionary _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) { if (!TryReadBuffer(src, out var data, out int w, out int h)) return false; return TryWriteBuffer(dst, data, w, h); } private bool TryReadBuffer(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)) { data = stored.Data; width = stored.Width; height = stored.Height; return true; } return false; case 'f': GetFrameBuffer(out data, out width, out height); return true; default: 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) { int n = width * height * 4; switch (BufferKind(id, out string key)) { case 'o': if (_copyOutputBuffer is null || _copyOutputBuffer.Length != n) _copyOutputBuffer = new byte[n]; Buffer.BlockCopy(data, 0, _copyOutputBuffer, 0, n); ReplaceBuffer(_copyOutputBuffer, width, height); return true; case 't': case 'c': if (!_buffers.TryGetValue(key, out var existing) || existing.Data.Length != n) existing.Data = new byte[n]; Buffer.BlockCopy(data, 0, existing.Data, 0, n); _buffers[key] = (existing.Data, width, height); return false; default: return false; } } private byte[]? _copyOutputBuffer; private static char BufferKind(string id, out string key) { key = string.Empty; int i = 0; while (i < id.Length && (id[i] == ' ' || id[i] == '\t')) i++; if (i >= id.Length) return '\0'; char kind = char.ToLowerInvariant(id[i]); if (kind == 't') key = "t"; else if (kind == 'c') { int colon = id.IndexOf(':', i); key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c"; } return kind; } public double RxRad => Rx * Math.PI / 180d; public double RyRad => Ry * Math.PI / 180d; public double RzRad => Rz * Math.PI / 180d; public int GroupIndex { get; set; } public int GroupCount { get; set; } public int TimelineTotalFrame { get; set; } public double TimelineTotalTime { get; set; } public bool IsSaving { get; set; } public double TimeRatio { get; set; } public string ScriptPath { get; set; } = string.Empty; public double HostVersion { get; set; } public double Bpm { get; set; } public int BpmBeat { get; set; } public double BpmOffset { get; set; } private Func? _pixelLoader; private byte[]? _pixelBuffer; private bool _pixelBufferLoaded; private bool _isPixelsDirty; private bool _bufferReplaced; public bool IsPixelsDirty => _isPixelsDirty; public bool BufferReplaced => _bufferReplaced; internal int TotalChannels => ImageWidth * ImageHeight * 4; internal void ClearQueries() => _objectQueries.Clear(); internal void SetPixelLoader(Func loader) { _pixelLoader = loader; _pixelBuffer = null; _pixelBufferLoaded = false; _isPixelsDirty = false; _bufferReplaced = false; } internal void ReplaceBuffer(byte[] buffer, int width, int height) { _pixelBuffer = buffer; _pixelBufferLoaded = true; _isPixelsDirty = true; _bufferReplaced = true; ImageWidth = width; ImageHeight = height; } internal void EnsurePixelBuffer() { if (_pixelBufferLoaded) return; _pixelBuffer = _pixelLoader?.Invoke(); _pixelBufferLoaded = true; } internal void SetResolvedBuffer(byte[] buffer, int width, int height) { _pixelBuffer = buffer; _pixelBufferLoaded = true; ImageWidth = width; ImageHeight = height; } internal byte[]? GetPixelBuffer() => _pixelBuffer; internal void MarkPixelsDirty() => _isPixelsDirty = true; public bool ResolveObject(string tag, int frame, out SceneObjectInfo info) { var resolver = ResolverProvider?.Invoke(); if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved)) { _objectQueries.Add(new SceneObjectQuery(tag, frame, resolved)); info = resolved; return true; } _objectQueries.Add(new SceneObjectQuery(tag, frame, null)); info = default; return false; } public void ApplyWriteBack( double newSx, double newSy, double newZoom, double newAspect, double newRx, double newRy, double newRz, double newRxr, double newRyr, double newRzr) { double initialSx = Sx; double initialSy = Sy; double initialZoom = Zoom; double initialAspect = Aspect; Sx = newSx; Sy = newSy; Zoom = newZoom; Aspect = newAspect; bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon; bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon; if (zoomAspectChanged && !sxsyChanged) { Sx = Zoom * (1.0 + Aspect); Sy = Zoom * (1.0 - Aspect); } double initialRxr = RxRad; Rx = Math.Abs(newRxr - initialRxr) > Epsilon ? newRxr * (180d / Math.PI) : newRx; double initialRyr = RyRad; Ry = Math.Abs(newRyr - initialRyr) > Epsilon ? newRyr * (180d / Math.PI) : newRy; double initialRzr = RzRad; Rz = Math.Abs(newRzr - initialRzr) > Epsilon ? newRzr * (180d / Math.PI) : newRz; } public unsafe (double r, double g, double b, double a) GetPixel(int x, int y) { EnsurePixelBuffer(); if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight) return (0d, 0d, 0d, 0d); fixed (byte* buf = _pixelBuffer) { byte* p = buf + (y * ImageWidth + x) * 4; double a = p[3]; if (a <= 0d) return (0d, 0d, 0d, 0d); double scale = 255d / a; return ( Math.Clamp(p[2] * scale, 0d, 255d), Math.Clamp(p[1] * scale, 0d, 255d), Math.Clamp(p[0] * scale, 0d, 255d), a ); } } public unsafe void SetPixel(int x, int y, double r, double g, double b, double a = 255d) { EnsurePixelBuffer(); if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight) return; _isPixelsDirty = true; double aK = Math.Clamp(a, 0d, 255d) / 255d; fixed (byte* buf = _pixelBuffer) { byte* p = buf + (y * ImageWidth + x) * 4; p[0] = (byte)Math.Clamp(b * aK, 0d, 255d); p[1] = (byte)Math.Clamp(g * aK, 0d, 255d); p[2] = (byte)Math.Clamp(r * aK, 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) { 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) == true) { _isPixelsDirty = true; return; } _isPixelsDirty = true; 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); fixed (byte* buf = _pixelBuffer) { for (int py = y0; py < y1; py++) { byte* p = buf + (py * cw + x0) * 4; for (int px = x0; px < x1; px++) { p[0] = pb; p[1] = pg; p[2] = pr; p[3] = pa; p += 4; } } } } 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) { EnsurePixelBuffer(); if (_pixelBuffer is null) return; int cw = ImageWidth; int ch = ImageHeight; if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset) == true) { _isPixelsDirty = true; return; } int count = cw * ch * 4; if (_convolveSource is null || _convolveSource.Length < count) _convolveSource = new double[count]; var src = _convolveSource; fixed (byte* buf = _pixelBuffer) { for (int pi = 0; pi < cw * ch; 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; _isPixelsDirty = true; fixed (byte* buf = _pixelBuffer) { for (int y = 0; y < ch; y++) { for (int x = 0; x < cw; 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, ch - 1); for (int kx = 0; kx < size; kx++) { int sx = Math.Clamp(x + kx - half, 0, cw - 1); double kv = kernel[ky * size + kx]; int si = (sy * cw + 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 * cw + 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 unsafe void Resize(int newWidth, int newHeight, bool linear) { 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) == true && processed is not null) { ReplaceBuffer(processed, newWidth, newHeight); return; } int srcCount = cw * ch * 4; if (_resizeSource is null || _resizeSource.Length < srcCount) _resizeSource = new byte[srcCount]; Buffer.BlockCopy(_pixelBuffer, 0, _resizeSource, 0, srcCount); int dstCount = newWidth * newHeight * 4; if (_resizeBuffer is null || _resizeBuffer.Length != dstCount) _resizeBuffer = new byte[dstCount]; var src = _resizeSource; var dst = _resizeBuffer; fixed (byte* s = src) fixed (byte* d = dst) { for (int y = 0; y < newHeight; y++) { for (int x = 0; x < newWidth; x++) { byte* o = d + (y * newWidth + x) * 4; if (!linear) { int sx = Math.Clamp((int)((x + 0.5) * cw / newWidth), 0, cw - 1); int sy = Math.Clamp((int)((y + 0.5) * ch / newHeight), 0, ch - 1); byte* p = s + (sy * cw + sx) * 4; o[0] = p[0]; o[1] = p[1]; o[2] = p[2]; o[3] = p[3]; } else { double u = (x + 0.5) * cw / newWidth - 0.5; double v = (y + 0.5) * ch / newHeight - 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, ch - 1); double wy = j == 0 ? 1d - ty : ty; for (int i = 0; i < 2; i++) { int sx = Math.Clamp(x0 + i, 0, cw - 1); double wx = i == 0 ? 1d - tx : tx; acc += s[(sy * cw + sx) * 4 + c] * wy * wx; } } o[c] = (byte)Math.Clamp(acc, 0d, 255d); } } } } } ReplaceBuffer(dst, newWidth, newHeight); } } }