- About the Lua Script Effect - The "Lua Script" video effect in YukkuriMovieMaker4 uses the Lua language for scripting. Scripts run on the bundled fast runtime (LuaJIT), and fall back to MoonSharp (Lua 5.2 compatible) when the runtime is unavailable. * This effect is a custom implementation and differs from the AviUtl2 script specification. * This is a separate specification from AviUtl2 script files (*.anm2, etc.). * Since IsAviUtlSupported = false, EXO output for AviUtl is not supported. - Notes - o The script execution engines are LuaJIT (default) and MoonSharp (Lua 5.2 compatible). o Available standard libraries are limited to the following: table, string, math, bit32 * io, os, debug, ffi, require, etc. are not available. o Script timeout is 5000ms (5 seconds). On timeout, execution is forcibly terminated and treated as an error. o Scripts cannot access the file system (including require). o Calling external scripts from within a script is not supported. o Pixel operations (getpixel/setpixel/getpixeldata) access the actual input image, so a GPU->CPU data transfer occurs only on the first access. Omitting these calls when unnecessary will speed up processing. - Execution Engines and Automatic Acceleration - Scripts are analyzed and automatically routed to the best engine. Scripts without a directive run on the bundled fast runtime (LuaJIT), and self-contained per-pixel maps are further compiled to the even faster CPU kernel. Either way the results match MoonSharp. o Automatic routing (when no directive is present) - A self-contained per-pixel map (see conditions below) -> CPU kernel (fast, exact) - Everything else -> Native (LuaJIT, only when deployed) - Native not deployed, or an empty script -> MoonSharp o Engine directives (a comment on the first line of the script) --!cpu : CPU kernel. Compiled at runtime to an expression tree and run in parallel on all CPU cores (bit-identical to MoonSharp). --!gpu : GPU kernel. Run as a Direct2D pixel shader, eliminating the GPU->CPU transfer for top speed. Results may differ slightly due to float32 precision (opt-in). --!native : LuaJIT (separate process). Fast and identical to MoonSharp. Requires the native folder deployed. --!moonsharp : Forces the classic MoonSharp engine. * If a directive is unavailable or unsupported, it automatically falls back to a lower engine (the output is never broken). o Syntax eligible for the fast kernel (a pure per-pixel map) Only a nested loop of the following form becomes a kernel. 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, r2, g2, b2 [, a2]) end end The following form using getpixeldata becomes a kernel as well. local data = obj.getpixeldata() for y = 0, data.height - 1 do for x = 0, data.width - 1 do local i = (y * data.width + x) * 4 local r = data:get(i + 1) data:set(i + 1, r2) data:set(i + 2, g2) data:set(i + 3, b2) end end obj.putpixeldata(data) - The body may use only arithmetic, math.*, comparisons, the threshold idiom "cond and value1 or value2", conditional assignment to local variables via if/elseif/else, and local variables. - Loop bounds may also use aliases such as local w = obj.w. - It may reference only the current pixel being processed and values such as obj/scene/time. - Anything using neighbor sampling (blur, etc.), writes to other coordinates, setpixel or set calls inside an if statement, getobject, or table/string operations is not turned into a kernel and automatically runs on the classic engine. Example (turns a white figure red): --!gpu 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 / 2, b / 2, a) end end - Parameters - The effect panel has 4 trackbars (animation-enabled) as follows. Each value can be referenced in the script as obj.track0 through obj.track3. Track0 : Parameter 0 (Default: 0, Range: Min ~ Max) Track1 : Parameter 1 (Default: 0, Range: Min ~ Max) Track2 : Parameter 2 (Default: 0, Range: Min ~ Max) Track3 : Parameter 3 (Default: 0, Range: Min ~ Max) * Each trackbar supports animation sliders (with interpolation). * .lua files can be imported/exported from the script editor toolbar. * The checkboxes (obj.check0 - obj.check3) and the color (color) appear in the effect panel automatically when the script references them (the trackbars are always shown). This general use carries no range/default declaration, so handle value ranges within the script. The AviUtl --track / --check / --color headers still work as before. There are 4 numeric sliders, referenced as obj.slider0 through obj.slider3. The values are integers and do not hold decimals. Slider0 : Integer slider (Range: 1 ~ 10) Slider1 : Integer slider (Range: 0 ~ 100) Slider2 : Integer slider (Range: 0 ~ 1000) Slider3 : Integer slider (Range: -1000 ~ 1000) String parameters are also available, referenced by the following names. obj.text : String from the text input field obj.font : Font name from the font selector obj.dir : Path from the folder selector obj.file_video : Path of a video file obj.file_audio : Path of an audio file obj.file_image : Path of an image file obj.file_project : Path of a project file obj.file_mp4 : Path of an MP4 file obj.file_exo : Path of an EXO file obj.file_subtitle : Path of a subtitle file obj.file_shader : Path of a shader file * The sliders and string parameters appear in the effect panel automatically when the script references them. * A file path can be passed to obj.load to load an image or movie. * These parameters are available in both the MoonSharp and native engines. - Global Variables - The following variables can be referenced directly in the global scope of the script. time : Current time in seconds relative to the object [ReadOnly] * Same value as obj.time. frame : Current frame number relative to the object [ReadOnly] * Same value as obj.frame. totalframe : Total number of frames in the object [ReadOnly] * Same value as obj.totalframe. framerate : Frame rate (fps) [ReadOnly] * Same value as obj.framerate. timelineframe : Current frame number relative to the entire timeline [ReadOnly] * obj.frame is a relative frame from the start of the object, while this is the absolute frame from the start of the timeline. timelinetime : Current time in seconds relative to the entire timeline [ReadOnly] layer : Layer number where the object is placed [ReadOnly] * Same value as obj.layer. obj : Object information table (see "obj Table" below) scene : Scene information table (see "scene Table" below) ymm4 : YMM4 specific meta-information table (see "ymm4 Table" below) anim : Animation utility table (see "anim Table" below) - scene Table - scene.width : Horizontal resolution (pixels) of the scene (project) [ReadOnly] scene.height : Vertical resolution (pixels) of the scene (project) [ReadOnly] scene.cx : Half of the scene's horizontal resolution (= scene.width / 2) [ReadOnly] scene.cy : Half of the scene's vertical resolution (= scene.height / 2) [ReadOnly] scene.set(name, value) Stores a value in a shared area scoped to the scene. The value can be read back with scene.get(name) from every Lua script effect in the same scene, across items and frames. name : Name of the value (string) value : Value to store (number, string, or boolean). Passing nil removes it. * Values other than numbers, strings, and booleans (tables, functions, etc.) are not stored. * Names and string values are truncated beyond 4095 bytes in UTF-8. Example: scene.set("shared_x", obj.x) scene.get(name) Retrieves a value stored with scene.set(). Returns nil for unset names. Example: local x = scene.get("shared_x") or 0 * Values written by your own script can be read back immediately with scene.get within the same run. Values written by other items become visible from the next frame, so the result does not depend on the order in which items are evaluated within a frame. * When a script ends with an error or a timeout, none of its writes are applied to the shared area. * When video export starts, the shared area starts empty, so exporting the same project always produces the same result. * Up to 4096 names can be stored per scene. Writes to new names beyond the limit are ignored. * Values are independent per scene and kept in memory until YMM4 exits. They are not saved into the project file. - obj Table - Variables - The following variables hold the current rendering information of the object. * Variables not marked ReadOnly can be modified in the script, and the changes will be reflected in rendering. o Position / Offset obj.x : Display reference coordinate X (writable) * Corresponds to "Display Reference X" in AviUtl2 specification. * Internally set from DrawDescription.Draw.X; changes take effect after the script runs. obj.y : Display reference coordinate Y (writable) * Internally set from DrawDescription.Draw.Y. obj.z : Display reference coordinate Z (writable) * Internally set from DrawDescription.Draw.Z. obj.ox : Center offset X (writable) * Internally set from DrawDescription.CenterPoint.X (inDesc). * Corresponds to "Relative X from reference coordinate (obj.ox)" in AviUtl2, but in this plugin it is treated as CenterPoint (center point offset). obj.oy : Center offset Y (writable) * Internally set from DrawDescription.CenterPoint.Y (inDesc). o Scale / Transform obj.zoom : Scale factor (writable) * 1.0 is 100% scale (not 0.0), compatible with AviUtl2. * Internally calculated as the average of ZoomX and ZoomY (zoomAvg). * On output, expanded to individual X/Y zoom as obj.zoom * (1 ± obj.aspect). obj.aspect : Aspect ratio (writable), Range: -1.0 ~ 1.0 * Positive values shrink in X direction; negative values shrink in Y direction. * Internally calculated as (ZoomX - ZoomY) / (ZoomX + ZoomY). obj.sx : Scale factor in X direction (writable) 1.0 = 100% * Precise independent scale control specific to YMM4. * Takes precedence over zoom/aspect modifications. obj.sy : Scale factor in Y direction (writable) 1.0 = 100% * Precise independent scale control specific to YMM4. * Takes precedence over zoom/aspect modifications. obj.alpha : Opacity (writable), Range: 0.0 ~ 255.0 * AviUtl2 uses 0.0~1.0, but this plugin uses 0.0~255.0. * Internally set from DrawDescription.Opacity * 255. * Divided by 255 and normalized to 0.0~1.0 on output (with Clamp). * The default script sets obj.alpha = math.min(time * 255, 255), providing a default fade-in implementation. o Rotation obj.rx : Rotation angle around X axis (writable), Unit: degrees (°), 360.0 = one full rotation * Internally set from DrawDescription.Rotation.X. obj.ry : Rotation angle around Y axis (writable), Unit: degrees (°), 360.0 = one full rotation * Internally set from DrawDescription.Rotation.Y. obj.rz : Rotation angle around Z axis (writable), Unit: degrees (°), 360.0 = one full rotation * Internally set from DrawDescription.Rotation.Z. obj.rxr : Rotation angle around X axis in radians (writable) * Takes precedence if rx is also modified simultaneously. obj.ryr : Rotation angle around Y axis in radians (writable) * Takes precedence if ry is also modified simultaneously. obj.rzr : Rotation angle around Z axis in radians (writable) * Takes precedence if rz is also modified simultaneously. o Image Size obj.w : Width of the input image in pixels [ReadOnly] * Internally an integer derived from D2D GetImageLocalBounds. obj.h : Height of the input image in pixels [ReadOnly] * Internally an integer derived from D2D GetImageLocalBounds. obj.hw : Half of the input image width (= obj.w / 2) [ReadOnly] obj.hh : Half of the input image height (= obj.h / 2) [ReadOnly] obj.diagonal : Diagonal length of the input image (= math.sqrt(w*w + h*h)) [ReadOnly] obj.cx : Center X coordinate of the image (= obj.w / 2) [ReadOnly] * Reference center coordinate for pixel operations. obj.cy : Center Y coordinate of the image (= obj.h / 2) [ReadOnly] o Time / Frame obj.time : Current time in seconds relative to the object [ReadOnly] * Same value as global variable time. * Internally set from EffectDescription.ItemPosition.Time.TotalSeconds. obj.frame : Current frame number relative to the object [ReadOnly] * Same value as global variable frame. * Internally set from EffectDescription.ItemPosition.Frame. obj.totalframe: Total number of frames in the object [ReadOnly] * Same value as global variable totalframe. * Internally set from EffectDescription.ItemDuration.Frame. obj.t : Current time progress ratio within the object (0.0 ~ 1.0) [ReadOnly] obj.framerate : Frame rate (fps) [ReadOnly] * Same value as global variable framerate. * Internally set from EffectDescription.FPS. o Trackbars obj.track0 : Current value of Track0 in the effect panel [ReadOnly] * Value after animation interpolation. obj.track1 : Current value of Track1 in the effect panel [ReadOnly] obj.track2 : Current value of Track2 in the effect panel [ReadOnly] obj.track3 : Current value of Track3 in the effect panel [ReadOnly] o Sliders obj.slider0 : Current value of Slider0 in the effect panel (integer) [ReadOnly] obj.slider1 : Current value of Slider1 in the effect panel (integer) [ReadOnly] obj.slider2 : Current value of Slider2 in the effect panel (integer) [ReadOnly] obj.slider3 : Current value of Slider3 in the effect panel (integer) [ReadOnly] o String parameters obj.text : String from the text input field [ReadOnly] obj.font : Font name from the font selector [ReadOnly] obj.dir : Path from the folder selector [ReadOnly] obj.file_video ~ obj.file_shader : Path from each file selector [ReadOnly] o Layer obj.layer : Layer number where the object is placed [ReadOnly] * Same value as global variable layer. * Internally set from EffectDescription.Layer. - obj Table - Variable Changes and Rendering Reflection - After script execution, only the following variables are read back into rendering (applied). Applied variables: obj.x, obj.y, obj.z obj.ox, obj.oy obj.zoom, obj.aspect obj.alpha obj.rx, obj.ry, obj.rz * obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time, obj.totalframe, obj.framerate, obj.track0 ~ obj.track3, obj.layer are ReadOnly and changes will not be reflected in rendering. Output value formulas: ZoomX = obj.zoom * (1.0 + obj.aspect) ZoomY = obj.zoom * (1.0 - obj.aspect) Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0) Draw = (obj.x, obj.y, obj.z) CenterPoint = (obj.ox, obj.oy) Rotation = (obj.rx, obj.ry, obj.rz) - obj Table - Functions - o obj.getobject(tag [, frame]) Gets the drawing information of another object that has the specified tag. * The tag matches the string entered in the target item's "Remark" field. * When the second argument frame is given, the values at that timeline frame are returned. When omitted, the current frame is used. * If multiple items share the same tag, the item visible at the target frame is returned with priority. If none is visible, the first matching item is returned. * Voice items (synthesized voices, etc.) are also targeted. For a voice item, the coordinates, scale, rotation and opacity are those of its caption (subtitle) display. * The returned values are the item's own coordinates, rotation and scale. Transforms from group control, camera control or upper effects are NOT included. * Each value uses the same unit system as the obj table. * .character / .text / .volume / .kind / .length are YMM4-specific extensions that do not exist in AviUtl. They work on both engines. tag : The string set in the target item's remark frame : The absolute timeline frame to sample (optional) Return : An object information table. Returns nil when no matching item exists. .exist : Whether it is visible at the target frame (boolean) .x : Display base coordinate X .y : Display base coordinate Y .z : Display base coordinate Z .zoom : Scale (1.0 = original size) .sx : Scale along X (= zoom) .sy : Scale along Y (= zoom) .rx : Rotation angle around X axis (degrees, always 0) .ry : Rotation angle around Y axis (degrees, always 0) .rz : Rotation angle around Z axis (degrees) .rxr : Rotation angle around X axis (radians, always 0) .ryr : Rotation angle around Y axis (radians, always 0) .rzr : Rotation angle around Z axis (radians) .alpha : Opacity (0.0 - 255.0, fade applied) .layer : Layer number where it is placed .length : Item length (number of frames) .volume : Current volume setting (voice items only; 0 otherwise) .character : Character name (voice items only; empty string otherwise) .text : Dialogue or displayed text (voice and text items only; empty string otherwise) .kind : Item type name (e.g. VoiceItem, TextItem, ImageItem) Example: local funnel = obj.getobject("funnel") if funnel then obj.x = funnel.x obj.y = funnel.y end Locking to the firing position (emitter remark is "funnel"): local fire = timelineframe - frame local src = obj.getobject("funnel", fire) if src then obj.x = src.x obj.y = src.y end Recoloring by character name (target remark is "voice"): local v = obj.getobject("voice") if v and v.character == "Marisa" then obj.effect("Monochrome", "strength", 100, "color", 0xffee55) end o obj.getpixel(x, y) Retrieves pixel information at the specified coordinates. * A GPU->CPU image data transfer occurs on the first call (involves processing overhead). * Pixel coordinates use the top-left of the image as (0, 0), with right and down as positive. * The returned values are straight alpha equivalents converted from premultiplied alpha. x : X coordinate (0 ~ obj.w - 1) y : Y coordinate (0 ~ obj.h - 1) Returns : 4 values r, g, b, a (multiple return values) r = Red component (0.0 ~ 255.0) g = Green component (0.0 ~ 255.0) b = Blue component (0.0 ~ 255.0) a = Alpha value (0.0 ~ 255.0) * Returns (0, 0, 0, 0) for out-of-range coordinates. Example: r, g, b, a = obj.getpixel(10, 20) o obj.setpixel(x, y, r, g, b [, a]) Overwrites pixel information at the specified coordinates. * The pixel data is automatically marked as "modified" on call, and the modified image is output after the script ends. * Stored internally in premultiplied alpha format (BGRA). A premultiplied conversion is performed on setpixel. x : X coordinate (0 ~ obj.w - 1) y : Y coordinate (0 ~ obj.h - 1) r : Red component (0.0 ~ 255.0) g : Green component (0.0 ~ 255.0) b : Blue component (0.0 ~ 255.0) a : Alpha value (default: 255.0) Example: obj.setpixel(10, 20, 255, 0, 0, 128) o obj.getpixeldata() Returns a proxy object for bulk access to all pixel data. * Faster pixel manipulation compared to getpixel/setpixel. * A GPU->CPU image data transfer occurs on the first call (involves processing overhead). Returns : PixelDataProxy object .width : Width of the image in pixels (= obj.w) .height : Height of the image in pixels (= obj.h) :get(index) : Get channel value by index :set(index, value) : Set channel value by index Index specification: Indices are 1-based (following Lua convention). Channel order is R, G, B, A repeating. R channel index for pixel(x, y) = (y * obj.w + x) * 4 + 1 G channel index for pixel(x, y) = (y * obj.w + x) * 4 + 2 B channel index for pixel(x, y) = (y * obj.w + x) * 4 + 3 A channel index for pixel(x, y) = (y * obj.w + x) * 4 + 4 * Modifying the alpha (channel 4) will also proportionally convert RGB. * Modifying RGB channels will apply a premultiplied conversion. * Retrieved values are straight alpha equivalents, same as get(index). Example: local pd = obj.getpixeldata() local idx = (10 * obj.w + 20) * 4 + 1 -- R channel of (x=20, y=10) local r = pd:get(idx) pd:set(idx, 128) o obj.putpixeldata() An empty (no-op) function defined for compatibility. * In AviUtl scripts, getpixeldata/putpixeldata are used together, but in this plugin changes via setpixel/set are automatically applied, so calling this function is unnecessary. o obj.rand(st, ed [, seed [, frame]]) Returns a deterministic integer random value within the range st ~ ed. * With the same seed and frame, it always returns the same value. * When seed is omitted it is treated as 0; when frame is omitted the current frame (obj.frame) is used. * Returns the same value on both the MoonSharp engine and the LuaJIT runtime. For an engine-independent floating-point random value, use anim.rand. st : Lower bound of the range (truncated to an integer) ed : Upper bound of the range (truncated to an integer) seed : Random seed (optional, default 0) frame : Frame used for variation (optional, default obj.frame) Returns : An integer within st ~ ed Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame) o obj.load(target, ...) Replaces the object buffer with generated content. The targets "figure", "text", "image" (image file), "movie" (video file), "scene" (project scene) and "brush" (YMM4 pattern) are supported. After loading, obj.w / obj.h, etc. are updated to the generated size and can be read by getpixel right after the load. Works on both the MoonSharp and the fast (LuaJIT) engine. * "scene" and "brush" are YMM4-only extensions that do not exist in AviUtl. obj.load("figure", name, color, size [, line [, aspect]]) Generates a shape and replaces the buffer (centered). name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形 (English aliases circle, rect, triangle, pentagon, hexagon, star are also accepted). color : Fill color 0xRRGGBB. size : Bounding size in pixels. line : Outline width (optional). 0 fills the shape. aspect : Distortion -1.0 ~ 1.0 (optional). Example: obj.load("figure", "円", 0xff3366, 200) obj.load("text", string) Draws the string with the font, size and color set by obj.setfont and replaces the buffer (rendered with DirectWrite). Example: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕") obj.load("image", path) Loads an image file and replaces the buffer. * For safety the leading header is validated and only genuine images (PNG / JPEG / GIF / BMP / TIFF / WebP) are loaded. Example: obj.load("image", "C:\\img\\logo.png") obj.load("movie", path [, time]) Loads the frame at the given time of a video file and replaces the buffer (decoded with Media Foundation). time : Seconds. Defaults to obj.time when omitted. * For safety the leading header is validated and only genuine videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded. Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time) obj.load("scene", sceneName [, time]) Renders another scene of the project and replaces the buffer. sceneName : The name shown in the scene list. time : Seconds. Defaults to obj.time when omitted. * The scene the current object belongs to cannot be specified. Loading a scene from inside a scene render is also rejected. * Frames that load a scene bypass the render cache and are re-executed every time. Example: obj.load("scene", "Sub Scene", obj.time) obj.load("brush", patternName [, width [, height]]) Generates an image filled with a YMM4 pattern (brush) and replaces the buffer. Patterns added by brush plugins can also be used. patternName : The name shown in the pattern list. width, height : Output size in pixels. Defaults to the current obj.w / obj.h when omitted. * The pattern is drawn with its default parameters. Example: obj.load("brush", "Stripe", 400, 300) o obj.brush(patternName [, width, height] [, paramName, value, ...]) Draws a YMM4 pattern (brush) with parameter overrides and replaces the buffer. The drawing is the same as obj.load("brush"), and in addition the pattern parameters can be changed with the same name-and-value pairs as obj.effect. patternName : The name shown in the pattern list. width, height : Output size in pixels. Defaults to the current obj.w / obj.h. Interpreted as the size only when both are given as numbers. paramName : The display name of a pattern setting, or its internal property name. value : A number, a boolean or a string. Colors are 0xRRGGBB numbers. * Parameters that are not specified are drawn with their default values. A call without pairs equals obj.load("brush"). * This is a YMM4-only extension that does not exist in AviUtl. Example: obj.brush("Stripe", "Angle", 45, "Color1", 0xff3366) o obj.setfont(font [, size [, style [, color]]]) Sets the font used by obj.load("text"). style : Bit flags. 1=bold, 2=italic, 3=bold+italic. color : 0xRRGGBB. Example: obj.setfont("Meiryo", 64, 1, 0xffffff) o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]]) Composites the current object image onto the accumulation buffer. Calling it multiple times draws overlapping copies (afterimages, particles, etc.). ox, oy, oz : Offset from the center (default 0). zoom : 1.0 is original size (default 1.0). alpha : 0.0 ~ 1.0 (default 1.0). aspect : -1.0 ~ 1.0 (default 0). * Once called, the standard draw is suppressed and the composited result is output. o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]]) Texture-maps the object image onto a quad given by 4 vertices. Vertex order is top-left, top-right, bottom-right, bottom-left. When UVs are omitted the whole image is used. * If only a 13th argument is given (UVs omitted), it is used as the alpha (12 coordinates + alpha). * Mapped with an affine transform (exact for parallelograms, approximate for non-parallelograms). o obj.copybuffer(destination, source) Copies an image between buffers, selected by the first character. "obj" : Object image buffer "tmp" : Temporary buffer "cache:name" : Named cache (kept across frames) Example: obj.copybuffer("tmp", "obj") -- save obj.copybuffer("obj", "tmp") -- restore * "frm" (frame buffer) can be used as a copy source. Its content is a virtual image made by compositing the object at its current position onto a transparent scene-sized area. YMM4 cannot access the background, so the background is not included. It cannot be used as a copy destination. o obj.pixelshader(name, target, resources [, constants [, blend [, sampler]]]) Runs an HLSL pixel shader defined inside the script on the GPU. Shaders are defined in a multi-line comment using the same notation as AviUtl ExEdit2; the registered name becomes the entry point. --[[pixelshader@name: Texture2D src : register(t0); float4 name(float4 pos : SV_Position) : SV_Target { ... } ]] name : Name of the defined shader as a string. target : One of "object", "tempbuffer", "cache:name", "framebuffer". "framebuffer" renders into a scene-sized virtual frame buffer and replaces the object image with the result. resources : Array of buffer names bound to t0-t7. A single name can be passed directly as a string. "random" binds a 256x256 region (R32_FLOAT) of random values in 0.0-1.0. "framebuffer" binds the scene-sized virtual frame buffer with the object composited at its current position. constants : Array of numbers, packed into constant buffer b0 as an array of floats. blend : "copy" (as is), "mask" (multiplies alpha only), "draw" (alpha blend), "add" (additive). Default is "copy". Passing a number equal to an obj.setoption("blend", n) mode composites the shader output onto the target with the corresponding YMM4 blend mode. sampler : One of "clip", "clamp", "loop", "mirror", "dot". Bound to SamplerState s0. Unset when omitted. The pixel shader input can be either of the following. float4 name(float4 pos : SV_Position) : SV_Target float4 name(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target uv is set so that the drawing area spans 0.0-1.0. Example: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy") * Runs on both engines. The shader itself always executes on the host GPU. * YMM4 cannot access the background, so the initial content of "framebuffer" is a virtual image made by compositing the object onto a transparent scene-sized area. * The call is skipped in environments without a usable GPU. o obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 extension) Fills the object image with a color, given as straight RGBA in 0-255 (same color model as obj.setpixel). r, g, b : Color components (0-255). a : Opacity (0-255). Default is 255. x, y, w, h: Rectangle to fill. Defaults to the whole image; out of range is clipped. Example: obj.fill(0, 0, 0, 0) -- clear to transparent obj.fill(255, 0, 0, 255, 10, 10, 20, 20) Runs on both engines. o obj.getpixelregion(x, y, w, h) (YMM4 extension) Reads a rectangular region of pixels into a straight RGBA array. The layout is r, g, b, a per pixel and is 1-based (index (row*w+col)*4+1..+4). Pixels outside the image are 0,0,0,0. Returns: an array of length w*h*4. Example: local t = obj.getpixelregion(0, 0, obj.w, obj.h) o obj.putpixelregion(x, y, w, h, data) (YMM4 extension) Writes an array in the same layout as obj.getpixelregion back into a rectangular region. Pixels outside the image are not written. data : straight RGBA array of length w*h*4 (1-based). Example: obj.putpixelregion(0, 0, obj.w, obj.h, t) o obj.convolve(kernel, size [, divisor [, offset]]) (YMM4 extension) Applies a size x size convolution to the object image. Useful for blur, sharpen, edge detection and so on. kernel : size*size coefficients, row-major and 1-based. size : odd number (3, 5, 7 ...). Even or below 1 is ignored. divisor : divides each pixel sum. Defaults to the kernel sum (1 when the sum is 0). offset : added to each component after the division. Default is 0. Edge pixels are extended by the nearest pixel. Applies to r, g, b, a. Example: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- box blur obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- sharpen Runs on both engines. o obj.resize(width, height [, filter]) (YMM4 extension) Scales the object image to the given size. obj.w / obj.h and the other dimensions are updated too. width, height : integers >= 1. filter : "nearest" for nearest-neighbor, or linear when omitted. Example: obj.resize(obj.w * 2, obj.h * 2) Runs on both engines. The fast runtime leaves the image unchanged when the result exceeds the maximum image size. o obj.getvalue(target) Gets the current value of obj (same as obj.x, obj.track0, etc.). target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", "alpha","sx","sy","track0"~"track3","time","frame", etc. Returns: a number (0 for an unknown target). o obj.getaudio(buf, file [, type [, size]]) Gets audio data. buf : A table that receives the data. Values are stored in buf[1]..buf[n]. Pass nil to receive the table as the third return value instead. file : Path of an audio file. The following special names are also accepted. "audiobuffer" : Reads the audio of the whole scene being edited (all items on the timeline mixed together). "itembuffer" : Reads the audio of the item this effect is attached to (after volume, pan, fade, and audio effects are applied). This is a YMM4-specific extension. type : Kind of data to get, as a string. Defaults to "pcm". "pcm" : Mono PCM on a 16-bit scale (-32768 to 32767). "spectrum" : Volume per frequency band (roughly 0 to 32768). size is the number of bands (up to 512, default 32). "fourier" : Magnitudes of the discrete Fourier transform (roughly 0.0 to 1.0). The frequency range is 1/2048 to 1/2; the default count is 1024. "xxxx.l" / "xxxx.r" : Left / right channel variant of the kinds above. Without a suffix, both channels are averaged. size : Number of values to get. Fewer values may be returned. Up to 1024 values can be read per call. Returns: the number of values read, the sampling rate [, the table]. The read position is the current timeline position for "audiobuffer", and the current playback position of the object (obj.time) otherwise. "pcm" returns consecutive samples from that position; "spectrum" / "fourier" analyze the interval starting there. Example: local buf = {} local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32) for i = 1, n do obj.draw((i - n / 2) * 8, -buf[i] / 200) end * Works in both engines. When the audio cannot be read, the count is 0 and no error is raised. * "itembuffer" returns a count of 0 for items without audio (images, shapes, etc.). When the YMM4 internals are not available, it falls back to the audio before volume and other effects are applied. o obj.getinfo(name) Gets various environment information. An unsupported name returns nil. "script_path" : Returns the path of the plugin install folder. It ends with a path separator. "filter" : Returns whether a filter effect is being processed. This plugin always returns true. "saving" : Returns whether the video is being exported (true only while exporting). "image_max" : Returns the maximum image size as width, height. "bpm" : Returns the BPM grid tempo, beat, and reference time (seconds). The tempo is 0 when no BPM grid is set. "clock" : Returns the elapsed time since YMM4 started, in seconds. "script_time" : Returns the elapsed time since the script started, in milliseconds. "version" : Returns the host version as the number major*10000 + minor*100 + build. Works in both engines. Example: if obj.getinfo("saving") == false then obj.drawpoly(...) -- show a frame only while editing end o obj.setoption(name, value) / obj.getoption(name) Sets / gets an option. Unsupported options are accepted so they do not stop the script (getoption returns the stored value, 0 if unset). Options that currently affect drawing: "antialias" : 0 = nearest neighbor, otherwise linear interpolation (obj.draw / obj.drawpoly). "blend" : blend mode number (obj.draw / obj.drawpoly). Same order (0-based) as YMM4's own "Blend mode" dropdown in the property panel: 0=Normal,1=Dissolve,2=Darker,3=Multiply,4=Color burn, 5=Linear burn,6=Lighter,7=Screen,8=Color dodge, 9=Linear dodge (Add),10=Add,11=Overlay,12=Soft light, 13=Hard light,14=Vivid light,15=Linear light,16=Pin light, 17=Hard mix,18=Difference,19=Exclution,20=Subtract, 21=Division,22=Hue,23=Saturation,24=Color,25=Luminance, 26=Lighter color,27=Behind,28=Darker color,29=Clear, 30=Clipping by background,31=XOR,32=Color inversion mask. Out-of-range or invalid values are treated as 0 (Normal). "draw_state" : a boolean that decides whether this effect emits its working image. true outputs the working image; false passes the input through unchanged. Use it to emit the working image without obj.draw or setpixel, or to suppress the output. It works in both engines. "drawtarget" : switches the destination of obj.draw / obj.drawpoly. "framebuffer" (default) composites into the frame buffer. "tempbuffer" composites into the working tmp buffer in place. In obj.setoption("drawtarget", "tempbuffer", w, h) the w, h give the size to initialize the tmp buffer; omit them to keep it. Bring the tmp result back to the working image with obj.copybuffer("obj", "tmp"). Compositing into tempbuffer is normal (source-over); blend applies to framebuffer drawing. It works in both engines. In MoonSharp the compositing into tempbuffer runs on the GPU and switches to the CPU compositing automatically when the GPU is unavailable. Due to rounding, the composited result may differ very slightly between the engines. o obj.pixeloption(name, value) Stores an option for pixel operations as state. o obj.setanchor(name, count [, option, ..]) Shows anchor points on the preview so their coordinates can be adjusted by mouse dragging. The adjusted coordinates are saved with the project. name : the name of the Lua variable that receives the coordinates, given as a string. The variable is laid out as pos={x0,y0,x1,y1,…}, or {x0,y0,z0,x1,y1,z1,…} with "xyz". Coordinates are relative to the object center. count : the number of anchor points. Up to 32. option : enumerated as strings. "line" : connect the anchor points with lines. "loop" : connect the anchor points and close the loop. "star" : connect each anchor point to the object center. "arm" : connect the object center to each anchor point in order. "xyz" : treat the anchor points as 3D coordinates. 2D by default. Returns the number of anchor points. It works in both engines. The "track" name is also supported; a count of 0 places 1 point. The selected anchor can be adjusted numerically via the X / Y / Z sliders in the Anchor group. Example: num = obj.track0 obj.setanchor("pos", num, "loop") for i = 0, num - 1 do obj.draw(pos[i * 2 + 1], pos[i * 2 + 2]) end - ymm4 Table - Table holding YMM4-specific meta-information. All values are ReadOnly. ymm4.group_index : Current item index within a group control (0-based) ymm4.group_count : Total number of items within a group control ymm4.group_ratio : Progress ratio within the group (group_index / group_count) ymm4.timeline_totalframe: Total number of frames for the entire timeline ymm4.timeline_totaltime : Total time in seconds for the entire timeline ymm4.time_ratio : Current playback position ratio (0.0 ~ 1.0) ymm4.is_saving : Whether video is currently being exported (true only during export) ymm4.is_playing : Whether the timeline is currently playing (true only during playback) ymm4.is_paused : Whether the timeline is currently paused (true only when paused) ymm4.scene_id : Unique ID (Guid string) of the current scene - anim Table - Pure utility functions and constants useful for animation calculations. anim.tau : 2 * Pi (math.pi * 2) anim.e : Euler's number (math.exp(1)) anim.phi : Golden ratio ((1 + math.sqrt(5)) / 2) anim.sqrt2 : Square root of 2 (math.sqrt(2)) anim.lerp(a, b, t) : Linear interpolation between a and b by t (0.0 ~ 1.0) anim.smoothstep(e0, e1, x): Smooth Hermite interpolation between e0 and e1 anim.smootherstep(e0, e1, x): Smoother Hermite interpolation between e0 and e1 (continuous 2nd derivative) anim.clamp(v, lo, hi) : Clamps value v between lo and hi anim.map(v, a1, b1, a2, b2): Maps value v from range a1~b1 to range a2~b2 anim.norm(v, lo, hi) : Gets the normalized ratio (0.0 ~ 1.0) of v within lo~hi anim.wrap(v, lo, hi) : Wraps value v to loop within the range lo~hi anim.pingpong(t, len) : Value that bounces back and forth between 0 and len anim.sign(v) : Gets the sign of v (1 for positive, -1 for negative, 0 for zero) anim.oscillate(t, lo, hi, freq): Smoothly oscillates between lo and hi at the given freq (sine wave) anim.triangle(t, freq) : Triangle wave oscillating between 0.0 and 1.0 at the given freq anim.square(t, freq) : Square wave switching between 1.0 and 0.0 at the given freq anim.duration(t, dur) : Current ratio over duration dur (0.0 ~ 1.0, clamped) anim.delay(t, d) : Time starting after delay d (0 if negative) anim.ease_in(t) : Quadratic ease-in (acceleration) anim.ease_out(t) : Quadratic ease-out (deceleration) anim.ease_in_out(t) : Quadratic ease-in-out (acceleration then deceleration) anim.elastic(t) : Bouncy spring easing anim.back(t) : Easing that slightly overshoots before returning anim.step(edge, x) : Returns 1.0 if x >= edge, otherwise 0.0 anim.fract(v) : Gets only the fractional part of v anim.bounce(t) : Bouncing ease effect anim.hsv_to_rgb(h, s, v): Converts HSV (Hue 0~360, Saturation 0~1, Value 0~1) to RGB (0~255) anim.rgb_to_hsv(r, g, b): Converts RGB (0~255) to HSV anim.noise(x, y, z) : 1D to 3D continuous smooth noise (0.0 ~ 1.0) anim.rand(min, max, s) : Stable random value based on seed `s` anim.len(x, y) : Gets the length (norm) of the vector (x, y) anim.dist(x1, y1, x2, y2): Gets the distance between two points (x1, y1) and (x2, y2) anim.dot(x1, y1, x2, y2): Gets the dot product of two vectors (x1, y1) and (x2, y2) anim.normalize(x, y) : Normalizes the vector (x, y) returning a direction vector tuple anim.polar(r, a) : Converts polar coordinates (radius, angle) to (x, y) tuple anim.rotate(x, y, a) : Rotates 2D point (x, y) by angle `a` (degrees) returning (x, y) tuple anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0) - AviUtl-Compatible Global Functions - The following functions can be called directly in the global scope. They return identical results on every execution engine (MoonSharp / native). RGB(r, g, b) RGB(col) RGB(r1, g1, b1, r2, g2, b2) Converts between a color value (0x000000-0xffffff) and its red, green, and blue components (0-255 each). With 3 arguments it composes a single color value, and with 1 argument it decomposes into r, g, b. With 6 arguments it returns a color that changes linearly from the first color to the second according to the object's elapsed time (obj.time / obj.totaltime). Example: col = RGB(64, 192, 255) -- 0x40C0FF Example: r, g, b = RGB(0x0080FF) -- 0, 128, 255 Example: col = RGB(64,192,255, 128,64,0) -- start color -> end color HSV(h, s, v) HSV(col) HSV(h1, s1, v1, h2, s2, v2) Converts between a color value (0x000000-0xffffff) and hue (0-360), saturation (0-100), and value (0-100). The arguments work like RGB(). Example: col = HSV(60, 100, 100) -- 0xFFFF00 Example: h, s, v = HSV(0x0080FF) -- 210, 100, 100 OR(a, b) / AND(a, b) / XOR(a, b) Performs bitwise operations (or / and / exclusive or) on 32-bit integers. Fractions up to exactly 0.5 are truncated when converting to integers (2.50 -> 2, 2.51 -> 3). Example: result = OR(8, 3) -- 11 SHIFT(a, shift) Performs an arithmetic shift. A positive shift shifts left and a negative shift shifts right. Example: result = SHIFT(5, 3) -- 40 Example: result = SHIFT(91, -2) -- 22 debug_print(text) Sends the given string to OutputDebugString(). For debugging. Messages can be viewed with a debug monitor tool such as DebugView. When a script execution error occurs, the error message is also sent automatically. Example: debug_print(string.format("x = %d", obj.x)) - Available Standard Libraries - math library: math.abs, math.ceil, math.cos, math.exp, math.floor, math.fmod, math.huge, math.log, math.max, math.min, math.modf, math.pi, math.random, math.randomseed, math.sin, math.sqrt, math.tan, math.atan, math.atan2, math.deg, math.rad, math.ldexp, math.frexp, math.sinh, math.cosh, math.tanh, math.type, math.tointeger, math.maxinteger, math.mininteger string library: string.format, string.len, string.sub, string.upper, string.lower, string.rep, string.reverse, string.find, string.match, string.gmatch, string.gsub, string.byte, string.char, string.dump, string.pack, string.unpack, string.packsize table library: table.insert, table.remove, table.sort, table.concat, table.unpack, table.move bit32 library: bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lshift, bit32.rshift, bit32.arshift, bit32.extract, bit32.replace, bit32.btest, bit32.countlz, bit32.countrz Basic functions: type, tostring, tonumber, select, error, assert, print, ipairs, pairs, next, unpack, setmetatable, getmetatable, rawget, rawset, rawequal, rawlen, pcall, xpcall - Syntax Extensions - A few notations that plain Lua does not have are added. The script is transformed before execution, so they work the same on every engine. The insides of strings and comments are not transformed. o is / is not a is b means a == b, and a is not b means a ~= b. Example: if frame is not 0 then obj.x = 100 end o != / ! / && / || != means ~=, ! means not, && means and, and || means or. o Compound assignment (+= -= *= /= %= ^= ..=) x += 1 expands to x = x + (1). ..= concatenates strings. o ?? (nil coalescing) a ?? b returns b only when a is nil. It does not fall back on false. o ??= / ||= / &&= x ??= b assigns only when x is nil. x ||= b is x = x or (b), and x &&= b is x = x and (b). o ++ x++ expands to x = x + 1. Use it as a statement on its own line. o Range for () for i in <0..10> do is the same as for i = 0, 10 do and includes the end. <0..<10> excludes the end. <0..10, 2> uses a step of 2. o Ternary (? :) cond ? a : b returns a when cond is truthy and b otherwise. It returns the false or nil branch as is. o nil-conditional (?. ?[ ]) t?.x returns nil when t is nil, otherwise t.x. t?[k] is index access. t is evaluated once. o Lambda (=>) (a, b) => expr expands to (function(a, b) return expr end). Use x => expr for a single parameter, or () => expr for none. o Pipe (|>) x |> f expands to f((x)), passing the left side as the first argument. x |> f(a, b) becomes f((x), a, b). |> can be chained. o Interpolated string (`...`) `x={a}` expands to ("x=" .. tostring(a)). Write an expression inside { }, where extension syntax is also available. o Range check (in <..>) x in <1..5> tests 1 <= x and x <= 5. <1..<5> excludes the upper bound. The left side is evaluated once. o [fast] (acceleration marker) * YMM4 extension Placing [fast] right before obj.fill / obj.convolve / obj.resize delegates that operation to the GPU. By default these run on the CPU. Example: [fast] obj.convolve(kernel, 5) * An error is shown when [fast] precedes anything other than those three functions. * Works in both the MoonSharp and native engines. - Script Examples - o Fade in (default script) obj.alpha = math.min(time * 255, 255) o Fade out obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0) o Control opacity with Track0 obj.alpha = obj.track0 o Rotate over time obj.rz = time * 90 -- 90 degrees per second o Invert the red component of pixels 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, 255 - r, g, b, a) end end o Grayscale conversion using getpixeldata (fast) local pd = obj.getpixeldata() local w = pd.width local h = pd.height for y = 0, h - 1 do for x = 0, w - 1 do local base = (y * w + x) * 4 local r = pd:get(base + 1) local g = pd:get(base + 2) local b = pd:get(base + 3) local a = pd:get(base + 4) local gray = r * 0.299 + g * 0.587 + b * 0.114 pd:set(base + 1, gray) pd:set(base + 2, gray) pd:set(base + 3, gray) end end o Control zoom with Track0 (1.0 = 100% scale) obj.zoom = obj.zoom * (1 + obj.track0 / 100) - AviUtl Script Compatibility (Partial) - A compatibility layer lets the transform, opacity and random portions of AviUtl animation effect scripts (the *.anm family) run without rewriting. When a script contains no AviUtl-specific notation, this layer does not intervene at all, and existing scripts behave exactly as before. o Script header directives Parameter declarations written as comments are interpreted, and the variables that the script body references are defined before execution. --dialog:label,local var=default;... Expands the declaration part of each item (such as local var=default) to the top of the body. In AviUtl these are edited in a dialog; here the default values are used. --color:0xRRGGBB Defines the variable color with the specified color. --check0:label,default Defines obj.check0 (0 to 3) with the default value. --param: Expands the written Lua statement to the top of the body. --track0: to --track3: Trackbar values are referenced via obj.track0 to obj.track3 as before. The label, range and default written in the header are not reflected in the UI. o Multiple sections with @ When a single script defines multiple effects with @name, only the first section is executed. o obj.rand(st, ed [, seed [, frame]]) A deterministic integer random function compatible with AviUtl. See "obj Table - Functions" for details. o Drawing, compositing and loading Drawing and compositing with obj.draw / obj.drawpoly, buffer operations with obj.copybuffer, generation and loading with obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect, obj.getvalue, obj.getaudio, obj.getinfo, and obj.setoption / obj.getoption / obj.pixeloption are supported. See "obj Table - Functions" for details. o AviUtl / AviUtl2 compatibility map for obj.effect obj.effect("effect name", "parameter name", value, ...) first consults the compatibility map. Effects declared as AviUtl / AviUtl2 names pass through the declared scale/offset conversion before reaching the YMM4 properties. Names not declared in the map are resolved directly by the YMM4 effect name or keyword, so existing calls keep working. The map is built as the inverse of YMM4's own AviUtl export (.exo output), so it round-trips exactly. The target engine is selected with --!aviutl (default) / --!aviutl2. The effect names declared in the map and their main parameters are as follows. ぼかし: 範囲, サイズ固定 境界ぼかし: 範囲 方向ブラー: 範囲, 角度, サイズ固定 放射ブラー: 範囲, X, Y, サイズを固定 閃光: 範囲, X, Y, サイズを固定 クロマキー: 色相範囲, 境界補正 クリッピング: 上, 下, 左, 右, 中心の位置を変更 斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅 領域拡張: 上, 下, 左, 右 座標: X, Y, Z 回転: X, Y, Z リサイズ: 拡大率, X, Y, 補間なし 画像ループ: 横回数, 縦回数 極座標変換: 中心幅, 渦巻 グラデーション: 強さ, 中心X, 中心Y, 角度, 幅 単色化: 強さ, 輝度を保持する 縁取り: サイズ, ぼかし 反転: - モザイク: サイズ ディスプレイスメントマップ: ぼかし 動画ファイル合成: X, Y, 拡大率 色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度 色ずれ: ずれ幅, 角度, 強さ 色調補正 and 色ずれ correspond to community plugin effects. The following are out of scope for this layer. Scripts that call them will not behave as intended. x Module loading via require, and arbitrary file access such as io / dofile (image / video loading via obj.load is supported with header validation). - Unsupported Features / Limitations - x obj.rand1(), obj.mes(), etc. from AviUtl2 are not supported. x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported. Only obj.load("image"/"movie") loads files confirmed to be genuine media by leading-header validation. x Modifying obj.z is reflected in rendering (included in ReadBack), but 3D rendering support is limited. x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated. Care must be taken in implementation to prevent infinite loops. x AviUtl2 header directives are only partially supported. The default values of --dialog / --color / --check / --param are interpreted (see "AviUtl Script Compatibility (Partial)"), but the label, range and default of --track@ are not reflected in the UI; values are used via Track0 ~ Track3.