aseprite

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package aseprite provides types and utilities for interacting with Aseprite's command-line interface and Lua scripting API.

This package includes:

  • Client for executing Aseprite commands and Lua scripts
  • Domain types (Color, Point, Rectangle, Pixel, SpriteInfo)
  • Lua script generation utilities
  • Palette extraction and image analysis functions

All operations require an explicit Aseprite executable path configured via Config. No automatic discovery or environment variables are used.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyAutoShading added in v0.4.0

func ApplyAutoShading(img image.Image, lightDir string, intensity float64, style string, hueShift bool) (*image.RGBA, []string, int, error)

ApplyAutoShading applies automatic geometry-based shading to an image.

This function:

  1. Detects edges and identifies distinct regions
  2. Calculates surface normals for each region
  3. Generates shadow and highlight colors for each base color
  4. Applies shading based on light direction and style

Parameters:

  • img: source image to apply shading to
  • lightDir: light direction (top_left, top, top_right, left, right, bottom_left, bottom, bottom_right)
  • intensity: shading intensity (0.0-1.0)
  • style: shading style ("cell", "smooth", "soft")
  • hueShift: whether to apply hue shifting (shadows→cool, highlights→warm)

Returns:

  • shaded image
  • array of generated palette colors (shadows and highlights)
  • number of regions shaded
  • error if any

func CountUniqueColors added in v0.4.0

func CountUniqueColors(img image.Image, preserveTransparency bool) int

CountUniqueColors counts the number of unique colors in an image.

func EscapeString

func EscapeString(s string) string

EscapeString escapes a string for safe use in Lua code.

