Add composable ASCII art with per-cell effects and explicit effect loading

Implements ascii_fx_zone effect that allows applying arbitrary sexp effects
to each character cell via cell_effect lambdas. Each cell is rendered as a
small image that effects can operate on.

Key changes:
- New ascii_fx_zone effect with cell_effect parameter for per-cell transforms
- Zone context (row, col, lum, sat, hue, etc.) available in cell_effect lambdas
- Effects are now loaded explicitly from recipe declarations, not auto-loaded
- Added effects_registry to plan for explicit effect dependency tracking
- Updated effect definition syntax across all sexp effects
- New run_staged.py for executing staged recipes
- Example recipes demonstrating alternating rotation and blur/rgb_split patterns

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
gilesb
2026-01-19 21:58:05 +00:00
parent 406cc7c0c7
commit 6ceaa37ab6
62 changed files with 2687 additions and 185 deletions

View File

@@ -1,14 +1,16 @@
;; ASCII Art effect - converts image to ASCII characters
;; @param char_size int [4, 32] default 8
;; @param alphabet string default "standard"
;; @param color_mode string default "color"
;; @param contrast float [1, 3] default 1.5
;; @param background list default (0 0 0)
(define-effect ascii_art
((char_size 8) (alphabet "standard") (color_mode "color") (contrast 1.5) (background (list 0 0 0)))
:params (
(char_size :type int :default 8 :range [4 32])
(alphabet :type string :default "standard")
(color_mode :type string :default "color" :desc ""color", "mono", "invert", or any color name/hex")
(background_color :type string :default "black" :desc "background color name/hex")
(invert_colors :type int :default 0 :desc "swap foreground and background colors")
(contrast :type float :default 1.5 :range [1 3])
)
(let* ((sample (cell-sample frame char_size))
(colors (nth sample 0))
(luminances (nth sample 1))
(chars (luminance-to-chars luminances alphabet contrast)))
(render-char-grid frame chars colors char_size color_mode background)))
(render-char-grid frame chars colors char_size color_mode background_color invert_colors)))

View File

@@ -0,0 +1,51 @@
;; ASCII Art FX - converts image to ASCII characters with per-character effects
(define-effect ascii_art_fx
:params (
;; Basic parameters
(char_size :type int :default 8 :range [4 32]
:desc "Size of each character cell in pixels")
(alphabet :type string :default "standard"
:desc "Character set to use")
(color_mode :type string :default "color"
:choices [color mono invert]
:desc "Color mode: color, mono, invert, or any color name/hex")
(background_color :type string :default "black"
:desc "Background color name or hex value")
(invert_colors :type int :default 0 :range [0 1]
:desc "Swap foreground and background colors (0/1)")
(contrast :type float :default 1.5 :range [1 3]
:desc "Character selection contrast")
;; Per-character effects
(char_jitter :type float :default 0 :range [0 20]
:desc "Position jitter amount in pixels")
(char_scale :type float :default 1.0 :range [0.5 2.0]
:desc "Character scale factor")
(char_rotation :type float :default 0 :range [0 180]
:desc "Rotation amount in degrees")
(char_hue_shift :type float :default 0 :range [0 360]
:desc "Hue shift in degrees")
;; Modulation sources
(jitter_source :type string :default "none"
:choices [none luminance inv_luminance saturation position_x position_y position_diag random center_dist]
:desc "What drives jitter modulation")
(scale_source :type string :default "none"
:choices [none luminance inv_luminance saturation position_x position_y position_diag random center_dist]
:desc "What drives scale modulation")
(rotation_source :type string :default "none"
:choices [none luminance inv_luminance saturation position_x position_y position_diag random center_dist]
:desc "What drives rotation modulation")
(hue_source :type string :default "none"
:choices [none luminance inv_luminance saturation position_x position_y position_diag random center_dist]
:desc "What drives hue shift modulation")
)
(let* ((sample (cell-sample frame char_size))
(colors (nth sample 0))
(luminances (nth sample 1))
(chars (luminance-to-chars luminances alphabet contrast)))
(render-char-grid-fx frame chars colors luminances char_size
color_mode background_color invert_colors
char_jitter char_scale char_rotation char_hue_shift
jitter_source scale_source rotation_source hue_source)))

View File

@@ -0,0 +1,99 @@
;; Composable ASCII Art with Per-Zone Expression-Driven Effects
;;
;; Two modes of operation:
;;
;; 1. EXPRESSION MODE: Use zone-* variables in expression parameters
;; Zone variables available:
;; zone-row, zone-col: Grid position (integers)
;; zone-row-norm, zone-col-norm: Normalized position (0-1)
;; zone-lum: Cell luminance (0-1)
;; zone-sat: Cell saturation (0-1)
;; zone-hue: Cell hue (0-360)
;; zone-r, zone-g, zone-b: RGB components (0-1)
;;
;; Example:
;; (ascii-fx-zone frame
;; :cols 80
;; :char_hue (* zone-lum 180)
;; :char_rotation (* zone-col-norm 30))
;;
;; 2. CELL EFFECT MODE: Pass a lambda to apply arbitrary effects per-cell
;; The lambda receives (cell-image zone-dict) and returns modified cell.
;; Zone dict contains: row, col, row-norm, col-norm, lum, sat, hue, r, g, b,
;; char, color, cell_size, plus any bound analysis values.
;;
;; Any loaded sexp effect can be called on cells - each cell is just a small frame:
;; (blur cell radius) - Gaussian blur
;; (rotate cell angle) - Rotate by angle degrees
;; (brightness cell factor) - Adjust brightness
;; (contrast cell factor) - Adjust contrast
;; (saturation cell factor) - Adjust saturation
;; (hue_shift cell degrees) - Shift hue
;; (rgb_split cell offset_x offset_y) - RGB channel split
;; (invert cell) - Invert colors
;; (pixelate cell block_size) - Pixelate
;; (wave cell amplitude freq) - Wave distortion
;; ... and any other loaded effect
;;
;; Example:
;; (ascii-fx-zone frame
;; :cols 60
;; :cell_effect (lambda [cell zone]
;; (blur (rotate cell (* (get zone "energy") 45))
;; (if (> (get zone "lum") 0.5) 3 0))))
(define-effect ascii_fx_zone
:params (
(cols :type int :default 80 :range [20 200]
:desc "Number of character columns")
(char_size :type int :default nil :range [4 32]
:desc "Character cell size in pixels (overrides cols if set)")
(alphabet :type string :default "standard"
:desc "Character set: standard, blocks, simple, digits, or custom string")
(color_mode :type string :default "color"
:desc "Color mode: color, mono, invert, or any color name/hex")
(background :type string :default "black"
:desc "Background color name or hex value")
(contrast :type float :default 1.5 :range [0.5 3.0]
:desc "Contrast for character selection")
(char_hue :type any :default nil
:desc "Hue shift expression (evaluated per-zone with zone-* vars)")
(char_saturation :type any :default nil
:desc "Saturation multiplier expression (1.0 = unchanged)")
(char_brightness :type any :default nil
:desc "Brightness multiplier expression (1.0 = unchanged)")
(char_scale :type any :default nil
:desc "Character scale expression (1.0 = normal size)")
(char_rotation :type any :default nil
:desc "Character rotation expression (degrees)")
(char_jitter :type any :default nil
:desc "Position jitter expression (pixels)")
(cell_effect :type any :default nil
:desc "Lambda (cell zone) -> cell for arbitrary per-cell effects")
;; Convenience params for staged recipes (avoids compile-time expression issues)
(energy :type float :default nil
:desc "Energy multiplier (0-1) from audio analysis bind")
(rotation_scale :type float :default 0
:desc "Max rotation at top-right when energy=1 (degrees)")
)
;; The ascii-fx-zone special form handles expression params
;; If energy + rotation_scale provided, it builds: energy * scale * position_factor
;; where position_factor = 0 at bottom-left, 3 at top-right
;; If cell_effect provided, each character is rendered to a cell image,
;; passed to the lambda, and the result composited back
(ascii-fx-zone frame
:cols cols
:char_size char_size
:alphabet alphabet
:color_mode color_mode
:background background
:contrast contrast
:char_hue char_hue
:char_saturation char_saturation
:char_brightness char_brightness
:char_scale char_scale
:char_rotation char_rotation
:char_jitter char_jitter
:cell_effect cell_effect
:energy energy
:rotation_scale rotation_scale))

View File

@@ -1,12 +1,13 @@
;; ASCII Zones effect - different character sets for different brightness zones
;; Dark areas use simple chars, mid uses standard, bright uses blocks
;; @param char_size int [4, 32] default 8
;; @param dark_threshold int [0, 128] default 80
;; @param bright_threshold int [128, 255] default 180
;; @param color_mode string default "color"
(define-effect ascii_zones
((char_size 8) (dark_threshold 80) (bright_threshold 180) (color_mode "color"))
:params (
(char_size :type int :default 8 :range [4 32])
(dark_threshold :type int :default 80 :range [0 128])
(bright_threshold :type int :default 180 :range [128 255])
(color_mode :type string :default "color")
)
(let* ((sample (cell-sample frame char_size))
(colors (nth sample 0))
(luminances (nth sample 1))

View File

@@ -8,7 +8,13 @@
;; pad-color - color for padding in fit mode [r g b]
(define-effect blend
((mode "overlay") (opacity 0.5) (resize-mode "fit") (priority "width") (pad-color (list 0 0 0)))
:params (
(mode :type string :default "overlay")
(opacity :type float :default 0.5)
(priority :type string :default "width")
(list :type string :default 0 0 0)
)
)
(let [a frame-a
a-w (width a)
a-h (height a)
@@ -45,4 +51,4 @@
b-resized))]
(if (= mode "alpha")
(blend-images a b opacity)
(blend-images a (blend-mode a b mode) opacity))))
(blend-images a (blend-mode a b mode) opacity)))

View File

@@ -1,10 +1,11 @@
;; Bloom effect - glow on bright areas
;; @param intensity float [0, 2] default 0.5
;; @param threshold int [0, 255] default 200
;; @param radius int [1, 50] default 15
(define-effect bloom
((intensity 0.5) (threshold 200) (radius 15))
:params (
(intensity :type float :default 0.5 :range [0 2])
(threshold :type int :default 200 :range [0 255])
(radius :type int :default 15 :range [1 50])
)
(let* ((bright (map-pixels frame
(lambda (x y c)
(if (> (luminance c) threshold)

View File

@@ -1,6 +1,7 @@
;; Blur effect - gaussian blur
;; @param radius int [1, 50] default 5
(define-effect blur
((radius 5))
:params (
(radius :type int :default 5 :range [1 50])
)
(blur frame (max 1 radius)))

View File

@@ -1,7 +1,8 @@
;; Brightness effect - adjusts overall brightness
;; @param amount float [-255, 255] default 0
;; Uses vectorized adjust primitive for fast processing
(define-effect brightness
((amount 0))
:params (
(amount :type int :default 0 :range [-255 255])
)
(adjust frame amount 1))

View File

@@ -1,8 +1,11 @@
;; Color adjustment effect - replaces TRANSFORM node
;; Params: brightness (-255 to 255), contrast (0 to 3+), saturation (0 to 2+)
(define-effect color-adjust
((brightness 0) (contrast 1) (saturation 1))
:params (
(brightness :type int :default 0 :range [-255 255] :desc "Brightness adjustment")
(contrast :type float :default 1 :range [0 3] :desc "Contrast multiplier")
(saturation :type float :default 1 :range [0 2] :desc "Saturation multiplier")
)
(-> frame
(adjust :brightness brightness :contrast contrast)
(shift-hsv :s saturation)))

View File

@@ -1,8 +1,9 @@
;; Color Cycle effect - animated hue rotation
;; @param speed float [0, 10] default 1
(define-effect color_cycle
((speed 1))
:params (
(speed :type int :default 1 :range [0 10])
)
(let ((shift (* t speed 360)))
(map-pixels frame
(lambda (x y c)

View File

@@ -1,7 +1,8 @@
;; Contrast effect - adjusts image contrast
;; @param amount float [0.5, 3] default 1
;; Uses vectorized adjust primitive for fast processing
(define-effect contrast
((amount 1))
:params (
(amount :type int :default 1 :range [0.5 3])
)
(adjust frame 0 amount))

View File

@@ -1,10 +1,11 @@
;; CRT effect - old monitor simulation
;; @param line_spacing int [1, 10] default 2
;; @param line_opacity float [0, 1] default 0.3
;; @param vignette float [0, 1] default 0.2
(define-effect crt
((line_spacing 2) (line_opacity 0.3) (vignette_amount 0.2))
:params (
(line_spacing :type int :default 2 :range [1 10])
(line_opacity :type float :default 0.3 :range [0 1])
(vignette_amount :type float :default 0.2)
)
(let* ((w (width frame))
(h (height frame))
(cx (/ w 2))

View File

@@ -1,11 +1,12 @@
;; Datamosh effect - glitch block corruption
;; @param block_size int [8, 128] default 32
;; @param corruption float [0, 1] default 0.3
;; @param max_offset int [0, 200] default 50
;; @param color_corrupt bool default true
(define-effect datamosh
((block_size 32) (corruption 0.3) (max_offset 50) (color_corrupt true))
:params (
(block_size :type int :default 32 :range [8 128])
(corruption :type float :default 0.3 :range [0 1])
(max_offset :type int :default 50 :range [0 200])
(color_corrupt :type bool :default true)
)
;; Get previous frame from state, or use current frame if none
(let ((prev (state-get "prev_frame" frame)))
(begin

View File

@@ -1,9 +1,10 @@
;; Echo effect - motion trails using frame buffer
;; @param num_echoes int [1, 20] default 4
;; @param decay float [0, 1] default 0.5
(define-effect echo
((num_echoes 4) (decay 0.5))
:params (
(num_echoes :type int :default 4 :range [1 20])
(decay :type float :default 0.5 :range [0 1])
)
(let* ((buffer (state-get 'buffer (list)))
(new-buffer (take (cons frame buffer) (+ num_echoes 1))))
(begin

View File

@@ -1,7 +1,8 @@
;; Edge detection effect - highlights edges
;; @param low int [10, 100] default 50
;; @param high int [50, 300] default 150
(define-effect edge_detect
((low 50) (high 150))
:params (
(low :type int :default 50 :range [10 100])
(high :type int :default 150 :range [50 300])
)
(edges frame low high))

View File

@@ -1,9 +1,10 @@
;; Emboss effect - creates raised/3D appearance
;; @param strength float [0.5, 3] default 1
;; @param blend float [0, 1] default 0.3
(define-effect emboss
((strength 1) (blend 0.3))
:params (
(strength :type int :default 1 :range [0.5 3])
(blend :type float :default 0.3 :range [0 1])
)
(let* ((kernel (list (list (- strength) (- strength) 0)
(list (- strength) 1 strength)
(list 0 strength strength)))

View File

@@ -1,9 +1,10 @@
;; Film Grain effect - adds film grain texture
;; @param intensity float [0, 1] default 0.2
;; @param colored bool default false
(define-effect film_grain
((intensity 0.2) (colored false))
:params (
(intensity :type float :default 0.2 :range [0 1])
(colored :type bool :default false)
)
(let ((grain-amount (* intensity 50)))
(map-pixels frame
(lambda (x y c)

View File

@@ -1,11 +1,12 @@
;; Fisheye effect - barrel/pincushion lens distortion
;; @param strength float [-1, 1] default 0.3
;; @param center_x float [0, 1] default 0.5
;; @param center_y float [0, 1] default 0.5
;; @param zoom_correct bool default true
(define-effect fisheye
((strength 0.3) (center_x 0.5) (center_y 0.5) (zoom_correct true))
:params (
(strength :type float :default 0.3 :range [-1 1])
(center_x :type float :default 0.5 :range [0 1])
(center_y :type float :default 0.5 :range [0 1])
(zoom_correct :type bool :default true)
)
(let* ((w (width frame))
(h (height frame))
(cx (* w center_x))

View File

@@ -1,9 +1,10 @@
;; Flip effect - flips image horizontally or vertically
;; @param horizontal bool default true
;; @param vertical bool default false
(define-effect flip
((horizontal true) (vertical false))
:params (
(horizontal :type bool :default true)
(vertical :type bool :default false)
)
(let ((result frame))
(if horizontal
(set! result (flip-h result))

View File

@@ -1,5 +1,6 @@
;; Grayscale effect - converts to grayscale
;; Uses vectorized mix-gray primitive for fast processing
(define-effect grayscale ()
(define-effect grayscale
:params ()
(mix-gray frame 1))

View File

@@ -1,9 +1,10 @@
;; Hue shift effect - rotates hue values
;; @param degrees float [0, 360] default 0
;; @param speed float default 0 - rotation per second
;; Uses vectorized shift-hsv primitive for fast processing
(define-effect hue_shift
((degrees 0) (speed 0))
:params (
(degrees :type int :default 0 :range [0 360])
(speed :type int :default 0 :desc "rotation per second")
)
(let ((shift (+ degrees (* speed t))))
(shift-hsv frame shift 1 1)))

View File

@@ -1,5 +1,6 @@
;; Invert effect - inverts all colors
;; Uses vectorized invert-img primitive for fast processing
(define-effect invert ()
(define-effect invert
:params ()
(invert-img frame))

View File

@@ -1,13 +1,14 @@
;; Kaleidoscope effect - mandala-like symmetry patterns
;; @param segments int [3, 16] default 6
;; @param rotation float [0, 360] default 0
;; @param rotation_speed float [-180, 180] default 0
;; @param center_x float [0, 1] default 0.5
;; @param center_y float [0, 1] default 0.5
;; @param zoom float [0.5, 3] default 1
(define-effect kaleidoscope
((segments 6) (rotation 0) (rotation_speed 0) (center_x 0.5) (center_y 0.5) (zoom 1))
:params (
(segments :type int :default 6 :range [3 16])
(rotation :type int :default 0 :range [0 360])
(rotation_speed :type int :default 0 :range [-180 180])
(center_x :type float :default 0.5 :range [0 1])
(center_y :type float :default 0.5 :range [0 1])
(zoom :type int :default 1 :range [0.5 3])
)
(let* ((w (width frame))
(h (height frame))
(cx (* w center_x))

View File

@@ -3,7 +3,12 @@
;; Params: x, y (position), opacity (0-1), mode (blend mode)
(define-effect layer
((x 0) (y 0) (opacity 1.0) (mode "alpha"))
:params (
(x :type int :default 0)
(y :type int :default 0)
(opacity :type float :default 1.0)
(mode :type string :default "alpha")
)
(let [bg (copy frame-a)
fg frame-b
;; Resize fg if needed to fit

View File

@@ -1,8 +1,9 @@
;; Mirror effect - mirrors half of image
;; @param mode string default "left_right"
(define-effect mirror
((mode "left_right"))
:params (
(mode :type string :default "left_right")
)
(let* ((w (width frame))
(h (height frame))
(hw (floor (/ w 2)))

View File

@@ -1,13 +1,13 @@
;; Neon Glow effect - glowing edge effect
;; @param edge_low int [10, 200] default 50
;; @param edge_high int [50, 300] default 150
;; @param glow_radius int [1, 50] default 15
;; @param glow_intensity float [0.5, 5] default 2
;; @param background float [0, 1] default 0.3
(define-effect neon_glow
((edge_low 50) (edge_high 150) (glow_radius 15)
(glow_intensity 2) (background 0.3))
:params (
(edge_low :type int :default 50 :range [10 200])
(edge_high :type int :default 150 :range [50 300])
(glow_radius :type int :default 15 :range [1 50])
(glow_intensity :type int :default 2 :range [0.5 5])
(background :type float :default 0.3 :range [0 1])
)
(let* ((edge-img (edges frame edge_low edge_high))
(glow (blur edge-img glow_radius))
;; Intensify the glow

View File

@@ -1,7 +1,8 @@
;; Noise effect - adds random noise
;; @param amount float [0, 100] default 20
;; Uses vectorized add-noise primitive for fast processing
(define-effect noise
((amount 20))
:params (
(amount :type int :default 20 :range [0 100])
)
(add-noise frame amount))

View File

@@ -1,11 +1,12 @@
;; Outline effect - shows only edges
;; @param thickness int [1, 10] default 2
;; @param threshold int [20, 300] default 100
;; @param color list default (0 0 0)
;; @param fill_mode string default "original"
(define-effect outline
((thickness 2) (threshold 100) (color (list 0 0 0)) (fill_mode "original"))
:params (
(thickness :type int :default 2 :range [1 10])
(threshold :type int :default 100 :range [20 300])
(color :type list :default (list 0 0 0)
)
(fill_mode "original"))
(let* ((edge-img (edges frame (/ threshold 2) threshold))
(dilated (if (> thickness 1)
(dilate edge-img thickness)

View File

@@ -1,8 +1,9 @@
;; Pixelate effect - creates blocky pixels
;; @param block_size int [2, 64] default 8
(define-effect pixelate
((block_size 8))
:params (
(block_size :type int :default 8 :range [2 64])
)
(let* ((w (width frame))
(h (height frame))
(small-w (max 1 (floor (/ w block_size))))

View File

@@ -1,10 +1,11 @@
;; Pixelsort effect - glitch art pixel sorting
;; @param sort_by string default "lightness"
;; @param threshold_low float [0, 255] default 50
;; @param threshold_high float [0, 255] default 200
;; @param angle float [0, 180] default 0
;; @param reverse bool default false
(define-effect pixelsort
((sort_by "lightness") (threshold_low 50) (threshold_high 200) (angle 0) (reverse false))
:params (
(sort_by :type string :default "lightness")
(threshold_low :type int :default 50 :range [0 255])
(threshold_high :type int :default 200 :range [0 255])
(angle :type int :default 0 :range [0 180])
(reverse :type bool :default false)
)
(pixelsort frame sort_by threshold_low threshold_high angle reverse))

View File

@@ -1,8 +1,9 @@
;; Posterize effect - reduces color levels
;; @param levels int [2, 32] default 8
(define-effect posterize
((levels 8))
:params (
(levels :type int :default 8 :range [2 32])
)
(let ((step (floor (/ 256 levels))))
(map-pixels frame
(lambda (x y c)

View File

@@ -1,7 +1,10 @@
;; Resize effect - replaces RESIZE node
;; Params: width, height, mode (linear, nearest, area)
;; Note: uses target-w/target-h to avoid conflict with width/height primitives
(define-effect resize-frame
((target-w 640) (target-h 480) (mode "linear"))
:params (
(target-w :type int :default 640 :desc "Target width in pixels")
(target-h :type int :default 480 :desc "Target height in pixels")
(mode :type string :default "linear" :choices [linear nearest area] :desc "Interpolation mode")
)
(resize frame target-w target-h mode))

View File

@@ -1,9 +1,10 @@
;; RGB Split effect - chromatic aberration
;; @param offset_x float [-50, 50] default 10
;; @param offset_y float [-50, 50] default 0
(define-effect rgb_split
((offset_x 10) (offset_y 0))
:params (
(offset_x :type int :default 10 :range [-50 50])
(offset_y :type int :default 0 :range [-50 50])
)
(let* ((r (channel frame 0))
(g (channel frame 1))
(b (channel frame 2))

View File

@@ -1,13 +1,14 @@
;; Ripple effect - radial wave distortion from center
;; @param frequency float [1, 20] default 5
;; @param amplitude float [0, 50] default 10
;; @param center_x float [0, 1] default 0.5
;; @param center_y float [0, 1] default 0.5
;; @param decay float [0, 5] default 1
;; @param speed float [0, 10] default 1
(define-effect ripple
((frequency 5) (amplitude 10) (center_x 0.5) (center_y 0.5) (decay 1) (speed 1))
:params (
(frequency :type int :default 5 :range [1 20])
(amplitude :type int :default 10 :range [0 50])
(center_x :type float :default 0.5 :range [0 1])
(center_y :type float :default 0.5 :range [0 1])
(decay :type int :default 1 :range [0 5])
(speed :type int :default 1 :range [0 10])
)
(let* ((w (width frame))
(h (height frame))
(cx (* w center_x))

View File

@@ -1,8 +1,9 @@
;; Rotate effect - rotates image
;; @param angle float [-360, 360] default 0
;; @param speed float default 0 - rotation per second
(define-effect rotate
((angle 0) (speed 0))
:params (
(angle :type int :default 0 :range [-360 360])
(speed :type int :default 0 :desc "rotation per second")
)
(let ((total-angle (+ angle (* speed t))))
(rotate-img frame total-angle)))

View File

@@ -1,7 +1,8 @@
;; Saturation effect - adjusts color saturation
;; @param amount float [0, 3] default 1
;; Uses vectorized shift-hsv primitive for fast processing
(define-effect saturation
((amount 1))
:params (
(amount :type int :default 1 :range [0 3])
)
(shift-hsv frame 0 amount 1))

View File

@@ -1,10 +1,11 @@
;; Scanlines effect - VHS-style horizontal line shifting
;; @param amplitude float [0, 100] default 10
;; @param frequency float [1, 100] default 10
;; @param randomness float [0, 1] default 0.5
(define-effect scanlines
((amplitude 10) (frequency 10) (randomness 0.5))
:params (
(amplitude :type int :default 10 :range [0 100])
(frequency :type int :default 10 :range [1 100])
(randomness :type float :default 0.5 :range [0 1])
)
(map-rows frame
(lambda (y row)
(let* ((sine-shift (* amplitude (sin (/ (* y 6.28) (max 1 frequency)))))

View File

@@ -1,7 +1,8 @@
;; Sepia effect - applies sepia tone
;; Classic warm vintage look
(define-effect sepia ()
(define-effect sepia
:params ()
(color-matrix frame
(list (list 0.393 0.769 0.189)
(list 0.349 0.686 0.168)

View File

@@ -1,8 +1,9 @@
;; Sharpen effect - sharpens edges
;; @param amount float [0, 5] default 1
(define-effect sharpen
((amount 1))
:params (
(amount :type int :default 1 :range [0 5])
)
(let ((kernel (list (list 0 (- amount) 0)
(list (- amount) (+ 1 (* 4 amount)) (- amount))
(list 0 (- amount) 0))))

View File

@@ -1,8 +1,9 @@
;; Strobe effect - holds frames for choppy look
;; @param frame_rate float [1, 60] default 12
(define-effect strobe
((frame_rate 12))
:params (
(frame_rate :type int :default 12 :range [1 60])
)
(let* ((held (state-get 'held nil))
(held-until (state-get 'held-until 0))
(frame-duration (/ 1 frame_rate)))

View File

@@ -1,12 +1,13 @@
;; Swirl effect - spiral vortex distortion
;; @param strength float [-10, 10] default 1
;; @param radius float [0.1, 2] default 0.5
;; @param center_x float [0, 1] default 0.5
;; @param center_y float [0, 1] default 0.5
;; @param falloff string default "quadratic"
(define-effect swirl
((strength 1) (radius 0.5) (center_x 0.5) (center_y 0.5) (falloff "quadratic"))
:params (
(strength :type int :default 1 :range [-10 10])
(radius :type float :default 0.5 :range [0.1 2])
(center_x :type float :default 0.5 :range [0 1])
(center_y :type float :default 0.5 :range [0 1])
(falloff :type string :default "quadratic")
)
(let* ((w (width frame))
(h (height frame))
(cx (* w center_x))

View File

@@ -1,9 +1,10 @@
;; Threshold effect - converts to black and white
;; @param level int [0, 255] default 128
;; @param invert bool default false
(define-effect threshold
((level 128) (invert false))
:params (
(level :type int :default 128 :range [0 255])
(invert :type bool :default false)
)
(map-pixels frame
(lambda (x y c)
(let* ((lum (luminance c))

View File

@@ -1,10 +1,11 @@
;; Tile Grid effect - tiles image in grid
;; @param rows int [1, 10] default 2
;; @param cols int [1, 10] default 2
;; @param gap int [0, 50] default 0
(define-effect tile_grid
((rows 2) (cols 2) (gap 0))
:params (
(rows :type int :default 2 :range [1 10])
(cols :type int :default 2 :range [1 10])
(gap :type int :default 0 :range [0 50])
)
(let* ((w (width frame))
(h (height frame))
(tile-w (floor (/ (- w (* gap (- cols 1))) cols)))

View File

@@ -1,8 +1,9 @@
;; Trails effect - persistent motion trails
;; @param persistence float [0, 0.99] default 0.8
(define-effect trails
((persistence 0.8))
:params (
(persistence :type float :default 0.8 :range [0 0.99])
)
(let* ((buffer (state-get 'buffer nil))
(current frame))
(if (= buffer nil)

View File

@@ -1,9 +1,10 @@
;; Vignette effect - darkens corners
;; @param strength float [0, 1] default 0.5
;; @param radius float [0.5, 2] default 1
(define-effect vignette
((strength 0.5) (radius 1))
:params (
(strength :type float :default 0.5 :range [0 1])
(radius :type int :default 1 :range [0.5 2])
)
(let* ((w (width frame))
(h (height frame))
(cx (/ w 2))

View File

@@ -1,11 +1,12 @@
;; Wave effect - sine wave displacement distortion
;; @param amplitude float [0, 100] default 10
;; @param wavelength float [10, 500] default 50
;; @param speed float [0, 10] default 1
;; @param direction string default "horizontal"
(define-effect wave
((amplitude 10) (wavelength 50) (speed 1) (direction "horizontal"))
:params (
(amplitude :type int :default 10 :range [0 100])
(wavelength :type int :default 50 :range [10 500])
(speed :type int :default 1 :range [0 10])
(direction :type string :default "horizontal")
)
(let* ((w (width frame))
(h (height frame))
;; Use _time for animation phase

View File

@@ -1,6 +1,7 @@
;; Zoom effect - zooms in/out from center
;; @param amount float [0.1, 5] default 1
(define-effect zoom
((amount 1))
:params (
(amount :type int :default 1 :range [0.1 5])
)
(scale-img frame amount amount))

View File

@@ -234,6 +234,10 @@ class Interpreter:
state[key] = value
return value
# ascii-fx-zone special form - delays evaluation of expression parameters
if form == 'ascii-fx-zone':
return self._eval_ascii_fx_zone(expr, env)
# Function call
fn = self.eval(head, env)
args = [self.eval(arg, env) for arg in expr[1:]]
@@ -362,32 +366,272 @@ class Interpreter:
return self.eval(clause[1], env)
return None
def _eval_ascii_fx_zone(self, expr: Any, env: Environment) -> Any:
"""
Evaluate ascii-fx-zone special form.
Syntax:
(ascii-fx-zone frame
:cols 80
:alphabet "standard"
:color_mode "color"
:background "black"
:contrast 1.5
:char_hue <expr> ;; NOT evaluated - passed to primitive
:char_saturation <expr>
:char_brightness <expr>
:char_scale <expr>
:char_rotation <expr>
:char_jitter <expr>)
The expression parameters (:char_hue, etc.) are NOT pre-evaluated.
They are passed as raw S-expressions to the primitive which
evaluates them per-zone with zone context variables injected.
"""
from .primitives import prim_ascii_fx_zone
# Expression parameter names that should NOT be evaluated
expr_params = {'char_hue', 'char_saturation', 'char_brightness',
'char_scale', 'char_rotation', 'char_jitter', 'cell_effect'}
# Parse arguments
frame = self.eval(expr[1], env) # First arg is always the frame
# Defaults
cols = 80
char_size = None # If set, overrides cols
alphabet = "standard"
color_mode = "color"
background = "black"
contrast = 1.5
char_hue = None
char_saturation = None
char_brightness = None
char_scale = None
char_rotation = None
char_jitter = None
cell_effect = None # Lambda for arbitrary per-cell effects
# Convenience params for staged recipes
energy = None
rotation_scale = 0
# Extra params to pass to zone dict for lambdas
extra_params = {}
# Parse keyword arguments
i = 2
while i < len(expr):
item = expr[i]
if isinstance(item, Keyword):
if i + 1 >= len(expr):
break
value_expr = expr[i + 1]
kw_name = item.name
if kw_name in expr_params:
# Resolve symbol references but don't evaluate expressions
# This handles the case where effect definition passes a param like :char_hue char_hue
resolved = value_expr
if isinstance(value_expr, Symbol):
try:
resolved = env.get(value_expr.name)
except NameError:
resolved = value_expr # Keep as symbol if not found
if kw_name == 'char_hue':
char_hue = resolved
elif kw_name == 'char_saturation':
char_saturation = resolved
elif kw_name == 'char_brightness':
char_brightness = resolved
elif kw_name == 'char_scale':
char_scale = resolved
elif kw_name == 'char_rotation':
char_rotation = resolved
elif kw_name == 'char_jitter':
char_jitter = resolved
elif kw_name == 'cell_effect':
cell_effect = resolved
else:
# Evaluate normally
value = self.eval(value_expr, env)
if kw_name == 'cols':
cols = int(value)
elif kw_name == 'char_size':
# Handle nil/None values
if value is None or (isinstance(value, Symbol) and value.name == 'nil'):
char_size = None
else:
char_size = int(value)
elif kw_name == 'alphabet':
alphabet = str(value)
elif kw_name == 'color_mode':
color_mode = str(value)
elif kw_name == 'background':
background = str(value)
elif kw_name == 'contrast':
contrast = float(value)
elif kw_name == 'energy':
if value is None or (isinstance(value, Symbol) and value.name == 'nil'):
energy = None
else:
energy = float(value)
extra_params['energy'] = energy
elif kw_name == 'rotation_scale':
rotation_scale = float(value)
extra_params['rotation_scale'] = rotation_scale
else:
# Store any other params for lambdas to access
extra_params[kw_name] = value
i += 2
else:
i += 1
# If energy and rotation_scale provided, build rotation expression
# rotation = energy * rotation_scale * position_factor
# position_factor: bottom-left=0, top-right=3
# Formula: 1.5 * (zone-col-norm + (1 - zone-row-norm))
if energy is not None and rotation_scale > 0:
# Build expression as S-expression list that will be evaluated per-zone
# (* (* energy rotation_scale) (* 1.5 (+ zone-col-norm (- 1 zone-row-norm))))
energy_times_scale = energy * rotation_scale
# The position part uses zone variables, so we build it as an expression
char_rotation = [
Symbol('*'),
energy_times_scale,
[Symbol('*'), 1.5,
[Symbol('+'), Symbol('zone-col-norm'),
[Symbol('-'), 1, Symbol('zone-row-norm')]]]
]
# Pull any extra params from environment that aren't standard params
# These are typically passed from recipes for use in cell_effect lambdas
standard_params = {
'cols', 'char_size', 'alphabet', 'color_mode', 'background', 'contrast',
'char_hue', 'char_saturation', 'char_brightness', 'char_scale',
'char_rotation', 'char_jitter', 'cell_effect', 'energy', 'rotation_scale',
'frame', 't', '_time', '__state__', '__interp__', 'true', 'false', 'nil'
}
# Check environment for extra bindings
current_env = env
while current_env is not None:
for k, v in current_env.bindings.items():
if k not in standard_params and k not in extra_params and not callable(v):
# Add non-standard, non-callable bindings to extra_params
if isinstance(v, (int, float, str, bool)) or v is None:
extra_params[k] = v
current_env = current_env.parent
# Call the primitive with interpreter and env for expression evaluation
return prim_ascii_fx_zone(
frame, cols, char_size, alphabet, color_mode, background, contrast,
char_hue, char_saturation, char_brightness,
char_scale, char_rotation, char_jitter,
self, env, extra_params, cell_effect
)
def _define_effect(self, expr: Any, env: Environment) -> EffectDefinition:
"""
Parse effect definition:
(define-effect name
((param1 default1) (param2 default2) ...)
body)
Parse effect definition.
Required syntax:
(define-effect name
:params (
(param1 :type int :default 8 :desc "description")
)
body)
Effects MUST use :params syntax. Legacy ((param default) ...) is not supported.
"""
name = expr[1].name if isinstance(expr[1], Symbol) else expr[1]
params_list = expr[2] if len(expr) > 2 else []
body = expr[3] if len(expr) > 3 else expr[2]
# Parse parameters
params = {}
if isinstance(params_list, list):
for p in params_list:
if isinstance(p, list) and len(p) >= 2:
pname = p[0].name if isinstance(p[0], Symbol) else p[0]
pdefault = p[1]
params[pname] = pdefault
elif isinstance(p, Symbol):
params[p.name] = None
body = None
found_params = False
# Parse :params and body
i = 2
while i < len(expr):
item = expr[i]
if isinstance(item, Keyword) and item.name == "params":
# :params syntax
if i + 1 >= len(expr):
raise SyntaxError(f"Effect '{name}': Missing params list after :params keyword")
params_list = expr[i + 1]
params = self._parse_params_block(params_list)
found_params = True
i += 2
elif isinstance(item, Keyword):
# Skip other keywords (like :desc)
i += 2
elif body is None:
# First non-keyword item is the body
if isinstance(item, list) and item:
first_elem = item[0]
# Check for legacy syntax and reject it
if isinstance(first_elem, list) and len(first_elem) >= 2:
raise SyntaxError(
f"Effect '{name}': Legacy parameter syntax ((name default) ...) is not supported. "
f"Use :params block instead."
)
body = item
i += 1
else:
i += 1
if body is None:
raise SyntaxError(f"Effect '{name}': No body found")
if not found_params:
raise SyntaxError(
f"Effect '{name}': Missing :params block. "
f"For effects with no parameters, use empty :params ()"
)
effect = EffectDefinition(name, params, body)
self.effects[name] = effect
return effect
def _parse_params_block(self, params_list: list) -> Dict[str, Any]:
"""
Parse :params block syntax:
(
(param_name :type int :default 8 :range [4 32] :desc "description")
)
"""
params = {}
for param_def in params_list:
if not isinstance(param_def, list) or len(param_def) < 1:
continue
# First element is the parameter name
first = param_def[0]
if isinstance(first, Symbol):
param_name = first.name
elif isinstance(first, str):
param_name = first
else:
continue
# Parse keyword arguments
default = None
i = 1
while i < len(param_def):
item = param_def[i]
if isinstance(item, Keyword):
if i + 1 >= len(param_def):
break
kw_value = param_def[i + 1]
if item.name == "default":
default = kw_value
i += 2
else:
i += 1
params[param_name] = default
return params
def load_effect(self, path: str) -> EffectDefinition:
"""Load an effect definition from a .sexp file."""
expr = parse_file(path)
@@ -444,6 +688,16 @@ class Interpreter:
state = {}
env.set('__state__', state)
# Validate that all provided params are known (except internal params)
# Extra params are allowed and will be passed through to cell_effect lambdas
known_params = set(effect.params.keys())
internal_params = {'_time', 'seed', '_binding', 'effect', 'cid', 'hash', 'effect_path'}
extra_effect_params = {} # Unknown params passed through for cell_effect lambdas
for k in params.keys():
if k not in known_params and k not in internal_params:
# Allow unknown params - they'll be passed to cell_effect lambdas via zone dict
extra_effect_params[k] = params[k]
# Bind parameters (defaults + overrides)
for pname, pdefault in effect.params.items():
value = params.get(pname)
@@ -455,6 +709,10 @@ class Interpreter:
value = pdefault
env.set(pname, value)
# Bind extra params (unknown params passed through for cell_effect lambdas)
for k, v in extra_effect_params.items():
env.set(k, v)
# Reset RNG with seed if provided
seed = params.get('seed', 42)
reset_rng(int(seed))
@@ -473,6 +731,41 @@ class Interpreter:
return result, state
def eval_with_zone(self, expr, env: Environment, zone) -> Any:
"""
Evaluate expression with zone-* variables injected.
Args:
expr: Expression to evaluate (S-expression)
env: Parent environment with bound values
zone: ZoneContext object with cell data
Zone variables injected:
zone-row, zone-col: Grid position (integers)
zone-row-norm, zone-col-norm: Normalized position (0-1)
zone-lum: Cell luminance (0-1)
zone-sat: Cell saturation (0-1)
zone-hue: Cell hue (0-360)
zone-r, zone-g, zone-b: RGB components (0-1)
Returns:
Evaluated result (typically a number)
"""
# Create child environment with zone variables
zone_env = Environment(env)
zone_env.set('zone-row', zone.row)
zone_env.set('zone-col', zone.col)
zone_env.set('zone-row-norm', zone.row_norm)
zone_env.set('zone-col-norm', zone.col_norm)
zone_env.set('zone-lum', zone.luminance)
zone_env.set('zone-sat', zone.saturation)
zone_env.set('zone-hue', zone.hue)
zone_env.set('zone-r', zone.r)
zone_env.set('zone-g', zone.g)
zone_env.set('zone-b', zone.b)
return self.eval(expr, zone_env)
# =============================================================================
# Convenience Functions

File diff suppressed because it is too large Load Diff

View File

@@ -150,6 +150,68 @@ def test_effect_execution():
return passed, failed
def test_ascii_fx_zone():
"""Test ascii_fx_zone effect with zone expressions."""
print("Testing ascii_fx_zone...")
interp = get_interpreter()
# Load the effect
effects_dir = Path(__file__).parent / "effects"
load_effects_dir(str(effects_dir))
# Create gradient test frame
frame = np.zeros((120, 160, 3), dtype=np.uint8)
for x in range(160):
frame[:, x] = int(x / 160 * 255)
frame = np.stack([frame[:,:,0]]*3, axis=2)
# Test 1: Basic without expressions
result, _ = run_effect('ascii_fx_zone', frame, {'cols': 20}, {})
assert result.shape == frame.shape
print(" Basic run: OK")
# Test 2: With zone-lum expression
expr = parse('(* zone-lum 180)')
result, _ = run_effect('ascii_fx_zone', frame, {
'cols': 20,
'char_hue': expr
}, {})
assert result.shape == frame.shape
print(" Zone-lum expression: OK")
# Test 3: With multiple expressions
scale_expr = parse('(+ 0.5 (* zone-lum 0.5))')
rot_expr = parse('(* zone-row-norm 30)')
result, _ = run_effect('ascii_fx_zone', frame, {
'cols': 20,
'char_scale': scale_expr,
'char_rotation': rot_expr
}, {})
assert result.shape == frame.shape
print(" Multiple expressions: OK")
# Test 4: With numeric literals
result, _ = run_effect('ascii_fx_zone', frame, {
'cols': 20,
'char_hue': 90,
'char_scale': 1.2
}, {})
assert result.shape == frame.shape
print(" Numeric literals: OK")
# Test 5: Zone position expressions
col_expr = parse('(* zone-col-norm 360)')
result, _ = run_effect('ascii_fx_zone', frame, {
'cols': 20,
'char_hue': col_expr
}, {})
assert result.shape == frame.shape
print(" Zone position expression: OK")
print(" ascii_fx_zone OK")
def main():
print("=" * 60)
print("S-Expression Effect Interpreter Tests")
@@ -159,6 +221,7 @@ def main():
test_interpreter_basics()
test_primitives()
test_effect_loading()
test_ascii_fx_zone()
passed, failed = test_effect_execution()
print("=" * 60)