Handles special characters that could break Lua syntax or introduce injection vulnerabilities:

  • Backslashes (\) are escaped to (\\)
  • Double quotes (") are escaped to (\")
  • Newlines (\n), carriage returns (\r), and tabs (\t) are escaped

Always use this function when embedding user-provided strings in generated Lua code to prevent script injection attacks.

func FindClosestPaletteColor

func FindClosestPaletteColor(targetColor colorful.Color, palette []PaletteColor) (string, int, error)

FindClosestPaletteColor finds the palette color closest to the given color.

func FloydSteinbergDither added in v0.4.0

func FloydSteinbergDither(img image.Image, palette []color.Color) *image.RGBA

FloydSteinbergDither applies Floyd-Steinberg error diffusion dithering.

func FormatColor

func FormatColor(c Color) string

FormatColor formats a Color as a Lua Color constructor call.

Returns a string like "Color(255, 0, 0, 255)" suitable for embedding in Lua scripts. The generated code creates an Aseprite Color object with RGBA values.

func FormatColorWithPalette

func FormatColorWithPalette(c Color, usePalette bool) string

FormatColorWithPalette formats a Color with optional palette snapping for img:putPixel.

If usePalette is false, returns a direct Color constructor call. If usePalette is true, wraps the color in snapToPaletteForPixel() to find the nearest palette color.

The snapToPaletteForPixel function must be defined in the script (use GeneratePaletteSnapperHelper). This is useful for palette-constrained pixel art to ensure all colors match the palette. Returns palette index in indexed mode, pixel color in other modes.

func FormatColorWithPaletteForTool

func FormatColorWithPaletteForTool(c Color, usePalette bool) string

FormatColorWithPaletteForTool formats a Color with optional palette snapping for app.useTool.

If usePalette is false, returns a direct Color constructor call. If usePalette is true, wraps the color in snapToPaletteForTool() to find the nearest palette color.

The snapToPaletteForTool function must be defined in the script (use GeneratePaletteSnapperHelper). Always returns a pixel color value suitable for app.useTool in all color modes.

func FormatPoint

func FormatPoint(p Point) string

FormatPoint formats a Point as a Lua Point constructor call.

Returns a string like "Point(10, 20)" suitable for embedding in Lua scripts. The generated code creates an Aseprite Point object with X, Y coordinates.

func FormatRectangle

func FormatRectangle(r Rectangle) string

FormatRectangle formats a Rectangle as a Lua Rectangle constructor call.

Returns a string like "Rectangle(10, 20, 30, 40)" suitable for embedding in Lua scripts. The generated code creates an Aseprite Rectangle object with X, Y, Width, Height.

func GeneratePaletteSnapperHelper

func GeneratePaletteSnapperHelper() string

GeneratePaletteSnapperHelper returns Lua code defining palette snapping helper functions.

Generates two helper functions:

  1. snapToPaletteForPixel(r, g, b, a) - for img:putPixel (returns index in indexed mode)
  2. snapToPaletteForTool(r, g, b, a) - for app.useTool (returns pixel color)

Both functions snap an arbitrary RGBA color to the nearest color in the sprite's active palette using Euclidean color space distance.

Include this helper at the start of scripts that use palette-aware drawing (use_palette=true).

func MedianCutQuantization added in v0.4.0

func MedianCutQuantization(pixels []color.Color, targetColors int) []color.Color

MedianCutQuantization implements the median cut algorithm for color quantization. Recursively splits color space by median values to produce a balanced palette.

func OctreeQuantization added in v0.4.0

func OctreeQuantization(pixels []color.Color, targetColors int) []color.Color

OctreeQuantization implements octree color quantization algorithm. Fast, tree-based color reduction suitable for large images.

func QuantizePalette added in v0.4.0

func QuantizePalette(img image.Image, targetColors int, algorithm string, preserveTransparency bool) ([]string, int, error)

QuantizePalette reduces image colors using specified quantization algorithm. Returns palette colors (hex strings), original color count, and error.

func RemapPixelsWithDithering added in v0.4.0

func RemapPixelsWithDithering(img image.Image, palette []color.Color, dither bool) *image.RGBA

RemapPixelsWithDithering remaps image pixels to palette colors with optional Floyd-Steinberg dithering.

func WrapInTransaction

func WrapInTransaction(code string) string

WrapInTransaction wraps Lua code in an app.transaction for atomicity.

Aseprite transactions ensure that sprite modifications are atomic - either all changes succeed or all fail. This is important for undo/redo functionality.

All mutation operations should be wrapped in transactions. The generated code has the form:

app.transaction(function()
  <your code here>
end)

Types

type BrightnessMap

type BrightnessMap struct {
	Grid   [][]int           `json:"grid"`   // 2D array of brightness levels
	Legend map[string]string `json:"legend"` // Maps level number to description
}

BrightnessMap represents quantized brightness levels across an image.

func GenerateBrightnessMap

func GenerateBrightnessMap(img image.Image, targetW, targetH, numLevels int) (*BrightnessMap, error)

GenerateBrightnessMap creates a quantized brightness map from an image. The image is downsampled to targetW x targetH and brightness is quantized into numLevels.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client executes Aseprite commands and Lua scripts in batch mode. It provides a high-level interface for sprite manipulation through Aseprite's command-line interface and Lua scripting API.

All operations execute with a configurable timeout and automatic temporary file cleanup. The client is safe for concurrent use from multiple goroutines.

func NewClient

func NewClient(execPath, tempDir string, timeout time.Duration) *Client

NewClient creates a new Aseprite client with the specified configuration.

Parameters:

  • execPath: absolute path to the Aseprite executable
  • tempDir: directory for temporary script files
  • timeout: maximum duration for command execution

The client will create the temp directory if it doesn't exist. All Lua scripts are written to temp files with restricted permissions (0600) and automatically cleaned up after execution.

func (*Client) CleanupOldTempFiles

func (c *Client) CleanupOldTempFiles(maxAge time.Duration) error

CleanupOldTempFiles removes temporary Lua script files older than the specified duration.

This method scans the temp directory for files matching the pattern "script-*.lua" and removes those with modification times older than maxAge. Files are removed silently - errors accessing individual files are ignored.

The temp directory itself is not removed, even if empty. If the directory doesn't exist, this method returns nil.

This is useful for periodic cleanup of leftover temp files from crashed or interrupted operations.

func (*Client) ExecuteCommand

func (c *Client) ExecuteCommand(ctx context.Context, args []string) (string, error)

ExecuteCommand runs an Aseprite command with the given arguments in batch mode.

The command executes with the configured timeout. If the timeout is exceeded, the command is terminated and an error is returned.

Returns the stdout output from Aseprite, or an error if execution fails. Stderr output is included in the error message for debugging.

func (*Client) ExecuteLua

func (c *Client) ExecuteLua(ctx context.Context, script string, spritePath string) (string, error)

ExecuteLua executes a Lua script in Aseprite batch mode.

The script is written to a temporary file with restricted permissions (0600) and automatically cleaned up after execution. Script execution respects the configured timeout.

Parameters:

  • ctx: context for cancellation and timeout control
  • script: Lua script code to execute
  • spritePath: path to sprite file to open (empty string to create new sprite)

If spritePath is non-empty, the sprite will be opened before running the script and the sprite file must exist. The script will have access to app.activeSprite.

Returns the stdout output from Aseprite, or an error if execution fails.

func (*Client) GetVersion

func (c *Client) GetVersion(ctx context.Context) (string, error)

GetVersion retrieves the Aseprite version string.

Executes "aseprite --version" and parses the version from the output. The version string typically has the format "Aseprite 1.3.x".

Returns the version string, or an error if the command fails or the version cannot be parsed from the output.

type Color

type Color struct {
	R uint8 `json:"r"` // Red channel (0-255)
	G uint8 `json:"g"` // Green channel (0-255)
	B uint8 `json:"b"` // Blue channel (0-255)
	A uint8 `json:"a"` // Alpha channel (0-255)
}

Color represents an RGBA color value with 8-bit channels.

Each channel (R, G, B, A) ranges from 0-255, where:

  • R (red): 0 is no red, 255 is full red
  • G (green): 0 is no green, 255 is full green
  • B (blue): 0 is no blue, 255 is full blue
  • A (alpha): 0 is fully transparent, 255 is fully opaque

Color values can be created from RGBA components using NewColor/NewColorRGB, or parsed from hex strings using FromHex.

func NewColor

func NewColor(r, g, b, a uint8) Color

NewColor creates a new Color with the specified RGBA values.

All parameters must be in the range 0-255. Values are clamped by the uint8 type.

func NewColorRGB

func NewColorRGB(r, g, b uint8) Color

NewColorRGB creates a new fully opaque Color with the specified RGB values.

The alpha channel is automatically set to 255 (fully opaque). All parameters must be in the range 0-255. Values are clamped by the uint8 type.

func (*Color) FromHex

func (c *Color) FromHex(hex string) error

FromHex parses a hex color string and updates the Color with the parsed values.

Supported formats:

  • "#RRGGBB" - RGB with implicit full opacity (alpha = 255)
  • "#RRGGBBAA" - RGBA with explicit alpha
  • "RRGGBB" - Same as above, without "#" prefix
  • "RRGGBBAA" - Same as above, without "#" prefix

Returns an error if the hex string format is invalid. The "#" prefix is optional.

func (Color) ToHex

func (c Color) ToHex() string

ToHex converts the color to a hex string in the format "#RRGGBBAA".

All four channels (R, G, B, A) are included in the output. Returns a string like "#FF0000FF" for opaque red.

func (Color) ToHexRGB

func (c Color) ToHexRGB() string

ToHexRGB converts the color to a hex string in the format "#RRGGBB".

Only RGB channels are included; alpha channel is ignored. Returns a string like "#FF0000" for red (regardless of alpha value).

type ColorMode

type ColorMode string

ColorMode represents the color mode of a sprite.

Aseprite supports three color modes:

  • RGB: Full color with 8-bit RGB channels (most common)
  • Grayscale: 8-bit grayscale values
  • Indexed: Palette-based colors (pixel art friendly)
const (
	// ColorModeRGB represents RGB color mode (8-bit per channel)
	ColorModeRGB ColorMode = "rgb"

	// ColorModeGrayscale represents grayscale color mode (8-bit values)
	ColorModeGrayscale ColorMode = "grayscale"

	// ColorModeIndexed represents indexed color mode (palette-based)
	ColorModeIndexed ColorMode = "indexed"
)

func (ColorMode) String

func (cm ColorMode) String() string

String returns the string representation of the color mode.

func (ColorMode) ToLua

func (cm ColorMode) ToLua() string

ToLua returns the Aseprite Lua API constant for the color mode.

Returns one of:

  • "ColorMode.RGB"
  • "ColorMode.GRAYSCALE"
  • "ColorMode.INDEXED"

Defaults to "ColorMode.RGB" for unrecognized modes.

type Composition

type Composition struct {
	FocalPoints    []FocalPoint      `json:"focal_points"`
	RuleOfThirds   RuleOfThirdsGuide `json:"rule_of_thirds"`
	DominantRegion Region            `json:"dominant_region"`
}

AnalyzeComposition performs basic composition analysis on an image.

func AnalyzeComposition

func AnalyzeComposition(img image.Image, edgeMap *EdgeMap) (*Composition, error)

AnalyzeComposition analyzes image composition and returns guide data.

type EdgeLine

type EdgeLine struct {
	From     Point   `json:"from"`     // Starting point
	To       Point   `json:"to"`       // Ending point
	Strength float64 `json:"strength"` // Edge strength 0-100
}

EdgeLine represents a detected edge line.

type EdgeMap

type EdgeMap struct {
	Grid       [][]int    `json:"grid"`        // 2D array where 1 = edge, 0 = no edge
	MajorEdges []EdgeLine `json:"major_edges"` // Significant edge contours
}

EdgeMap represents detected edges in an image.

func DetectEdges

func DetectEdges(img image.Image, threshold int, targetW, targetH int) (*EdgeMap, error)

DetectEdges applies Sobel edge detection to an image. Returns a binary edge map where 1 = edge detected, 0 = no edge. If targetW and targetH are > 0, the image is downsampled before edge detection.

type FocalPoint

type FocalPoint struct {
	X      int     `json:"x"`
	Y      int     `json:"y"`
	Weight float64 `json:"weight"` // 0.0-1.0, higher = more prominent
}

FocalPoint represents a point of visual interest.

type Intersection

type Intersection struct {
	X             int  `json:"x"`
	Y             int  `json:"y"`
	HasFocalPoint bool `json:"has_focal_point"`
}

Intersection represents a rule-of-thirds intersection point.

type LuaGenerator

type LuaGenerator struct{}

LuaGenerator provides utilities for generating Lua scripts for Aseprite batch operations.

All generated scripts are designed to run in Aseprite's batch mode (--batch --script). Scripts include proper error handling, transactions for atomicity, and sprite saving.

The generator is stateless and safe for concurrent use.

func NewLuaGenerator

func NewLuaGenerator() *LuaGenerator

NewLuaGenerator creates a new Lua script generator.

The generator is stateless and can be reused for multiple script generation operations.

func (*LuaGenerator) AddFrame

func (g *LuaGenerator) AddFrame(durationMs int) string

AddFrame generates a Lua script to add a new frame.

Creates a new animation frame at the end of the frame sequence with the specified duration. Frame durations control animation playback speed.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the frame is created.

Parameters:

  • durationMs: frame duration in milliseconds (converted to seconds for Aseprite)

Prints the total frame count on success. Returns an error if no sprite is active.

func (*LuaGenerator) AddLayer

func (g *LuaGenerator) AddLayer(layerName string) string

AddLayer generates a Lua script to add a new layer.

Creates a new layer in the active sprite with the specified name. The layer is added above all existing layers in the layer stack.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the layer is created.

Parameters:

  • layerName: name for the new layer (automatically escaped for Lua safety)

Prints "Layer added successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) AddPaletteColor

func (g *LuaGenerator) AddPaletteColor(hexColor string) string

AddPaletteColor generates a Lua script to add a new color to the palette.

Appends a new color to the end of the palette, expanding it by one entry. This is useful for incrementally building palettes or adding discovered colors.

Parameters:

  • hexColor: color in #RRGGBB or #RRGGBBAA format

The palette is resized to accommodate the new color (up to maximum of 256 colors). The new color is assigned the next available index.

The sprite is saved after the color is added.

Prints JSON with the new color index: {"color_index":N} Returns an error if:

  • No sprite is active
  • No palette exists in the sprite
  • Palette is already at maximum size (256 colors)

func (*LuaGenerator) ApplyAutoShadingResult added in v0.4.0

func (g *LuaGenerator) ApplyAutoShadingResult(tempImagePath string, layerName string, frameNumber int, generatedColors []string, regionsShadedCount int) string

ApplyAutoShadingResult generates a Lua script to apply auto-shading results to a sprite.

This script:

  1. Loads the shaded image from a temporary file
  2. Applies the shaded pixels to the specified layer
  3. Adds generated colors to the palette
  4. Returns JSON with colors added, final palette, and regions shaded count

Parameters:

  • tempImagePath: path to temporary PNG with shaded image
  • layerName: name of layer to apply shading to
  • frameNumber: frame number (1-based)
  • generatedColors: array of hex colors generated during shading
  • regionsShadedCount: number of regions that were shaded

The script imports the shaded image and applies it to the specified layer/frame.

func (*LuaGenerator) ApplyOutline

func (g *LuaGenerator) ApplyOutline(layerName string, frameNumber int, color Color, thickness int) string

ApplyOutline generates a Lua script to apply an outline effect to a layer.

Adds a colored outline border around non-transparent pixels in the specified cel. This is useful for adding emphasis, creating shadows, or separating sprites from backgrounds.

Parameters:

  • layerName: name of the layer to apply outline to (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to apply outline to
  • color: outline color in RGBA format
  • thickness: outline thickness in pixels (1 = single pixel border)

The outline is added outside the existing pixel bounds, expanding the visual size of the content by the thickness amount on all sides.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the outline is applied.

Prints "Outline applied successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • No cel exists at the specified layer/frame

func (*LuaGenerator) ApplyQuantizedPalette added in v0.4.0

func (g *LuaGenerator) ApplyQuantizedPalette(palette []string, originalColors int, algorithm string, convertToIndexed bool, dither bool) string

ApplyQuantizedPalette generates a Lua script to apply a quantized palette to a sprite.

This script:

  1. Sets the sprite's palette to the quantized colors
  2. Remaps all pixels to the nearest palette color (with optional dithering)
  3. Optionally converts the sprite to indexed color mode
  4. Returns JSON with original color count, quantized color count, color mode, palette, and algorithm used

Parameters:

  • palette: slice of hex color strings (#RRGGBB or #RRGGBBAA format) from quantization
  • originalColors: number of unique colors in the original sprite
  • algorithm: name of the quantization algorithm used
  • convertToIndexed: whether to convert the sprite to indexed color mode
  • dither: whether dithering was applied (for reporting purposes)

The script uses Aseprite's built-in color quantization when converting to indexed mode.

func (*LuaGenerator) ApplyShading

func (g *LuaGenerator) ApplyShading(layerName string, frameNumber int, x, y, width, height int, palette []string, lightDirection string, intensity float64, style string) string

ApplyShading generates a Lua script to apply palette-constrained shading based on light direction.

Applies realistic shading to a region by simulating light and shadow using only colors from the provided palette. This enables professional pixel art shading techniques while maintaining palette constraints.

Parameters:

  • layerName: name of the layer to shade (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to shade
  • x, y: top-left corner of the shading region
  • width: region width in pixels
  • height: region height in pixels
  • palette: ordered slice of colors from darkest to lightest (hex strings #RRGGBB)
  • lightDirection: light source position - "top_left", "top", "top_right", "left", "right", "bottom_left", "bottom", "bottom_right"
  • intensity: shading strength (0.0-1.0, where 0 = no shading, 1 = maximum contrast)
  • style: shading style - "smooth", "hard", or "pillow"

Shading styles:

  • "smooth": gradual luminance-based transitions between palette colors
  • "hard": sharp, cell-shaded look with minimal blending
  • "pillow": pillow shading with highlights in center, shadows at edges

Algorithm:

  1. For each pixel, determine light/shadow based on light direction and style
  2. Calculate target luminance adjustment based on intensity
  3. Find closest palette color matching the target luminance
  4. Replace pixel with palette-constrained shaded color

The operation is wrapped in a transaction for atomicity and the sprite is saved after shading is applied.

Prints "Shading applied successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • No cel exists at the specified layer/frame

func (*LuaGenerator) CopySelection

func (g *LuaGenerator) CopySelection() string

CopySelection generates a Lua script to copy the selected pixels to clipboard.

Copies the pixels within the current selection to the clipboard without removing them. The clipboard content can then be pasted elsewhere.

The clipboard content is stored in a hidden layer (__mcp_clipboard__) which persists across operations. The selection is restored from sprite.data if needed.

The sprite is saved to persist the clipboard content.

Prints "Copy selection completed successfully" on success. Returns an error if:

  • No sprite is active
  • No selection exists

func (*LuaGenerator) CreateCanvas

func (g *LuaGenerator) CreateCanvas(width, height int, colorMode ColorMode, filename string) string

CreateCanvas generates a Lua script to create a new sprite.

Creates a sprite with the specified dimensions and color mode, then saves it to disk. The sprite is created using Aseprite's Sprite constructor and saved to the provided path.

For indexed color mode sprites, the transparent color is set to palette index 255 instead of the default index 0. This allows palette index 0 to be used for actual colors without being treated as transparent by Aseprite's cel trimming operations.

Parameters:

  • width: sprite width in pixels (1-65535)
  • height: sprite height in pixels (1-65535)
  • colorMode: color mode (RGB, Grayscale, or Indexed)
  • filename: absolute path where the sprite file should be saved

The generated script prints the filename on success.

func (*LuaGenerator) CreateTag

func (g *LuaGenerator) CreateTag(tagName string, fromFrame, toFrame int, direction string) string

CreateTag generates a Lua script to create an animation tag.

Creates a named tag spanning a range of frames. Tags are used to define animation sequences within a sprite, such as "walk", "jump", or "idle". Each tag can have its own playback direction.

Parameters:

  • tagName: name for the animation tag (automatically escaped for Lua safety)
  • fromFrame: 1-based starting frame index (inclusive)
  • toFrame: 1-based ending frame index (inclusive)
  • direction: playback direction - "forward" (default), "reverse", or "pingpong"

Direction modes:

  • "forward": plays frames from start to end
  • "reverse": plays frames from end to start
  • "pingpong": plays forward then backward in a loop

The operation is wrapped in a transaction for atomicity and the sprite is saved after the tag is created.

Prints "Tag created successfully" on success. Returns an error if:

  • No sprite is active
  • The frame range exceeds the sprite's frame count

func (*LuaGenerator) CropSprite

func (g *LuaGenerator) CropSprite(x, y, width, height int) string

CropSprite generates a Lua script to crop a sprite to a rectangular region.

Trims the sprite canvas to the specified rectangular region, discarding all content outside the crop bounds. This affects all layers and frames.

Parameters:

  • x, y: top-left corner of the crop region (must be non-negative)
  • width: crop width in pixels (must be positive)
  • height: crop height in pixels (must be positive)

The crop bounds are validated against the sprite dimensions:

  • x + width must not exceed sprite.width
  • y + height must not exceed sprite.height

The operation is wrapped in a transaction for atomicity and the sprite is saved after cropping is complete.

Prints "Sprite cropped successfully" on success. Returns an error if:

  • No sprite is active
  • Crop position is negative
  • Crop dimensions are not positive
  • Crop bounds exceed sprite dimensions

func (*LuaGenerator) CutSelection

func (g *LuaGenerator) CutSelection(layerName string, frameNumber int) string

CutSelection generates a Lua script to cut the selected pixels to clipboard.

Removes the pixels within the current selection and copies them to the clipboard. The cut area becomes transparent (filled with transparent pixels).

Parameters:

  • layerName: name of the layer to cut from (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to cut from

The operation is wrapped in a transaction for atomicity and the sprite is saved after the cut is complete.

Prints "Cut selection completed successfully" on success. Returns an error if:

  • No sprite is active
  • No selection exists
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) DeleteFrame

func (g *LuaGenerator) DeleteFrame(frameNumber int) string

DeleteFrame generates a Lua script to delete a frame.

Removes the specified frame from the active sprite's animation sequence. As a safety measure, the script prevents deletion of the last remaining frame.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the frame is deleted.

Parameters:

  • frameNumber: 1-based frame index to delete

Prints "Frame deleted successfully" on success. Returns an error if:

  • No sprite is active
  • The frame number is invalid or not found
  • Attempting to delete the last frame in the sprite

func (*LuaGenerator) DeleteLayer

func (g *LuaGenerator) DeleteLayer(layerName string) string

DeleteLayer generates a Lua script to delete a layer.

Removes the specified layer from the active sprite. The layer is found by name. As a safety measure, the script prevents deletion of the last remaining layer.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the layer is deleted.

Parameters:

  • layerName: name of the layer to delete (automatically escaped for Lua safety)

Prints "Layer deleted successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • Attempting to delete the last layer in the sprite

func (*LuaGenerator) DeleteTag

func (g *LuaGenerator) DeleteTag(tagName string) string

DeleteTag generates a Lua script to delete an animation tag.

Removes a named animation tag from the sprite. The frames themselves are not deleted, only the tag metadata is removed.

Parameters:

  • tagName: name of the tag to delete (automatically escaped for Lua safety)

The operation is wrapped in a transaction for atomicity and the sprite is saved after the tag is deleted.

Prints "Tag deleted successfully" on success. Returns an error if:

  • No sprite is active
  • The tag is not found

func (*LuaGenerator) Deselect

func (g *LuaGenerator) Deselect() string

Deselect generates a Lua script to clear the current selection.

Removes the current selection mask, allowing operations to affect the entire canvas again. This is the opposite of SelectAll.

The persisted selection state in sprite.data is cleared and the sprite is saved.

Prints "Deselect completed successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) DownsampleImage

func (g *LuaGenerator) DownsampleImage(sourcePath, outputPath string, targetWidth, targetHeight int) string

DownsampleImage generates a Lua script to downsample an image using box filter (area averaging).

Reduces image resolution using high-quality box filtering (area averaging). This is ideal for converting high-resolution photos to pixel art by preserving color information and reducing aliasing artifacts.

Parameters:

  • sourcePath: absolute path to source image file (automatically escaped for Lua safety)
  • outputPath: absolute path for output file (automatically escaped for Lua safety)
  • targetWidth: target width in pixels
  • targetHeight: target height in pixels

Algorithm details:

  • Uses box filter (area averaging) for high-quality downsampling
  • Each target pixel averages all source pixels in its corresponding region
  • Preserves color mode from source image
  • Superior to simple nearest-neighbor for photo-to-pixel-art conversion

The source image is opened, processed, and the result is saved to the output path. Both sprites are closed after the operation completes.

Prints the output path on success. Returns an error if:

  • Source image cannot be opened
  • Source sprite has no layers or frames
  • Source sprite has no cel in first frame

func (*LuaGenerator) DrawCircle

func (g *LuaGenerator) DrawCircle(layerName string, frameNumber int, centerX, centerY, radius int, color Color, filled bool, usePalette bool) string

DrawCircle generates a Lua script to draw a circle (ellipse).

Draws either a filled or outlined circle using Aseprite's ellipse tools. The circle is defined by its center point and radius. Note that this actually draws a perfect circle, not an arbitrary ellipse.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • centerX, centerY: center point coordinates
  • radius: circle radius in pixels (must be positive)
  • color: fill/stroke color in RGBA format
  • filled: if true, uses filled_ellipse tool; if false, draws outline only
  • usePalette: if true, snaps color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after the circle is drawn.

Prints "Circle drawn successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) DrawContour

func (g *LuaGenerator) DrawContour(layerName string, frameNumber int, points []Point, color Color, thickness int, closed bool, usePalette bool) string

DrawContour generates a Lua script to draw a polyline or polygon by connecting multiple points.

Draws a series of connected line segments forming either an open polyline or closed polygon. This is useful for creating complex shapes like hand-drawn paths, borders, or traced outlines.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • points: ordered slice of Point structs defining the path vertices
  • color: line color in RGBA format
  • thickness: brush size in pixels (1 = single pixel line)
  • closed: if true, connects the last point back to the first to form a polygon
  • usePalette: if true, snaps color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after the contour is drawn. Each segment is drawn as a separate line to ensure proper vertex connection.

Prints "Contour drawn successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • The points slice is empty

func (*LuaGenerator) DrawLine

func (g *LuaGenerator) DrawLine(layerName string, frameNumber int, x1, y1, x2, y2 int, color Color, thickness int, usePalette bool) string

DrawLine generates a Lua script to draw a line.

Draws a straight line between two points using Aseprite's line tool. The line is anti-aliased and uses the specified brush thickness.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • x1, y1: starting point coordinates
  • x2, y2: ending point coordinates
  • color: line color in RGBA format
  • thickness: brush size in pixels (1 = single pixel line)
  • usePalette: if true, snaps color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after the line is drawn.

Prints "Line drawn successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) DrawPixels

func (g *LuaGenerator) DrawPixels(layerName string, frameNumber int, pixels []Pixel, usePalette bool) string

DrawPixels generates a Lua script to draw multiple pixels.

Draws a batch of pixels to the specified layer and frame. This is the most efficient way to draw multiple pixels as they are all committed in a single transaction.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • pixels: slice of Pixel structs containing {X, Y, Color} data
  • usePalette: if true, snaps each pixel color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after pixels are drawn. If the specified layer has no cel at the target frame, a new cel is created automatically.

Prints "Pixels drawn successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) DrawRectangle

func (g *LuaGenerator) DrawRectangle(layerName string, frameNumber int, x, y, width, height int, color Color, filled bool, usePalette bool) string

DrawRectangle generates a Lua script to draw a rectangle.

Draws either a filled or outlined rectangle using Aseprite's rectangle tools. The rectangle is defined by its top-left corner position and dimensions.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • x, y: top-left corner coordinates
  • width: rectangle width in pixels (must be positive)
  • height: rectangle height in pixels (must be positive)
  • color: fill/stroke color in RGBA format
  • filled: if true, uses filled_rectangle tool; if false, draws outline only
  • usePalette: if true, snaps color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after the rectangle is drawn.

Prints "Rectangle drawn successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) DrawWithDither

func (g *LuaGenerator) DrawWithDither(layerName string, frameNumber int, x, y, width, height int, color1, color2 string, pattern string, density float64) string

DrawWithDither generates a Lua script to fill a region with a dithering pattern.

Applies a dithering pattern to create texture, gradients, or retro aesthetic effects. Supports 15 different patterns including Bayer matrices and texture patterns.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • x, y: top-left corner of the dither region
  • width: region width in pixels
  • height: region height in pixels
  • color1: first color as hex string (e.g., "#FF0000FF")
  • color2: second color as hex string (alternates with color1 based on pattern)
  • pattern: dithering pattern name (see below for available patterns)
  • density: pattern density/threshold (0.0-1.0, where 0.5 = balanced mix)

Available patterns:

  • "bayer_2x2", "bayer_4x4", "bayer_8x8" - Ordered dithering matrices
  • "checkerboard" - Simple alternating pattern
  • "grass", "water", "stone", "cloud" - Organic texture patterns
  • "brick" - Masonry pattern
  • "dots", "diagonal", "cross" - Geometric patterns
  • "noise" - Pseudo-random pattern
  • "horizontal_lines", "vertical_lines" - Directional line patterns

The operation is wrapped in a transaction for atomicity and the sprite is saved after the dither is applied.

Prints "Dithering applied successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • The pattern name is not recognized

func (*LuaGenerator) DuplicateFrame

func (g *LuaGenerator) DuplicateFrame(sourceFrame int, insertAfter int) string

DuplicateFrame generates a Lua script to duplicate a frame.

Creates a complete copy of a frame, including all layer cels and the frame's duration. The new frame can be inserted at a specific position or at the end of the timeline.

Parameters:

  • sourceFrame: 1-based frame index to duplicate
  • insertAfter: 1-based position to insert after (0 = insert at end of timeline)

The operation copies:

  • All layer cels (pixel data and positions)
  • Frame duration settings

The operation is wrapped in a transaction for atomicity and the sprite is saved after the frame is duplicated.

Prints the new frame number on success. Returns an error if:

  • No sprite is active
  • The source frame is not found
  • The insert position exceeds the sprite's frame count (when insertAfter > 0)

func (*LuaGenerator) ExportSprite

func (g *LuaGenerator) ExportSprite(outputPath string, frameNumber int) string

ExportSprite generates a Lua script to export a sprite.

Exports the sprite to a standard image format (PNG, GIF, JPG, BMP). Can export either all frames or a specific frame. For multi-frame exports, the output format determines the result (PNG = image sequence, GIF = animation).

Parameters:

  • outputPath: absolute path for output file (automatically escaped for Lua safety)
  • frameNumber: frame to export (0 = export all frames, >0 = export specific frame)

Export behavior:

  • frameNumber = 0: exports all frames using saveCopyAs (behavior depends on format)
  • frameNumber > 0: creates temporary sprite with single flattened frame

Supported formats (detected from file extension):

  • PNG: supports transparency, multi-frame creates image sequence
  • GIF: supports animation, palette-based
  • JPG/JPEG: no transparency, lossy compression
  • BMP: no transparency, uncompressed

Prints "Exported successfully" on success. Returns an error if:

  • No sprite is active
  • The frame number is invalid (when frameNumber > 0)

func (*LuaGenerator) ExportSpritesheet

func (g *LuaGenerator) ExportSpritesheet(outputPath string, layout string, padding int, includeJSON bool) string

ExportSpritesheet generates a Lua script to export animation frames as a spritesheet.

Combines all animation frames into a single image arranged according to the specified layout. Optionally generates JSON metadata with frame positions and timing information.

Parameters:

  • outputPath: absolute path for output image (automatically escaped for Lua safety)
  • layout: frame arrangement - "horizontal", "vertical", "rows", "columns", or "packed"
  • padding: spacing in pixels between frames and around sheet edges
  • includeJSON: if true, exports metadata JSON alongside the image

Layout options:

  • "horizontal": single row, frames left to right
  • "vertical": single column, frames top to bottom
  • "rows": multiple rows, fills left to right then down
  • "columns": multiple columns, fills top to bottom then right
  • "packed": bin-packing algorithm for space efficiency

When includeJSON is true, generates a .json file with:

  • Frame positions and dimensions
  • Frame durations for animation timing
  • Layer information

Prints JSON with spritesheet_path, frame_count, and optionally metadata_path. Returns an error if no sprite is active.

func (*LuaGenerator) FillArea

func (g *LuaGenerator) FillArea(layerName string, frameNumber int, x, y int, color Color, tolerance int, usePalette bool) string

FillArea generates a Lua script to flood fill an area (paint bucket).

Performs a flood fill operation starting from the specified point, replacing all contiguous pixels of similar color with the target color. The tolerance parameter controls how similar colors must be to be considered the same.

Parameters:

  • layerName: name of the target layer (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to draw on
  • x, y: starting point coordinates for the flood fill
  • color: fill color in RGBA format
  • tolerance: color similarity threshold (0-255, where 0 = exact match only)
  • usePalette: if true, snaps color to nearest palette color

The operation is wrapped in a transaction for atomicity and the sprite is saved after the fill is complete. The fill is contiguous, meaning it only affects connected pixels, not all pixels of the same color.

Prints "Area filled successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid

func (*LuaGenerator) FlattenLayers added in v0.4.0

func (g *LuaGenerator) FlattenLayers() string

FlattenLayers generates a Lua script to flatten all visible layers into a single layer.

This merges all visible layers into one layer, compositing them according to their blend modes and opacity settings. The result is a single layer containing the flattened image.

This is useful before exporting when you want a single composite image.

func (*LuaGenerator) FlipSprite

func (g *LuaGenerator) FlipSprite(direction, target string) string

FlipSprite generates a Lua script to flip a sprite, layer, or cel.

Flips the image content either horizontally or vertically. The flip can be applied to the entire sprite, a single layer, or just the active cel.

Parameters:

  • direction: flip direction - "horizontal" (default) or "vertical"
  • target: scope of the flip - "sprite" (default), "layer", or "cel"

Target modes:

  • "sprite": flips all layers and frames
  • "layer": flips only the active layer across all frames
  • "cel": flips only the active cel (single layer, single frame)

The operation is wrapped in a transaction for atomicity and the sprite is saved after the flip is complete.

Prints "Sprite flipped [direction] successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) GetPalette

func (g *LuaGenerator) GetPalette() string

GetPalette generates a Lua script to retrieve the sprite's current palette.

Extracts all colors from the sprite's palette and returns them as a JSON object. This is useful for analyzing color usage, extracting palettes for reuse, or implementing palette-based drawing operations.

Returns JSON with format: {"colors":["#RRGGBB","#RRGGBB",...],"size":N} The colors array contains hex strings without alpha channel.

Returns an error if:

  • No sprite is active
  • No palette exists in the sprite

func (*LuaGenerator) GetPixels

func (g *LuaGenerator) GetPixels(layerName string, frameNumber int, x, y, width, height int) string

GetPixels generates a Lua script to read pixel data from a rectangular region.

Reads all pixel colors from the specified rectangular region on a layer. This is a convenience wrapper around GetPixelsWithPagination with no pagination.

Parameters:

  • layerName: name of the layer to read from (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to read from
  • x, y: top-left corner of the read region
  • width: region width in pixels
  • height: region height in pixels

Returns JSON array of pixels with format: [{"x":N,"y":N,"color":"#RRGGBBAA"},...] Pixels outside the cel bounds are skipped (not included in output).

For large regions, consider using GetPixelsWithPagination to limit memory usage.

Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • No cel exists at the specified layer/frame

func (*LuaGenerator) GetPixelsWithPagination

func (g *LuaGenerator) GetPixelsWithPagination(layerName string, frameNumber int, x, y, width, height int, offset int, limit int) string

GetPixelsWithPagination generates a Lua script to read pixel data with pagination support.

Reads pixel colors from a rectangular region with optional offset/limit for pagination. This is useful for reading large regions in chunks or sampling specific portions of a layer.

Parameters:

  • layerName: name of the layer to read from (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to read from
  • x, y: top-left corner of the read region
  • width: region width in pixels
  • height: region height in pixels
  • offset: number of pixels to skip from start (0 = start from first pixel)
  • limit: maximum number of pixels to return (0 = return all pixels)

Pixels are indexed in row-major order (left to right, top to bottom). For example, in a 10x10 region:

  • Pixel 0 is at (x, y)
  • Pixel 10 is at (x, y+1)
  • offset=5, limit=10 returns pixels 5-14

Returns JSON array of pixels with format: [{"x":N,"y":N,"color":"#RRGGBBAA"},...] Pixels outside the cel bounds are skipped (not included in output).

Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • No cel exists at the specified layer/frame

func (*LuaGenerator) GetSpriteInfo

func (g *LuaGenerator) GetSpriteInfo() string

GetSpriteInfo generates a Lua script to retrieve sprite metadata.

Extracts complete metadata from the active sprite including:

  • Dimensions (width, height)
  • Color mode (RGB, Grayscale, or Indexed)
  • Frame count
  • Layer count and names

The script outputs JSON-formatted sprite information to stdout. Returns an error if no sprite is active.

func (*LuaGenerator) ImportImage

func (g *LuaGenerator) ImportImage(imagePath, layerName string, frameNumber int, x, y *int) string

ImportImage generates a Lua script to import an external image as a layer.

Loads an external image file and places it as a cel in the specified layer and frame. If the layer doesn't exist, it is created automatically.

Parameters:

  • imagePath: absolute path to source image file (automatically escaped for Lua safety)
  • layerName: name of target layer (created if not found, automatically escaped)
  • frameNumber: 1-based frame index to import to
  • x: optional x-position for the imported image (nil = 0)
  • y: optional y-position for the imported image (nil = 0)

The imported image is placed as a new cel with its top-left corner at (x, y). The image retains its original dimensions and color mode.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the image is imported.

Prints "Image imported successfully" on success. Returns an error if:

  • No sprite is active
  • The image file cannot be loaded
  • The frame number is invalid

func (*LuaGenerator) LinkCel

func (g *LuaGenerator) LinkCel(layerName string, sourceFrame, targetFrame int) string

LinkCel generates a Lua script to create a linked cel.

Creates a cel in the target frame that shares the same image data as the source cel. Linked cels are useful for animation efficiency - when the same image appears in multiple frames, linking saves memory and ensures consistency.

Parameters:

  • layerName: name of the layer to link within (automatically escaped for Lua safety)
  • sourceFrame: 1-based frame index containing the cel to link from
  • targetFrame: 1-based frame index where the linked cel will be created

IMPORTANT: Changes to the image in either the source or target cel will affect both cels since they share the same image reference.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the cel is linked.

Prints "Cel linked successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The source frame is not found
  • The target frame is not found
  • No cel exists in the source frame

func (*LuaGenerator) MoveSelection

func (g *LuaGenerator) MoveSelection(dx, dy int) string

MoveSelection generates a Lua script to translate the selection bounds.

Shifts the selection mask by the specified offset without moving the pixel content. This is useful for repositioning the selection after creating it, or for aligning selections with specific features.

Parameters:

  • dx: horizontal offset in pixels (positive = right, negative = left)
  • dy: vertical offset in pixels (positive = down, negative = up)

The selection is restored from sprite.data if needed, then moved and persisted back. The sprite is saved after the selection is moved.

Prints "Selection moved successfully" on success. Returns an error if:

  • No sprite is active
  • No selection exists to move

func (*LuaGenerator) PasteClipboard

func (g *LuaGenerator) PasteClipboard(layerName string, frameNumber int, x, y *int) string

PasteClipboard generates a Lua script to paste clipboard content.

Pastes the clipboard content (from a previous copy or cut operation) to the specified layer and frame. The paste position can be explicitly set or will use the current position if not specified.

Parameters:

  • layerName: name of the layer to paste to (automatically escaped for Lua safety)
  • frameNumber: 1-based frame index to paste to
  • x: optional x-coordinate for paste position (nil = current position)
  • y: optional y-coordinate for paste position (nil = current position)

The clipboard content is retrieved from the hidden layer (__mcp_clipboard__).

The operation is wrapped in a transaction for atomicity and the sprite is saved after the paste is complete.

Prints "Paste completed successfully" on success. Returns an error if:

  • No sprite is active
  • The layer is not found
  • The frame number is invalid
  • Clipboard is empty

func (*LuaGenerator) ReplaceWithImage added in v0.4.0

func (g *LuaGenerator) ReplaceWithImage(imagePath string) string

ReplaceWithImage generates a Lua script to replace sprite content with an external image. This flattens all layers and replaces the content with the provided image.

func (*LuaGenerator) ResizeCanvas

func (g *LuaGenerator) ResizeCanvas(width, height int, anchor string) string

ResizeCanvas generates a Lua script to resize the canvas without scaling content.

Changes the canvas size without scaling the pixel content. Content is anchored at the specified position, and empty space is added (or content is cropped) to reach the target dimensions.

Parameters:

  • width: new canvas width in pixels
  • height: new canvas height in pixels
  • anchor: content anchor position (see below for options)

Anchor positions:

  • "center" (default): centers content in new canvas
  • "top_left": anchors content to top-left corner
  • "top_right": anchors content to top-right corner
  • "bottom_left": anchors content to bottom-left corner
  • "bottom_right": anchors content to bottom-right corner

If the new dimensions are smaller than the current size, content will be cropped according to the anchor position.

The operation is wrapped in a transaction for atomicity and the sprite is saved after the canvas is resized.

Prints "Canvas resized successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) RotateSprite

func (g *LuaGenerator) RotateSprite(angle int, target string) string

RotateSprite generates a Lua script to rotate a sprite, layer, or cel.

Rotates the image content by 90, 180, or 270 degrees clockwise. The rotation can be applied to the entire sprite, a single layer, or just the active cel.

Parameters:

  • angle: rotation angle in degrees - must be 90, 180, or 270 (default: 90)
  • target: scope of the rotation - "sprite" (default), "layer", or "cel"

Target modes:

  • "sprite": rotates all layers and frames (canvas dimensions change for 90/270)
  • "layer": rotates only the active layer across all frames
  • "cel": rotates only the active cel (single layer, single frame)

The operation is wrapped in a transaction for atomicity and the sprite is saved after the rotation is complete.

Prints "Sprite rotated [angle] degrees successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) SaveAs

func (g *LuaGenerator) SaveAs(newPath string) string

SaveAs generates a Lua script to save the sprite to a new file path.

Saves the active sprite to a new location, effectively creating a copy or moving the sprite. The sprite remains open with the new path as its filename.

Parameters:

  • newPath: absolute path for the saved sprite (automatically escaped for Lua safety)

The file format is determined by the file extension. Supported formats:

  • .aseprite/.ase: native format (preserves all layers, frames, metadata)
  • .png, .gif, .jpg, .bmp: exports to image format (see ExportSprite for details)

Prints JSON with success status and file path: {"success":true,"file_path":"path"} Returns an error if no sprite is active.

func (*LuaGenerator) ScaleSprite

func (g *LuaGenerator) ScaleSprite(scaleX, scaleY float64, algorithm string) string

ScaleSprite generates a Lua script to scale a sprite with a specified algorithm.

Resizes the entire sprite (all layers and frames) by the specified scale factors using one of three scaling algorithms. This changes the canvas dimensions.

Parameters:

  • scaleX: horizontal scale factor (e.g., 2.0 = double width, 0.5 = half width)
  • scaleY: vertical scale factor (e.g., 2.0 = double height, 0.5 = half height)
  • algorithm: scaling algorithm - "nearest", "bilinear", or "rotsprite" (default: "nearest")

Scaling algorithms:

  • "nearest": nearest neighbor (fast, sharp, best for pixel art)
  • "bilinear": bilinear interpolation (smooth, best for photos)
  • "rotsprite": rotation sprite (high-quality pixel art upscaling)

The operation is wrapped in a transaction for atomicity and the sprite is saved after scaling is complete.

Prints JSON with new dimensions: {"success":true,"new_width":N,"new_height":N} Returns an error if no sprite is active.

func (*LuaGenerator) SelectAll

func (g *LuaGenerator) SelectAll() string

SelectAll generates a Lua script to select the entire canvas.

Creates a selection covering the entire sprite canvas from (0,0) to (sprite.width, sprite.height). This is useful before copy/cut operations or to quickly select all content for transformations.

The selection is persisted to sprite.data as JSON and restored across operations. The sprite is saved after the selection is created.

Prints "Select all completed successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) SelectEllipse

func (g *LuaGenerator) SelectEllipse(x, y, width, height int, mode string) string

SelectEllipse generates a Lua script to create an elliptical selection.

Creates or modifies the current selection using an elliptical region. The ellipse is defined by its bounding rectangle and filled using the midpoint ellipse algorithm.

Parameters:

  • x, y: top-left corner of the ellipse bounding box
  • width: bounding box width in pixels (ellipse diameter on x-axis)
  • height: bounding box height in pixels (ellipse diameter on y-axis)
  • mode: selection mode - "replace" (default), "add", "subtract", or "intersect"

Selection modes:

  • "replace": replaces current selection with new ellipse
  • "add": adds ellipse to current selection (union)
  • "subtract": removes ellipse from current selection
  • "intersect": keeps only the intersection of current and new selection

The selection is persisted to sprite.data as JSON and restored across operations. The sprite is saved after the selection is created.

Prints "Ellipse selection created successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) SelectRectangle

func (g *LuaGenerator) SelectRectangle(x, y, width, height int, mode string) string

SelectRectangle generates a Lua script to create a rectangular selection.

Creates or modifies the current selection using a rectangular region. Selections are used to limit drawing operations, cut/copy content, or define regions for transformations.

Parameters:

  • x, y: top-left corner of the selection rectangle
  • width: rectangle width in pixels (must be positive)
  • height: rectangle height in pixels (must be positive)
  • mode: selection mode - "replace" (default), "add", "subtract", or "intersect"

Selection modes:

  • "replace": replaces current selection with new rectangle
  • "add": adds rectangle to current selection (union)
  • "subtract": removes rectangle from current selection
  • "intersect": keeps only the intersection of current and new selection

The selection is persisted to sprite.data as JSON and restored across operations. The sprite is saved after the selection is created.

Prints "Rectangle selection created successfully" on success. Returns an error if no sprite is active.

func (*LuaGenerator) SetFrameDuration

func (g *LuaGenerator) SetFrameDuration(frameNumber int, durationMs int) string

SetFrameDuration generates a Lua script to set the duration of a frame.

Modifies the display duration of a specific animation frame. Frame duration controls how long each frame is displayed during animation playback.

Parameters:

  • frameNumber: 1-based frame index to modify
  • durationMs: frame duration in milliseconds (automatically converted to seconds for Aseprite)

The operation is wrapped in a transaction for atomicity and the sprite is saved after the duration is set.

Prints "Frame duration set successfully" on success. Returns an error if:

  • No sprite is active
  • The frame number is invalid

func (*LuaGenerator) SetPalette

func (g *LuaGenerator) SetPalette(colors []string) string

SetPalette generates a Lua script to set the sprite's palette to the specified colors.

Replaces the entire sprite palette with the provided color list. This is useful for applying extracted palettes from reference images or enforcing a specific color scheme across the sprite.

Parameters:

  • colors: slice of hex color strings in #RRGGBB or #RRGGBBAA format

The palette is resized to match the color count (1-256 colors). Color strings are parsed to extract RGBA components:

  • #RRGGBB format assumes full opacity (alpha = 255)
  • #RRGGBBAA format includes alpha channel
  • Invalid colors are skipped

The sprite is saved after the palette is set.

Prints "Palette set successfully" on success. Returns an error if:

  • No sprite is active
  • No palette exists in the sprite
  • No colors are provided

func (*LuaGenerator) SetPaletteColor

func (g *LuaGenerator) SetPaletteColor(index int, hexColor string) string

SetPaletteColor generates a Lua script to set a specific palette color at an index.

Modifies a single color in the palette at the specified index. This is useful for fine-tuning palettes or implementing color ramps.

Parameters:

  • index: 0-based palette index (0 to palette_size-1)
  • hexColor: color in #RRGGBB or #RRGGBBAA format

The index is validated against the current palette size. Setting a color at a valid index replaces the existing color at that position.

The sprite is saved after the color is set.

Prints "Palette color set successfully" on success. Returns an error if:

  • No sprite is active
  • No palette exists in the sprite
  • The index is out of range (negative or >= palette size)

func (*LuaGenerator) SortPalette

func (g *LuaGenerator) SortPalette(method string, ascending bool) string

SortPalette generates a Lua script to sort the palette by a specified method.

Reorders palette colors based on HSL color space properties. This is useful for organizing palettes logically, creating color ramps, or improving palette usability in indexed color mode.

Parameters:

  • method: sorting criterion - "hue", "saturation", "brightness", or "luminance"
  • ascending: if true, sorts from low to high; if false, sorts from high to low

Sorting methods:

  • "hue": sorts by color hue (red → yellow → green → cyan → blue → magenta)
  • "saturation": sorts by color intensity (gray → vivid)
  • "brightness" or "luminance": sorts by perceived lightness (dark → light)

The sort is performed by converting each color to HSL color space, sorting by the selected component, then applying the reordered colors back to the palette.

The sprite is saved after the palette is sorted.

Prints "Palette sorted by [method] successfully" on success. Returns an error if:

  • No sprite is active
  • No palette exists in the sprite

type PaletteColor

type PaletteColor struct {
	Color        string  `json:"color"`         // Hex color #RRGGBB
	Hue          float64 `json:"hue"`           // 0-360 degrees
	Saturation   float64 `json:"saturation"`    // 0-100%
	Lightness    float64 `json:"lightness"`     // 0-100%
	UsagePercent float64 `json:"usage_percent"` // Percentage of pixels using this color
	Role         string  `json:"role"`          // "dark_shadow", "midtone", "highlight", etc.
}

PaletteColor represents a single color in a palette with metadata.

func ExtractPalette

func ExtractPalette(img image.Image, numColors int) ([]PaletteColor, error)

ExtractPalette extracts a limited color palette from an image using k-means clustering. Colors are extracted in LAB color space (perceptually uniform) and sorted by hue then lightness.

type Pixel

type Pixel struct {
	Point       // Embedded point for X, Y coordinates
	Color Color `json:"color"` // RGBA color value
}

Pixel represents a single pixel with both position and color information.

Combines a Point (X, Y coordinates) with a Color (RGBA values). Used for bulk pixel operations and pixel data inspection.

type Point

type Point struct {
	X int `json:"x"` // Horizontal position (pixels from left edge)
	Y int `json:"y"` // Vertical position (pixels from top edge)
}

Point represents a 2D coordinate in pixel space.

Used for specifying positions, offsets, and dimensions in sprite operations. The coordinate system has origin (0,0) at the top-left corner.

type Rectangle

type Rectangle struct {
	X      int `json:"x"`      // Left edge position
	Y      int `json:"y"`      // Top edge position
	Width  int `json:"width"`  // Width in pixels
	Height int `json:"height"` // Height in pixels
}

Rectangle represents a rectangular region in pixel space.

Defined by top-left corner (X, Y) and size (Width, Height). The coordinate system has origin (0,0) at the top-left corner.

type Region

type Region struct {
	X      int `json:"x"`
	Y      int `json:"y"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

Region represents a rectangular area.

type RuleOfThirdsGuide

type RuleOfThirdsGuide struct {
	VerticalLines   []int          `json:"vertical_lines"`   // X coordinates at 1/3 and 2/3
	HorizontalLines []int          `json:"horizontal_lines"` // Y coordinates at 1/3 and 2/3
	Intersections   []Intersection `json:"intersections"`    // Four power points
}

RuleOfThirdsGuide represents the rule of thirds grid.

type ShadingRegion added in v0.4.0

type ShadingRegion struct {
	Bounds    image.Rectangle
	BaseColor color.Color
	Pixels    []image.Point
	Normal    Vector3D
}

ShadingRegion represents a contiguous region of similar colors for shading.

type SpriteInfo

type SpriteInfo struct {
	Width      int      `json:"width"`       // Sprite width in pixels
	Height     int      `json:"height"`      // Sprite height in pixels
	ColorMode  string   `json:"color_mode"`  // Color mode: "0" (RGB), "1" (Grayscale), "2" (Indexed)
	FrameCount int      `json:"frame_count"` // Number of animation frames
	LayerCount int      `json:"layer_count"` // Number of layers
	Layers     []string `json:"layers"`      // Layer names in order
}

SpriteInfo contains metadata about an Aseprite sprite.

Retrieved from sprites using the get_sprite_info tool. Provides dimensions, color mode, animation frame count, and layer information.

type Vector3D added in v0.4.0

type Vector3D struct {
	X, Y, Z float64
}

Vector3D represents a 3D vector for surface normals and light direction.

func (Vector3D) Dot added in v0.4.0

func (v Vector3D) Dot(other Vector3D) float64

Dot calculates the dot product with another vector.

func (Vector3D) Normalize added in v0.4.0

func (v Vector3D) Normalize() Vector3D

Normalize returns a unit vector in the same direction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL